Esempio n. 1
2
 public function __invoke(Job $job)
 {
     $job = $this->elasticsearch->getJob($job->getId());
     // find and kill child jobs
     $childJobs = $this->elasticsearch->getJobs(['query' => 'runId:' . $job->getRunId() . '.*', 'project.id' => $job->getProject()['id']]);
     $this->logger->debug("Child jobs found", ['jobs' => $childJobs]);
     $snsClient = new SnsClient(['credentials' => ['key' => $this->snsConfig['key'], 'secret' => $this->snsConfig['secret']], 'region' => isset($this->snsConfig['region']) ? $this->snsConfig['region'] : 'us-east-1', 'version' => '2010-03-31']);
     // kill them all
     if (!empty($childJobs)) {
         foreach ($childJobs as $childJob) {
             $snsClient->publish(['TopicArn' => $this->snsConfig['topic_arn'], 'Message' => json_encode(['jobId' => $childJob['id']])]);
         }
     }
     $callback = $this->cleanupCallback;
     $callback($job);
     $endTime = time();
     $duration = $endTime - strtotime($job->getStartTime());
     $job->setStatus(Job::STATUS_TERMINATED);
     $job->setResult(['message' => 'Job has been terminated']);
     $job->setEndTime(date('c', $endTime));
     $job->setDurationSeconds($duration);
     $this->jobMapper->update($job);
 }
