Move partition to under-loaded replication-group if possible.
133
def move_partition_replica(self, under_loaded_rg, eligible_partition):
        """"""
        # Evaluate possible source and destination-broker
        source_broker, dest_broker = self._get_eligible_broker_pair(
            under_loaded_rg,
            eligible_partition,
        )
        if source_broker and dest_broker:
            self.log.debug(
                'Moving partition {p_name} from broker {source_broker} to '
                'replication-group:broker {rg_dest}:{dest_broker}'.format(
                    p_name=eligible_partition.name,
                    source_broker=source_broker.id,
                    dest_broker=dest_broker.id,
                    rg_dest=under_loaded_rg.id,
                ),
            )
            # Move partition if eligible brokers found
            source_broker.move_partition(eligible_partition, dest_broker)
1285346
function move(src, dest) {
	return rename(src, dest).catch((err) => {
		// try copying
		return copy(src, dest).then(() => {
			// delete source
			return unlink(src);
		});
	});
}
628424
def in_use(self):
        """"""
        if self.is_mounted or self.is_unlocked:
            return True
        if self.is_partition_table:
            for device in self._daemon:
                if device.partition_slave == self and device.in_use:
                    return True
        return False
206021
public void doRestart(List<Long> masters, Map<Integer, Long> partitionMasters)
    {
        List<Long> copy = new ArrayList<Long>(masters);
        m_restartMasters.set(copy);

        m_restartMastersMap.set(Maps.newHashMap(partitionMasters));
    }
571684
def _decommission_brokers_in_group(self, group):
        """"""
        try:
            group.rebalance_brokers()
        except EmptyReplicationGroupError:
            self.log.warning("No active brokers left in replication group %s", group)
        for broker in group.brokers:
            if broker.decommissioned and not broker.empty():
                # In this case we need to reassign the remaining partitions
                # to other replication groups
                self.log.info(
                    "Broker %s can't be decommissioned within the same "
                    "replication group %s. Moving partitions to other "
                    "replication groups.",
                    broker,
                    broker.replication_group,
                )
                self._force_broker_decommission(broker)
                # Broker should be empty now
                if not broker.empty():
                    # Decommission may be impossible if there are not enough
                    # brokers to redistributed the replicas.
                    self.log.error(
                        "Could not decommission broker %s. "
                        "Partitions %s cannot be reassigned.",
                        broker,
                        broker.partitions,
                    )
                    raise BrokerDecommissionError("Broker decommission failed.")
514892
private void commitSource() {
        int partitionId = getPartitionId();
        InternalPartitionServiceImpl partitionService = getService();
        PartitionReplicaManager replicaManager = partitionService.getReplicaManager();

        ILogger logger = getLogger();

        int sourceNewReplicaIndex = migrationInfo.getSourceNewReplicaIndex();
        if (sourceNewReplicaIndex < 0) {
            clearPartitionReplicaVersions(partitionId);
            if (logger.isFinestEnabled()) {
                logger.finest("Replica versions are cleared in source after migration. partitionId=" + partitionId);
            }
        } else if (migrationInfo.getSourceCurrentReplicaIndex() != sourceNewReplicaIndex && sourceNewReplicaIndex > 1) {
            for (ServiceNamespace namespace : replicaManager.getNamespaces(partitionId)) {
                long[] versions = updatePartitionReplicaVersions(replicaManager, partitionId,
                                                                 namespace, sourceNewReplicaIndex - 1);
                if (logger.isFinestEnabled()) {
                    logger.finest("Replica versions are set after SHIFT DOWN migration. partitionId="
                            + partitionId + " namespace: " + namespace + " replica versions=" + Arrays.toString(versions));
                }
            }
        }
    }
743506
def add_partition(self, partition):
        """"""
        assert(partition not in self._partitions)
        # Add partition to existing set
        self._partitions.add(partition)
        # Add broker to replica list
        partition.add_replica(self)
948581
def _prepare_output(partitions, unavailable_brokers, verbose):
    """"""
    partitions_count = len(partitions)
    out = {}
    out['raw'] = {
        'replica_unavailability_count': partitions_count,
    }

    if partitions_count == 0:
        out['message'] = 'All replicas available for communication.'
    else:
        out['message'] = "{replica_unavailability} replicas unavailable for communication. " \
            "Unavailable Brokers: {unavailable_brokers}".format(
            replica_unavailability=partitions_count,
            unavailable_brokers=', '.join([str(e) for e in unavailable_brokers]),
        )
        if verbose:
            lines = (
                '{}:{}'.format(topic, partition)
                for (topic, partition) in partitions
            )
            out['verbose'] = "Partitions:\n" + "\n".join(lines)

    if verbose:
        out['raw']['partitions'] = [
            {'topic': topic, 'partition': partition}
            for (topic, partition) in partitions
        ]

    return out
847759
def set_partition(self, partition):
        
        assert len(partition) == self.numgrp
        self.partition, self.prev_partition = partition, self.partition
84260
def collected(self, group, filename=None, host=None, location=None, move=True, all=True):
        '''
        
        '''
        ret = {
            'name': 'support.collected',
            'changes': {},
            'result': True,
            'comment': '',
        }
        location = location or tempfile.gettempdir()
        self.check_destination(location, group)
        ret['changes'] = __salt__['support.sync'](group, name=filename, host=host,
                                                  location=location, move=move, all=all)

        return ret
