Submits a command to the cluster.
517687
private <T> void submitCommand(Command<T> command, CompletableFuture<T> future) {
    CommandRequest request = CommandRequest.builder()
      .withSession(state.getSessionId())
      .withSequence(state.nextCommandRequest())
      .withCommand(command)
      .build();
    submitCommand(request, future);
  }
1317088
async def send_cluster_commands(self, stack, raise_on_error=True, allow_redirections=True):
        
        # the first time sending the commands we send all of the commands that were queued up.
        # if we have to run through it again, we only retry the commands that failed.
        attempt = sorted(stack, key=lambda x: x.position)

        # build a list of node objects based on node names we need to
        nodes = {}

        # as we move through each command that still needs to be processed,
        # we figure out the slot number that command maps to, then from the slot determine the node.
        for c in attempt:
            # refer to our internal node -> slot table that tells us where a given
            # command should route to.
            slot = self._determine_slot(*c.args)
            node = self.connection_pool.get_node_by_slot(slot)

            # little hack to make sure the node name is populated. probably could clean this up.
            self.connection_pool.nodes.set_node_name(node)

            # now that we know the name of the node ( it's just a string in the form of host:port )
            # we can build a list of commands for each node.
            node_name = node['name']
            if node_name not in nodes:
                nodes[node_name] = NodeCommands(self.parse_response, self.connection_pool.get_connection_by_node(node))

            nodes[node_name].append(c)

        # send the commands in sequence.
        # we  write to all the open sockets for each node first, before reading anything
        # this allows us to flush all the requests out across the network essentially in parallel
        # so that we can read them all in parallel as they come back.
        # we dont' multiplex on the sockets as they come available, but that shouldn't make too much difference.
        node_commands = nodes.values()
        for n in node_commands:
            await n.write()

        for n in node_commands:
            await n.read()

        # release all of the redis connections we allocated earlier back into the connection pool.
        # we used to do this step as part of a try/finally block, but it is really dangerous to
        # release connections back into the pool if for some reason the socket has data still left in it
        # from a previous operation. The write and read operations already have try/catch around them for
        # all known types of errors including connection and socket level errors.
        # So if we hit an exception, something really bad happened and putting any of
        # these connections back into the pool is a very bad idea.
        # the socket might have unread buffer still sitting in it, and then the
        # next time we read from it we pass the buffered result back from a previous
        # command and every single request after to that connection will always get
        # a mismatched result. (not just theoretical, I saw this happen on production x.x).
        for n in nodes.values():
            self.connection_pool.release(n.connection)

        # if the response isn't an exception it is a valid response from the node
        # we're all done with that command, YAY!
        # if we have more commands to attempt, we've run into problems.
        # collect all the commands we are allowed to retry.
        # (MOVED, ASK, or connection errors or timeout errors)
        attempt = sorted([c for c in attempt if isinstance(c.result, ERRORS_ALLOW_RETRY)], key=lambda x: x.position)
        if attempt and allow_redirections:
            # RETRY MAGIC HAPPENS HERE!
            # send these remaing comamnds one at a time using `execute_command`
            # in the main client. This keeps our retry logic in one place mostly,
            # and allows us to be more confident in correctness of behavior.
            # at this point any speed gains from pipelining have been lost
            # anyway, so we might as well make the best attempt to get the correct
            # behavior.
            #
            # The client command will handle retries for each individual command
            # sequentially as we pass each one into `execute_command`. Any exceptions
            # that bubble out should only appear once all retries have been exhausted.
            #
            # If a lot of commands have failed, we'll be setting the
            # flag to rebuild the slots table from scratch. So MOVED errors should
            # correct themselves fairly quickly.
            await self.connection_pool.nodes.increment_reinitialize_counter(len(attempt))
            for c in attempt:
                try:
                    # send each command individually like we do in the main client.
                    c.result = await super(StrictClusterPipeline, self).execute_command(*c.args, **c.options)
                except RedisError as e:
                    c.result = e

        # turn the response back into a simple flat array that corresponds
        # to the sequence of commands issued in the stack in pipeline.execute()
        response = [c.result for c in sorted(stack, key=lambda x: x.position)]

        if raise_on_error:
            self.raise_first_error(stack)

        return response
