init_redis_shards is used internally to connect to the Redis sentinels
        and populate self.shards with the redis.StrictRedis instances. This
        is a convenient method to override / stub out in unit tests.
977151
def _init_redis_shards(self):
        
        self._shards = {}
        if self._sentinels is not None:
            self.init_shards_from_sentinel()
        elif self._masters is not None:
            self.init_shards_from_masters()
        else:
            raise Exception("You must either specify sentinels or masters")
148078
def reset(self):
        """"""
        # Ensure all shards by calling "reset" on each.
        for shard_id in self._shards:
            if self._shards[shard_id].get('isReplicaSet'):
                singleton = ReplicaSets()
            elif self._shards[shard_id].get('isServer'):
                singleton = Servers()
            singleton.command(self._shards[shard_id]['_id'], 'reset')
        # Ensure all config servers by calling "reset" on each.
        for config_id in self._configsvrs:
            self.configdb_singleton.command(config_id, 'reset')
        # Ensure all routers by calling "reset" on each.
        for router_id in self._routers:
            Servers().command(router_id, 'reset')
        return self.info()
748146
function init() {  // {{{2
/**
 * Class constructor
 *
 * @method constructor
 * @internal
 */

  O.inherited(this)();

  this.setMaxListeners(Consts.coreListeners);

  this.subjectState = this.SUBJECT_STATE.INIT;

  this.peers = {};
  this.shards = {};
}
1058879
private void initStandaAloneServices() {
        Set<String> serviceSet = new LinkedHashSet<>();
        addDefaultServices(serviceSet);
        addRequiredServices(serviceSet);
        addConfiguredStorageServices(serviceSet);
        initServices(serviceSet);
    }
378213
function init(shard, socket) {  // {{{2
/**
 * Sends request to the master shard to establish a link.
 *
 * @param shard {Object} Slave shard
 * @param ws {Object} WebSocket
 *
 * @method constructor
 */

  if (shard.slaves) {
    if (socket._lid in shard.slaves) {
      return L.error(socket, O.log.todo('Duplicit lid', shard, socket._lid));
    }
  } else {
    shard.slaves = {};
  }

  this.shard = shard;
  shard.slaves[socket._lid] = this;

  return L.open(this, socket, {
    home: shard.isAtHome() || shard.masterState === shard.MASTER_STATE.HOME,
    homeTime: Date.now() + shard.homeTimeOffset,
  });
}
821369
@Override
  protected ShardsIterator shards(ClusterState clusterState, GetIndicesVersionRequest request, String[] concreteIndices) {
    return clusterState.routingTable().allShards(concreteIndices);
  }
218865
public void init(HttpOutboundServiceContext sc, BNFHeaders hdrs) {
        setOwner(sc);
        setBinaryParseState(HttpInternalConstants.PARSING_BINARY_VERSION);
        if (null != hdrs) {
            hdrs.duplicate(this);
        }
    }
188985
def init(key, value)
      with_failure_grace(value) {
        @redis.set(key, value) if get(key, nil).nil?
      }
    end
1093805
def init(*args, **kwargs):
    
    global _initial_client
    client = Client(*args, **kwargs)
    Hub.current.bind_client(client)
    rv = _InitGuard(client)
    if client is not None:
        _initial_client = weakref.ref(client)
    return rv
481021
public void setShards(java.util.Collection<Shard> shards) {
        if (shards == null) {
            this.shards = null;
            return;
        }

        this.shards = new java.util.ArrayList<Shard>(shards);
    }
179253
function init(shard, eid) {  // {{{2
/**
 * Entry constructor
 *
 * @param shard {Object} Entry owner shard instance
 * @param eid {Number|String} Entry id
 *
 * @method constructor
 */

  O.inherited(this)();

  this.setMaxListeners(Consts.coreListeners);

  this.subjectState = this.SUBJECT_STATE.INIT;

  this.shard = shard;  // {{{3
  /**
   * Reference to containing [shard]
   *
   * @property shard
   * @type Object
   */

  this.id = eid;  // {{{3
  /**
   * Unique id of entry within containing [shard]
   *
   * @property id
   * @type Integer
   */

  // }}}3

  if (eid in shard.cache) {
    throw O.log.error(this, 'Duplicit eid', eid);
  }

  shard.cache[eid] = this;
}
590324
public void setShards(java.util.Collection<Shard> shards) {
        if (shards == null) {
            this.shards = null;
            return;
        }

        this.shards = new com.amazonaws.internal.SdkInternalList<Shard>(shards);
    }
