Esempio n. 1
0
	def SetQueueAttributes(self, queueUrl, AttributeName, AttributeValue):
		"""The setQueueAttributes action sets one attribute of a queue per request. When you change a queue's attributes,
			the change can take up to 60 seconds to propagate throughout the SQS system.

			AttributeName -- The name of the attribute you want to set. One of:
				VisibilityTimeout - The length of time (in seconds) that a message received from a queue will be invisible to
					other receiving components when they ask to receive messages. For more information about VisibilityTimeout,
					see Visibility Timeout in the Amazon SQS Developer Guide.
				Policy - The formal description of the permissions for a resource. For more information about Policy, see Basic
					Policy Structure in the Amazon SQS Developer Guide.
				MaximumMessageSize - The limit of how many bytes a message can contain before Amazon SQS rejects it.
				MessageRetentionPeriod - The number of seconds Amazon SQS retains a message.
			AttributeValue -- The value of the attribute you want to set. To delete a queue's access control policy,
				set the policy to "". Values supplied depend on AttributeName, as follows:
				VisibilityTimeout - An integer from 0 to 43200 (12 hours).
				Policy - A valid json-encoded policy. For more information about policy structure, see
					Basic Policy Structure in the Amazon SQS Developer Guide.
				MaximumMessageSize - An integer from 1024 bytes (1KB) up to 65536 bytes (64KB). The default
					for this attribute is 8192 (8KB).
				MessageRetentionPeriod - Integer representing seconds, from 3600 (1 hour) to 1209600 (14 days).
					The default for this attribute is 345600 (4 days).
			Returns True on success
			"""

		def response(status, reason, data):
			if status == 200:
				return True
			raise AWSError(status, reason, data)
		p = urlparse(queueUrl)
		return request.AWSRequest(self._endpoint, p.path, self._key, self._secret, 'SetQueueAttributes', {
			'Version': self.version,
			'Attribute.Name': AttributeName,
			'Attribute.Value': AttributeValue,
		}, response)
Esempio n. 2
0
    def AddPermission(self, TopicArn, Permissions, Label):
        """The AddPermission action adds a statement to a topic's access control policy,
                granting access for the specified AWS accounts to the specified actions.

                TopicArn -- The ARN of the topic whose access control policy you wish to modify.
                Permissions -- Either a dict or an iterable of tuples of the form (AWSAccountId, ActionName)
                        AWSAccountId - An AWS account ID of the user (principal) who will be
                                given access to the specified actions. The user must have an AWS account, but
                                does not need to be signed up for this service.
                        ActionName - the name of a method (e.g. publish) this accountid may call.
                Label -- A unique identifier for the new policy statement.

                Returns -- True if HTTP request succeeds
                """
        def response(status, reason, data):
            if status == 200:
                return True
            raise AWSError(status, reason, data)

        r = request.AWSRequest(self._endpoint, '/', self._key, self._secret,
                               'AddPermission', {
                                   'TopicArn': TopicArn,
                                   'Label': Label,
                               }, response)
        if hasattr(Permissions, 'items'):
            Permissions = Permissions.items()
        for idx, (accountid, action) in enumerate(Permissions):
            r.addParm('AWSAccountId.member.%d' % (idx + 1), accountid)
            r.addParm('ActionName.member.%d' % (idx + 1), action)
        return r
Esempio n. 3
0
    def DeleteQueue(self, queueUrl):
        """The DeleteQueue action deletes the queue specified by the queue URL, regardless of whether the queue is empty.
            If the specified queue does not exist, SQS returns a successful response.
            Caution: Use DeleteQueue with care; once you delete your queue, any messages in the queue are no longer available.

            When you delete a queue, the deletion process takes up to 60 seconds. Requests you send involving that queue
            during the 60 seconds might succeed. For example, a sendMessage request might succeed, but after the 60 seconds,
            the queue and that message you sent no longer exist. Also, when you delete a queue, you must wait at least 60
            seconds before creating a queue with the same name.

            Amazon reserves the right to delete queues that have had no activity for more than 30 days. For more information,
            see About SQS Queues in the Amazon SQS Developer Guide.

            queueUrl - As obtained by CreateQueue
            Returns True on success
            """
        def response(status, reason, data):
            if status == 200:
                return True
            raise AWSError(status, reason, data)

        p = urlparse(queueUrl)
        return request.AWSRequest(self._endpoint, p.path, self._key,
                                  self._secret, 'DeleteQueue', {
                                      'Version': self.version,
                                  }, response)
Esempio n. 4
0
	def Select(self, SelectExpression, NextToken=None, ConsistentRead=None, boxusage=None):
		"""The Select operation returns a set of Attributes for ItemNames that match the select expression. Select is
			similar to the standard SQL SELECT statement.

			Amazon SimpleDB keeps multiple copies of each domain. When data is written or updated, all copies of the data are
			updated. However, it takes time for the update to propagate to all storage locations. The data will eventually be
			consistent, but an immediate read might not show the change. If eventually consistent reads are not acceptable for
			your application, use ConsistentRead. Although this operation might take longer than a standard read, it always
			returns the last updated value.

			The total size of the response cannot exceed 1 MB. Amazon SimpleDB automatically adjusts the number of items
			returned per page to enforce this limit. For example, even if you ask to retrieve 2500 items, but each individual
			item is 10 KB in size, the system returns 100 items and an appropriate next token so you can get the next page of
			results.

			For information on how to construct select expressions, see Using Select to Create Amazon SimpleDB Queries.

			NOTE: Operations that run longer than 5 seconds return a time-out error response or a partial or empty result set.
			Partial and empty result sets contains a next token which allow you to continue the operation from where it left off.
			Responses larger than one megabyte return a partial result set.
			Your application should not excessively retry queries that return RequestTimeout errors. If you receive too many
			RequestTimeout errors, reduce the complexity of your query expression.
			When designing your application, keep in mind that Amazon SimpleDB does not guarantee how attributes are ordered
			in the returned response.
			For information about limits that affect Select, see Limits.
			The select operation is case-sensitive.

			SelectExpression -- The expression used to query the domain.
			NextToken -- String that tells Amazon SimpleDB where to start the next list of ItemNames.
			ConsistentRead -- When set to true, ensures that the most recent data is returned. For more information, see Consistency

			returns a list of items which are tuples of (ItemName, Attributes) where Attributes is a list of (Name, Value) tuples.
			"""

		def response(status, reason, data):
			if status == 200:
