Esempio n. 1
0
def __sendMessage(queue, messageObject):
    result = apiMgmt.getDefaultResult()

    try:
        # https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sqs.html#SQS.Queue.send_message
        response = queue.send_message(**messageObject)
        logger.info(
            f"awsSqsHelper::__sendMessage() >> response: {jsonHelper.convertObjectToFormattedJson(response)}"
        )

        responseMetaData = response.get(
            CONSTANTS.SQS.RESPONSE.RESPONSE_META_DATA)
        result[CONSTANTS.RESPONSE.PROVIDER_RESPONSE_DATA] = responseMetaData

        responeHttpStatusCode = responseMetaData.get(
            CONSTANTS.SQS.RESPONSE.HTTP_STATUS_CODE)
        if (awsCommonHelper.isResponseHttpStatusCodeSuccess(
                responeHttpStatusCode)):
            apiMgmt.setResultStatusSuccess(result)
            result[
                CONSTANTS.RESPONSE.
                ADDITIONAL_REQUEST_DATA] = __composeSendMessageAdditionalResponseData(
                    response)

    except Exception as ex:
        apiMgmt.setResultFailed(result,
                                exception=str(ex),
                                stackTrace=traceback.format_exc())
        # logger.error(f"awsSqsHelper::__sendMessage() >> Exception has occurred. Error: '{str(ex)}'")

    return result
Esempio n. 2
0
def getQueue(queueName):
    result = apiMgmt.getDefaultResult()

    try:
        if (queueName == None):
            apiMgmt.setResultFailed(result,
                                    exception="Invalid queue Name passed!")
        else:
            # https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sqs.html#SQS.ServiceResource.get_queue_by_name
            queue = __sqsResource.get_queue_by_name(QueueName=queueName)
            result[CONSTANTS.CONTEXT.QUEUE] = queue
            apiMgmt.setResultStatusSuccess(result)
            logger.info(
                f"awsSqsHelper::getQueue() >> SQS Queue - Name: '{queueName}'\
, DelaySeconds: '{queue.attributes.get('DelaySeconds')}'\
, FifoQueue: '{queue.attributes.get('FifoQueue')}'\
, ContentBasedDeduplication: '{queue.attributes.get('ContentBasedDeduplication')}'\
, Url: '{queue.url}'")

    except Exception as ex:
        apiMgmt.setResultFailed(result,
                                exception=str(ex),
                                stackTrace=traceback.format_exc())
        # logger.error(f"awsSqsHelper::getQueue() >> Exception has occurred. Error: '{str(ex)}'")

    return result
Esempio n. 3
0
def getTopic(topicName):
    result = apiMgmt.getDefaultResult()

    try:
        if (topicName == None):
            apiMgmt.setResultFailed(result,
                                    exception="Invalid Topic Name passed!")
        else:
            # https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sns.html#SNS.Client.list_topics
            response = __snsClient.list_topics()
            responseMetaData = response.get(
                CONSTANTS.SNS.RESPONSE.RESPONSE_META_DATA)
            result[
                CONSTANTS.RESPONSE.PROVIDER_RESPONSE_DATA] = responseMetaData

            responeHttpStatusCode = responseMetaData.get(
                CONSTANTS.SNS.RESPONSE.HTTP_STATUS_CODE)
            if (awsCommonHelper.isResponseHttpStatusCodeSuccess(
                    responeHttpStatusCode)):
                for topic in response[CONSTANTS.SNS.RESPONSE.TOPICS]:
                    topicArn = topic.get(CONSTANTS.SNS.RESPONSE.TOPIC_ARN)
                    if (topicArn.find(topicName) != -1):
                        result[CONSTANTS.CONTEXT.TOPIC_ARN] = topicArn
                        apiMgmt.setResultStatusSuccess(result)
                        logger.info(
                            f"awsSnsHelper::getTopic() >> SNS Topic - Name: '{topicName}', TopicArn: '{topicArn}"
                        )

    except Exception as ex:
        apiMgmt.setResultFailed(result,
                                exception=str(ex),
                                stackTrace=traceback.format_exc())
        # logger.error(f"awsSnsHelper::getTopic() >> Exception has occurred. Error: '{str(ex)}'")

    return result