962732
function startAllConnections() {
  try {
    myUtils.validateConfig();
  }
  catch(e) {
    console.error(e.message);
    process.exit(2);
  }

  // redefine keys method before connections are started
  if (config.get('redis.useScan')) {
    console.log('Using scan instead of keys');
    Object.defineProperty(Redis.prototype, 'keys', {
      value: function(pattern, cb) {
        let keys = [];
        let that = this;
        let scanCB = function(err, res) {
          if (err) {
            if (typeof cb === 'function') cb(err);
            else {
              console.log('ERROR in redefined "keys" function to use "scan" instead without callback: ' + JSON.stringify(err));
            }
          }
          else {
            let count = res[0], curKeys = res[1];
            console.log("scanning: " + count + ": " + curKeys.length);
            keys = keys.concat(curKeys);
            if (Number(count) === 0) {
              if (typeof cb === 'function') cb(null, keys);
              else {
                console.log('ERROR in redefined "keys" function to use "scan" instead - no callback given!');
              }
            }
            else {
              that.scan(count, 'MATCH', pattern, 'COUNT', config.get('redis.scanCount'), scanCB);
            }
          }
        };
        return this.scan(0, 'MATCH', pattern, 'COUNT', config.get('redis.scanCount'), scanCB);
      }
    });
  }

  // first default connections from config object
  // second connection from cli params (redis-host, redis-port, ...)
  startDefaultConnections(config.connections, function (err) {
    if (err) {
      console.log(err);
      process.exit();
    }
    let db = parseInt(args['redis-db']);
    if (isNaN(db)) {
        db = 0;
    }

    let client;
    if (args['sentinel-host'] || args['sentinels'] || args['redis-host'] || args['redis-port'] || args['redis-socket'] || args['redis-password']) {
      let newDefault = {
        "label": config.get('redis.defaultLabel'),
        "dbIndex": db,
        "password": args['redis-password'] || '',
        "connectionName": config.get('redis.connectionName')
      };

      if (args['redis-socket']) {
        newDefault.path = args['redis-socket'];
      }
      else {
        newDefault.host = args['redis-host'] || "localhost";
        newDefault.port = args['redis-port'] || "6379";
        newDefault.sentinel_name = args['sentinel-name'];
        if (args['sentinels']) {
          newDefault.sentinels = myUtils.parseRedisSentinel('--sentinels', args['sentinels']);
        }
        else if (args['sentinel-host']) {
          newDefault.sentinels = myUtils.parseRedisSentinel( '--sentinel-host or --sentinel-port',
            args['sentinel-host'] + ':' + args['sentinel-port']);
        }
      }

      if (args['redis-tls']) {
        newDefault.tls = {};
      }

      if (!myUtils.containsConnection(config.connections, newDefault)) {
        client = myUtils.createRedisClient(newDefault);
        redisConnections.push(client);
        config.connections.push(newDefault);
        if (!config.get('noSave')) {
          myUtils.saveConnections(config,function (err) {
            if (err) {
              console.log("Problem saving connection config.");
              console.error(err);
            }
          });
        }
        setUpConnection(client, db);
      }
    } else if (config.connections.length === 0) {
      // fallback to localhost if nothing else configured
      client = myUtils.createRedisClient({label: config.get('redis.defaultLabel')});
      redisConnections.push(client);
      setUpConnection(client, db);
    }

    return startWebApp();
  });

  // wait a bit before starting browser to let http server start
  if (args['open']) {
    setTimeout(function() {
      let address = '127.0.0.1';
      if (config.get('server.address') !== '0.0.0.0' && config.get('server.address') !== '::') {
        address = config.get('server.address');
      }
      require('opener')('http://' + address + ':' + config.get('server.port'));
    }, 1000);
  }
}
399329
private static void initialize(Storage storage, String counterId) {
    LOG.debug("Initializing counter shards for resource {}", counterId);
    for (int startIndex = 0; startIndex < NUM_SHARDS; startIndex += TRANSACTION_GROUP_SIZE) {
      initShardRange(storage, counterId, startIndex,
                     Math.min(NUM_SHARDS, startIndex + TRANSACTION_GROUP_SIZE));
    }
  }
