Run the given script on the given host.

@param  string  $host
@param  \Laravel\Envoy\Task  $task
@return array
175362
protected function getProcess($host, Task $task)
    {
        $target = $this->getConfiguredServer($host) ?: $host;

        $env = $this->getEnvironment($host);

        if (in_array($target, ['local', 'localhost', '127.0.0.1'])) {
            $process = new Process($task->script, null, $env);
        }

        // Here we'll run the SSH task on the server inline. We do not need to write the
        // script out to a file or anything. We will start the SSH process then pass
        // these lines of output back to the parent callback for display purposes.
        else {
            $delimiter = 'EOF-LARAVEL-ENVOY';

            foreach ($env as $k => $v) {
                if ($v !== false) {
                    $env[$k] = 'export '.$k.'="'.$v.'"'.PHP_EOL;
                }
            }

            if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
                $process = new Process("ssh $target -T");

                $process->setInput(
                    implode(PHP_EOL, $env)
                    .'set -e '.PHP_EOL
                    .str_replace("\r", '', $task->script)
                );
            } else {
                $process = new Process(
                    "ssh $target 'bash -se' << \\$delimiter".PHP_EOL
                    .implode(PHP_EOL, $env).PHP_EOL
                    .'set -e'.PHP_EOL
                    .$task->script.PHP_EOL
                    .$delimiter
                );
            }
        }

        return [$target, $process->setTimeout(null)];
    }
582781
public function run($workload, TaskWrapper $task)
    {
        $result = false;
        $this->id = $task->getId();
        $this->name = $task->getName();

        try {
            if (false !== $this->beforeRun($workload, $task)) {
                $result = $this->doRun($workload, $task);

                $this->afterRun($result);
            }
        } catch (\Exception $e) {
            $this->onException($e);
        }

        return $result;
    }
783228
public function runTask($taskId, $context = array())
    {
        $param =  array(
            'actionName' => 'runTask',
            'authPass'   => $this->getConfig('password'),
            'authUser'   => $this->getConfig('login'),
            'taskId'     => $taskId,
            'mode'       => 'synchronous'
        );

        if ($this->getConfig('context') != '' && is_array($this->getConfig('context'))) {
            $context = array_merge($this->getConfig('context'), $context);
        }

        if (!empty($context) && is_array($context)) {
            $param['context'] = $context;
        }

        return $this->getContent($this->doRequest($this->get('?'. $this->getJsonEncoded($param))));
    }
471848
public function task($site, $taskId)
    {
        $variables = array(
            'site' => $site,
            'task' => $taskId,
        );
        $request = $this->get(array('{+base_path}/sites/{site}/tasks/{task}.json', $variables));
        return new Response\Task($request);
    }
824858
public static function co(array $tasks): array
    {
        $taskCos = [];
        foreach ($tasks as $task) {
            if (! isset($task['type']) || ! isset($task['name']) || ! isset($task['method']) || ! isset($task['params'])) {
                App::error(sprintf('Task %s format error.', $task['name'] ?? '[UNKNOWN]'));
                continue;
            }

            $type = $task['type'];
            if ($type !== static::TYPE_CO) {
                App::error(sprintf('Task %s is not a coroutine task.', $task['name']));
                continue;
            }

            $taskCos[] = TaskHelper::pack($task['name'], $task['method'], $task['params'], $task['type']);
        }

        $result = [];
        if (! empty($taskCos)) {
            $result = App::$server->getServer()->taskCo($tasks);
        }

        return $result;
    }
68005
private function executeComposerInstall($host)
    {
        $ssh = $host->getSshClient();
        $ssh->exec(array(
            sprintf('cd %s;', $host->getWorkingDirectory()),
            'stat composer.phar'
        ));
        if ($ssh->getExitCode()) {
            $this->installComposer($host);
        }
        $ssh = $host->getSshClient();
        $ssh->exec(
            array(
                sprintf('cd %s;', $host->getWorkingDirectory()),
                'php composer.phar install --no-dev'
            ),
            null,
            self::TIMEOUT_MAX_RUNTIME_COMPOSER_INSTALL
        );
        if ($ssh->getExitCode()) {
            throw new SynchronisationException($host->getName(), sprintf(
                'Unable to execute composer install: "%s".',
                $ssh->getErrorOutput()
            ));
        }
    }