#				print data
				root = ET.fromstring(data)
				if boxusage is not None:
					boxusage.append(root.find('.//{%s}BoxUsage' % self.xmlns).text)
				items = []
				for node in root.findall('.//{%s}Item' % self.xmlns):
					name = node.find('{%s}Name' % self.xmlns).text
					attribs = []
					for attr in node.findall('{%s}Attribute' % self.xmlns):
						attribs.append((attr.find('{%s}Name' % self.xmlns).text, attr.find('{%s}Value' % self.xmlns).text))
					items.append((name, attribs))
				token = None
				node = root.find('.//{%s}NextToken')
				if node is not None:
					token = node.text
				return items, token
			raise AWSError(status, reason, data)

		return request.AWSRequest(self._endpoint, '/', self._key, self._secret, 'Select', {
				'SelectExpression': SelectExpression,
				'NextToken': NextToken,
				'ConsistentRead': ConsistentRead,
				'Version': self.version,
			}, response, request.ListFollow)
Esempio n. 5
0
	def ListDomains(self, MaxDomains=100, NextToken=None):
		"""The ListDomains operation lists all domains associated with the Access Key ID. It returns domain names up to
			the limit set by MaxNumberOfDomains. A NextToken is returned if there are more than MaxNumberOfDomains domains.
			Calling ListDomains successive times with the NextToken returns up to MaxNumberOfDomains more domain names each
			time.

			MaxNumberOfDomains -- The maximum number of domain names you want returned.
			NextToken -- String that tells Amazon SimpleDB where to start the next list of domain names.

			returns [domains], nextToken
			"""

		def response(status, reason, data):
			if status == 200:
#				print data
				root = ET.fromstring(data)
				result = root.find('.//{%s}ListDomainsResult' % self.xmlns)
				domains = []
				for node in result.findall('{%s}DomainName' % self.xmlns):
					domains.append(node.text)
				token = None
				node = root.find('.//{%s}NextToken' % self.xmlns)
				if node is not None:
					token = node.text
				return domains, token
			raise AWSError(status, reason, data)
		return request.AWSRequest(self._endpoint, '/', self._key, self._secret, 'ListDomains', {
				'MaxDomains': MaxDomains,
				'NextToken': NextToken,
				'Version': self.version,
			}, response, request.ListFollow)
Esempio n. 6
0
    def CreateQueue(self, QueueName, DefaultVisibilityTimeout=None):
        """The CreateQueue action creates a new queue.
            When you request CreateQueue, you provide a name for the queue. To successfully create a new queue, you must provide
            a name that is unique within the scope of your own queues. If you provide the name of an existing queue, a new queue
            isn't created and an error isn't returned. Instead, the request succeeds and the queue URL for the existing queue
            is returned (for more information about queue URLs, see Queue and Message Identifiers in the Amazon SQS Developer Guide).
            Exception: if you provide a value for DefaultVisibilityTimeout that is different from the value for the existing queue, you receive an error.
            Note: If you delete a queue, you must wait at least 60 seconds before creating a queue with the same name.

            QueueName -- String name to use for the queue created.
                Constraints: Maximum 80 characters; alphanumeric characters, hyphens (-), and underscores (_) are allowed
            DefaultVisibilityTimeout -- Integer visibility timeout (in seconds) to use for this queue.
                Constraints: 0 to 43200 (maximum 12 hours)
                Default: 30 seconds

            Returns queueUrl (to be supplied to other SQS methods)
            """
        def response(status, reason, data):
            if status == 200:
                root = ET.fromstring(data)
                node = root.find(
                    './/{http://queue.amazonaws.com/doc/%s/}QueueUrl' %
                    self.version)
                if node is not None:
                    return node.text
            raise AWSError(status, reason, data)

        return request.AWSRequest(
            self._endpoint, '/', self._key, self._secret, 'CreateQueue', {
                'QueueName': QueueName,
                'Version': self.version,
                'DefaultVisibilityTimeout': DefaultVisibilityTimeout,
            }, response)
Esempio n. 7
0
	def ChangeMessageVisibility(self, queueUrl, ReceiptHandle, VisibilityTimeout):
		"""The changeMessageVisibility action changes the visibility timeout of a specified message in a queue to a new value. The maximum
			allowed timeout value you can set the value to is 12 hours. This means you can't extend the timeout of a message in an existing
			queue to more than a total visibility timeout of 12 hours. (For more information visibility timeout, see Visibility Timeout in
			the Amazon SQS Developer Guide.)

			For example, let's say the timeout for the queue is 30 seconds, and you receive a message. Once you're 20 seconds into the
			timeout for that message (i.e., you have 10 seconds left), you extend it by 60 seconds by calling changeMessageVisibility with
			VisibilityTimeoutset to 60 seconds. You have then changed the remaining visibility timeout from 10 seconds to 60 seconds.

			Important: If you attempt to set the VisibilityTimeout to an amount more than the maximum time left, Amazon SQS returns an error.
			It will not automatically recalculate and increase the timeout to the maximum time remaining.

			Important: Unlike with a queue, when you change the visibility timeout for a specific message, that timeout value is applied
			immediately but is not saved in memory for that message. If you don't delete a message after it is received, the visibility timeout
			for the message the next time it is received reverts to the original timeout value, not the value you set with the
			changeMessageVisibility action.

			ReceiptHandle -- The receipt handle associated with the message whose visibility timeout you want to change. This parameter is
				returned by the ReceiveMessage action.
			VisibilityTimeout -- The new value for the message's visibility timeout (in seconds).
				Constraints: Integer from 0 to 43200 (maximum 12 hours)
			Returns True on success
			"""

		def response(status, reason, data):
			if status == 200:
				return True
			raise AWSError(status, reason, data)
		p = urlparse(queueUrl)
		return request.AWSRequest(self._endpoint, p.path, self._key, self._secret, 'ChangeMessageVisibility', {
			'Version': self.version,
			'ReceiptHandle': ReceiptHandle,
			'VisibilityTimeout': VisibilityTimeout,
		}, response)
