public function manage()
 {
     $this->manager = new Manager();
     $this->manager->setProcessManagerDto($this->gearmanDto->getProcessManagerDto());
     //Gearman worker block any signal besides SIGKILL,
     //so its become impossible to correct send SIGTERM and handle it (execute some other actions before termination)
     $this->manager->setSigTermBlockingAgent(true);
     $this->manager->manage();
     $this->manager->getExecutionDto()->setExecutionMessage("PM with id " . $this->gearmanDto->getTaskId() . " going to finish.");
     $this->manager->getExecutionDto()->setTaskId($this->gearmanDto->getTaskId());
     $this->job->sendComplete(serialize($this->manager->getExecutionDto()));
     return null;
 }
Exemplo n.º 2
0
 function sleepFunc(\GearmanJob $job)
 {
     $sleepSeconds = intval(unserialize($job->workload()));
     $this->log('in sleepFunc() - sleeping for ' . $sleepSeconds . ' seconds');
     sleep($sleepSeconds);
     $job->sendComplete('completed');
 }
Exemplo n.º 3
0
 /**
  * Notify the Client
  *
  * @param int    $type one of NOTIFY_*
  * @param string $data
  * @return bool
  */
 public function notify($type, $data = null)
 {
     if ($type == JobInterface::NOTIFY_COMPLETE) {
         return $this->job->sendComplete($data);
     }
     if ($type == JobInterface::NOTIFY_DATA) {
         return $this->job->sendData($data);
     }
     if ($type == JobInterface::NOTIFY_EXCEPTION) {
         return $this->job->sendException($data);
     }
     if ($type == JobInterface::NOTIFY_FAIL) {
         return $this->job->sendFail();
     }
     if ($type == JobInterface::NOTIFY_WARNING) {
         return $this->job->notifyWarning($data);
     }
     return false;
 }
Exemplo n.º 4
0
 /**
  * A function that is CPU intensive for testing the load-limiting starting of workers.
  */
 function calcPi(\GearmanJob $job)
 {
     $this->log('in calcPi()');
     $pi = 4;
     $top = 4;
     $bot = 3;
     $minus = TRUE;
     $accuracy = 10000000;
     for ($i = 0; $i < $accuracy; $i++) {
         $pi += $minus ? -($top / $bot) : $top / $bot;
         $minus = $minus ? FALSE : TRUE;
         $bot += 2;
     }
     $this->log('Pi = ' . $pi);
     $job->sendComplete('completed');
 }
Exemplo n.º 5
0
 public function initAdapted(\GearmanJob $job)
 {
     $this->loop = Factory::create();
     $this->read = new \React\Stream\Stream(STDIN, $this->loop);
     $this->read->bufferSize = 8192;
     $this->write = new \React\Stream\Stream(STDOUT, $this->loop);
     $this->write->bufferSize = 8192;
     $this->job = $job;
     //protect from repeated execution
     $initStart = false;
     $pmErrorDtoAlreadySent = false;
     /**
      * Receive sockets params json from PM to set it into performer
      */
     $this->read->on('data', function ($data) use($initStart, $pmErrorDtoAlreadySent) {
         if (!is_array($this->pmWorkerDta)) {
             $this->pmWorkerDta = @json_decode($data, true);
             if ($this->pmWorkerDta !== false && is_array($this->pmWorkerDta)) {
                 if ($initStart === false) {
                     $initStart = true;
                     try {
                         $this->initBasicParams();
                         $this->adaptedService->getTerminatorPauseStander()->setPublisherPmSocketAddress($this->pmWorkerDta[DataTransferConstants::PUBLISHER_PM]);
                         $this->adaptedService->getTerminatorPauseStander()->setUSleepTime(5000000);
                         $performerSocketParams = new PerformerSocketsParamsDto();
                         $performerSocketParams->setRequestPulsarRsSocketAddress($this->pmWorkerDta[DataTransferConstants::REQUEST_PULSAR_RS]);
                         $performerSocketParams->setPublisherPulsarSocketAddress($this->pmWorkerDta[DataTransferConstants::PUBLISHER_PULSAR]);
                         $performerSocketParams->setPushPulsarSocketAddress($this->pmWorkerDta[DataTransferConstants::PUSH_PULSAR]);
                         $this->adaptedService->getZmqPerformer()->setSocketsParams($performerSocketParams);
                         $this->adaptedService->getZmqPerformer()->setLogger($this->logger);
                         $this->adaptedService->serviceExec();
                         $this->adaptedService->getExecutionDto()->setExecutionMessage($this->adaptedService->getParams());
                         $this->job->sendComplete(serialize($this->adaptedService->getExecutionDto()));
                         $this->jobInfoWasSent = true;
                         $this->logger->critical("Job complete was sent.");
                     } catch (\Exception $e) {
                         $errorMsg = "Adapter die in Exception with \$e: " . $e->getMessage() . "|params: " . serialize($this->adaptedService->getParams());
                         //. $e->getTraceAsString();
                         $this->logger->critical($errorMsg . " | " . serialize($this->pmWorkerDta));
                         $this->job->sendComplete(serialize(InspectionHelper::prepareErrorExecutionDto($this->adaptedService->getTaskId(), $errorMsg)));
                         $this->jobInfoWasSent = true;
                         $this->logger->critical("Job complete with exception was sent.");
                         die;
                     }
                     $this->loop->nextTick(function () {
                         $this->loop->stop();
                     });
                 }
             } else {
                 if ($pmErrorDtoAlreadySent === false) {
                     $pmErrorDtoAlreadySent = true;
                     $pmErrorArr = [];
                     $pmErrorArr[DataTransferConstants::ERROR_LEVEL] = ErrorsConstants::CRITICAL;
                     $pmErrorArr[DataTransferConstants::ERROR_REASON] = PmErrorConstants::WORKER_NOT_RECEIVE_CORRECT_DTO;
                     $pmErrorArr[DataTransferConstants::ERROR_ELEMENT] = $this->pmWorkerDta;
                     //write to PM's allotted STDIN about critical error
                     $this->write->write(json_encode($pmErrorArr));
                     $this->loop->nextTick(function () {
                         $this->loop->stop();
                     });
                 }
             }
         }
     });
     $timerIteration = 0;
     $this->loop->addPeriodicTimer(3, function (Timer $timer) use(&$timerIteration) {
         if ($this->pmWorkerDta === null) {
             if ($timerIteration > $this->maxTimerIteration) {
                 $this->initBasicParams();
                 die;
             }
             $timerIteration++;
         } else {
             $timer->cancel();
         }
     });
     $this->loop->run();
     if ($pmErrorDtoAlreadySent) {
         die;
     }
 }