Esempio n. 2
1
 /**
  * @param string      $request
  * @param string|null $resource_type
  * @param string|null $resource_id
  *
  * @return array
  * @throws BadRequestException
  * @throws InternalServerErrorException
  * @throws NotFoundException
  * @throws null
  */
 public function publish($request, $resource_type = null, $resource_id = null)
 {
     /** http://docs.aws.amazon.com/aws-sdk-php/latest/class-Aws.Sns.SnsClient.html#_publish */
     $data = [];
     if (is_array($request)) {
         if (null !== ($message = ArrayUtils::get($request, 'Message'))) {
             $data = array_merge($data, $request);
             if (is_array($message)) {
                 $data['Message'] = json_encode($message);
                 if (!ArrayUtils::has($request, 'MessageStructure')) {
                     $data['MessageStructure'] = 'json';
                 }
             }
         } else {
             //  This array is the message
             $data['Message'] = json_encode($request);
             $data['MessageStructure'] = 'json';
         }
     } else {
         //  This string is the message
         $data['Message'] = $request;
     }
     switch ($resource_type) {
         case SnsTopic::RESOURCE_NAME:
             $data['TopicArn'] = $this->addArnPrefix($resource_id);
             break;
         case SnsEndpoint::RESOURCE_NAME:
             $data['TargetArn'] = $this->addArnPrefix($resource_id);
             break;
         default:
             //  Must contain resource, either Topic or Endpoint ARN
             $topic = ArrayUtils::get($data, 'Topic', ArrayUtils::get($data, 'TopicArn'));
             $endpoint = ArrayUtils::get($data, 'Endpoint', ArrayUtils::get($data, 'EndpointArn', ArrayUtils::get($data, 'TargetArn')));
             if (!empty($topic)) {
                 $data['TopicArn'] = $this->addArnPrefix($topic);
             } elseif (!empty($endpoint)) {
                 $data['TargetArn'] = $this->addArnPrefix($endpoint);
             } else {
                 throw new BadRequestException("Publish request does not contain resource, either 'Topic' or 'Endpoint'.");
             }
             break;
     }
     try {
         if (null !== ($result = $this->conn->publish($data))) {
             $id = ArrayUtils::get($result->toArray(), 'MessageId', '');
             return ['MessageId' => $id];
         }
     } catch (\Exception $ex) {
         if (null !== ($newEx = static::translateException($ex))) {
             throw $newEx;
         }
         throw new InternalServerErrorException("Failed to push message.\n{$ex->getMessage()}", $ex->getCode());
     }
     return [];
 }
    public function publish($subject, $body, $channels = [])
    {
        $structured = ['default' => $body];
        foreach ($channels as $channel) {
            $is_supported = true;
            switch ($channel) {
                case self::CHANNEL_EMAIL:
                case self::CHANNEL_SQS:
                case self::CHANNEL_LAMBDA:
                case self::CHANNEL_HTTP:
                case self::CHANNEL_HTTPS:
                case self::CHANNEL_SMS:
                    // don't touch body
                    break;
                case self::CHANNEL_APNS:
                case self::CHANNEL_APNS_SANDBOX:
                case self::CHANNEL_APNS_VOIP:
                case self::CHANNEL_APNS_VOIP_SANDBOX:
                case self::CHANNEL_MACOS:
                case self::CHANNEL_MACOS_SANDBOX:
                    $body = ["aps" => ["alert" => $body]];
                    break;
                case self::CHANNEL_GCM:
                case self::CHANNEL_ADM:
                    $body = ["data" => ["message" => $body]];
                    break;
                case self::CHANNEL_BAIDU:
                    $body = ["title" => $body, "description" => $body];
                    break;
                case self::CHANNEL_MPNS:
                    $body = htmlentities($body, ENT_XML1);
                    $body = <<<XML
<?xml version="1.0" encoding="utf-8"?><wp:Notification xmlns:wp="WPNotification"><wp:Tile><wp:Count>ENTER COUNT</wp:Count><wp:Title>{$body}</wp:Title></wp:Tile></wp:Notification>
XML;
                    break;
                default:
                    mwarning("Channel [%s] is not supported by %s", $channels, static::class);
                    $is_supported = false;
                    break;
            }
            if ($is_supported) {
                $structured[$channel] = $body;
            }
        }
        $json = json_encode($structured);
        $this->client->publish(["Subject" => $subject, "Message" => $json, "MessageStructure" => "json", "TopicArn" => $this->topic_arn]);
    }
 /**
  * Send message to sqs and trigger lambda
  *
  * @param string $message to be send via sqs
  *
  */
 public function publish($message)
 {
     // http://docs.aws.amazon.com/aws-sdk-php/v2/api/class-Aws.Sqs.SqsClient.html#_sendMessage
     $this->sqs->sendMessage(['QueueUrl' => $this->sqsQueueUrl, 'MessageBody' => $message]);
     // http://docs.aws.amazon.com/aws-sdk-php/v2/api/class-Aws.Sns.SnsClient.html#_publish
     $this->sns->publish(['TopicArn' => $this->snsTopicArn, 'Message' => 'SQS Message send', 'Subject' => 'SQS Message send']);
 }
 public function send($message, $type, $entityData, Model\AbstractEndpoint $endpoint, $avatarUrl)
 {
     try {
         $this->sns->publish(array('TargetArn' => $endpoint->getArn(), 'MessageStructure' => 'json', 'Message' => $endpoint->getPlatformMessage($message, $type, $entityData, $avatarUrl)));
     } catch (Exception\SnsException $e) {
         if ($e instanceof Exception\EndpointDisabledException || $e instanceof Exception\NotFoundException) {
             $this->removeEndpoint($endpoint);
         }
     }
 }
Esempio n. 6
0
 /**
  * {@inheritDoc}
  */
 protected function write(array $record)
 {
     try {
         $this->sns->publish(['TopicArn' => $this->topicArn, 'Message' => mb_strcut($this->getFormatter()->format($record), 0, 262144), 'Subject' => $this->subject]);
     } catch (SnsException $e) {
         if ($this->logger) {
             $this->logger->error("Failed to send message via AmazonSNS", ['exception' => $e]);
         }
     }
 }