Esempio n. 8
0
    def CreateTopic(self, Name):
        """The CreateTopic action creates a topic to which notifications can be published.
                Users can create at most 25 topics. This action is idempotent, so if the requester
                already owns a topic with the specified name, that topic's ARN will be returned
                without creating a new topic.

                Name -- The name of the topic you want to create.
                        Constraints: Topic names must be made up of only uppercase and lowercase ASCII
                        letters, numbers, and hyphens, and must be between 1 and 256 characters long.
                        Type: String
                        Required: Yes

                Returns -- TopicArn
                        The Amazon Resource Name (ARN) assigned to the created topic.
                        Type: String
        """
        def response(status, reason, data):
            if status == 200:
                root = ET.fromstring(data)
                node = root.find('.//{%s}TopicArn' % self.xmlns)
                if node is not None:
                    return node.text
            raise AWSError(status, reason, data)

        return request.AWSRequest(self._endpoint, '/', self._key, self._secret,
                                  'CreateTopic', {
                                      'Name': Name,
                                  }, response)
Esempio n. 9
0
    def ListSubscriptionsByTopic(self, TopicArn, NextToken=None):
        """The ListSubscriptionsByTopic action returns a list of the subscriptions to a specific
                topic. Each call returns a limited list of subscriptions, up to 100. If there are more
                subscriptions, a NextToken is also returned. Use the NextToken parameter in a new
                ListSubscriptionsByTopic call to get further results.

                TopicArn -- The ARN of the topic you want to delete.
                        Type: String
                        Required: Yes

                NextToken -- Token returned by the previous listTopics request.
                        Type: String
                        Required: No

                Returns -- Subscriptions, NextToken
                        NextToken -- Token to pass along to the next ListSubscriptions request. This
                                element is returned if there are additional topics to retrieve. (Otherwise None)
                        Subscriptions -- A list of dicts. Each dict contains the following keys:
                                TopicArn, Protocol, SubscriptionArn, Owner, Endpoint
                """

        return request.AWSRequest(self._endpoint, '/', self._key, self._secret,
                                  'ListSubscriptionsByTopic', {
                                      'TopicArn': TopicArn,
                                      'NextToken': NextToken,
                                  }, self._Response_ListSubscriptions,
                                  request.ListFollow)
Esempio n. 10
0
    def GetTopicAttributes(self, TopicArn):
        """The GetTopicAttributes action returns all of the properties of a topic customers
                have created. Topic properties returned might differ based on the authorization of
                the user.

                TopicArn -- The ARN of the topic you want to delete.
                        Type: String
                        Required: Yes

                Returns -- A dict of the topic's attributes. Attributes in this map include:
                        TopicArn -- the topic's ARN
                        Owner -- the AWS account ID of the topic's owner
                        Policy -- the JSON serialization of the topic's access control policy
                        DisplayName -- the human-readable name used in the "From" field for notifications
                                to email and email-json endpoints
                        Type: dict(String -> String)
                """
        def response(status, reason, data):
            if status == 200:
                root = ET.fromstring(data)
                attrib = {}
                for node in root.findall('.//{%s}entry' % self.xmlns):
                    name = node.find('{%s}key' % self.xmlns)
                    val = node.find('{%s}value' % self.xmlns)
                    attrib[name.text] = val.text
                return attrib
            raise AWSError(status, reason, data)

        return request.AWSRequest(self._endpoint, '/', self._key, self._secret,
                                  'GetTopicAttributes', {
                                      'TopicArn': TopicArn,
                                  }, response)
Esempio n. 11
0
    def SendMessageBatch(self, queueUrl, MessageBodyList):
        """The sendMessageBatch action delivers a message to the specified queue.

        MessageBodyList -- A list of MessageBody as in SendMessage

        Returns MessageId, MD5OfMessageBody (both strings)
        """
        def response(status, reason, data):
            if status == 200:
                root = ET.fromstring(data)
                n1 = root.findall(
                    './/{http://queue.amazonaws.com/doc/%s/}MD5OfMessageBody' %
                    self.version)
                n2 = root.findall(
                    './/{http://queue.amazonaws.com/doc/%s/}MessageId' %
                    self.version)
                if n1 is not None and n2 is not None:
                    return [(a.text, b.text) for a, b in zip(n1, n2)]

            raise AWSError(status, reason, data)

        params = {
            'Version': self.version,
        }

        for idx, message in enumerate(MessageBodyList):
            idx += 1
            params['SendMessageBatchRequestEntry.%d.Id' % idx] = "msg%d" % idx
            params['SendMessageBatchRequestEntry.%d.MessageBody' %
                   idx] = message

        p = urlparse(queueUrl)
        return request.AWSRequest(self._endpoint, p.path, self._key,
                                  self._secret, 'SendMessageBatch', params,
                                  response)