395686
public function execute(AbstractTask $task, $parameters = array()) {

        $this->task = $task;

        $this->loadHtml($this->obtainHtml($parameters));

        $ignore_rules = $task->getIgnoreRules();

        foreach ($ignore_rules as $rule) {
            $this->useIgnoreRule($rule);
        }

        $class = $task->getClassName();

        $entity = new $class;

        $task->setEntity($entity);

        $rules = $task->getParseRules();

        foreach ($rules as $rule) {
            $this->useParseRule($rule, $entity);
        }
        return $entity;
    }
646066
public function forkTask(Task $task)
    {
        $cronExpression = $task->getCronExpression();
        if (true === $cronExpression->isDue()) {
            $this->getLogger()->info(
                sprintf('Starting cron task "%s"', $task->getName()),
                array(
                    'command' => $task->getCommandToExecute()
                )
            );
            $taskProcess = new Process($task->getCommandToExecute());
            $taskProcess->start();
        }
    }
129460
public function shouldBePerformed(...$hosts)
    {
        // don't allow to run again it the task has been marked to run only once
        if ($this->once && $this->hasRun) {
            return false;
        }

        foreach ($hosts as $host) {
            $onHost = empty($this->on['hosts']) || in_array($host->getHostname(), $this->on['hosts'], true);

            $onRole = empty($this->on['roles']);
            foreach ((array) $host->get('roles', []) as $role) {
                if (in_array($role, $this->on['roles'], true)) {
                    $onRole = true;
                }
            }

            $onStage = empty($this->on['stages']);
            if ($host->has('stage')) {
                if (in_array($host->get('stage'), $this->on['stages'], true)) {
                    $onStage = true;
                }
            }

            if ($onHost && $onRole && $onStage) {
                return true;
            }
        }

        return empty($hosts);
    }
1251027
public static function deliver($clazz, $method = "run", $params = null, $task_id = -1) {
        $app = Ioc::get(Application::class);
        /* @var $deliver TaskConfig */
        $deliver = Ioc::get(TaskConfig::class);
        $bean = ['clazz' => $clazz,
                 'method' => $method,
                 'params' => $params,
                 'config' => $deliver->getTaskInitConfig()];
        if (IS_SWOOLE) {
            $app->server->task($bean, $task_id);
        }
    }
547655
public function runForApplication($tasks)
    {
        $folder = $this->config->getContextually('remote.directories.subdirectory');
        $folder = $this->releasesManager->getCurrentReleasePath($folder);

        return $this->modulable->runInFolder($folder, $tasks);
    }
703867
public function run(Task $task)
    {
        // get configured filters for this task
        $filters = $task
            ->getConfiguration()
            ->getParameter('filters');

        // get sources files
        $sources = $this->fetchSources($task);
        $destinations = $this->fetchDestinations($task);

        foreach ($filters as $filterName) {
            // get current configured filter
            $filter = $this->getFilter($filterName);

            // filter the files supported by this filter
            $filteredSources = $this->filterSources($sources, $filter);

            // apply the filter
            $updatedSources = $filter->run($filteredSources, $destinations);

            // update new sources if exists
            if ($updatedSources === null) {
                $updatedSources = [];
            }
            $sources = $this->updateSources($sources, $filteredSources, $updatedSources);
        }

        if (!$this->isDebug) {
            foreach ($filters as $filterName) {
                // get current configured filter
                $filter = $this->getFilter($filterName);

                // clean the files generated by the filter
                $filter->clean();
            }
        }
    }