Esempio n. 7
0
 /**
  * Send a message to an endpoint
  *
  * @param Message|string $message
  * @param string $endpointArn
  * @throws MessageTooLongException
  */
 public function send($message, $endpointArn)
 {
     if ($this->debug) {
         $this->logger && $this->logger->notice("Message would have been sent to {$endpointArn}", ['Message' => $message]);
         return;
     }
     if (!$message instanceof Message) {
         $message = new Message($message);
     }
     $this->sns->publish(['TargetArn' => $endpointArn, 'Message' => $this->encodeMessage($message), 'MessageStructure' => 'json']);
 }
 /**
  * @param             $token
  * @param PushMessage $message
  *
  * @return mixed
  */
 private function sendOne($token, $message)
 {
     $client = new SnsClient(['credentials' => new Credentials($this->accessKey, $this->secretKey), 'region' => $this->region, 'version' => 'latest']);
     $endpoint = $client->createPlatformEndpoint(['PlatformApplicationArn' => $this->appArn, 'Token' => $token]);
     $published = $client->publish(['MessageStructure' => 'json', 'Message' => Json::encode(['default' => $message->getBody(), $message->getService() => $this->formatMessage($message)]), 'TargetArn' => $endpoint['EndpointArn']]);
     return $published['MessageId'];
 }
Esempio n. 9
0
function sms($number, $message)
{
    if (empty($number) || empty($message)) {
        return false;
    }
    $SnsClient = new Aws\Sns\SnsClient(['version' => 'latest', 'region' => "ap-southeast-1"]);
    $result = $SnsClient->publish(array('Message' => $message, 'PhoneNumber' => $number, 'MessageAttributes' => array('AWS.SNS.SMS.SMSType' => array('StringValue' => 'Transactional', 'DataType' => 'String'), 'AWS.SNS.SMS.SenderID' => array('StringValue' => explode('.', getenv('HOST'), 2)[0], 'DataType' => 'String'))));
    return $result['MessageId'];
}
Esempio n. 10
0
 /**
  * {@inheritDoc}
  *
  * This method will either use a SNS Topic to publish a queued message or
  * straight to SQS depending on the application configuration.
  *
  * @return string
  */
 public function publish(array $message, array $options = [])
 {
     $options = $this->mergeOptions($options);
     $publishStart = microtime(true);
     // ensures that the SQS Queue and SNS Topic exist
     if (!$this->queueExists()) {
         $this->create();
     }
     if ($options['push_notifications']) {
         if (!$this->topicExists()) {
             $this->create();
         }
         $message = ['default' => $this->getNameWithPrefix(), 'sqs' => json_encode($message), 'http' => $this->getNameWithPrefix(), 'https' => $this->getNameWithPrefix()];
         $result = $this->sns->publish(['TopicArn' => $this->topicArn, 'Subject' => $this->getName(), 'Message' => json_encode($message), 'MessageStructure' => 'json']);
         $context = ['TopicArn' => $this->topicArn, 'MessageId' => $result->get('MessageId'), 'push_notifications' => $options['push_notifications'], 'publish_time' => microtime(true) - $publishStart];
         $this->log(200, "Message published to SNS", $context);
         return $result->get('MessageId');
     }
     $result = $this->sqs->sendMessage(['QueueUrl' => $this->queueUrl, 'MessageBody' => json_encode($message), 'DelaySeconds' => $options['message_delay']]);
     $context = ['QueueUrl' => $this->queueUrl, 'MessageId' => $result->get('MessageId'), 'push_notifications' => $options['push_notifications']];
     $this->log(200, "Message published to SQS", $context);
     return $result->get('MessageId');
 }
Esempio n. 11
0
 /**
  * @depends testSubscribesToTopic
  */
 public function testPublishesTopic($subscriptionArn)
 {
     $result = $this->sns->publish(array('Message' => '{"default":"test","foo":"baz"}', 'Subject' => 'Testing', 'TopicArn' => self::$topicArn));
     $this->assertArrayHasKey('MessageId', $result->toArray());
     self::log('Published a message: ' . $result['MessageId']);
 }