Esempio n. 12
0
    def CreatePlatformEndpoint(self,
                               PlatformApplicationArn,
                               Token,
                               CustomUserData=None,
                               Attributes=None):
        """Creates an endpoint for a device and mobile app on one of the supported push notification services,
			such as GCM and APNS. CreatePlatformEndpoint requires the PlatformApplicationArn that is returned from
			CreatePlatformApplication. The EndpointArn that is returned when using CreatePlatformEndpoint can then
			be used by the Publish action to send a message to a mobile app or by the Subscribe action for
			subscription to a topic.

			The CreatePlatformEndpoint action is idempotent, so if the requester already owns an endpoint with the
			same device token and attributes, that endpoint's ARN is returned without creating a new endpoint.
			For more information, see Using Amazon SNS Mobile Push Notifications.

			PlatformApplicationArn -- PlatformApplicationArn returned from CreatePlatformApplication is used to
										create an endpoint.
				Type: String
				Required: Yes

			Token -- Unique identifier created by the notification service for an app on a device. The specific
						name for Token will vary, depending on which notification service is being used.
						For example, when using APNS as the notification service, you need the device token.
						Alternatively, when using GCM or ADM, the device token equivalent is called the registration ID.
				Type: String
				Required: Yes

			CustomUserData - Arbitrary user data to associate with the endpoint. Amazon SNS does not use this data.
								The data must be in UTF-8 format and less than 2KB.
				Type: String
				Required: No

			Attributes - For a list of attributes, see SetEndpointAttributes.
				Type: enumerable of (key, value) Strings. Can also be a dict of String->String
				Required: No
		"""
        def response(status, reason, data):
            if status == 200:
                root = ET.fromstring(data)
                node = root.find(
                    './/{http://sns.amazonaws.com/doc/2010-03-31/}EndpointArn')
                if node is not None:
                    return node.text
            raise AWSError(status, reason, data)

        r = request.AWSRequest(
            self._endpoint, '/', self._key, self._secret,
            'CreatePlatformEndpoint', {
                'PlatformApplicationArn': PlatformApplicationArn,
                'Token': Token,
            }, response)
        if CustomUserData is not None:
            r.addParm('CustomUserData', CustomUserData)
        if Attributes is not None:
            if hasattr(Attributes, 'items'):
                Attributes = Attributes.items()
            for idx, (key, value) in enumerate(Attributes):
                r.addParm('Attributes.entry.%d.key' % (idx + 1), str(key))
                r.addParm('Attributes.entry.%d.value' % (idx + 1), str(value))
        return r
Esempio n. 13
0
    def SendMessage(self, queueUrl, MessageBody):
        """The sendMessage action delivers a message to the specified queue. The maximum allowed message size is 64 KB.

            MessageBody -- The string message to send. maximum 64 KB in size.
                Conditions: Characters are in the following range #x9 | #xA | #xD | [#x20 to #xD7FF] | [#xE000 to #xFFFD] | [#x10000 to #x10FFFF]

            Returns MessageId, MD5OfMessageBody (both strings)
        """
        def response(status, reason, data):
            if status == 200:
                root = ET.fromstring(data)
                n1 = root.find(
                    './/{http://queue.amazonaws.com/doc/%s/}MD5OfMessageBody' %
                    self.version)
                n2 = root.find(
                    './/{http://queue.amazonaws.com/doc/%s/}MessageId' %
                    self.version)
                if n1 is not None and n2 is not None:
                    return n2.text, n1.text
            raise AWSError(status, reason, data)

        p = urlparse(queueUrl)
        return request.AWSRequest(self._endpoint, p.path, self._key,
                                  self._secret, 'SendMessage', {
                                      'Version': self.version,
                                      'MessageBody': MessageBody,
                                  }, response)
Esempio n. 14
0
    def ListTopics(self, NextToken=None):
        """The ListTopics action returns a list of the requester's topics. Each call returns a
                limited list of topics, up to 100. If there are more topics, a NextToken is also
                returned. Use the NextToken parameter in a new ListTopics call to get further results.

                NextToken -- Token returned by the previous ListTopics request.
                        Type: String
                        Required: No

                Returns -- Topics, NextToken
                        NextToken -- Token to pass along to the next ListTopics request. This element is
                                returned if there are additional topics to retrieve. (Otherwise None)
                        Topics -- A list of topic ARNs.
                """
        def response(status, reason, data):
            if status == 200:
                root = ET.fromstring(data)
                token = None
                node = root.find('.//{%s}NextToken' % self.xmlns)
                if node is not None:
                    token = node.text
                topics = []
                for node in root.findall('.//{%s}TopicArn' % self.xmlns):
                    topics.append(node.text)
                return topics, token
            raise AWSError(status, reason, data)

        return request.AWSRequest(self._endpoint, '/', self._key, self._secret,
                                  'ListTopics', {
                                      'NextToken': NextToken,
                                  }, response, request.ListFollow)
Esempio n. 15
0
    def SetTopicAttributes(self, TopicArn, AttributeName, AttributeValue):
        """The SetTopicAttributes action allows a topic owner to set an attribute of the topic to a
                new value.

                TopicArn -- The ARN of the topic to modify.
                        Type: String
                        Required: Yes

                AttributeName -- The name of the attribute you want to set. Only a subset of the topic's
                                attributes are mutable.
                        Valid values: Policy | DisplayName
                        Type: String
                        Required: Yes

                AttributeValue -- The new value for the attribute.
                        Type: String
                        Required: Yes

                Returns -- True if HTTP request succeeds
                """
        def response(status, reason, data):
            if status == 200:
                return True
            raise AWSError(status, reason, data)

        return request.AWSRequest(
            self._endpoint, '/', self._key, self._secret, 'SetTopicAttributes',
            {
                'TopicArn': TopicArn,
                'AttributeName': AttributeName,
                'AttributeValue': AttributeValue,
            }, response)
