Manage panic clients in bulk, either locally or remotely.

@class Manager
@param {Mixed} remote - Either an http.Server to attach to,
a URL to connect to, or `undefined` if there is no remote.
169865
function Manager (remote) {

	/** Allow usage without `new`. */
	if (!(this instanceof Manager)) {
		return new Manager(remote);
	}

	/**
	 * @property {Boolean} isRemote
	 * Whether the manager is remote.
	 */
	this.isRemote = false;

	/**
	 * @property {Socket} socket
	 * A socket.io instance, or `null` if using locally.
	 */
	this.socket = null;

	/** If only using locally, stop here. */
	if (!remote) {
		return this;
	}

	/** If it's a URL, connect to it. */
	if (typeof remote === 'string') {
		this.isRemote = true;

		/** Automatically postfix the manager scope. */
		var url = remote + '/panic-manager';

		/** Connect to the remote manager. */
		this.socket = socket.client(url);

		return this;
	}

	/** Listen for /panic-manager connections. */
	var server = socket.server(remote).of('/panic-manager');

	/** Listen for connections. */
	server.on('connection', function (socket) {

		/** Listen for start commands. */
		socket.on('start', function (config) {
			spawn(config);
		});

	});

	this.socket = server;

}
362804
function(id, socket) {
  EventEmitter.call(this);
  this.id = id;
  this.socket = socket;

  if(!socket._socket) {
    this.remoteAddress = {
      ip: socket.address().address,
      port: socket.address().port
    };
  } else {
    this.remoteAddress = {
      ip: socket._socket.remoteAddress,
      port: socket._socket.remotePort
    };
  }

  var self = this;

  socket.once('close', this.emit.bind(this, 'disconnect'));
  socket.on('error', this.emit.bind(this, 'error'));

  socket.on('message', function(msg) {
    if(msg) {
      msg = Package.decode(msg);
      handler(self, msg);
    }
  });

  this.state = ST_INITED;

  // TODO: any other events?
}
368675
function (err) {
        if (err) {
            try{
                pub.util.sendSocketCallbackMsg(easyrtcid, socketCallback, pub.util.getErrorMsg("LOGIN_GEN_FAIL"), appObj);
                socket.disconnect();
                pub.util.logError("["+easyrtcid+"] General authentication error. Socket disconnected.", err);
            }catch(e) {}
        } else {
            callback(null, connectionObj);
        }
    }
888264
function (server, callback) {
            var self = this;

            this.$server = server;
            this._start(function(err) {
                self.$started = true;
                callback(err);
            });
        }
322387
public void init(CommsErrorListener CEL,
                   RoutingManager RM)
  {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.entry(tc, "init", new Object[] { CEL, RM});

    // Lock exclusively for start operations
    mpioLockManager.lockExclusive();
    _commsErrorListener = CEL;
    _routingManager = RM;
    
    synchronized(_mpConnectionsByMEConnection)
    {
      _mpConnectionsByMEUuid.clear();
      _mpConnectionsByMEConnection.clear();
    }
    
    // Create a new RemoteMessageReceiver if we don't already have one
    // or re-initialise the existing one to refresh any cached data
    // (used when an ME is re-started without the Server being re-started) 
    if(_remoteMessageReciever == null)
      _remoteMessageReciever = new RemoteMessageReceiver(_messageProcessor, this);
    else
      _remoteMessageReciever.init();
    
    started = true;    
    mpioLockManager.unlockExclusive();
          
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.exit(tc, "init");
  }