902953
public function cmdAddOrder()
    {
        $submitted = $this->getParam();

        $this->setSubmitted(null, $submitted);
        $this->setSubmittedJson('data');

        $this->validateComponent('order');

        if ($this->isError()) {
            $this->output();
        }

        $id = $this->order->add($this->getSubmitted());

        if (empty($id)) {
            $this->errorAndExit($this->text('Unexpected result'));
        }

        $this->line($id);
        $this->output();
    }
70823
def send_command(self, obj, command, *arguments):
        
        index_command = obj._build_index_command(command, *arguments)
        self.chassis_list[obj.chassis].sendQueryVerify(index_command)
801844
private void handleCluster(HttpGetCommand command) {
        Node node = textCommandService.getNode();
        StringBuilder res = new StringBuilder(node.getClusterService().getMemberListString());
        res.append("\n");
        NetworkingService ns = node.getNetworkingService();
        EndpointManager cem = ns.getEndpointManager(CLIENT);
        AggregateEndpointManager aem = ns.getAggregateEndpointManager();
        res.append("ConnectionCount: ").append(cem.getActiveConnections().size());
        res.append("\n");
        res.append("AllConnectionCount: ").append(aem.getActiveConnections().size());
        res.append("\n");
        command.setResponse(null, stringToBytes(res.toString()));
    }
737704
function send_command(command, cb) {
        var cmd = commands[command.toUpperCase()];
        if(parseInt(cmd)) {
            post('/roap/api/command', `<?xml version='1.0' encoding='utf-8'?><command><name>HandleKeyInput</name><value>${cmd}</value></command>`, (body) => {
                try {
                    var doc = new dom().parseFromString(body);
                    if(cb) cb(xpath.select('//ROAPErrorDetail/text()', doc).toString() == 'OK')
                } catch(error) {
                    log(`error send_command:  ${error.message}`)
                    if(cb) cb(false)
                }
            });
        }
    }
1346383
public void submit() throws IOException, InterruptedException,
                              ClassNotFoundException {
    ensureState(JobState.DEFINE);
    setUseNewAPI();
    info = jobClient.submitJobInternal(conf);
    state = JobState.RUNNING;
   }
1325160
def do_POST(self):
        """"""
        logging.debug("New POST request.")

        query = parse_qs(urlparse(self.path).query)
        sample = query['sample'][0]
        async = bool(int(query.get('async', [False])[0]))

        path = self.store_file(mkdtemp(), sample)
        command = query['command'][0].format(sample=path).split(' ')

        output = run_command(command, asynchronous=async)

        self.respond(output)
1293232
def submit(command_filename, workingdir, send_mail = False, username = None):
    ''''''

    # Open streams
    command_filename = command_filename
    outfile = command_filename + ".out"
    file_stdout = open(outfile, 'w')

    # Form command
    command = ['qsub']

    if send_mail and username:
        #username = 'Shane.OConnor@ucsf.edu'
        command.extend(['-m', 'eas', '-M', '%s@chef.compbio.ucsf.edu' % username])
    command.append(command_filename)

    # Submit the job and capture output.
    try:
        subp = subprocess.Popen(command, stdout=file_stdout, stderr=file_stdout, cwd=workingdir)
    except Exception, e:
        colortext.error('Failed running qsub command: %s in cwd %s.' % (command, workingdir))
        raise

    waitfor = 0
    errorcode = subp.wait()
    file_stdout.close()

    file_stdout = open(outfile, 'r')
    output = file_stdout.read().strip()
    file_stdout.close()

    if errorcode != 0:
        colortext.error('Failed running qsub command: %s in cwd %s.' % (command, workingdir))
        raise Exception(output)

    # Match job id
    # This part of the script may be error-prone as it depends on the server message.
    matches = re.match('Your job-array (\d+).(\d+)-(\d+):(\d+)', output)
    if not matches:
        matches = re.match('Your job (\d+) \(".*"\) has been submitted.*', output)

    if matches:
        jobid = int(matches.group(1))
    else:
        jobid = -1

    output = output.replace('"', "'")
    if output.startswith("qsub: ERROR"):
        raise Exception(output)

    os.remove(outfile)
    #os.remove(command_filename)

    return jobid, output