531279
public function processTask(TaskInterface $task)
    {
        if ($this->taskLog->getStatus($task->getId()) != TaskLogInterface::STATUS_CANCELLED) {
            $report = Report::createInfo(__('Running task %s', $task->getId()));

            try {
                $this->logDebug('Processing task ' . $task->getId(), $this->getLogContext());

                $rowsTouched = $this->taskLog->setStatus($task->getId(), TaskLogInterface::STATUS_RUNNING, TaskLogInterface::STATUS_DEQUEUED);

                // if the task is being executed by another worker, just return, no report needs to be saved
                if (!$rowsTouched) {
                    $this->logDebug('Task ' . $task->getId() . ' seems to be processed by another worker.', $this->getLogContext());
                    return TaskLogInterface::STATUS_UNKNOWN;
                }

                // let the task know that it is called from a worker
                $task->applyWorkerContext();

                // execute the task
                $taskReport = $task();

                if (!$taskReport instanceof Report) {
                    $this->logWarning('Task ' . $task->getId() . ' should return a report object.', $this->getLogContext());
                    $taskReport = Report::createInfo(__('Task not returned any report.'));
                }

                $report->add($taskReport);

                unset($taskReport, $rowsTouched);
            } catch (\Exception $e) {
                $this->logError('Executing task ' . $task->getId() . ' failed with MSG: ' . $e->getMessage(), $this->getLogContext());
                $report = Report::createFailure(__('Executing task %s failed', $task->getId()));
            }

            // Initial status
            $status = $report->getType() == Report::TYPE_ERROR || $report->containsError()
                ? TaskLogInterface::STATUS_FAILED
                : TaskLogInterface::STATUS_COMPLETED;

            // Change the status if the task has children
            if ($task->hasChildren() && $status == TaskLogInterface::STATUS_COMPLETED) {
                $status = TaskLogInterface::STATUS_CHILD_RUNNING;
            }

            $cloneCreated = false;

            // if the task is a special sync task: the status of the parent task depends on the status of the remote task.
            if ($this->isRemoteTaskSynchroniser($task) && $status == TaskLogInterface::STATUS_COMPLETED) {
                // if the remote task is still in progress, we have to reschedule this task
                // the RESTApi returns TaskLogCategorizedStatus values
                if (in_array($this->getRemoteStatus($task), [CategorizedStatus::STATUS_CREATED, CategorizedStatus::STATUS_IN_PROGRESS])) {
                    if ($this->queuer->count() <= 1) {
                        //if there is less than or exactly one task in the queue, let's sleep a bit, in order not to regenerate the same task too much
                        sleep(3);
                    }

                    $cloneCreated = $this->queuer->enqueue(clone $task, $task->getLabel());
                } elseif ($this->getRemoteStatus($task) == CategorizedStatus::STATUS_FAILED) {
                    // if the remote task status is failed
                    $status = TaskLogInterface::STATUS_FAILED;
                }
            }

            if (!$cloneCreated) {
                $this->taskLog->setReport($task->getId(), $report, $status);
            } else {
                // if there is a clone, delete the old task log
                //TODO: once we have the centralized way of cleaning up the log table, this should be refactored
                $this->taskLog->getBroker()->deleteById($task->getId());
            }

            // Update parent
            if ($task->hasParent()) {
                /** @var EntityInterface $parentLogTask */
                $parentLogTask = $this->taskLog->getById($task->getParentId());
                if (!$parentLogTask->isMasterStatus()) {
                    $this->taskLog->updateParent($task->getParentId());
                }
            }

            unset($report);
        } else {
            $this->taskLog->setReport(
                $task->getId(),
                Report::createInfo(__('Task %s has been cancelled, message was not processed.', $task->getId())),
                TaskLogInterface::STATUS_CANCELLED
            );

            $status = TaskLogInterface::STATUS_CANCELLED;
        }

        // delete message from queue
        $this->queuer->acknowledge($task);

        return $status;
    }
1100367
public static function runTask($command, $groupName, $immediate = false)
    {
        $task = ExtensionDataHelper::buildTask($command, $groupName);
        if ($task->registerTask()) {
            if ($immediate) {
                DeferredHelper::runImmediateTask($task->model()->id);
            }
        } else {
            throw new ServerErrorHttpException("Unable to start task");
        }
    }
796904
protected function _run(array $task) {
		$this->ProcessManager->fork(function () use ($task) {
			$this->_makeRunner($task)->start();
		});
	}
1070002
public function run($taskId, $operation, array $arguments)
    {

        try {

            $lambda = new Lambda($operation, $this->ioc);

            if ($lambda->isInstanceMethod()) {
                $this->connectHooks($taskId, $lambda->getCallInstance());
            }

            $this->taskRepository->write($taskId, ['state' => Queue::RUNNING]);

            $result = $this->performTask($lambda, $arguments);

            $this->taskRepository->write($taskId, ['state' => Queue::FINISHED]);

            return $result;

        } catch (\Exception $e) {

            $this->taskRepository->writeMessage($taskId, $this->exceptionMessage($e), Chatty::FATAL);
            $this->taskRepository->write($taskId, ['state' => Queue::FAILED]);

        }

    }
852253
def run(self, host=None, port=None, debug=None, **options):
        

        tasks = options.get('tasks', [])
        for task in tasks:
            if task is not None and hasattr(task, '__call__'):
                _batch_tasks.append(task)

        thread = Thread(target=self.batch_work)
        thread.start()

        try:
            super(AgoraApp, self).run(host='0.0.0.0', port=self.config['PORT'], debug=True, use_reloader=False)
        except Exception, e:
            print e.message
        self._stop_event.set()
        if thread.isAlive():
            thread.join()