Esempio n. 16
0
    def CreateDomain(self, DomainName):
        """The CreateDomain operation creates a new domain. The domain name must be unique among the domains
                associated with the Access Key ID provided in the request. The CreateDomain operation might take 10
                or more seconds to complete.

                NOTE: CreateDomain is an idempotent operation; running it multiple times using the same domain name will not result
                in an error response.
                You can create up to 250 domains per account.
                If you require additional domains, go to http://aws.amazon.com/contact-us/simpledb-limit-request/.

                DomainName -- The name of the domain to create. The name can range between 3 and 255 characters and can contain the
                        following characters: a-z, A-Z, 0-9, '_', '-', and '.'.

                returns True on success
                """
        def response(status, reason, data):
            if status == 200:
                return True
            raise AWSError(status, reason, data)

        return request.AWSRequest(self._endpoint, '/', self._key, self._secret,
                                  'CreateDomain', {
                                      'DomainName': DomainName,
                                      'Version': self.version,
                                  }, response)
Esempio n. 17
0
    def ReceiveMessage(self,
                       queueUrl,
                       AttributeNames=None,
                       MaxNumberOfMessages=None,
                       VisibilityTimeout=None):
        """The receiveMessage action retrieves one or more messages from the specified queue.

            AttributeNames -- A list of strings giving the attribute names you wish to receive. If not supplied then no attributes are returned.
                Valid values: All | SenderId | SentTimestamp | ApproximateReceiveCount | ApproximateFirstReceiveTimestamp

            MaxNumberOfMessages -- Maximum number of messages to return (1 to 10). SQS never returns more messages than this value but might return fewer.
                Default: 1

            VisibilityTimeout -- The duration (in seconds) that the received messages are hidden from subsequent retrieve requests after being
                    retrieved by a ReceiveMessage request.
                Constraints: 0 to 43200 (maximum 12 hours)
                Default: The visibility timeout for the queue

            Returns a list of dicts. Each dict contains the following keys (and any AttributeNames requested):
                Body - The message body
                MD5OfBody - MD5 checksum
                MessageId - Unique Id for this message
                ReceiptHandle - required for calls to ChangeMessageVisibility + DeleteMessage
            """
        def response(status, reason, data):
            def findadd(m, node, attr):
                node = node.find('{%s}%s' % (self.xmlns, attr))
                if node is not None:
                    m[attr] = node.text

            if status == 200:
                root = ET.fromstring(data)
                msgs = []
                for node in root.findall('.//{%s}Message' % self.xmlns):
                    m = {}
                    findadd(m, node, 'Body')
                    findadd(m, node, 'MD5OfBody')
                    findadd(m, node, 'MessageId')
                    findadd(m, node, 'ReceiptHandle')
                    for attrnode in node.findall('{%s}Attribute' % self.xmlns):
                        name = attrnode.find('{%s}Name' % self.xmlns).text
                        value = attrnode.find('{%s}Value' % self.xmlns).text
                        m[name] = value
                    msgs.append(m)
                return msgs
            raise AWSError(status, reason, data)

        p = urlparse(queueUrl)
        r = request.AWSRequest(
            self._endpoint, p.path, self._key, self._secret, 'ReceiveMessage',
            {
                'Version': self.version,
                'MaxNumberOfMessages': MaxNumberOfMessages,
                'VisibilityTimeout': VisibilityTimeout,
            }, response)
        if AttributeNames is not None:
            for idx, attr in enumerate(AttributeNames):
                r.addParm('AttributeName.%d' % (idx + 1), attr)
        return r
Esempio n. 18
0
    def DeleteAttributes(self,
                         DomainName,
                         ItemName,
                         Attributes=None,
                         Expected=None):
        """Deletes one or more attributes associated with the item. If all attributes of an item are deleted, the item is deleted.

                NOTE: If you specify DeleteAttributes without attributes, all the attributes for the item are deleted.
                Unless you specify conditions, the DeleteAttributes is an idempotent operation; running it multiple times on the same item
                or attribute does not result in an error response.
                Conditional deletes are useful for only deleting items and attributes if specific conditions are met. If the conditions are
                met, Amazon SimpleDB performs the delete. Otherwise, the data is not deleted.
                When using eventually consistent reads, a getAttributes or select request (read) immediately after a DeleteAttributes or
                Put Attributes request (write) might not return the updated data. A consistent read always reflects all writes that received
                a successful response prior to the read. For more information, see Consistency.
                You can perform the expected conditional check on one attribute per operation.

                DomainName -- The name of the domain in which to perform the operation.
                        Type: String
                        Required: Yes
                ItemName -- The name of the item.
                        Type: String
                        Required: Yes
                Attributes -- Either a dict or iterable of tuples/strings specifying the attributes to be deleted. Each 'key' specifies the
                        attribute name to delete; if a value is specified (not None) then only the specified key/value is deleted (for multi-value
                        attributes).
                        Type: dict or iterable of tuples/strings
                        Required: No
                """
        def response(status, reason, data):
            if status == 200:
                return True
            raise AWSError(status, reason, data)

        r = request.AWSRequest(
            self._endpoint, '/', self._key, self._secret, 'DeleteAttributes', {
                'DomainName': DomainName,
                'ItemName': ItemName,
                'Version': self.version,
            }, response)
        if Attributes is not None:
            if hasattr(Attributes, 'items'):
                Attributes = Attributes.items()
            for idx, (name, value) in enumerate(Attributes):
                r.addParm('Attribute.%d.Name' % idx, name)
                r.addParm('Attribute.%d.Value' % idx, value)
        if Expected is not None:
            if hasattr(Expected, 'items'):
                Expected = Expected.items()
            for idx, (name, value) in enumerate(Expected):
                r.addParm('Expected.%d.Name' % idx, name)
                if value is None:
                    r.addParm('Expected.%d.Exists' % idx, True)
                else:
                    r.addParm('Expected.%d.Value' % idx, value)
                    r.addParm('Expected.%d.Exists' % idx, False)
        return r