1246128
function(cmdPointer, next) {

                                        // Publish it now...
                                        commandDispatcher.dispatch(cmdPointer.command, function(err) {
                                            if (cmdPointer.callback) cmdPointer.callback(null);
                                            next();
                                        });
                                    }
1175464
def send_cluster_time(self, command, session, client):
        """"""
        if self.max_wire_version >= 6 and client:
            client._send_cluster_time(command, session)
552251
private void submit(final ActiveContext context, final String command) {
    try {
      LOG.log(Level.INFO, "Send command {0} to context: {1}", new Object[]{command, context});
      final JavaConfigurationBuilder cb = Tang.Factory.getTang().newConfigurationBuilder();
      cb.addConfiguration(
          TaskConfiguration.CONF
              .set(TaskConfiguration.IDENTIFIER, context.getId() + "_task")
              .set(TaskConfiguration.TASK, ShellTask.class)
              .build()
      );
      cb.bindNamedParameter(Command.class, command);
      context.submitTask(cb.build());
    } catch (final BindException ex) {
      LOG.log(Level.SEVERE, "Bad Task configuration for context: " + context.getId(), ex);
      context.close();
      throw new RuntimeException(ex);
    }
  }
398116
void submit() {

        int action = -1;

        if (isModeAll()) {
            action = CmsFlexCache.CLEAR_ONLINE_ALL;
        } else {
            action = CmsFlexCache.CLEAR_ONLINE_ENTRIES;
        }

        OpenCms.fireCmsEvent(
            new CmsEvent(
                I_CmsEventListener.EVENT_FLEX_CACHE_CLEAR,
                Collections.<String, Object> singletonMap(CmsFlexCache.CACHE_ACTION, new Integer(action))));
    }
966152
void submit() {

        CmsResource target = m_context.getResources().get(0);
        String resPath = m_context.getCms().getSitePath(target);
        try {
            m_context.getCms().copyResourceToProject(resPath);

            m_context.finish(Collections.singletonList(target.getStructureId()));
        } catch (CmsException e) {
            m_context.error(e);
        }
    }
625918
def submit(script, workspace, **params):
    """"""
    from klab import cluster, process

    # Make sure the rosetta symlink has been created.

    if not os.path.exists(workspace.rosetta_dir):
        raise pipeline.RosettaNotFound(workspace)

    # Parse some job parameters for the keyword arguments.

    params = dict((k, v) for k, v in params.items() if v is not None)
    test_run = params.get('test_run', False)
    nstruct = params.get('nstruct')
    max_runtime = params.get('max_runtime', '6:00:00')
    max_memory = params.get('max_memory', '1G')

    if test_run:
        nstruct = 1

    if nstruct is None:
        raise TypeError("submit() requires the keyword argument 'nstruct' for production runs.")

    # Use Jinja to render the XML script that will be passed to rosetta.

    finalize_protocol(workspace, params)

    # Submit the job and put it immediately into the hold state.

    qsub_command = 'qsub', '-h', '-cwd',
    qsub_command += '-o', workspace.log_dir,
    qsub_command += '-j', 'y',
    qsub_command += '-t', '1-{0}'.format(nstruct),
    qsub_command += '-l', 'h_rt={0}'.format(max_runtime),
    qsub_command += '-l', 'mem_free={0}'.format(max_memory),
    qsub_command += pipeline.big_job_path(script),
    qsub_command += workspace.focus_dir,

    status = process.check_output(qsub_command)
    status_pattern = re.compile(r'Your job-array (\d+).[0-9:-]+ \(".*"\) has been submitted')
    status_match = status_pattern.match(status)

    if not status_match:
        print status
        sys.exit()

    # Figure out the job id, then make a params file specifically for it.

    job_id = status_match.group(1)

    with open(workspace.job_info_path(job_id), 'w') as file:
        json.dump(params, file)

    # Release the hold on the job.

    qrls_command = 'qrls', job_id
    process.check_output(qrls_command)
    print status,
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)
724317
def handle_cluster_request(self, tsn, command_id, args):
        """"""
        if command_id == 0:
            if self._timer_handle:
                self._timer_handle.cancel()
            loop = asyncio.get_event_loop()
            self._timer_handle = loop.call_later(30, self._turn_off)