Exemplo n.º 6
0
/**
 * Functions registered with the worker
 *
 * @param GearmanJob $job
 * @return boolean
 */
function send_email($job)
{
    //Get the info of the job
    $workload = unserialize($job->workload());
    //Ensure the minimum info
    if (!array_key_exists('text', $workload) && !array_key_exists('html', $workload)) {
        echo sprintf("%s: To send an email we need at least the text or html\n", date('r'));
        $job->sendFail();
        return FALSE;
    }
    if (!array_key_exists('to', $workload) || array_key_exists('to', $workload) && empty($workload['to'])) {
        echo sprintf("%s: To send an email we need the recipient address\n", date('r'));
        $job->sendFail();
        return FALSE;
    }
    if (!array_key_exists('subject', $workload)) {
        echo sprintf("%s: To send an email we need the subject of the email\n", date('r'));
        $job->sendFail();
        return FALSE;
    }
    echo sprintf("%s: Received a task to send email to %s\n", date('r'), implode(', ', is_array($workload['to']) ? $workload['to'] : array($workload['to'])));
    $config = getConfig();
    $mail = new Zend_Mail('utf-8');
    if ($config->system->email_system->send_by_amazon_ses) {
        $transport = new App_Mail_Transport_AmazonSES(array('accessKey' => $config->amazon->aws_access_key, 'privateKey' => $config->amazon->aws_private_key));
    }
    if (array_key_exists('text', $workload)) {
        $mail->setBodyText($workload['text']);
    }
    if (array_key_exists('html', $workload)) {
        $mail->setBodyHtml($workload['html']);
    }
    if (array_key_exists('reply', $workload) && !empty($workload['reply'])) {
        $mail->setReplyTo($workload['reply']);
    }
    $mail->setFrom($config->amazon->ses->from_address, $config->amazon->ses->from_name);
    $mail->addTo($workload['to']);
    $mail->setSubject($workload['subject']);
    //Prepare gearman client
    $config = getConfig();
    $gearmanClient = new GearmanClient();
    if (!empty($config->gearman->servers)) {
        $gearmanClient->addServers($config->gearman->servers->toArray());
    } else {
        $gearmanClient->addServer();
    }
    //Add the callbacks
    $gearmanClient->setCompleteCallback('taskCompleted');
    $gearmanClient->setFailCallback('taskFailed');
    try {
        if (isset($transport) && $transport instanceof App_Mail_Transport_AmazonSES) {
            $mail->send($transport);
        } else {
            $mail->send();
        }
        //Some status info
        echo sprintf("%s: Email (%s) sent to %s\n", date('r'), $workload['subject'], implode(', ', is_array($workload['to']) ? $workload['to'] : array($workload['to'])));
        echo sprintf("%s: Task finished successfully\n\n", date('r'));
        $job->sendComplete(TRUE);
        return TRUE;
    } catch (Exception $e) {
        logError(sprintf("Error while sending an email to %s.\n\nError: %s\n", $workload['to'], $e->getMessage()));
        $job->sendFail();
        return FALSE;
    }
}
Exemplo n.º 7
0
 /**
  * Sends result data and the complete status update for this job.
  *
  * @link http://php.net/manual/en/gearmanjob.sendcomplete.php
  * @param $data
  * @return bool
  */
 public function sendComplete($data)
 {
     return $this->_job->sendComplete($data);
 }