Esempio n. 19
0
    def DescribeInstances(self, InstanceIds=None, Filters=None):
        """Returns information about instances that you own. If you specify one or more instance IDs, Amazon EC2 returns information
                for those instances. If you do not specify instance IDs, Amazon EC2 returns information for all relevant instances. If
                you specify an invalid instance ID, an error is returned. If you specify an instance that you do not own, it will not be
                included in the returned results.
                Recently terminated instances might appear in the returned results.This interval is usually less than one hour.
                You can filter the results to return information only about instances that match criteria you specify. For example, you
                could get information about only instances launched with a certain key pair. You can specify multiple values for a filter
                (e.g., the instance was launched with either key pair A or key pair B). An instance must match at least one of the
                specified values for it to be included in the results.
                You can specify multiple filters (e.g., the instance was launched with a certain key pair and uses an Amazon EBS volume
                as the root device). An instance must match all the filters for it to be included in the results. If there's no match, no
                special message is returned; the response is simply empty.
                You can use wildcards with the filter values: * matches zero or more characters, and ? matches exactly one character. You
                can escape special characters using a backslash before the character. For example, a value of \\*amazon\\?\\\\ searches for
                the literal string *amazon?\\.
                """

        def findadd(m, node, attr):
            for part in attr.split('.'):
                if node is None:
                    break
                node = node.find('{%s}%s' % (self.xmlns, part))
            if node is not None:
                m[attr] = node.text

        def response(status, reason, data):
            if status == 200:
#                               print data
                root = ET.fromstring(data)
                instances = []
                for node in root.findall('.//{%s}instancesSet' % self.xmlns):
                    for item in node.findall('{%s}item' % self.xmlns):
                        i = {}
                        for attr in ('instanceId', 'imageId', 'privateDnsName', 'dnsName', 'keyName', 'amiLaunchIndex', 'instanceType', 'launchTime',
                                        'kernelId', 'privateIpAddress', 'ipAddress', 'architecture', 'rootDeviceType', 'rootDeviceName', 'virtualizationType',
                                        'instanceState.code', 'instanceState.name', 'placement.availabilityZone', 'placement.tenancy', 'monitoring.state', 'hypervisor'):
                            findadd(i, item, attr)
                        # XXX: groupSet, blockDeviceMapping
                        tags = {}
                        tagSet = item.find('{%s}tagSet' % self.xmlns)
                        for tagitem in tagSet.findall('{%s}item' % self.xmlns):
                            tags[tagitem.find('{%s}key' % self.xmlns).text] = tagitem.find('{%s}value' % self.xmlns).text
                        i['tags'] = tags
                        instances.append(i)
                return instances
            raise AWSError(status, reason, data)

        r = request.AWSRequest(self._endpoint, '/', self._key, self._secret, 'DescribeInstances', {
                        'Version': self.version,
                }, response)
        if InstanceIds is not None:
            for idx, iid in enumerate(InstanceIds):
                r.addParm('InstanceId.%d' % idx, iid)
        # XXX: Filters
        return r
Esempio n. 20
0
	def DeleteMessage(self, queueUrl, receiptHandle):
		"""The DeleteMessage action deletes the specified message from the specified queue. You specify the message by using the message's receipt
			handle and not the message ID you received when you sent the message. Even if the message is locked by another reader due to the visibility
			timeout setting, it is still deleted from the queue. If you leave a message in the queue for more than 4 days, SQS automatically deletes it."""

		def response(status, reason, data):
			if status == 200:
				return True
			raise AWSError(status, reason, data)
		p = urlparse(queueUrl)
		return request.AWSRequest(self._endpoint, p.path, self._key, self._secret, 'DeleteMessage', {
			'Version': '2009-02-01',
			'ReceiptHandle': receiptHandle,
		}, response)
Esempio n. 21
0
    def ConfirmSubscription(self,
                            TopicArn,
                            Token,
                            AuthenticateOnUnsubscribe=None):
        """The ConfirmSubscription action verifies an endpoint owner's intent to receive messages
                by validating the token sent to the endpoint by an earlier subscribe action. If the
                token is valid, the action creates a new subscription and returns its Amazon Resource
                Name (ARN). This call requires an AWS signature only when the AuthenticateOnUnsubscribe
                flag is set to "true".

                TopicArn -- The ARN of the topic whose access control policy you wish to modify.
                        Type: String
                        Required: Yes

                Token -- Short-lived token sent to an endpoint during the subscribe action.
                        Type: String
                        Required: Yes

                AuthenticateOnUnsubscribe -- Indicates that you want to disable unauthenticated
                                unsubsciption of the subscription. If parameter is present in the request, the
                                request has an AWS signature, and the value of this parameter is true, only the
                                topic owner and the subscription owner will be permitted to unsubscribe the
                                endpoint, and the unsubscribe action will require AWS authentication.
                        Type: String
                        Required: No

                Returns -- SubscriptionArn
                        The ARN of the created subscription.
                        Type: String
                """
        def response(status, reason, data):
            if status == 200:
                root = ET.fromstring(data)
                node = root.find(
                    './/{http://sns.amazonaws.com/doc/2010-03-31/}SubscriptionArn'
                )
                if node is not None:
                    return node.text
            raise AWSError(status, reason, data)

        r = request.AWSRequest(self._endpoint, '/', self._key, self._secret,
                               'ConfirmSubscription', {
                                   'TopicArn': TopicArn,
                                   'Token': Token,
                               }, response)
        if AuthenticateOnUnsubscribe is not None:
            r.addParm('AuthenticateOnUnsubscribe', 'Yes')
        return r