949886
function startServer(alerts, params, port, resources) {
    const compiledAlerts = compileMarkdown(alerts);
    const app = http.createServer((req, res) =>
        res.end(resources[req.url] || resources['/index.html']));
    const io = listen(app);
    io.on('connection', socket => {
        emitInfo(`new session for ${socket.handshake.address}`);
        socket.emit('update', compiledAlerts);
        socket.on('disconnect', () => {
            emitInfo(`disconnected session ${socket.handshake.address}`);
        });
    });

    return new Promise(resolve => app.listen(port, emitRungEmoji & resolve))
        .then(~watchChanges(io, params));
}
543478
function NetworkServer(server) {
  this.server = server;
  function connection(socket) {
    server.connection(socket, this);
  }
  this.on('connection', connection);
}
376187
def init_remotes(self, remotes, per_remote_overrides=(),
                     per_remote_only=PER_REMOTE_ONLY,
                     global_only=GLOBAL_ONLY):
        '''
        
        '''
        # The global versions of the auth params (gitfs_user,
        # gitfs_password, etc.) default to empty strings. If any of them
        # are defined and the provider is not one that supports auth, then
        # error out and do not proceed.
        override_params = copy.deepcopy(per_remote_overrides)
        global_auth_params = [
            '{0}_{1}'.format(self.role, x) for x in AUTH_PARAMS
            if self.opts['{0}_{1}'.format(self.role, x)]
        ]
        if self.provider in AUTH_PROVIDERS:
            override_params += AUTH_PARAMS
        elif global_auth_params:
            msg = (
                '{0} authentication was configured, but the \'{1}\' '
                '{0}_provider does not support authentication. The '
                'providers for which authentication is supported in {0} '
                'are: {2}.'.format(
                    self.role, self.provider, ', '.join(AUTH_PROVIDERS)
                )
            )
            if self.role == 'gitfs':
                msg += (
                    ' See the GitFS Walkthrough in the Salt documentation '
                    'for further information.'
                )
            log.critical(msg)
            failhard(self.role)

        per_remote_defaults = {}
        global_values = set(override_params)
        global_values.update(set(global_only))
        for param in global_values:
            key = '{0}_{1}'.format(self.role, param)
            if key not in self.opts:
                log.critical(
                    'Key \'%s\' not present in global configuration. This is '
                    'a bug, please report it.', key
                )
                failhard(self.role)
            per_remote_defaults[param] = enforce_types(key, self.opts[key])

        self.remotes = []
        for remote in remotes:
            repo_obj = self.git_providers[self.provider](
                self.opts,
                remote,
                per_remote_defaults,
                per_remote_only,
                override_params,
                self.cache_root,
                self.role
            )
            if hasattr(repo_obj, 'repo'):
                # Sanity check and assign the credential parameter
                repo_obj.verify_auth()
                repo_obj.setup_callbacks()
                if self.opts['__role'] == 'minion' and repo_obj.new:
                    # Perform initial fetch on masterless minion
                    repo_obj.fetch()

                # Reverse map to be used when running envs() to detect the
                # available envs.
                repo_obj.saltenv_revmap = {}

                for saltenv, saltenv_conf in six.iteritems(repo_obj.saltenv):
                    if 'ref' in saltenv_conf:
                        ref = saltenv_conf['ref']
                        repo_obj.saltenv_revmap.setdefault(
                            ref, []).append(saltenv)

                        if saltenv == 'base':
                            # Remove redundant 'ref' config for base saltenv
                            repo_obj.saltenv[saltenv].pop('ref')
                            if ref != repo_obj.base:
                                log.warning(
                                    'The \'base\' environment has been '
                                    'defined in the \'saltenv\' param for %s '
                                    'remote %s and will override the '
                                    'branch/tag specified by %s_base (or a '
                                    'per-remote \'base\' parameter).',
                                    self.role, repo_obj.id, self.role
                                )
                                # Rewrite 'base' config param
                                repo_obj.base = ref

                # Build list of all envs defined by ref mappings in the
                # per-remote 'saltenv' param. We won't add any matching envs
                # from the global saltenv map to the revmap.
                all_envs = []
                for env_names in six.itervalues(repo_obj.saltenv_revmap):
                    all_envs.extend(env_names)

                # Add the global saltenv map to the reverse map, skipping envs
                # explicitly mapped in the per-remote 'saltenv' param.
                for key, conf in six.iteritems(repo_obj.global_saltenv):
                    if key not in all_envs and 'ref' in conf:
                        repo_obj.saltenv_revmap.setdefault(
                            conf['ref'], []).append(key)

                self.remotes.append(repo_obj)

        # Don't allow collisions in cachedir naming
        cachedir_map = {}
        for repo in self.remotes:
            cachedir_map.setdefault(repo.cachedir, []).append(repo.id)

        collisions = [x for x in cachedir_map if len(cachedir_map[x]) > 1]
        if collisions:
            for dirname in collisions:
                log.critical(
                    'The following %s remotes have conflicting cachedirs: '
                    '%s. Resolve this using a per-remote parameter called '
                    '\'name\'.', self.role, ', '.join(cachedir_map[dirname])
                )
                failhard(self.role)

        if any(x.new for x in self.remotes):
            self.write_remote_map()