Esempio n. 4
0
def __publishMessage(messageObject):
    result = apiMgmt.getDefaultResult()

    try:
        # https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sns.html#SNS.Client.publish
        response = __snsClient.publish(**messageObject)
        logger.debug(
            f"awsSnsHelper::__publishMessage() >> response: {jsonHelper.convertObjectToFormattedJson(response)}"
        )
        result[CONSTANTS.RESPONSE.MESSAGE_ID] = response.get(
            CONSTANTS.SNS.RESPONSE.MESSAGE_ID)
        responseMetaData = response.get(
            CONSTANTS.SNS.RESPONSE.RESPONSE_META_DATA)
        result[CONSTANTS.RESPONSE.PROVIDER_RESPONSE_DATA] = responseMetaData

        responeHttpStatusCode = responseMetaData.get(
            CONSTANTS.SNS.RESPONSE.HTTP_STATUS_CODE)
        if (awsCommonHelper.isResponseHttpStatusCodeSuccess(
                responeHttpStatusCode)):
            apiMgmt.setResultStatusSuccess(result)

    except Exception as ex:
        apiMgmt.setResultFailed(result,
                                exception=str(ex),
                                stackTrace=traceback.format_exc())
        # logger.error(f"awsSqsHelper::__sendMessage() >> Exception has occurred. Error: '{str(ex)}'")

    return result
Esempio n. 5
0
def deleteMessage(message):
    result = apiMgmt.getDefaultResult()

    try:
        # https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sqs.html#SQS.Message.delete
        result = message.delete()
        apiMgmt.setResultStatusSuccess(result)

    except Exception as ex:
        apiMgmt.setResultFailed(result,
                                exception=str(ex),
                                stackTrace=traceback.format_exc())

    return result
Esempio n. 6
0
def publishMessage(topicName,
                   messageBody,
                   messageAttributes=None,
                   subject=None):
    result = apiMgmt.getDefaultResult()

    try:
        resultGetTopic = getTopic(topicName)
        if (apiMgmt.isResultFailure(resultGetTopic)):
            result = resultGetTopic
        else:
            topicArn = resultGetTopic.get(CONSTANTS.CONTEXT.TOPIC_ARN)

            messageObject = {}

            messageObject[CONSTANTS.SNS.REQUEST.TARGET_ARN] = topicArn
            # Message Body
            messageObject[CONSTANTS.SNS.REQUEST.
                          MESSAGE_BODY] = awsCommonHelper.getMessageJsonString(
                              messageBody)
            # Subject
            if (subject):
                messageObject[CONSTANTS.SNS.REQUEST.SUBJECT] = subject
            # Message Attibutes
            if (messageAttributes):
                newNessageAttributes = awsCommonHelper.serializeDictToAttributeList(
                    messageAttributes)
                messageObject[CONSTANTS.SNS.REQUEST.
                              MESSAGE_ATTRIBUTE] = newNessageAttributes
            logger.info(
                f"awsSnsHelper::sendMessage() >> messageObject: {jsonHelper.convertObjectToFormattedJson(messageObject)}"
            )

            result = __publishMessage(messageObject)

    except Exception as ex:
        apiMgmt.setResultFailed(result,
                                exception=str(ex),
                                stackTrace=traceback.format_exc())

    return result