Esempio n. 22
0
    def BatchDeleteAttributes(self, DomainName, Items):
        """Performs multiple DeleteAttributes operations in a single call, which reduces round trips and
                latencies. This enables Amazon SimpleDB to optimize requests, which generally yields better throughput.

                NOTE: If you specify BatchDeleteAttributes without attributes or values, all the attributes for the
                item are deleted.
                BatchDeleteAttributes is an idempotent operation; running it multiple times on the same item or attribute
                doesn't result in an error.
                The BatchDeleteAttributes operation succeeds or fails in its entirety. There are no partial deletes.
                You can execute multiple BatchDeleteAttributes operations and other operations in parallel. However,
                large numbers of concurrent BatchDeleteAttributes calls can result in Service Unavailable (503) responses.
                This operation is vulnerable to exceeding the maximum URL size when making a REST request using the HTTP GET method.
                This operation does not support conditions using Expected.X.Name, Expected.X.Value, or Expected.X.Exists.

                The following limitations are enforced for this operation:
                        * 1MB request size
                        * 25 item limit per batchDeleteAttributes operation

                DomainName -- The name of the domain in which to perform the operation.
                Items -- Either a dict or an iterable of (ItemName, attributes) tuples.
                        attributes is either a dict or an iterable of (name, value) tuples.

                returns True on success
                """
        def response(status, reason, data):
            if status == 200:
                return True
            raise AWSError(status, reason, data)

        r = request.AWSRequest(self._endpoint, '/', self._key, self._secret,
                               'BatchDeleteAttributes', {
                                   'DomainName': DomainName,
                                   'Version': self.version,
                               }, response)
        if hasattr(Items, 'items'):
            Items = Items.items()
        for itemIdx, (name, attributes) in enumerate(Items):
            r.addParm('Item.%d.ItemName' % itemIdx, name)
            if attributes is not None:
                if hasattr(attributes, 'items'):
                    attributes = attributes.items()
                for attrIdx, (name, value) in enumerate(attributes):
                    r.addParm('Item.%d.Attribute.%d.Name' % (itemIdx, attrIdx),
                              name)
                    r.addParm(
                        'Item.%d.Attribute.%d.Value' % (itemIdx, attrIdx),
                        value)
        return r
Esempio n. 23
0
    def Subscribe(self, TopicArn, Protocol, Endpoint):
        """The Subscribe action prepares to subscribe an endpoint by sending the endpoint a confirmation
                message. To actually create a subscription, the endpoint owner must call the ConfirmSubscription
                action with the token from the confirmation message. Confirmation tokens are valid for three days.

                TopicArn -- The ARN of topic you want to subscribe to.
                        Type: String
                        Required: Yes

                Endpoint -- The endpoint that you want to receive notifications. Endpoints vary by protocol:
                                For the http protocol, the endpoint is an URL beginning with "http://"
                                For the https protocol, the endpoint is a URL beginning with "https://"
                                For the email protocol, the endpoint is an e-mail address
                                For the email-json protocol, the endpoint is an e-mail address
                                For the sqs protocol, the endpoint is the ARN of an Amazon SQS queue
                        Type: String
                        Required: Yes

                Protocol -- The protocol you want to use. Supported protocols include:
                                http -- delivery of JSON-encoded message via HTTP POST
                                https -- delivery of JSON-encoded message via HTTPS POST
                                email -- delivery of message via SMTP
                                email-json -- delivery of JSON-encoded message via SMTP
                                sqs -- delivery of JSON-encoded message to an Amazon SQS queue
                        Type: String
                        Required: Yes

                Returns -- SubscriptionArn
                        The ARN of the subscription, if the service was able to create a subscription immediately
                        (without requiring endpoint owner confirmation).
                        Type: String
                """
        def response(status, reason, data):
            if status == 200:
                root = ET.fromstring(data)
                node = root.find('.//{%s}SubscriptionArn' % self.xmlns)
                if node is not None:
                    return node.text
                return None
            raise AWSError(status, reason, data)

        return request.AWSRequest(self._endpoint, '/', self._key, self._secret,
                                  'Subscribe', {
                                      'TopicArn': TopicArn,
                                      'Endpoint': Endpoint,
                                      'Protocol': Protocol,
                                  }, response)
Esempio n. 24
0
    def ListAction(self, Elements):
        """listAction tests that lists pass correctly through the system

                Returns -- True if HTTP request succeeds
                """
        def response(status, reason, data):
            if status == 200:
                return True
            raise AWSError(status, reason, data)

        r = request.AWSRequest(self._endpoint, '/', self._key, self._secret,
                               'ListAction', {
                                   'Version': self.version,
                               }, response)
        for idx, e in enumerate(Elements):
            r.addParm('Element.%d' % idx, e)
        return r
Esempio n. 25
0
    def ExampleAction(self, Title, FirstName, Surname=None):
        """exampleAction prints a greeting on the console where the server runs.

                Returns -- True if HTTP request succeeds
                """
        def response(status, reason, data):
            if status == 200:
                return True
            raise AWSError(status, reason, data)

        return request.AWSRequest(
            self._endpoint, '/', self._key, self._secret, 'ExampleAction', {
                'Version': self.version,
                'Title': Title,
                'FirstName': FirstName,
                'Surname': Surname,
            }, response)
Esempio n. 26
0
	def RemovePermission(self, queueUrl, Label):
		"""The removePermission action revokes any permissions in the queue policy that matches the Label parameter. Only the
			owner of the queue can remove permissions.

			Label -- The identfication of the permission you want to remove. This is the label you added in AddPermission.
			Returns True on success
			"""

		def response(status, reason, data):
			if status == 200:
				return True
			raise AWSError(status, reason, data)
		p = urlparse(queueUrl)
		return request.AWSRequest(self._endpoint, p.path, self._key, self._secret, 'RemovePermission', {
			'Version': self.version,
			'Label': Label,
		}, response)