1040365
function singleServerOperation(client, cmd, args, keys) {
	return new Promise((resolve, reject) => {
		if (!keys.length) { return reject(new Error('Invalid arguments')); }

		let server;

		for (let i = 0; i < keys.length; i++) {
			const as = client.serverNameForKey(keys[i]);
			if (!server) server = as;
			if (server !== as) return reject(new Error(`Keys are mapped to different hash slots for command ${cmd}`));
		}

		return client.sendToServer(server, client, args, { resolve, reject });
	});
}
687122
function shutdown(callback) {
  var closed = 0;
  var connected = clients ? clients.length : 0;

  function maybeFinished() {
    if(++closed >= connected) {
      clients = null;
      log.info('[Shutdown] All client connections safely closed.');
      return callback();
    }

    log.info('[Shutdown] Closed client %s of %s.', closed, connected);
  }

  if(!connected) {
    return maybeFinished();
  }

  var client;

  for(var i = 0; i < connected; i++) {
    client = clients[i] || null;

    if(!client) {
      maybeFinished();
    } else {
      client.once('closed', maybeFinished);

      if(client.state !== States.CLOSING && client.state !== States.CLOSED) {
        client.close();
      }
    }
  }
}
357278
function Server(/* [options], [connectionListener] */) {
    events.EventEmitter.call(this);
    var self = this;

    var options;
    if (typeof arguments[0] === 'function') {
        options = {};
        this.on('connection', arguments[0]);
    } else {
        options = arguments[0] || {};
        if (typeof arguments[1] === 'function') {
            this.on('connection', arguments[1]);
        }
    }

    this._server = net.createServer(options, this._handler.bind(this));
    this._server.on('listening', function () {
        self.emit('listening');
    })
    this._server.on('close', function () {
        self.emit('close');
    })
    this._server.on('error', function (e) {
        self.emit('error', e);
    });
}
981064
function(err) {
  // this set to the appropriate client via apply call in performConnect
  var client = this;
  if (typeof client === 'undefined'/* || client.constructor !== Client*/) {
    logger.entry('processQueuedActions', 'client was not set');
    logger.exit('processQueuedActions', 'client not set returning', null);
    return;
  }
  logger.entry('processQueuedActions', client.id);
  logger.log('parms', client.id, 'err:', err);
  logger.log('data', client.id, 'client.state:', client.state);

  if (!err) {
    var performSend = function() {
      logger.entry('performSend', client.id);
      logger.log('data', client.id, 'client._queuedSends',
                 client._queuedSends);
      while (client._queuedSends.length > 0 &&
              client.state === STATE_STARTED) {
        var remaining = client._queuedSends.length;
        var msg = client._queuedSends.shift();
        client.send(msg.topic, msg.data, msg.options, msg.callback);
        if (client._queuedSends.length >= remaining) {
          // Calling client.send can cause messages to be added back into
          // _queuedSends, if the network connection is broken.  Check that the
          // size of the array is decreasing to avoid looping forever...
          break;
        }
      }

      logger.exit('performSend', client.id, null);
    };

    var performUnsub = function() {
      logger.entry('performUnsub', client.id);

      if (client._queuedUnsubscribes.length > 0 &&
          client.state === STATE_STARTED) {
        var rm = client._queuedUnsubscribes.shift();
        logger.log('data', client.id, 'rm:', rm);
        if (rm.noop) {
          // no-op, so just trigger the callback without actually unsubscribing
          if (rm.callback) {
            logger.entry('performUnsub.callback', client.id);
            rm.callback.apply(client, [null, rm.topicPattern, rm.share]);
            logger.exit('performUnsub.callback', client.id, null);
          }
          setImmediate(function() {
            performUnsub.apply(client);
          });
        } else {
          client.unsubscribe(rm.topicPattern, rm.share, rm.options,
              function(err, topicPattern, share) {
                if (rm.callback) {
                  logger.entry('performUnsub.callback', client.id);
                  rm.callback.apply(client, [err, topicPattern, share]);
                  logger.exit('performUnsub.callback', client.id, null);
                }
                setImmediate(function() {
                  performUnsub.apply(client);
                });
              }
          );
        }
      } else {
        performSend.apply(client);
      }

      logger.exit('performUnsub', client.id, null);
    };

    var performSub = function() {
      logger.entry('performSub', client.id);

      if (client._queuedSubscriptions.length > 0 &&
          client.state === STATE_STARTED) {
        var sub = client._queuedSubscriptions.shift();
        logger.log('data', client.id, 'sub:', sub);
        if (sub.noop) {
          // no-op, so just trigger the callback without actually subscribing
          if (sub.callback) {
            process.nextTick(function() {
              logger.entry('performSub.callback', client.id);
              logger.log('parms', client.id, 'err:', err, ', topicPattern:',
                         sub.topicPattern, ', originalShareValue:', sub.share);
              sub.callback.apply(client,
                  [err, sub.topicPattern, sub.originalShareValue]);
              logger.exit('performSub.callback', client.id, null);
            });
          }
          setImmediate(function() {
            performSub.apply(client);
          });
        } else {
          client.subscribe(sub.topicPattern, sub.share, sub.options,
              function(err, topicPattern, share) {
                if (sub.callback) {
                  process.nextTick(function() {
                    logger.entry('performSub.callback',
                                 client.id);
                    logger.log('parms', client.id, 'err:', err,
                               ', topicPattern:', topicPattern,
                               ', share:', share);
                    sub.callback.apply(client,
                        [err, topicPattern, share]);
                    logger.exit('performSub.callback',
                                client.id, null);
                  });
                }
                setImmediate(function() {
                  performSub.apply(client);
                });
              }
          );
        }
      } else {
        performUnsub.apply(client);
      }

      logger.exit('performSub', client.id, null);
    };

    performSub();
  }
  logger.exit('processQueuedActions', client.id, null);
}
645001
def disconnect_handler(remote, *args, **kwargs):
    
    if not current_user.is_authenticated:
        return current_app.login_manager.unauthorized()

    remote_account = RemoteAccount.get(user_id=current_user.get_id(),
                                       client_id=remote.consumer_key)
    external_ids = [i.id for i in current_user.external_identifiers
                    if i.method == GLOBUS_EXTERNAL_METHOD]

    if external_ids:
        oauth_unlink_external_id(dict(id=external_ids[0],
                                      method=GLOBUS_EXTERNAL_METHOD))

    if remote_account:
        with db.session.begin_nested():
            remote_account.delete()

    return redirect(url_for('invenio_oauthclient_settings.index'))
