/*
The master node class handles incoming node connections.
557995
function MasterNode(io, config, pass) {
  EventEmitter.call(this);
  this.connected = [];  // array of connected clients.
  this.disconnected = []; // an array of disconnected and removed clients.
  this.disconnecting = [];  //array of disconnecting clients (didn't reconnect within 10sec)
  this.io = io;
  this.config = config;
  this.config.password = crux.util.sha2(pass);
  this.__loadDump();
  this.bind();
}
1308233
function activate () {
    if (_active) return node
    _active = true
    debug('activated')

    if (!external) {
      _masterBroker.bind()
      _masterResolver.bind()
    }
    if (!node.isReady) _seekForMaster()
    return node
  }
832692
protected static function _ForceMasterConnect () {
		foreach (static::$_dsnList as $connection_name => $dsn) {
			if (isset($dsn['master'])) {
				foreach ($dsn['master'] as $idx => $master_dsn) {
					static::GetConnection([$connection_name, 'master', $idx]);
				}
			}
		}
	}
713537
protected void sendNextPing() {
		Set<String> nodeIDs = transporter.getAllNodeIDs();

		// Remove this node's ID
		nodeIDs.remove(nodeID);

		// Remove duplications by IP address
		int size = nodeIDs.size() * 2;
		HashSet<String> ips = new HashSet<>(size);
		Iterator<String> i = nodeIDs.iterator();
		while (i.hasNext()) {
			Tree descriptor = transporter.getDescriptor(i.next());
			if (descriptor == null) {
				continue;
			}
			Tree ipList = descriptor.get("ipList");
			if (ipList == null) {
				continue;
			}
			for (Tree ip : ipList) {
				if (ip == null) {
					continue;
				}
				String value = ip.asString();
				if (value == null || value.startsWith("127.")) {
					continue;
				}
				if (ips.contains(value)) {
					i.remove();
					break;
				}
				ips.add(value);
			}
			try {
				Thread.sleep(5);
			} catch (InterruptedException interrupt) {
				return;
			}
		}

		// Has peers?
		if (nodeIDs.isEmpty()) {
			return;
		}

		// Find the next nodeID
		boolean submitted = false;
		if (previousNodeID != null) {
			boolean found = false;
			for (String nextNodeID : nodeIDs) {
				if (previousNodeID.equals(nextNodeID)) {
					found = true;
					continue;
				}
				if (found && !nodeID.equals(nextNodeID)) {

					// Send PING to the next node
					submitted = true;
					previousNodeID = nextNodeID;
					sendPing(nextNodeID);
					break;
				}
			}
		}

		// Send PING to the first node
		if (!submitted) {
			for (String nextNodeID : nodeIDs) {
				if (!nodeID.equals(nextNodeID)) {
					previousNodeID = nextNodeID;
					sendPing(nextNodeID);
					break;
				}
			}
		}
	}
876954
def connect!
      info "connecting to master at #{@api_uri}"
      headers = {
          'Kontena-Node-Id' => @node_id.to_s,
          'Kontena-Node-Name' => @node_name,
          'Kontena-Version' => Kontena::Agent::VERSION,
          'Kontena-Node-Labels' => @node_labels.join(','),
          'Kontena-Connected-At' => Time.now.utc.strftime(STRFTIME),
      }

      if @node_token
        headers['Kontena-Node-Token'] = @node_token.to_s
      elsif @grid_token
        headers['Kontena-Grid-Token'] = @grid_token.to_s
      else
        fail "Missing grid, node token"
      end

      @ws = Kontena::Websocket::Client.new(@api_uri,
        headers: headers,
        ssl_params: @ssl_params,
        ssl_hostname: @ssl_hostname,
        connect_timeout: CONNECT_TIMEOUT,
        open_timeout: OPEN_TIMEOUT,
        ping_interval: PING_INTERVAL,
        ping_timeout: PING_TIMEOUT,
        close_timeout: CLOSE_TIMEOUT,
      )

      async.connect_client @ws

      publish('websocket:connect', nil)

    rescue => exc
      error exc
      reconnect!
    end
1008175
public void initEventHandlers(final CmsSitemapTreeNode node) {

        node.getOpener().addClickListener(new ClickListener() {

            private static final long serialVersionUID = 1L;

            public void buttonClick(ClickEvent event) {

                CmsSitemapTreeController.this.onClickOpen(node);
            }
        });
    }
1000427
private void sendMasterAnswer(Address target) {
        Address masterAddress = clusterService.getMasterAddress();
        if (masterAddress == null) {
            logger.info(format("Cannot send master answer to %s since master node is not known yet", target));
            return;
        }

        if (masterAddress.equals(node.getThisAddress())
                && node.getNodeExtension().getInternalHotRestartService()
                    .isMemberExcluded(masterAddress, clusterService.getThisUuid())) {
            // I already know that I will do a force-start so I will not allow target to join me
            logger.info("Cannot send master answer because " + target + " should not join to this master node.");
            return;
        }

        if (masterAddress.equals(target)) {
            logger.fine("Cannot send master answer to " + target + " since it is the known master");
            return;
        }

        MasterResponseOp op = new MasterResponseOp(masterAddress);
        nodeEngine.getOperationService().send(op, target);
    }
395676
function handleConnection(client) {
        // set ghostmode callbacks
        if (bs.options.get("ghostMode")) {
            addGhostMode(client);
        }

        client.emit("connection", bs.options.toJS()); //todo - trim the amount of options sent to clients

        emitter.emit("client:connected", {
            ua: client.handshake.headers["user-agent"]
        });
    }
518603
def _handle_nodes(nodes: MaybeNodeList) -> List[BaseEntity]:
    """"""
    if isinstance(nodes, BaseEntity):
        return [nodes]

    return [
        (
            parse_result_to_dsl(node)
            if not isinstance(node, BaseEntity) else
            node
        )
        for node in nodes
    ]
1230050
function Node (host, customSettings) {
  let node = new EventEmitter()

  let _settings = {...defaultSettings, ...customSettings, host}
  _validateSettings(_settings)

  let _id = getNodeId(_settings)
  let _name = nodeIdToName(_id)
  let _active = false
  let _deactivating = false
  let _canPublish = false
  let _receiving = false
  let _master = null

  let { external } = _settings

  //  Debug
  const _debugStr = `dnsmq-messagebus:${external ? 'externalnode' : 'dnsnode'}`
  const _debug = D(_debugStr)
  const debug = (...args) => _debug(_name, ...args)

  /**
   * starts a master node resolution;
   * if a master node is found starts a connection to it
   */
  const _seekForMaster = () => {
    if (!_active || _masterResolver.isResolving) return
    _masterResolver
    .resolve()
    .then(_connectToMaster)
    .catch(() => {
      _seekForMaster()
    })
  }
  /**
   * starts a connection of the PUB and SUB interfaces
   * to a given master
   * @param  {string} id
   * @param  {string} name
   * @param  {object} endpoints
   */
  const _connectToMaster = ({id, name, endpoints}) => {
    if (!_active) return
    _master = {id, name, endpoints}
    _subConnection.connect({name, endpoint: endpoints.pub})
    _pubConnection.connect({name, endpoint: endpoints.sub})
    if (!external) {
      name === _name ? _masterBroker.startHeartbeats() : _masterBroker.stoptHeartbeats()
    }
  }

  /**
   * publish interface
   * @type {object}
   */
  let _pubConnection = PubConnection(node)
  _pubConnection.on('connect', () => {
    _canPublish = true
    node.emit('can:publish')
    if (_receiving) node.emit('ready')
  })
  _pubConnection.on('disconnect', () => {
    _canPublish = false
    node.emit('cannot:publish')
    if (_receiving) node.emit('not:ready')
  })

  /**
   * subscribe interface
   * @type {object}
   */
  let _subConnection = SubConnection(node)
  _subConnection.on('missingmaster', () => {
    _pubConnection.disconnect()
    _seekForMaster()
  })
  _subConnection.on('newmaster', _connectToMaster)
  _subConnection.on('connect', () => {
    _receiving = true
    node.emit('receiving')
    if (_canPublish) node.emit('ready')
  })
  _subConnection.on('disconnect', () => {
    _receiving = false
    _master = null
    node.emit('not:receiving')
    if (_canPublish) node.emit('not:ready')
  })

  /**
   * master resolution component
   * @type {object}
   */
  let _masterResolver

  /**
   * master broker component
   * The external nodes dont have this component
   * @type {object}
   */
  let _masterBroker

  if (!external) {
    _masterBroker = MasterBroker(node)
    _masterResolver = MasterElector(node, _masterBroker)
    _masterResolver.on('newmaster', _connectToMaster)
  } else {
    _masterResolver = MasterFinder(node)
  }

  /**
   * Activates the node
   * @return {object} node instance
   */
  function activate () {
    if (_active) return node
    _active = true
    debug('activated')

    if (!external) {
      _masterBroker.bind()
      _masterResolver.bind()
    }
    if (!node.isReady) _seekForMaster()
    return node
  }
  /**
   * Starts the node's deactivation routine
   * @return {object} node instance
   */
  function deactivate () {
    if (!_active || _deactivating) return node
    debug('deactivating')

    if (external) {
      _active = false
      _subConnection.disconnect()
      _pubConnection.disconnect()
      node.emit('deactivated')
    } else {
      _deactivating = true
      let ensuredMaster = Promise.resolve()

      const isMaster = _subConnection.master && _subConnection.master.name === _name

      if (isMaster) {
        debug(`I'm the master node. I will try to elect another master before disconnecting.`)

        let advertiseId = `zz-zzzzzzzz-${_id}`
        ensuredMaster = _masterResolver
                        .resolve(advertiseId)
                        .then(master => {
                          debug(`successfully elected a new master: ${master.name}`)
                          try {
                            _masterBroker.signalNewMaster(master)
                          } catch (e) {
                            console.log(e)
                          }
                        })
                        .catch(() => {
                          debug(`failed to elect a new master. Disconnecting anyway.`)
                        })
      }

      ensuredMaster
      .then(() => {
        _subConnection.disconnect()
        _pubConnection.disconnect()
        _masterResolver.unbind()
        let timeout = isMaster ? 1000 : 1
        setTimeout(() => {
          debug('deactivated')
          node.emit('deactivated')
          _masterBroker.unbind()
        }, timeout)
      })
    }

    return node
  }
  /**
   * Sends a message through the bus, published on a particular channel
   * @param  {string} channel
   * @param  {array} args
   * @return {object} node instance
   */
  function publish (channel, ...args) {
    if (!isString(channel)) throw new TypeError(`${_debugStr}: .publish(channel, [...args]) channel MUST be a string`)
    if (~internalChannels.indexOf(channel)) {
      console.warn(`${_debugStr} channel '${channel}' is used internally and you cannot publish in it`)
      return node
    }
    if (!_pubConnection.connected) {
      console.warn(`${_debugStr} cannot publish on bus.`)
      return node
    }
    _pubConnection.publish(channel, ...args)
    return node
  }
  /**
   * Subscribes the node to the provided channels
   * @param  {string|array<string>} channels
   * @return {object} node instance
   */
  function subscribe (channels) {
    if (!isArray(channels)) channels = [channels]
    if (!every(channels, isString)) throw new TypeError(`${_debugStr}: .subscribe([...channels]) channels must be represented by strings`)

    channels.forEach(channel => {
      if (~internalChannels.indexOf(channel)) {
        console.warn(`${_debugStr} channel '${channel}' is used internally and you cannot subscribe to it.`)
        return
      }
      _subConnection.subscribe([channel])
    })
    return node
  }
  /**
   * Unsubscribes the node from the provided channels
   * @param  {string|array<string>} channels
   * @return {object} node instance
   */
  function unsubscribe (channels) {
    if (!isArray(channels)) channels = [channels]
    if (!every(channels, isString)) throw new TypeError(`${_debugStr}: .unsubscribe([channels]) channels must be represented by strings`)

    channels.forEach(channel => {
      if (~internalChannels.indexOf(channel)) {
        console.warn(`${_debugStr} channel '${channel}' is used internally and you cannot unsubscribe from it.`)
        return
      }
      _subConnection.unsubscribe([channel])
    })
    return node
  }

  return Object.defineProperties(node, {
    id: {get: () => _id},
    name: {get: () => _name},
    settings: {get: () => ({..._settings})},
    type: {get: () => external ? EXTERNAL_NODE : DNS_NODE},
    canPublish: {get: () => _pubConnection.connected},
    isReceiving: {get: () => _subConnection.connected},
    isReady: {get: () => _pubConnection.connected && _subConnection.connected},
    subscribedChannels: {get: () => _subConnection.subscribedChannels},
    isMaster: {get: () => _master && _master.name === _name || false},
    master: {get: () => _master && {..._master, endpoints: {..._master.endpoints}}},
    activate: {value: activate},
    deactivate: {value: deactivate},
    publish: {value: publish},
    subscribe: {value: subscribe},
    unsubscribe: {value: unsubscribe}
  })
}
536865
function setup(connection) {

                node.connection = connection;

                // node connected
                node.status({ fill: 'green', shape: 'dot', text: 'connected' });

                // build sender options based on node configuration
                var options = {
                    target: {
                        address: node.address,
                        dynamic: node.dynamic,
                        durable: node.durable,
                        expiry_policy: node.expirypolicy
                    },
                    autosettle: node.autosettle,
                    snd_settle_mode: node.sndsettlemode,
                    rcv_settle_mode: node.rcvsettlemode
                };
                node.sender = node.connection.open_sender(options);

                node.sender.on('accepted', function(context) {
                    var msg = outDelivery(node, context.delivery);
                    node.send(msg);
                });

                node.sender.on('released', function(context) {
                    var msg = outDelivery(node, context.delivery);
                    node.send(msg);
                });

                node.sender.on('rejected', function(context) {
                    var msg = outDelivery(node, context.delivery);
                    node.send(msg);
                });

                node.connection.on('disconnected', function(context) {
                    // node disconnected
                    node.status({fill: 'red', shape: 'dot', text: 'disconnected' });
                });

                node.on('input', function(msg) {
                    // enough credits to send
                    if (node.sender.sendable()) {
                        node.sender.send(msg.payload);
                    }
                });

                node.on('close', function() {
                    if (node.sender != null)
                        node.sender.detach();
                    node.connection.close();
                });
            }