Esempio n. 27
0
    def GetAttributes(self,
                      DomainName,
                      ItemName,
                      AttributeNames=None,
                      ConsistentRead=None):
        """Returns all of the attributes associated with the item. Optionally, the attributes returned can be limited to one or more specified
                attribute name parameters.

                Amazon SimpleDB keeps multiple copies of each domain. When data is written or updated, all copies of the data are updated. However,
                it takes time for the update to propagate to all storage locations. The data will eventually be consistent, but an immediate read
                might not show the change. If eventually consistent reads are not acceptable for your application, use ConsistentRead. Although this
                operation might take longer than a standard read, it always returns the last updated value.

                NOTE: If the item does not exist on the replica that was accessed for this operation, an empty set is returned.
                If you specify GetAttributes without any attribute names, all the attributes for the item are returned.

                domain -- The name of the domain in which to perform the operation.
                itemName -- The name of the item.
                attributeNames -- The name of the attributes to retrieve. If specified it should be an iterable of strings.
                consistentRead -- Boolean specifying whether consistent read should be performed. Default False.
                """
        def response(status, reason, data):
            if status == 200:
                #                               print data
                root = ET.fromstring(data)
                result = root.find('.//{%s}GetAttributesResult' % self.xmlns)
                attribs = []
                for node in result.findall('{%s}Attribute' % self.xmlns):
                    attribs.append((node.find('{%s}Name' % self.xmlns).text,
                                    node.find('{%s}Value' % self.xmlns).text))
                return attribs
            raise AWSError(status, reason, data)

        r = request.AWSRequest(
            self._endpoint, '/', self._key, self._secret, 'GetAttributes', {
                'DomainName': DomainName,
                'ItemName': ItemName,
                'ConsistentRead': ConsistentRead,
                'Version': self.version,
            }, response)
        if AttributeNames is not None:
            for idx, name in enumerate(AttributeNames):
                r.addParm('AttributeName.%d' % idx, name)
        return r
Esempio n. 28
0
    def GetQueueAttributes(self, queueUrl, Attributes=None):
        """The GetQueueAttributes action returns one or all attributes of a queue.

            Attributes -- If not supplied, than all attributes are returned.
                If supplied it should be an iterable of strings; each string can have one of the following values:
                All - returns all values.
                ApproximateNumberOfMessages - returns the approximate number of visible messages in a queue. For more information, see Resources Required
                    to Process Messages in the Amazon SQS Developer Guide.
                ApproximateNumberOfMessagesNotVisible - returns the approximate number of messages that are not timed-out and not deleted. For more
                    information, see Resources Required to Process Messages in the Amazon SQS Developer Guide.
                VisibilityTimeout - returns the visibility timeout for the queue. For more information about visibility timeout, see Visibility Timeout
                    in the Amazon SQS Developer Guide.
                CreatedTimestamp - returns the time when the queue was created (epoch time in seconds).
                LastModifiedTimestamp - returns the time when the queue was last changed (epoch time in seconds).
                Policy - returns the queue's policy.
                MaximumMessageSize - returns the limit of how many bytes a message can contain before Amazon SQS rejects it.
                MessageRetentionPeriod - returns the number of seconds Amazon SQS retains a message.
                QueueArn - returns the queue's Amazon resource name (ARN).

            Returns a dict of attributes.
            """
        def response(status, reason, data):
            if status == 200:
                root = ET.fromstring(data)
                attributes = {}
                for node in root.findall('.//{%s}Attribute' % self.xmlns):
                    name = node.find('{%s}Name' % self.xmlns).text
                    value = node.find('{%s}Value' % self.xmlns).text
                    attributes[name] = value
                return attributes
            raise AWSError(status, reason, data)

        p = urlparse(queueUrl)
        r = request.AWSRequest(self._endpoint, p.path, self._key, self._secret,
                               'GetQueueAttributes', {
                                   'Version': self.version,
                               }, response)
        if Attributes is None:
            r.addParm('AttributeName.1', 'All')
        else:
            for idx, attr in enumerate(Attributes):
                r.addParm('AttributeName.%d' % (idx + 1), attr)
        return r
Esempio n. 29
0
    def DeleteMessageBatch(self, queueUrl, receiptHandleList):
        """The DeleteMessageBatch action deletes the specified message from the specified queue in bulk."""
        def response(status, reason, data):
            if status == 200:
                return True
            raise AWSError(status, reason, data)

        p = urlparse(queueUrl)
        params = {
            'Version': self.version,
        }
        for idx, receipt in enumerate(receiptHandleList):
            idx += 1  # Ids start from 1
            params["DeleteMessageBatchRequestEntry.%d.Id" %
                   idx] = "msg%d" % idx
            params["DeleteMessageBatchRequestEntry.%d.ReceiptHandle" %
                   idx] = receipt
        return request.AWSRequest(self._endpoint, p.path, self._key,
                                  self._secret, 'DeleteMessageBatch', params,
                                  response)
Esempio n. 30
0
	def DeleteDomain(self, DomainName):
		"""The DeleteDomain operation deletes a domain. Any items (and their attributes) in the domain are deleted as well.
			The DeleteDomain operation might take 10 or more seconds to complete.

			Note: Running DeleteDomain on a domain that does not exist or running the function multiple times using the same domain name
			will not result in an error response.

			domain -- The name of the domain to delete.
				Type: string
				Required: Yes
			"""

		def response(status, reason, data):
			if status == 200:
				return True
			raise AWSError(status, reason, data)
		return request.AWSRequest(self._endpoint, '/', self._key, self._secret, 'DeleteDomain', {
				'DomainName': DomainName,
				'Version': self.version,
			}, response)