Esempio n. 7
0
def receiveMessages(queueName,
                    maxNumberOfMessages=5,
                    visibilityTimeoutInSecs=30,
                    waitTimeSecondsInSecs=20,
                    attributeNames=['All'],
                    messageAttributeNames=['All'],
                    messageProcessorFunc=None):
    result = apiMgmt.getDefaultResult()

    try:
        resultGetQueue = getQueue(queueName)
        if (apiMgmt.isResultFailure(resultGetQueue)):
            result = resultGetQueue
        else:
            logger.info(f"awsSqsHelper::receiveMessages() >> parameters:")
            logger.info(
                f"  MaxNumberOfMessages: {maxNumberOfMessages}, VisibilityTimeout: {visibilityTimeoutInSecs} seconds, WaitTimeSeconds: {waitTimeSecondsInSecs} seconds"
            )
            logger.info(
                f"  QueueName: '{queueName}', MessageAttributeNames: {messageAttributeNames}, AttributeNames: {attributeNames}"
            )

            queue = resultGetQueue.get(CONSTANTS.CONTEXT.QUEUE)
            # https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sqs.html#SQS.Queue.receive_messages
            messages = queue.receive_messages(
                AttributeNames=attributeNames,
                MessageAttributeNames=messageAttributeNames,
                MaxNumberOfMessages=maxNumberOfMessages,
                VisibilityTimeout=visibilityTimeoutInSecs,
                WaitTimeSeconds=waitTimeSecondsInSecs)

            result[CONSTANTS.CONTEXT.MESSAGES] = messages
            apiMgmt.setResultStatusSuccess(result)

    except Exception as ex:
        apiMgmt.setResultFailed(result,
                                exception=str(ex),
                                stackTrace=traceback.format_exc())

    return result
Esempio n. 8
0
def sendMessage(queueName,
                messageBody,
                messageAttributes=None,
                messageId=None,
                messageGroupId=None,
                messageDeduplicationId=None):
    result = apiMgmt.getDefaultResult()

    try:
        resultGetQueue = getQueue(queueName)
        if (apiMgmt.isResultFailure(resultGetQueue)):
            result = resultGetQueue
        else:
            queueObj = resultGetQueue.get(CONSTANTS.CONTEXT.QUEUE)
            isFifoQueue = awsCommonHelper.getAwsObjectBooleanAttributeValue(
                queueObj, "FifoQueue", False)
            isContentBasedDeduplication = awsCommonHelper.getAwsObjectBooleanAttributeValue(
                queueObj, "ContentBasedDeduplication", False)

            messageObject = {}
            # Message ID
            if (messageId):
                messageObject[CONSTANTS.SQS.REQUEST.ID] = messageId
            # Message Group ID
            #       The tag that specifies that a message belongs to a specific message group. Messages that belong to the same message
            #       group are processed in a FIFO manner (however, messages in different message groups might be processed out of order)
            if (isFifoQueue == True and messageGroupId == None):
                messageObject[CONSTANTS.SQS.REQUEST.MESSAGE_GROUP_ID] = str(
                    uuid.uuid4())
            elif (isFifoQueue == True and messageGroupId):
                messageObject[
                    CONSTANTS.SQS.REQUEST.MESSAGE_GROUP_ID] = messageGroupId
            # Message Deduplication ID
            #       The token used for deduplication of sent messages, Use for deduplicating messages with Deduplication Interval
            #       If ContentBasedDeduplication is enabled then this parameter is optional, if provided it will be used first
            if (isFifoQueue == True and messageDeduplicationId):
                messageObject[
                    CONSTANTS.SQS.REQUEST.
                    MESSAGE_DEDUPLICATION_ID] = messageDeduplicationId
            elif (isFifoQueue == True and messageDeduplicationId == None
                  and isContentBasedDeduplication == False):
                messageObject[
                    CONSTANTS.SQS.REQUEST.MESSAGE_DEDUPLICATION_ID] = str(
                        uuid.uuid4())
            # Message Body
            messageObject[CONSTANTS.SQS.REQUEST.
                          MESSAGE_BODY] = awsCommonHelper.getMessageJsonString(
                              messageBody)
            # Message Attibutes
            if (messageAttributes):
                newNessageAttributes = awsCommonHelper.serializeDictToAttributeList(
                    messageAttributes)
                messageObject[CONSTANTS.SQS.REQUEST.
                              MESSAGE_ATTRIBUTE] = newNessageAttributes
            logger.info(
                f"awsSqsHelper::sendMessage() >> messageObject: {jsonHelper.convertObjectToFormattedJson(messageObject)}"
            )

            result = __sendMessage(queueObj, messageObject)

    except Exception as ex:
        apiMgmt.setResultFailed(result,
                                exception=str(ex),
                                stackTrace=traceback.format_exc())

    return result