19092
def run_command(self, ct, cluster_balancer):
        """"""
        if self.args.topic in ct.topics:
            topic = ct.topics[self.args.topic]
        else:
            self.log.error(
                "Topic {topic} not found. Exiting."
                .format(topic=self.args.topic),
            )
            sys.exit(1)

        if topic.replication_factor == self.args.replication_factor:
            self.log.info(
                "Topic {topic} already has replication factor {rf}. "
                "No action to perform."
                .format(topic=topic.id, rf=self.args.replication_factor),
            )
            return

        if self.args.replication_factor > len(ct.brokers):
            self.log.error(
                "Replication factor {rf} is greater than the total number of "
                "brokers {brokers}. Exiting."
                .format(
                    rf=self.args.replication_factor,
                    brokers=len(ct.brokers)
                ),
            )
            sys.exit(1)

        base_assignment = ct.assignment

        changes_per_partition = abs(
            self.args.replication_factor - topic.replication_factor
        )

        if topic.replication_factor < self.args.replication_factor:
            self.log.info(
                "Increasing topic {topic} replication factor from {old_rf} to "
                "{new_rf}."
                .format(
                    topic=topic.id,
                    old_rf=topic.replication_factor,
                    new_rf=self.args.replication_factor,
                ),
            )
            for partition in topic.partitions:
                cluster_balancer.add_replica(
                    partition.name,
                    changes_per_partition,
                )
        else:
            self.log.info(
                "Decreasing topic {topic} replication factor from {old_rf} to "
                "{new_rf}."
                .format(
                    topic=topic.id,
                    old_rf=topic.replication_factor,
                    new_rf=self.args.replication_factor,
                ),
            )
            topic_data = self.zk.get_topics(topic.id)[topic.id]
            for partition in topic.partitions:
                partition_data = topic_data['partitions'][str(partition.partition_id)]
                isr = partition_data['isr']
                osr_broker_ids = [b.id for b in partition.replicas if b.id not in isr]
                if osr_broker_ids:
                    self.log.info(
                        "The out of sync replica(s) {osr_broker_ids} will be "
                        "prioritized for removal."
                        .format(osr_broker_ids=osr_broker_ids)
                    )
                cluster_balancer.remove_replica(
                    partition.name,
                    osr_broker_ids,
                    changes_per_partition,
                )

        # Each replica addition/removal for each partition counts for one
        # partition movement
        partition_movement_count = len(topic.partitions) * changes_per_partition

        reduced_assignment = self.get_reduced_assignment(
            base_assignment,
            ct,
            max_partition_movements=partition_movement_count,
            max_leader_only_changes=0,
        )
        self.process_assignment(reduced_assignment, allow_rf_change=True)
695661
def _move_to_store(self, srcpath, objhash):
        
        destpath = self.object_path(objhash)
        if os.path.exists(destpath):
            # Windows: delete any existing object at the destination.
            os.chmod(destpath, S_IWUSR)
            os.remove(destpath)
        os.chmod(srcpath, S_IRUSR | S_IRGRP | S_IROTH)  # Make read-only
        move(srcpath, destpath)
1231458
def _prepare_output(partitions, verbose):
    """"""
    out = {}
    partitions_count = len(partitions)
    out['raw'] = {
        'not_enough_replicas_count': partitions_count,
    }

    if partitions_count == 0:
        out['message'] = 'All replicas in sync.'
    else:
        out['message'] = (
            "{0} partition(s) have the number of replicas in "
            "sync that is lower than the specified min ISR."
        ).format(partitions_count)

        if verbose:
            lines = (
                "isr={isr} is lower than min_isr={min_isr} for {topic}:{partition}"
                .format(
                    isr=p['isr'],
                    min_isr=p['min_isr'],
                    topic=p['topic'],
                    partition=p['partition'],
                )
                for p in partitions
            )
            out['verbose'] = "Partitions:\n" + "\n".join(lines)
    if verbose:
        out['raw']['partitions'] = partitions

    return out
1158405
def move_outdir_orphan (outdir):
    """"""
    entries = os.listdir(outdir)
    if len(entries) == 1:
        src = os.path.join(outdir, entries[0])
        dst = os.path.join(os.path.dirname(outdir), entries[0])
        if os.path.exists(dst) or os.path.islink(dst):
            return (False, "local file exists")
        shutil.move(src, dst)
        os.rmdir(outdir)
        return (True, entries[0])
    return (False, "multiple files in root")
266480
def cli(env, columns, sortby, volume_id):
    """"""
    file_storage_manager = SoftLayer.FileStorageManager(env.client)

    legal_centers = file_storage_manager.get_replication_locations(
        volume_id
    )

    if not legal_centers:
        click.echo("No data centers compatible for replication.")
    else:
        table = formatting.KeyValueTable(columns.columns)
        table.sortby = sortby
        for legal_center in legal_centers:
            table.add_row([value or formatting.blank()
                           for value in columns.row(legal_center)])

        env.fout(table)
192670
def ActivateInstanceDisks(r, instance, ignore_size=False):
    

    return r.request("put", "/2/instances/%s/activate-disks" % instance,
                     query={"ignore_size": ignore_size})
1074248
def move(self, new_path, replication=None):
        
        if not new_path.startswith('/'):
            new_path = self._normpath(self.dirname + '/' + new_path)
        else:
            new_path = self._normpath(new_path)
        if new_path == self.path:
            raise ValueError('New path should be different from the original one.')
        update_def = self.UpdateRequestXML(path=new_path)
        if replication:
            update_def.replication = replication
        headers = {
            'Content-Type': 'application/xml',
            'x-odps-volume-fs-path': self.path,
        }
        self._client.put(self.parent.resource(), params={'meta': ''}, headers=headers, data=update_def.serialize())
        self._del_cache(self.path)
        self.path = new_path
        self.reload()