505339
def shards(self, add_shard=False):
        
        url = self._service_url + 'shards/'
        if add_shard:
            response = requests.post(url, **self._instances._default_request_kwargs)
        else:
            response = requests.get(url, **self._instances._default_request_kwargs)

        return response.json()
630777
public BaseRedisPubSubHub<ID, DATA> init() {
        if (jedisConnector == null) {
            jedisConnector = buildJedisConnector();
            myOwnRedis = jedisConnector != null;
        }

        super.init();

        if (jedisConnector == null) {
            throw new IllegalStateException("Jedis connector is null.");
        }

        return this;
    }
846419
def reindex(self, request):
    
    r = redis.StrictRedis.from_url(request.registry.settings["celery.scheduler_url"])
    try:
        with SearchLock(r, timeout=30 * 60, blocking_timeout=30):
            p = urllib.parse.urlparse(request.registry.settings["elasticsearch.url"])
            client = elasticsearch.Elasticsearch(
                [urllib.parse.urlunparse(p[:2] + ("",) * 4)],
                verify_certs=True,
                ca_certs=certifi.where(),
                timeout=30,
                retry_on_timeout=True,
                serializer=serializer.serializer,
            )
            number_of_replicas = request.registry.get("elasticsearch.replicas", 0)
            refresh_interval = request.registry.get("elasticsearch.interval", "1s")

            # We use a randomly named index so that we can do a zero downtime reindex.
            # Essentially we'll use a randomly named index which we will use until all
            # of the data has been reindexed, at which point we'll point an alias at
            # our randomly named index, and then delete the old randomly named index.

            # Create the new index and associate all of our doc types with it.
            index_base = request.registry["elasticsearch.index"]
            random_token = binascii.hexlify(os.urandom(5)).decode("ascii")
            new_index_name = "{}-{}".format(index_base, random_token)
            doc_types = request.registry.get("search.doc_types", set())
            shards = request.registry.get("elasticsearch.shards", 1)

            # Create the new index with zero replicas and index refreshes disabled
            # while we are bulk indexing.
            new_index = get_index(
                new_index_name,
                doc_types,
                using=client,
                shards=shards,
                replicas=0,
                interval="-1",
            )
            new_index.create(wait_for_active_shards=shards)

            # From this point on, if any error occurs, we want to be able to delete our
            # in progress index.
            try:
                request.db.execute("SET statement_timeout = '600s'")

                for _ in parallel_bulk(
                    client, _project_docs(request.db), index=new_index_name
                ):
                    pass
            except:  # noqa
                new_index.delete()
                raise
            finally:
                request.db.rollback()
                request.db.close()

            # Now that we've finished indexing all of our data we can update the
            # replicas and refresh intervals.
            client.indices.put_settings(
                index=new_index_name,
                body={
                    "index": {
                        "number_of_replicas": number_of_replicas,
                        "refresh_interval": refresh_interval,
                    }
                },
            )

            # Point the alias at our new randomly named index and delete the old index.
            if client.indices.exists_alias(name=index_base):
                to_delete = set()
                actions = []
                for name in client.indices.get_alias(name=index_base):
                    to_delete.add(name)
                    actions.append({"remove": {"index": name, "alias": index_base}})
                actions.append({"add": {"index": new_index_name, "alias": index_base}})
                client.indices.update_aliases({"actions": actions})
                client.indices.delete(",".join(to_delete))
            else:
                client.indices.put_alias(name=index_base, index=new_index_name)
    except redis.exceptions.LockError as exc:
        raise self.retry(countdown=60, exc=exc)