466286
def handle_available(node, snapshots)
      reconcile(node)

      # no-op if we already know about this node
      return if @master == node || (@master && @slaves.include?(node))
      logger.info("Handling available node: #{node}")

      if @master
        # master already exists, make a slave
        node.make_slave!(@master)
        @slaves << node
      else
        # no master exists, make this the new master
        promote_new_master(snapshots, node)
      end

      @unavailable.delete(node)
    end
536762
function() {
      var t = this,
          map = {},
          router = Monitor.getRouter(),
          hostName = Monitor.getRouter().getHostName(),
          appName = Monitor.Config.Monitor.appName,
          appInstance = process.env.NODE_APP_INSTANCE;

      // Add this process to the map
      map[hostName] = {};
      map[hostName][appName] = {
        instances: [appInstance],
        probeClasses: _.keys(Probe.classes)
      };

      // Process all known connections
      var connections = router.findConnections();
      connections.forEach(function(connection) {
        hostName = connection.get('hostName') || connection.get('remoteHostName');
        appName = connection.get('remoteAppName') || '';
        appInstance = connection.get('remoteAppInstance') || '';

        // Don't add to the map not yet connected
        if (connection.connecting || !connection.connected) {
          return;
        }

        // Add the hostname to the map
        var host = map[hostName];
        if (!host) {
          host = map[hostName] = {};
        }

        // Add the app to the map
        var app = host[appName];
        if (!app) {
          app = host[appName] = {
            instances: [appInstance],
            probeClasses: connection.get('remoteProbeClasses')
          };
        } else {
          app.instances.push(appInstance);
        }
      });
      log.info('buildMap', map);

      // Set the map if it's changed.  This method is called whenever
      // connections come and go - including firewalled connections which
      // aren't visible in the map.  Only update if the map has changed.
      if (!_.isEqual(map, t.get('map'))) {
        log.info('mapChanged');
        t.set({
          map: map,
          updateSequence: t.updateSequence++
        });
      } else {
        log.info('mapNotChanged');
      }
    }
