Scale service container.

        Args:
            replicas (int): The number of containers that should be running.

        Returns:
            bool: ``True`` if successful.
16612
def scale(self, replicas):
        

        if 'Global' in self.attrs['Spec']['Mode'].keys():
            raise InvalidArgument('Cannot scale a global container')

        service_mode = ServiceMode('replicated', replicas)
        return self.client.api.update_service(self.id, self.version,
                                              mode=service_mode,
                                              fetch_current_spec=True)
1241842
public void setReplicaSettings(java.util.Collection<ReplicaSettingsDescription> replicaSettings) {
        if (replicaSettings == null) {
            this.replicaSettings = null;
            return;
        }

        this.replicaSettings = new java.util.ArrayList<ReplicaSettingsDescription>(replicaSettings);
    }
363821
def index_create(self, index, number_of_shards=5,number_of_replicas=1):
        '''
        
        '''
        request = self.session
        content = {'settings' : dict(number_of_shards=number_of_shards, number_of_replicas=number_of_replicas)}
        if self.verbose:
            print content
        url = 'http://%s:%s/%s' % (self.host, self.port, index)
        response = request.put(url,content)
        return response
315671
def _offload_service_containers(self, service):
        
        if not isinstance(service, Service):
            raise TypeError("service must be an instance of Service")

        if service.containers:
            for key in list(service.containers.keys()):
                if key in service.containers:
                    del service.containers[key]
54785
def scale_up(self, n, pods=None, **kwargs):
        
        maximum = dask.config.get('kubernetes.count.max')
        if maximum is not None and maximum < n:
            logger.info("Tried to scale beyond maximum number of workers %d > %d",
                        n, maximum)
            n = maximum
        pods = pods or self._cleanup_terminated_pods(self.pods())
        to_create = n - len(pods)
        new_pods = []
        for i in range(3):
            try:
                for _ in range(to_create):
                    new_pods.append(self.core_api.create_namespaced_pod(
                        self.namespace, self.pod_template))
                    to_create -= 1
                break
            except kubernetes.client.rest.ApiException as e:
                if e.status == 500 and 'ServerTimeout' in e.body:
                    logger.info("Server timeout, retry #%d", i + 1)
                    time.sleep(1)
                    last_exception = e
                    continue
                else:
                    raise
        else:
            raise last_exception

        return new_pods
991242
private long[] updatePartitionReplicaVersions(PartitionReplicaManager replicaManager, int partitionId,
                                                  ServiceNamespace namespace, int replicaIndex) {
        long[] versions = replicaManager.getPartitionReplicaVersions(partitionId, namespace);
        // No need to set versions back right now. actual version array is modified directly.
        Arrays.fill(versions, 0, replicaIndex, 0);

        return versions;
    }
701739
def _construct_replset(self, basedir, portstart, name, num_nodes,
                           arbiter, extra=''):
        
        self.config_docs[name] = {'_id': name, 'members': []}

        # Construct individual replica set nodes
        for i in num_nodes:
            datapath = self._create_paths(basedir, '%s/rs%i' % (name, i + 1))
            self._construct_mongod(os.path.join(datapath, 'db'),
                                   os.path.join(datapath, 'mongod.log'),
                                   portstart + i, replset=name, extra=extra)

            host = '%s:%i' % (self.args['hostname'], portstart + i)
            member_config = {
                '_id': len(self.config_docs[name]['members']),
                'host': host,
            }

            # First node gets increased priority.
            if i == 0 and self.args['priority']:
                member_config['priority'] = 10

            if i >= 7:
                member_config['votes'] = 0
                member_config['priority'] = 0

            self.config_docs[name]['members'].append(member_config)

        # launch arbiter if True
        if arbiter:
            datapath = self._create_paths(basedir, '%s/arb' % (name))
            self._construct_mongod(os.path.join(datapath, 'db'),
                                   os.path.join(datapath, 'mongod.log'),
                                   portstart + self.args['nodes'],
                                   replset=name)

            host = '%s:%i' % (self.args['hostname'],
                              portstart + self.args['nodes'])
            (self.config_docs[name]['members']
             .append({'_id': len(self.config_docs[name]['members']),
                      'host': host,
                      'arbiterOnly': True}))

        return(name + '/' +
               ','.join([c['host']
                         for c in self.config_docs[name]['members']]))
677945
def validate_capacity(capacity):
    """"""

    if capacity not in VALID_SCALING_CONFIGURATION_CAPACITIES:
        raise ValueError(
            "ScalingConfiguration capacity must be one of: {}".format(
                ", ".join(map(
                    str,
                    VALID_SCALING_CONFIGURATION_CAPACITIES
                ))
            )
        )
    return capacity
709438
def stop(self, instances, count=0):
        
        if not instances:
            return
        if count > 0:
            instances = self._scale_down(instances, count)
        self.ec2.stop_instances([i.id for i in instances])