241274
function start(callback) {
        var serverDeferred = Q.defer();

        if (typeof callback !== 'function') {
            callback = function () {
            };
        }

        if (self.isRunning) {
            // FIXME: should this be an error?
            callback();
            return;
        }

        sockets = {};

        __httpServer = Http.createServer(__app);

        if (gmeConfig.server.timeout > -1) {
            __httpServer.timeout = gmeConfig.server.timeout;
        }

        function handleNewConnection(socket) {
            var socketId = socket.remoteAddress + ':' + socket.remotePort;

            if (socket.encrypted) { // https://nodejs.org/api/tls.html#tls_tlssocket_encrypted
                socketId += ':encrypted';
            }

            sockets[socketId] = socket;
            logger.debug('socket connected (added to list) ' + socketId);

            socket.on('close', function () {
                if (sockets.hasOwnProperty(socketId)) {
                    logger.debug('socket closed (removed from list) ' + socketId);
                    delete sockets[socketId];
                }
            });
        }

        __httpServer.on('connection', handleNewConnection);
        __httpServer.on('secureConnection', handleNewConnection);

        __httpServer.on('clientError', function (err/*, socket*/) {
            logger.debug('clientError', err);
        });

        __httpServer.on('error', function (err) {
            if (err.code === 'EADDRINUSE') {
                logger.error('Failed to start server', {metadata: {port: gmeConfig.server.port, error: err}});
                serverDeferred.reject(err);
            } else {
                logger.error('Server raised an error', {metadata: {port: gmeConfig.server.port, error: err}});
            }
        });

        logger.debug('starting server');

        __gmeAuth.connect()
            .then(function (db) {
                var promises = [];

                logger.debug('gmeAuth connected');

                promises.push(Q.ninvoke(__workerManager, 'start'));
                promises.push(__storage.openDatabase());

                if (__executorServer) {
                    promises.push(__executorServer.start({mongoClient: db}));
                }

                return Q.all(promises);
            })
            .then(function () {
                var promises = [];
                __webSocket.start(__httpServer);

                promises.push(apiReady);

                routeComponents.forEach(function (component) {
                    promises.push(Q.ninvoke(component, 'start'));
                });

                return Q.all(promises);
            })
            .then(function () {
                // Finally start listening to the server port.
                __httpServer.listen(gmeConfig.server.handle || gmeConfig.server.port, function () {
                    logger.info('Server is listening ...');
                    serverDeferred.resolve();
                });

                return serverDeferred.promise;
            })
            .then(function () {
                return webgmeUtils.createStartUpProjects(gmeConfig, __gmeAuth, __storage, logger, getUrl());
            })
            .nodeify(function (err) {
                self.isRunning = true;
                if (err) {
                    logger.error('Error at server start', err);
                }

                callback(err);
            });
    }