Esempio n. 12
0
$userS3finishedurl = $url;
$status = 0;
$issubscribed = 0;
mysqli_query($link, "INSERT INTO jssUserImages (idTable,userNameTable,userEmailTable,userTelephoneTable,rawS3URLTable,finishedS3URLTable,fileNameTable,stateTable,dateTable) \nVALUES (NULL,'{$name}','{$email}','{$phone}','{$userS3rawurl}','{$userS3finishedurl}','{$filename}','{$status}','NULL')");
$stmt->bind_param("sssssii", $name, $email, $phone, $userS3rawurl, $userS3finishedurl, $filename, $status, $issubscribed);
//execution of SQL insert
if (!$stmt->execute()) {
    echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
printf("%d Row inserted.\n", $stmt->affected_rows);
/* explicit close recommended */
$stmt->close();
$link->real_query("SELECT * FROM jssUserImages");
$res = $link->use_result();
echo "Result set order...\n";
while ($row = $res->fetch_assoc()) {
    print $row['idTable'] . " " . $row['userEmailTable'] . " " . $row['userTelephoneTable'];
}
//using aws sns
use Aws\Sns\SnsClient;
$sns = new Aws\Sns\SnsClient(['version' => 'latest', 'region' => 'us-east-1', 'credentials' => ['key' => '', 'secret' => '']]);
//creating the sns topic
$result = $sns->createTopic(['Name' => 'JSSSNS']);
$snsARN = $result['TopicArn'];
//subscribing user to sns
$result = $sns->subscribe(['Endpoint' => $email, 'Protocol' => 'email', 'TopicArn' => $snsARN]);
//push out the subscription
$result = $sns->publish(['Message' => 'Hello! This is an automated message informing you that your file has been uploaded!', 'Subject' => 'File Uploaded to AWS S3 bucket', 'TopicArn' => $snsARN]);
//this is for the gallery session page
$_SESSION['gallerySession'] = TRUE;
$link->close();
$phone = $_POST['phone'];
$s3rawurl = $url;
$filename = basename($_FILES['userfile']['name']);
$s3finishedurl = $finishedurl;
$status = 0;
$date = '2015-11-10 12:00:00';
$stmt->bind_param("sssssii", $email, $phone, $filename, $s3rawurl, $s3finishedurl, $state, $date);
if (!$stmt->execute()) {
    echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
printf("%d Row inserted.\n", $stmt->affected_rows);
/* explicit close recommended */
$stmt->close();
$link->real_query("SELECT * FROM arshadsTable");
$res = $link->use_result();
echo "Result set order...\n";
while ($row = $res->fetch_assoc()) {
    echo $row['ID'] . " " . $row['email'] . " " . $row['phone'];
}
$sns = new Aws\Sns\SnsClient(['version' => 'latest', 'region' => 'us-east-1']);
$result = $sns->createTopic(['Name' => 'My-New-SNS-topic']);
$topicArn = $result['TopicArn'];
echo "Topic ARN is ::: {$topicArn}";
$result = $sns->setTopicAttributes(['AttributeName' => 'DisplayName', 'AttributeValue' => 'MP2-SNS-TOPIC', 'TopicArn' => $topicArn]);
$result = $sns->subscribe(['Endpoint' => $email, 'Protocol' => 'email', 'TopicArn' => $topicArn]);
sleep(30);
//=======================sleep for 30 seconds so that the user can subscribe==================
$result = $sns->publish(['TopicArn' => $topicArn, 'Subject' => 'Image uploaded', 'Message' => 'Congratulations! Your image has been successfully uploaded']);
$link->close();
header('Location: gallery.php');
exit;
Esempio n. 14
0
 public function killAction($jobId)
 {
     /** @var Search $elasticsearch */
     $elasticsearch = $this->container->get('syrup.elasticsearch.search');
     $job = $elasticsearch->getJob($jobId);
     if ($job == null) {
         throw new SyrupComponentException(404, sprintf("Job '%s' not found", $jobId));
     }
     $sapiData = $this->container->get('syrup.storage_api')->getTokenData();
     $projectId = $sapiData['owner']['id'];
     if ($job->getProject()['id'] != $projectId) {
         throw new SyrupComponentException(404, sprintf("Job id '%s' not found in project", $jobId));
     }
     $sapiEvent = new Event();
     $sapiEvent->setComponent($job->getComponent());
     $sapiEvent->setMessage('Requested job termination');
     $sapiEvent->setRunId($this->storageApi->getRunId());
     $sapiEvent->setType(Event::TYPE_INFO);
     $sapiEvent->setRunId($job->getRunId());
     $sapiEvent->setParams(['jobId' => $jobId]);
     $this->storageApi->createEvent($sapiEvent);
     $snsConfig = $this->container->getParameter('sns');
     $snsClient = new SnsClient(['credentials' => ['key' => $snsConfig['key'], 'secret' => $snsConfig['secret']], 'region' => isset($snsConfig['region']) ? $snsConfig['region'] : 'us-east-1', 'version' => '2010-03-31']);
     $snsClient->publish(['TopicArn' => $snsConfig['topic_arn'], 'Message' => json_encode(['jobId' => $jobId])]);
     $jobData = $job->getData();
     if (array_key_exists('terminatedBy', $jobData)) {
         $job->setTerminatedBy(['id' => $sapiData['id'], 'description' => $sapiData['description']]);
     }
     $jobMapper = $this->getComponentJobMapper($job->getComponent());
     $jobMapper->update($job);
     return $this->createJsonResponse(["message" => "job termination request accepted for processing"], 202);
 }
Esempio n. 15
0
$email = $_POST['email'];
$phone = $_POST['phone'];
$s3rawurl = $url;
$filename = basename($_FILES['userfile']['name']);
$s3finishedurl = $urlren;
$status = 0;
$date = '2015-05-30 10:09:00';
$stmt->bind_param("sssssii", $email, $phone, $filename, $s3rawurl, $s3finishedurl, $state, $date);
if (!$stmt->execute()) {
    echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
printf("%d Row inserted.\n", $stmt->affected_rows);
/* explicit close recommended */
$stmt->close();
$link->real_query("SELECT * FROM jgldata");
$res = $link->use_result();
echo "Result set order...\n";
while ($row = $res->fetch_assoc()) {
    echo $row['ID'] . " " . $row['email'] . " " . $row['phone'];
}
$sns = new Aws\Sns\SnsClient(array('version' => 'latest', 'region' => 'us-east-1'));
$ArnArray = $sns->createTopic(['Name' => 'mp2-jgl-pict']);
$Arn = $ArnArray['TopicArn'];
//Send an email to the user that the original image has been uploaded
$result = $sns->publish(array('TopicArn' => $Arn, 'Message' => 'Orignal Image uploaded successfully', 'Subject' => 'Original Image upload'));
//Send an email to the user that the rendered image has been uploaded
$result = $sns->publish(array('TopicArn' => $Arn, 'Message' => 'Rendered Image uploaded successfully', 'Subject' => 'Rendered Image upload'));
echo "\r\n";
echo "Successfull publish to user";
$link->close();
header('Location: gallery.php');
Esempio n. 16
0
 protected function requeue($jobId)
 {
     sleep(5);
     $snsConfig = $this->getContainer()->getParameter('sns');
     $snsClient = new SnsClient(['credentials' => ['key' => $snsConfig['key'], 'secret' => $snsConfig['secret']], 'region' => isset($snsConfig['region']) ? $snsConfig['region'] : 'us-east-1', 'version' => '2010-03-31']);
     $snsClient->publish(['TopicArn' => $snsConfig['topic_arn'], 'Message' => json_encode(['jobId' => $jobId])]);
 }
 /**
  * @param mixed[] $args
  * @return Result
  * @throws ExceptionInterface
  */
 private function publishClaimCheck(array $args = [])
 {
     $claimCheckSerializer = $this->configuration->getClaimCheckSerializer();
     $message = array_key_exists('Message', $args) ? $args['Message'] : '';
     $claimCheck = $this->storeMessageInS3($message);
     $args['Message'] = $claimCheckSerializer->serialize($claimCheck);
     return $this->snsClient->publish($args);
 }