774917
def is_replicaset_initialized(self):
        

        # it's possible isMaster returns an "incomplete" result if we
        # query a replica set member while it's loading the replica set config
        # https://jira.mongodb.org/browse/SERVER-13458
        # let's try to detect this state before proceeding
        # seems like if the "secondary" field is present, but "setName" isn't,
        # it's a good indicator that we just need to wait a bit
        # add an uptime check in for good measure

        for member in self.get_members():
            server = member.get_server()

            if server.has_joined_replica():
                return True

        return False
793071
protected void updatePeerEurekaNodes(List<String> newPeerUrls) {
        if (newPeerUrls.isEmpty()) {
            logger.warn("The replica size seems to be empty. Check the route 53 DNS Registry");
            return;
        }

        Set<String> toShutdown = new HashSet<>(peerEurekaNodeUrls);
        toShutdown.removeAll(newPeerUrls);
        Set<String> toAdd = new HashSet<>(newPeerUrls);
        toAdd.removeAll(peerEurekaNodeUrls);

        if (toShutdown.isEmpty() && toAdd.isEmpty()) { // No change
            return;
        }

        // Remove peers no long available
        List<PeerEurekaNode> newNodeList = new ArrayList<>(peerEurekaNodes);

        if (!toShutdown.isEmpty()) {
            logger.info("Removing no longer available peer nodes {}", toShutdown);
            int i = 0;
            while (i < newNodeList.size()) {
                PeerEurekaNode eurekaNode = newNodeList.get(i);
                if (toShutdown.contains(eurekaNode.getServiceUrl())) {
                    newNodeList.remove(i);
                    eurekaNode.shutDown();
                } else {
                    i++;
                }
            }
        }

        // Add new peers
        if (!toAdd.isEmpty()) {
            logger.info("Adding new peer nodes {}", toAdd);
            for (String peerUrl : toAdd) {
                newNodeList.add(createPeerEurekaNode(peerUrl));
            }
        }

        this.peerEurekaNodes = newNodeList;
        this.peerEurekaNodeUrls = new HashSet<>(newPeerUrls);
    }
1071983
def restore_replicas(self) -> None:
        '''
        
        '''
        self.backup_instances_faulty.clear()
        for inst_id in range(self.node.requiredNumberOfInstances):
            if inst_id not in self.node.replicas.keys():
                self.node.replicas.add_replica(inst_id)
733172
def server_list_min(self):
        '''
        
        '''
        nt_ks = self.compute_conn
        ret = {}
        for item in nt_ks.servers.list(detailed=False):
            try:
                ret[item.name] = {
                    'id': item.id,
                    'state': 'Running'
                }
            except TypeError:
                pass
        return ret
917631
def replicated_partitions
      result, mutex = [], Mutex.new
      threads = cluster.partitions.map do |partition|
        Thread.new do
          Thread.abort_on_exception = true
          select = partition.replicas.include?(self)
          mutex.synchronize { result << partition } if select
        end
      end
      threads.each(&:join)
      result
    end
1279215
def forward(self, request: Request):
        
        key = request.key
        num_replicas = self.replicas.num_replicas
        logger.debug('{} forwarding request {} to {} replicas'
                     .format(self, key, num_replicas))
        self.replicas.pass_message(ReqKey(key))
        self.monitor.requestUnOrdered(key)
        self.requests.mark_as_forwarded(request, num_replicas)
698158
def display_scale_help
      return if service.running_count >= service.desired_count

      events = service["events"][0..3] # only check most recent 4 messages
      error_event = events.find do |e|
        e.message =~ /was unable to place a task/
      end
      return unless error_event

      puts "There is an issue scaling the #{@service.color(:green)} service to #{service.desired_count}.  Here's the error:"
      puts error_event.message.color(:red)
      if service.launch_type == "EC2"
        puts "If AutoScaling is set up for the container instances, it can take a little time to add additional instances. You'll see this message until the capacity is added."
      end
    end
1360989
final void rebalance() {
        // Let's start distribute the vbuckets across the servers
        configurationRwLock.writeLock().lock();
        try {
            Info.incrementConfigRevision();
            List<MemcachedServer> nodes = activeServers();
            for (int ii = 0; ii < numVBuckets; ++ii) {
                Collections.shuffle(nodes);
                vbInfo[ii].setOwner(nodes.get(0));
                if (nodes.size() < 2) {
                    continue;
                }
                List<MemcachedServer> replicas = nodes.subList(1, nodes.size());
                if (replicas.size() > numReplicas) {
                    replicas = replicas.subList(0, numReplicas);
                }
                vbInfo[ii].setReplicas(replicas);
            }
        } finally {
            Info.incrementConfigRevision();
            configurationRwLock.writeLock().unlock();
        }
    }