565210
function() {
        try {
          var server = {
            "host": params.host,
            "port": params.port,
            "timeout": params.timeout || 20000,
            "connectHeaders": {
              "host": "/",
              "login": params.username,
              "passcode": params.password,
              "heart-beat": "5000, 5000"
            }
          };

          var servers = [server];

          var reconnectOptions = {
            'maxReconnects': 20
          };

          var manager = new Stompit.ConnectFailover(servers, reconnectOptions);

          manager.connect(function(error, stompClient, reconnect) {
            if (error) {
              fireEvent("error", {
                errorCode: error.code,
                errorMessage: error.message,
                errorEvent: error
              });

              return;
            }

            client = stompClient;

            client.on('error', function(error) {
              fireEvent("error", {
                errorCode: 999,
                errorMessage: "ActiveMQ client has had an error",
                errorEvent: error
              });
              reconnect();
            });

            fireEvent("init");
          });

        } catch (error) {
          console.error(error);
        }
      }
862647
function transmit(callback) {
  // Will call next(data, next)
  // Expect OUR next to be called with (err) so we know if it worked
  var iRes;
  var iReq;
  var msg = null;
  var outpacket = {
    responses: [],
    requests : []
  };

  if (typeof callback !== 'function') {
    callback = this.transmitter;
  }
  if (!this.active || typeof callback !== 'function') {
    return this;
  }

  iRes = this.outbox.responses.length;
  iReq = this.outbox.requests.length;
  if (
    iRes > 0
    && iReq > 0
    && 'system.extension.dual-batch' in this.remoteComponents
  ) {
    // Use dual-batch extension to send it all at once
    outpacket = msg = {
      responses: this.outbox.responses,
      requests : this.outbox.requests
    };
    // Setting length=0 would preserve references and we want to renew them
    this.outbox.responses = [];
    this.outbox.requests = [];
  } else if (iRes > 0) {
    // Responses have priority over requests
    if (iRes > 1) {
      outpacket.responses = msg = this.outbox.responses;
      this.outbox.responses = [];
    } else {
      outpacket.responses.push(msg = this.outbox.responses.pop());
    }
  } else if (iReq > 0) {
    if (iReq > 1) {
      outpacket.requests = msg = this.outbox.requests;
      this.outbox.requests = [];
    } else {
      outpacket.requests.push(msg = this.outbox.requests.pop());
    }
  } else {
    return this;
  }

  // Send msg using callback
  setImmediate(
    callback,
    JSON.stringify(msg),
    confirmTransmit.bind(this, outpacket)
  );

  return this;
}
50870
function makeRemote(id) {
        var remotePromise = Q.makePromise({
            when: function () {
                return this;
            }
        }, function (op, args) {
            var localId = makeId();
            var response = makeLocal(localId);
            _debug("sending:", "R" + JSON.stringify(id), JSON.stringify(op), JSON.stringify(encode(args)));
            connection.put(JSON.stringify({
                "type": "send",
                "to": id,
                "from": localId,
                "op": op,
                "args": encode(args)
            }));
            return response;
        });
        remotes.set(r,id);
        return remotePromise;
    }