1081253
void connectTo(final Node<T> o) {
    if (!this.graph.equals(o.graph))
      throw new IllegalArgumentException("Cannot connect to nodes of two different graphs.");
    if (this.equals(o)) {
      return;
    }
    neighbours.add(o);
  }
1049954
function(master)
{
    var self = this;

    this.methods   = {};
    this.processes = {};
    this.master    = master;

    // Inject predefined methods
    var defaultIPCPath = __dirname + '/ipc/';
    fs.readdirSync(defaultIPCPath).forEach(function(file) {

        if (!file.match(/\.js$/)) {
            return;
        }

        var ObjectClass = require(defaultIPCPath + file);
        var obj         = new ObjectClass({master: master});
        var className   = file.replace(/\.js$/i, '');

        Object.getOwnPropertyNames(ObjectClass.prototype).forEach(function(method) {

            if ('constructor' === method) {
                return;
            }

            self.addMethod(className + '.' + method, obj[method], obj);
        });
    });
}
447672
function() {
      workers = [];
      netBinding = process.binding('net');
      if (server_socket) {
        netBinding.close(server_socket);
      }
      if (the_server) {
        the_server.watcher.stop();
        the_server = null;
      }
      server_socket = null;
      if (master_server) {
        master_server.close();
      }
      if (master_socket_path) {
        // try to remove the
        try {
          require('fs').unlinkSync(master_socket_path);
        } catch(excp) {
          // do nothing
        }
        master_socket_path = null;
      }
      master_server = null;
      process.removeListener('SIGINT', killer);
      process.removeListener('SIGHUP', killer);
      process.removeListener('SIGTERM', killer);
      process.removeListener('SIGUSR2', respawner); 
      
      try {
        process.stdout.end();
      } catch(exxcpe) {
        // do nothing
      }
    }
86936
@NotNull
		private Promise<Map<RawServerId, MasterRepository>> doEnsureMasterRepositories() {
			return ensureMasterNodes()
					.whenResult($ -> {
						difference(masterRepositories.keySet(), masterNodes.keySet())
								.forEach(masterRepositories::remove);
						difference(masterNodes.keySet(), masterRepositories.keySet())
								.forEach(serverId -> masterRepositories.put(serverId,
										new MasterRepository(serverId, repositoryId, masterNodes.get(serverId))));
					}