code stringlengths 1 1.72M | language stringclasses 1 value |
|---|---|
# Copyright (c) 2006-2010 Mitch Garnaat http://garnaat.org/
# Copyright (c) 2010, Eucalyptus Systems, Inc.
# All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
import boto
from boto.pyami.config import Config, BotoConfigLocations
from boto.storage_uri import BucketStorageUri, FileStorageUri
import os, re, sys
import logging
import logging.config
from boto.exception import InvalidUriError
__version__ = '2.0b3'
Version = __version__ # for backware compatibility
UserAgent = 'Boto/%s (%s)' % (__version__, sys.platform)
config = Config()
def init_logging():
for file in BotoConfigLocations:
try:
logging.config.fileConfig(os.path.expanduser(file))
except:
pass
class NullHandler(logging.Handler):
def emit(self, record):
pass
log = logging.getLogger('boto')
log.addHandler(NullHandler())
init_logging()
# convenience function to set logging to a particular file
def set_file_logger(name, filepath, level=logging.INFO, format_string=None):
global log
if not format_string:
format_string = "%(asctime)s %(name)s [%(levelname)s]:%(message)s"
logger = logging.getLogger(name)
logger.setLevel(level)
fh = logging.FileHandler(filepath)
fh.setLevel(level)
formatter = logging.Formatter(format_string)
fh.setFormatter(formatter)
logger.addHandler(fh)
log = logger
def set_stream_logger(name, level=logging.DEBUG, format_string=None):
global log
if not format_string:
format_string = "%(asctime)s %(name)s [%(levelname)s]:%(message)s"
logger = logging.getLogger(name)
logger.setLevel(level)
fh = logging.StreamHandler()
fh.setLevel(level)
formatter = logging.Formatter(format_string)
fh.setFormatter(formatter)
logger.addHandler(fh)
log = logger
def connect_sqs(aws_access_key_id=None, aws_secret_access_key=None, **kwargs):
"""
:type aws_access_key_id: string
:param aws_access_key_id: Your AWS Access Key ID
:type aws_secret_access_key: string
:param aws_secret_access_key: Your AWS Secret Access Key
:rtype: :class:`boto.sqs.connection.SQSConnection`
:return: A connection to Amazon's SQS
"""
from boto.sqs.connection import SQSConnection
return SQSConnection(aws_access_key_id, aws_secret_access_key, **kwargs)
def connect_s3(aws_access_key_id=None, aws_secret_access_key=None, **kwargs):
"""
:type aws_access_key_id: string
:param aws_access_key_id: Your AWS Access Key ID
:type aws_secret_access_key: string
:param aws_secret_access_key: Your AWS Secret Access Key
:rtype: :class:`boto.s3.connection.S3Connection`
:return: A connection to Amazon's S3
"""
from boto.s3.connection import S3Connection
return S3Connection(aws_access_key_id, aws_secret_access_key, **kwargs)
def connect_gs(gs_access_key_id=None, gs_secret_access_key=None, **kwargs):
"""
@type gs_access_key_id: string
@param gs_access_key_id: Your Google Storage Access Key ID
@type gs_secret_access_key: string
@param gs_secret_access_key: Your Google Storage Secret Access Key
@rtype: L{GSConnection<boto.gs.connection.GSConnection>}
@return: A connection to Google's Storage service
"""
from boto.gs.connection import GSConnection
return GSConnection(gs_access_key_id, gs_secret_access_key, **kwargs)
def connect_ec2(aws_access_key_id=None, aws_secret_access_key=None, **kwargs):
"""
:type aws_access_key_id: string
:param aws_access_key_id: Your AWS Access Key ID
:type aws_secret_access_key: string
:param aws_secret_access_key: Your AWS Secret Access Key
:rtype: :class:`boto.ec2.connection.EC2Connection`
:return: A connection to Amazon's EC2
"""
from boto.ec2.connection import EC2Connection
return EC2Connection(aws_access_key_id, aws_secret_access_key, **kwargs)
def connect_elb(aws_access_key_id=None, aws_secret_access_key=None, **kwargs):
"""
:type aws_access_key_id: string
:param aws_access_key_id: Your AWS Access Key ID
:type aws_secret_access_key: string
:param aws_secret_access_key: Your AWS Secret Access Key
:rtype: :class:`boto.ec2.elb.ELBConnection`
:return: A connection to Amazon's Load Balancing Service
"""
from boto.ec2.elb import ELBConnection
return ELBConnection(aws_access_key_id, aws_secret_access_key, **kwargs)
def connect_autoscale(aws_access_key_id=None, aws_secret_access_key=None, **kwargs):
"""
:type aws_access_key_id: string
:param aws_access_key_id: Your AWS Access Key ID
:type aws_secret_access_key: string
:param aws_secret_access_key: Your AWS Secret Access Key
:rtype: :class:`boto.ec2.autoscale.AutoScaleConnection`
:return: A connection to Amazon's Auto Scaling Service
"""
from boto.ec2.autoscale import AutoScaleConnection
return AutoScaleConnection(aws_access_key_id, aws_secret_access_key, **kwargs)
def connect_cloudwatch(aws_access_key_id=None, aws_secret_access_key=None, **kwargs):
"""
:type aws_access_key_id: string
:param aws_access_key_id: Your AWS Access Key ID
:type aws_secret_access_key: string
:param aws_secret_access_key: Your AWS Secret Access Key
:rtype: :class:`boto.ec2.cloudwatch.CloudWatchConnection`
:return: A connection to Amazon's EC2 Monitoring service
"""
from boto.ec2.cloudwatch import CloudWatchConnection
return CloudWatchConnection(aws_access_key_id, aws_secret_access_key, **kwargs)
def connect_sdb(aws_access_key_id=None, aws_secret_access_key=None, **kwargs):
"""
:type aws_access_key_id: string
:param aws_access_key_id: Your AWS Access Key ID
:type aws_secret_access_key: string
:param aws_secret_access_key: Your AWS Secret Access Key
:rtype: :class:`boto.sdb.connection.SDBConnection`
:return: A connection to Amazon's SDB
"""
from boto.sdb.connection import SDBConnection
return SDBConnection(aws_access_key_id, aws_secret_access_key, **kwargs)
def connect_fps(aws_access_key_id=None, aws_secret_access_key=None, **kwargs):
"""
:type aws_access_key_id: string
:param aws_access_key_id: Your AWS Access Key ID
:type aws_secret_access_key: string
:param aws_secret_access_key: Your AWS Secret Access Key
:rtype: :class:`boto.fps.connection.FPSConnection`
:return: A connection to FPS
"""
from boto.fps.connection import FPSConnection
return FPSConnection(aws_access_key_id, aws_secret_access_key, **kwargs)
def connect_mturk(aws_access_key_id=None, aws_secret_access_key=None, **kwargs):
"""
:type aws_access_key_id: string
:param aws_access_key_id: Your AWS Access Key ID
:type aws_secret_access_key: string
:param aws_secret_access_key: Your AWS Secret Access Key
:rtype: :class:`boto.mturk.connection.MTurkConnection`
:return: A connection to MTurk
"""
from boto.mturk.connection import MTurkConnection
return MTurkConnection(aws_access_key_id, aws_secret_access_key, **kwargs)
def connect_cloudfront(aws_access_key_id=None, aws_secret_access_key=None, **kwargs):
"""
:type aws_access_key_id: string
:param aws_access_key_id: Your AWS Access Key ID
:type aws_secret_access_key: string
:param aws_secret_access_key: Your AWS Secret Access Key
:rtype: :class:`boto.fps.connection.FPSConnection`
:return: A connection to FPS
"""
from boto.cloudfront import CloudFrontConnection
return CloudFrontConnection(aws_access_key_id, aws_secret_access_key, **kwargs)
def connect_vpc(aws_access_key_id=None, aws_secret_access_key=None, **kwargs):
"""
:type aws_access_key_id: string
:param aws_access_key_id: Your AWS Access Key ID
:type aws_secret_access_key: string
:param aws_secret_access_key: Your AWS Secret Access Key
:rtype: :class:`boto.vpc.VPCConnection`
:return: A connection to VPC
"""
from boto.vpc import VPCConnection
return VPCConnection(aws_access_key_id, aws_secret_access_key, **kwargs)
def connect_rds(aws_access_key_id=None, aws_secret_access_key=None, **kwargs):
"""
:type aws_access_key_id: string
:param aws_access_key_id: Your AWS Access Key ID
:type aws_secret_access_key: string
:param aws_secret_access_key: Your AWS Secret Access Key
:rtype: :class:`boto.rds.RDSConnection`
:return: A connection to RDS
"""
from boto.rds import RDSConnection
return RDSConnection(aws_access_key_id, aws_secret_access_key, **kwargs)
def connect_emr(aws_access_key_id=None, aws_secret_access_key=None, **kwargs):
"""
:type aws_access_key_id: string
:param aws_access_key_id: Your AWS Access Key ID
:type aws_secret_access_key: string
:param aws_secret_access_key: Your AWS Secret Access Key
:rtype: :class:`boto.emr.EmrConnection`
:return: A connection to Elastic mapreduce
"""
from boto.emr import EmrConnection
return EmrConnection(aws_access_key_id, aws_secret_access_key, **kwargs)
def connect_sns(aws_access_key_id=None, aws_secret_access_key=None, **kwargs):
"""
:type aws_access_key_id: string
:param aws_access_key_id: Your AWS Access Key ID
:type aws_secret_access_key: string
:param aws_secret_access_key: Your AWS Secret Access Key
:rtype: :class:`boto.sns.SNSConnection`
:return: A connection to Amazon's SNS
"""
from boto.sns import SNSConnection
return SNSConnection(aws_access_key_id, aws_secret_access_key, **kwargs)
def connect_iam(aws_access_key_id=None, aws_secret_access_key=None, **kwargs):
"""
:type aws_access_key_id: string
:param aws_access_key_id: Your AWS Access Key ID
:type aws_secret_access_key: string
:param aws_secret_access_key: Your AWS Secret Access Key
:rtype: :class:`boto.iam.IAMConnection`
:return: A connection to Amazon's IAM
"""
from boto.iam import IAMConnection
return IAMConnection(aws_access_key_id, aws_secret_access_key, **kwargs)
def connect_euca(host, aws_access_key_id=None, aws_secret_access_key=None,
port=8773, path='/services/Eucalyptus', is_secure=False,
**kwargs):
"""
Connect to a Eucalyptus service.
:type host: string
:param host: the host name or ip address of the Eucalyptus server
:type aws_access_key_id: string
:param aws_access_key_id: Your AWS Access Key ID
:type aws_secret_access_key: string
:param aws_secret_access_key: Your AWS Secret Access Key
:rtype: :class:`boto.ec2.connection.EC2Connection`
:return: A connection to Eucalyptus server
"""
from boto.ec2 import EC2Connection
from boto.ec2.regioninfo import RegionInfo
reg = RegionInfo(name='eucalyptus', endpoint=host)
return EC2Connection(aws_access_key_id, aws_secret_access_key,
region=reg, port=port, path=path,
is_secure=is_secure, **kwargs)
def connect_walrus(host, aws_access_key_id=None, aws_secret_access_key=None,
port=8773, path='/services/Walrus', is_secure=False,
**kwargs):
"""
Connect to a Walrus service.
:type host: string
:param host: the host name or ip address of the Walrus server
:type aws_access_key_id: string
:param aws_access_key_id: Your AWS Access Key ID
:type aws_secret_access_key: string
:param aws_secret_access_key: Your AWS Secret Access Key
:rtype: :class:`boto.s3.connection.S3Connection`
:return: A connection to Walrus
"""
from boto.s3.connection import S3Connection
from boto.s3.connection import OrdinaryCallingFormat
return S3Connection(aws_access_key_id, aws_secret_access_key,
host=host, port=port, path=path,
calling_format=OrdinaryCallingFormat(),
is_secure=is_secure, **kwargs)
def check_extensions(module_name, module_path):
"""
This function checks for extensions to boto modules. It should be called in the
__init__.py file of all boto modules. See:
http://code.google.com/p/boto/wiki/ExtendModules
for details.
"""
option_name = '%s_extend' % module_name
version = config.get('Boto', option_name, None)
if version:
dirname = module_path[0]
path = os.path.join(dirname, version)
if os.path.isdir(path):
log.info('extending module %s with: %s' % (module_name, path))
module_path.insert(0, path)
_aws_cache = {}
def _get_aws_conn(service):
global _aws_cache
conn = _aws_cache.get(service)
if not conn:
meth = getattr(sys.modules[__name__], 'connect_'+service)
conn = meth()
_aws_cache[service] = conn
return conn
def lookup(service, name):
global _aws_cache
conn = _get_aws_conn(service)
obj = _aws_cache.get('.'.join((service,name)), None)
if not obj:
obj = conn.lookup(name)
_aws_cache['.'.join((service,name))] = obj
return obj
def storage_uri(uri_str, default_scheme='file', debug=0, validate=True):
"""Instantiate a StorageUri from a URI string.
:type uri_str: string
:param uri_str: URI naming bucket + optional object.
:type default_scheme: string
:param default_scheme: default scheme for scheme-less URIs.
:type debug: int
:param debug: debug level to pass in to boto connection (range 0..2).
:type validate: bool
:param validate: whether to check for bucket name validity.
We allow validate to be disabled to allow caller
to implement bucket-level wildcarding (outside the boto library;
see gsutil).
:rtype: :class:`boto.StorageUri` subclass
:return: StorageUri subclass for given URI.
uri_str must be one of the following formats:
gs://bucket/name
s3://bucket/name
gs://bucket
s3://bucket
filename
The last example uses the default scheme ('file', unless overridden)
"""
# Manually parse URI components instead of using urlparse.urlparse because
# what we're calling URIs don't really fit the standard syntax for URIs
# (the latter includes an optional host/net location part).
end_scheme_idx = uri_str.find('://')
if end_scheme_idx == -1:
# Check for common error: user specifies gs:bucket instead
# of gs://bucket. Some URI parsers allow this, but it can cause
# confusion for callers, so we don't.
if uri_str.find(':') != -1:
raise InvalidUriError('"%s" contains ":" instead of "://"' % uri_str)
scheme = default_scheme.lower()
path = uri_str
else:
scheme = uri_str[0:end_scheme_idx].lower()
path = uri_str[end_scheme_idx + 3:]
if scheme not in ['file', 's3', 'gs']:
raise InvalidUriError('Unrecognized scheme "%s"' % scheme)
if scheme == 'file':
# For file URIs we have no bucket name, and use the complete path
# (minus 'file://') as the object name.
return FileStorageUri(path, debug)
else:
path_parts = path.split('/', 1)
bucket_name = path_parts[0]
if (validate and bucket_name and
not re.match('^[a-z0-9][a-z0-9\._-]{1,253}[a-z0-9]$', bucket_name)):
raise InvalidUriError('Invalid bucket name in URI "%s"' % uri_str)
# If enabled, ensure the bucket name is valid, to avoid possibly
# confusing other parts of the code. (For example if we didn't
# catch bucket names containing ':', when a user tried to connect to
# the server with that name they might get a confusing error about
# non-integer port numbers.)
object_name = ''
if len(path_parts) > 1:
object_name = path_parts[1]
return BucketStorageUri(scheme, bucket_name, object_name, debug)
def storage_uri_for_key(key):
"""Returns a StorageUri for the given key.
:type key: :class:`boto.s3.key.Key` or subclass
:param key: URI naming bucket + optional object.
"""
if not isinstance(key, boto.s3.key.Key):
raise InvalidUriError('Requested key (%s) is not a subclass of '
'boto.s3.key.Key' % str(type(key)))
prov_name = key.bucket.connection.provider.get_provider_name()
uri_str = '%s://%s/%s' % (prov_name, key.bucket.name, key.name)
return storage_uri(uri_str)
| Python |
# Copyright (c) 2008 Chris Moyer http://coredumped.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
import base64
import urllib
import xml.sax
import uuid
import boto
import boto.utils
from boto import handler
from boto.connection import AWSQueryConnection
from boto.resultset import ResultSet
from boto.exception import FPSResponseError
class FPSConnection(AWSQueryConnection):
APIVersion = '2007-01-08'
SignatureVersion = '1'
def __init__(self, aws_access_key_id=None, aws_secret_access_key=None,
is_secure=True, port=None, proxy=None, proxy_port=None,
proxy_user=None, proxy_pass=None,
host='fps.sandbox.amazonaws.com', debug=0,
https_connection_factory=None, path="/"):
AWSQueryConnection.__init__(self, aws_access_key_id, aws_secret_access_key,
is_secure, port, proxy, proxy_port,
proxy_user, proxy_pass, host, debug,
https_connection_factory, path)
def install_payment_instruction(self, instruction, token_type="Unrestricted", transaction_id=None):
"""
InstallPaymentInstruction
instruction: The PaymentInstruction to send, for example:
MyRole=='Caller' orSay 'Roles do not match';
token_type: Defaults to "Unrestricted"
transaction_id: Defaults to a new ID
"""
if(transaction_id == None):
transaction_id = uuid.uuid4()
params = {}
params['PaymentInstruction'] = instruction
params['TokenType'] = token_type
params['CallerReference'] = transaction_id
response = self.make_request("InstallPaymentInstruction", params)
return response
def install_caller_instruction(self, token_type="Unrestricted", transaction_id=None):
"""
Set us up as a caller
This will install a new caller_token into the FPS section.
This should really only be called to regenerate the caller token.
"""
response = self.install_payment_instruction("MyRole=='Caller';", token_type=token_type, transaction_id=transaction_id)
body = response.read()
if(response.status == 200):
rs = ResultSet()
h = handler.XmlHandler(rs, self)
xml.sax.parseString(body, h)
caller_token = rs.TokenId
try:
boto.config.save_system_option("FPS", "caller_token", caller_token)
except(IOError):
boto.config.save_user_option("FPS", "caller_token", caller_token)
return caller_token
else:
raise FPSResponseError(response.status, response.reason, body)
def install_recipient_instruction(self, token_type="Unrestricted", transaction_id=None):
"""
Set us up as a Recipient
This will install a new caller_token into the FPS section.
This should really only be called to regenerate the recipient token.
"""
response = self.install_payment_instruction("MyRole=='Recipient';", token_type=token_type, transaction_id=transaction_id)
body = response.read()
if(response.status == 200):
rs = ResultSet()
h = handler.XmlHandler(rs, self)
xml.sax.parseString(body, h)
recipient_token = rs.TokenId
try:
boto.config.save_system_option("FPS", "recipient_token", recipient_token)
except(IOError):
boto.config.save_user_option("FPS", "recipient_token", recipient_token)
return recipient_token
else:
raise FPSResponseError(response.status, response.reason, body)
def make_url(self, returnURL, paymentReason, pipelineName, **params):
"""
Generate the URL with the signature required for a transaction
"""
params['callerKey'] = str(self.aws_access_key_id)
params['returnURL'] = str(returnURL)
params['paymentReason'] = str(paymentReason)
params['pipelineName'] = pipelineName
if(not params.has_key('callerReference')):
params['callerReference'] = str(uuid.uuid4())
deco = [(key.lower(),i,key) for i,key in enumerate(params.keys())]
deco.sort()
keys = [key for _,_,key in deco]
url = ''
canonical = ''
for k in keys:
url += "&%s=%s" % (k, urllib.quote_plus(str(params[k])))
canonical += "%s%s" % (k, str(params[k]))
url = "/cobranded-ui/actions/start?%s" % ( url[1:])
hmac = self.hmac.copy()
hmac.update(canonical)
signature = urllib.quote_plus(base64.encodestring(hmac.digest()).strip())
return "https://authorize.payments-sandbox.amazon.com%s&awsSignature=%s" % (url, signature)
def pay(self, transactionAmount, senderTokenId, chargeFeeTo="Recipient",
callerReference=None, senderReference=None, recipientReference=None,
senderDescription=None, recipientDescription=None, callerDescription=None,
metadata=None, transactionDate=None, reserve=False):
"""
Make a payment transaction. You must specify the amount.
This can also perform a Reserve request if 'reserve' is set to True.
"""
params = {}
params['SenderTokenId'] = senderTokenId
params['TransactionAmount.Amount'] = str(transactionAmount)
params['TransactionAmount.CurrencyCode'] = "USD"
params['ChargeFeeTo'] = chargeFeeTo
params['RecipientTokenId'] = boto.config.get("FPS", "recipient_token")
params['CallerTokenId'] = boto.config.get("FPS", "caller_token")
if(transactionDate != None):
params['TransactionDate'] = transactionDate
if(senderReference != None):
params['SenderReference'] = senderReference
if(recipientReference != None):
params['RecipientReference'] = recipientReference
if(senderDescription != None):
params['SenderDescription'] = senderDescription
if(recipientDescription != None):
params['RecipientDescription'] = recipientDescription
if(callerDescription != None):
params['CallerDescription'] = callerDescription
if(metadata != None):
params['MetaData'] = metadata
if(callerReference == None):
callerReference = uuid.uuid4()
params['CallerReference'] = callerReference
if reserve:
response = self.make_request("Reserve", params)
else:
response = self.make_request("Pay", params)
body = response.read()
if(response.status == 200):
rs = ResultSet()
h = handler.XmlHandler(rs, self)
xml.sax.parseString(body, h)
return rs
else:
raise FPSResponseError(response.status, response.reason, body)
def get_transaction_status(self, transactionId):
"""
Returns the status of a given transaction.
"""
params = {}
params['TransactionId'] = transactionId
response = self.make_request("GetTransactionStatus", params)
body = response.read()
if(response.status == 200):
rs = ResultSet()
h = handler.XmlHandler(rs, self)
xml.sax.parseString(body, h)
return rs
else:
raise FPSResponseError(response.status, response.reason, body)
def cancel(self, transactionId, description=None):
"""
Cancels a reserved or pending transaction.
"""
params = {}
params['transactionId'] = transactionId
if(description != None):
params['description'] = description
response = self.make_request("Cancel", params)
body = response.read()
if(response.status == 200):
rs = ResultSet()
h = handler.XmlHandler(rs, self)
xml.sax.parseString(body, h)
return rs
else:
raise FPSResponseError(response.status, response.reason, body)
def settle(self, reserveTransactionId, transactionAmount=None):
"""
Charges for a reserved payment.
"""
params = {}
params['ReserveTransactionId'] = reserveTransactionId
if(transactionAmount != None):
params['TransactionAmount'] = transactionAmount
response = self.make_request("Settle", params)
body = response.read()
if(response.status == 200):
rs = ResultSet()
h = handler.XmlHandler(rs, self)
xml.sax.parseString(body, h)
return rs
else:
raise FPSResponseError(response.status, response.reason, body)
def refund(self, callerReference, transactionId, refundAmount=None, callerDescription=None):
"""
Refund a transaction. This refunds the full amount by default unless 'refundAmount' is specified.
"""
params = {}
params['CallerReference'] = callerReference
params['TransactionId'] = transactionId
if(refundAmount != None):
params['RefundAmount'] = refundAmount
if(callerDescription != None):
params['CallerDescription'] = callerDescription
response = self.make_request("Refund", params)
body = response.read()
if(response.status == 200):
rs = ResultSet()
h = handler.XmlHandler(rs, self)
xml.sax.parseString(body, h)
return rs
else:
raise FPSResponseError(response.status, response.reason, body)
def get_recipient_verification_status(self, recipientTokenId):
"""
Test that the intended recipient has a verified Amazon Payments account.
"""
params ={}
params['RecipientTokenId'] = recipientTokenId
response = self.make_request("GetRecipientVerificationStatus", params)
body = response.read()
if(response.status == 200):
rs = ResultSet()
h = handler.XmlHandler(rs, self)
xml.sax.parseString(body, h)
return rs
else:
raise FPSResponseError(response.status, response.reason, body)
def get_token_by_caller_reference(self, callerReference):
"""
Returns details about the token specified by 'callerReference'.
"""
params ={}
params['callerReference'] = callerReference
response = self.make_request("GetTokenByCaller", params)
body = response.read()
if(response.status == 200):
rs = ResultSet()
h = handler.XmlHandler(rs, self)
xml.sax.parseString(body, h)
return rs
else:
raise FPSResponseError(response.status, response.reason, body)
def get_token_by_caller_token(self, tokenId):
"""
Returns details about the token specified by 'callerReference'.
"""
params ={}
params['TokenId'] = tokenId
response = self.make_request("GetTokenByCaller", params)
body = response.read()
if(response.status == 200):
rs = ResultSet()
h = handler.XmlHandler(rs, self)
xml.sax.parseString(body, h)
return rs
else:
raise FPSResponseError(response.status, response.reason, body)
| Python |
# Copyright (c) 2008, Chris Moyer http://coredumped.org
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
| Python |
# Copyright (c) 2010 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
import xml.sax
def pythonize_name(name):
s = ''
if name[0].isupper:
s = name[0].lower()
for c in name[1:]:
if c.isupper():
s += '_' + c.lower()
else:
s += c
return s
class XmlHandler(xml.sax.ContentHandler):
def __init__(self, root_node, connection):
self.connection = connection
self.nodes = [('root', root_node)]
self.current_text = ''
def startElement(self, name, attrs):
self.current_text = ''
t = self.nodes[-1][1].startElement(name, attrs, self.connection)
if t != None:
if isinstance(t, tuple):
self.nodes.append(t)
else:
self.nodes.append((name, t))
def endElement(self, name):
self.nodes[-1][1].endElement(name, self.current_text, self.connection)
if self.nodes[-1][0] == name:
self.nodes.pop()
self.current_text = ''
def characters(self, content):
self.current_text += content
def parse(self, s):
xml.sax.parseString(s, self)
class Element(dict):
def __init__(self, connection=None, element_name=None,
stack=None, parent=None, list_marker='Set'):
dict.__init__(self)
self.connection = connection
self.element_name = element_name
self.list_marker = list_marker
if stack is None:
self.stack = []
else:
self.stack = stack
self.parent = parent
def __getattr__(self, key):
if key in self:
return self[key]
for k in self:
e = self[k]
if isinstance(e, Element):
try:
return getattr(e, key)
except AttributeError:
pass
raise AttributeError
def startElement(self, name, attrs, connection):
self.stack.append(name)
if name.endswith(self.list_marker):
l = ListElement(self.connection, name, self.list_marker)
self[pythonize_name(name)] = l
return l
if len(self.stack) > 0:
element_name = self.stack[-1]
e = Element(self.connection, element_name, self.stack, self, self.list_marker)
self[pythonize_name(element_name)] = e
return (element_name, e)
else:
return None
def endElement(self, name, value, connection):
if len(self.stack) > 0:
self.stack.pop()
value = value.strip()
if value:
if isinstance(self.parent, Element):
self.parent[pythonize_name(name)] = value
elif isinstance(self.parent, ListElement):
self.parent.append(value)
class ListElement(list):
def __init__(self, connection=None, element_name=None,
list_marker='Set', item_marker='member'):
list.__init__(self)
self.connection = connection
self.element_name = element_name
self.list_marker = list_marker
self.item_marker = item_marker
def startElement(self, name, attrs, connection):
if name.endswith(self.list_marker):
l = ListElement(self.connection, name)
setattr(self, pythonize_name(name), l)
return l
elif name == self.item_marker:
e = Element(self.connection, name, parent=self)
self.append(e)
return e
else:
return None
def endElement(self, name, value, connection):
if name == self.element_name:
if len(self) > 0:
empty = []
for e in self:
if isinstance(e, Element):
if len(e) == 0:
empty.append(e)
for e in empty:
self.remove(e)
else:
setattr(self, pythonize_name(name), value)
| Python |
# Copyright (c) 2010 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
import boto
import boto.iam.response
from boto.connection import AWSQueryConnection
#boto.set_stream_logger('iam')
class IAMConnection(AWSQueryConnection):
APIVersion = '2010-05-08'
SignatureVersion = '2'
def __init__(self, aws_access_key_id=None, aws_secret_access_key=None,
is_secure=True, port=None, proxy=None, proxy_port=None,
proxy_user=None, proxy_pass=None, host='iam.amazonaws.com',
debug=0, https_connection_factory=None, path='/'):
AWSQueryConnection.__init__(self, aws_access_key_id, aws_secret_access_key,
is_secure, port, proxy, proxy_port, proxy_user, proxy_pass,
host, debug, https_connection_factory, path)
def get_response(self, action, params, path='/', parent=None,
verb='GET', list_marker='Set'):
"""
Utility method to handle calls to IAM and parsing of responses.
"""
if not parent:
parent = self
response = self.make_request(action, params, path, verb)
body = response.read()
boto.log.debug(body)
if response.status == 200:
e = boto.iam.response.Element(list_marker=list_marker)
h = boto.iam.response.XmlHandler(e, parent)
h.parse(body)
return e
else:
boto.log.error('%s %s' % (response.status, response.reason))
boto.log.error('%s' % body)
raise self.ResponseError(response.status, response.reason, body)
#
# Group methods
#
def get_all_groups(self, path_prefix='/', marker=None, max_items=None):
"""
List the groups that have the specified path prefix.
:type path_prefix: string
:param path_prefix: If provided, only groups whose paths match
the provided prefix will be returned.
:type marker: string
:param marker: Use this only when paginating results and only in
follow-up request after you've received a response
where the results are truncated. Set this to the
value of the Marker element in the response you
just received.
:type max_items: int
:param max_items: Use this only when paginating results to indicate
the maximum number of groups you want in the
response.
"""
params = {}
if path_prefix:
params['PathPrefix'] = path_prefix
if marker:
params['Marker'] = marker
if max_items:
params['MaxItems'] = max_items
return self.get_response('ListGroups', params, list_marker='Groups')
def get_group(self, group_name, marker=None, max_items=None):
"""
Return a list of users that are in the specified group.
:type group_name: string
:param group_name: The name of the group whose information should
be returned.
:type marker: string
:param marker: Use this only when paginating results and only in
follow-up request after you've received a response
where the results are truncated. Set this to the
value of the Marker element in the response you
just received.
:type max_items: int
:param max_items: Use this only when paginating results to indicate
the maximum number of groups you want in the
response.
"""
params = {'GroupName' : group_name}
if marker:
params['Marker'] = marker
if max_items:
params['MaxItems'] = max_items
return self.get_response('GetGroup', params, list_marker='Users')
def create_group(self, group_name, path='/'):
"""
Create a group.
:type group_name: string
:param group_name: The name of the new group
:type path: string
:param path: The path to the group (Optional). Defaults to /.
"""
params = {'GroupName' : group_name,
'Path' : path}
return self.get_response('CreateGroup', params)
def delete_group(self, group_name):
"""
Delete a group. The group must not contain any Users or
have any attached policies
:type group_name: string
:param group_name: The name of the group to delete.
"""
params = {'GroupName' : group_name}
return self.get_response('DeleteGroup', params)
def update_group(self, group_name, new_group_name=None, new_path=None):
"""
Update a group by adding or removing a user to/from it.
:type group_name: string
:param group_name: The name of the new group
:type new_group_name: string
:param new_group_name: If provided, the name of the group will be
changed to this name.
:type new_path: string
:param new_path: If provided, the path of the group will be
changed to this path.
"""
params = {'GroupName' : group_name}
if new_group_name:
params['NewGroupName'] = new_group_name
if new_path:
params['NewPath'] = new_path
return self.get_response('UpdateGroup', params)
def add_user_to_group(self, group_name, user_name):
"""
Add a user to a group
:type group_name: string
:param group_name: The name of the new group
:type user_name: string
:param user_name: The to be added to the group.
"""
params = {'GroupName' : group_name,
'UserName' : user_name}
return self.get_response('AddUserToGroup', params)
def remove_user_from_group(self, group_name, user_name):
"""
Remove a user from a group.
:type group_name: string
:param group_name: The name of the new group
:type user_name: string
:param user_name: The user to remove from the group.
"""
params = {'GroupName' : group_name,
'UserName' : user_name}
return self.get_response('RemoveUserFromGroup', params)
def put_group_policy(self, group_name, policy_name, policy_json):
"""
Adds or updates the specified policy document for the specified group.
:type group_name: string
:param group_name: The name of the group the policy is associated with.
:type policy_name: string
:param policy_name: The policy document to get.
:type policy_json: string
:param policy_json: The policy document.
"""
params = {'GroupName' : group_name,
'PolicyName' : policy_name,
'PolicyDocument' : policy_json}
return self.get_response('PutGroupPolicy', params, verb='POST')
def get_all_group_policies(self, group_name, marker=None, max_items=None):
"""
List the names of the policies associated with the specified group.
:type group_name: string
:param group_name: The name of the group the policy is associated with.
:type marker: string
:param marker: Use this only when paginating results and only in
follow-up request after you've received a response
where the results are truncated. Set this to the
value of the Marker element in the response you
just received.
:type max_items: int
:param max_items: Use this only when paginating results to indicate
the maximum number of groups you want in the
response.
"""
params = {'GroupName' : group_name}
if marker:
params['Marker'] = marker
if max_items:
params['MaxItems'] = max_items
return self.get_response('ListGroupPolicies', params,
list_marker='PolicyNames')
def get_group_policy(self, group_name, policy_name):
"""
Retrieves the specified policy document for the specified group.
:type group_name: string
:param group_name: The name of the group the policy is associated with.
:type policy_name: string
:param policy_name: The policy document to get.
"""
params = {'GroupName' : group_name,
'PolicyName' : policy_name}
return self.get_response('GetGroupPolicy', params, verb='POST')
def delete_group_policy(self, group_name, policy_name):
"""
Deletes the specified policy document for the specified group.
:type group_name: string
:param group_name: The name of the group the policy is associated with.
:type policy_name: string
:param policy_name: The policy document to delete.
"""
params = {'GroupName' : group_name,
'PolicyName' : policy_name}
return self.get_response('DeleteGroupPolicy', params, verb='POST')
def get_all_users(self, path_prefix='/', marker=None, max_items=None):
"""
List the users that have the specified path prefix.
:type path_prefix: string
:param path_prefix: If provided, only users whose paths match
the provided prefix will be returned.
:type marker: string
:param marker: Use this only when paginating results and only in
follow-up request after you've received a response
where the results are truncated. Set this to the
value of the Marker element in the response you
just received.
:type max_items: int
:param max_items: Use this only when paginating results to indicate
the maximum number of groups you want in the
response.
"""
params = {'PathPrefix' : path_prefix}
if marker:
params['Marker'] = marker
if max_items:
params['MaxItems'] = max_items
return self.get_response('ListUsers', params, list_marker='Users')
#
# User methods
#
def create_user(self, user_name, path='/'):
"""
Create a user.
:type user_name: string
:param user_name: The name of the new user
:type path: string
:param path: The path in which the user will be created.
Defaults to /.
"""
params = {'UserName' : user_name,
'Path' : path}
return self.get_response('CreateUser', params)
def delete_user(self, user_name):
"""
Delete a user including the user's path, GUID and ARN.
If the user_name is not specified, the user_name is determined
implicitly based on the AWS Access Key ID used to sign the request.
:type user_name: string
:param user_name: The name of the user to delete.
"""
params = {'UserName' : user_name}
return self.get_response('DeleteUser', params)
def get_user(self, user_name=None):
"""
Retrieve information about the specified user.
If the user_name is not specified, the user_name is determined
implicitly based on the AWS Access Key ID used to sign the request.
:type user_name: string
:param user_name: The name of the user to delete.
If not specified, defaults to user making
request.
"""
params = {}
if user_name:
params['UserName'] = user_name
return self.get_response('GetUser', params)
def update_user(self, user_name, new_user_name=None, new_path=None):
"""
Updates name and/or path of the specified user.
:type user_name: string
:param user_name: The name of the user
:type new_user_name: string
:param new_user_name: If provided, the username of the user will be
changed to this username.
:type new_path: string
:param new_path: If provided, the path of the user will be
changed to this path.
"""
params = {'UserName' : user_name}
if new_user_name:
params['NewUserName'] = new_user_name
if new_path:
params['NewPath'] = new_path
return self.get_response('UpdateUser', params)
def get_all_user_policies(self, user_name, marker=None, max_items=None):
"""
List the names of the policies associated with the specified user.
:type user_name: string
:param user_name: The name of the user the policy is associated with.
:type marker: string
:param marker: Use this only when paginating results and only in
follow-up request after you've received a response
where the results are truncated. Set this to the
value of the Marker element in the response you
just received.
:type max_items: int
:param max_items: Use this only when paginating results to indicate
the maximum number of groups you want in the
response.
"""
params = {'UserName' : user_name}
if marker:
params['Marker'] = marker
if max_items:
params['MaxItems'] = max_items
return self.get_response('ListUserPolicies', params,
list_marker='PolicyNames')
def put_user_policy(self, user_name, policy_name, policy_json):
"""
Adds or updates the specified policy document for the specified user.
:type user_name: string
:param user_name: The name of the user the policy is associated with.
:type policy_name: string
:param policy_name: The policy document to get.
:type policy_json: string
:param policy_json: The policy document.
"""
params = {'UserName' : user_name,
'PolicyName' : policy_name,
'PolicyDocument' : policy_json}
return self.get_response('PutUserPolicy', params, verb='POST')
def get_user_policy(self, user_name, policy_name):
"""
Retrieves the specified policy document for the specified user.
:type user_name: string
:param user_name: The name of the user the policy is associated with.
:type policy_name: string
:param policy_name: The policy document to get.
"""
params = {'UserName' : user_name,
'PolicyName' : policy_name}
return self.get_response('GetUserPolicy', params, verb='POST')
def delete_user_policy(self, user_name, policy_name):
"""
Deletes the specified policy document for the specified user.
:type user_name: string
:param user_name: The name of the user the policy is associated with.
:type policy_name: string
:param policy_name: The policy document to delete.
"""
params = {'UserName' : user_name,
'PolicyName' : policy_name}
return self.get_response('DeleteUserPolicy', params, verb='POST')
def get_groups_for_user(self, user_name, marker=None, max_items=None):
"""
List the groups that a specified user belongs to.
:type user_name: string
:param user_name: The name of the user to list groups for.
:type marker: string
:param marker: Use this only when paginating results and only in
follow-up request after you've received a response
where the results are truncated. Set this to the
value of the Marker element in the response you
just received.
:type max_items: int
:param max_items: Use this only when paginating results to indicate
the maximum number of groups you want in the
response.
"""
params = {'UserName' : user_name}
if marker:
params['Marker'] = marker
if max_items:
params['MaxItems'] = max_items
return self.get_response('ListUsers', params, list_marker='Groups')
#
# Access Keys
#
def get_all_access_keys(self, user_name, marker=None, max_items=None):
"""
Get all access keys associated with an account.
:type user_name: string
:param user_name: The username of the new user
:type marker: string
:param marker: Use this only when paginating results and only in
follow-up request after you've received a response
where the results are truncated. Set this to the
value of the Marker element in the response you
just received.
:type max_items: int
:param max_items: Use this only when paginating results to indicate
the maximum number of groups you want in the
response.
"""
params = {'UserName' : user_name}
if marker:
params['Marker'] = marker
if max_items:
params['MaxItems'] = max_items
return self.get_response('ListAccessKeys', params,
list_marker='AccessKeyMetadata')
def create_access_key(self, user_name=None):
"""
Create a new AWS Secret Access Key and corresponding AWS Access Key ID
for the specified user. The default status for new keys is Active
If the user_name is not specified, the user_name is determined
implicitly based on the AWS Access Key ID used to sign the request.
:type user_name: string
:param user_name: The username of the new user
"""
params = {'UserName' : user_name}
return self.get_response('CreateAccessKey', params)
def update_access_key(self, access_key_id, status, user_name=None):
"""
Changes the status of the specified access key from Active to Inactive
or vice versa. This action can be used to disable a user's key as
part of a key rotation workflow.
If the user_name is not specified, the user_name is determined
implicitly based on the AWS Access Key ID used to sign the request.
:type access_key_id: string
:param access_key_id: The ID of the access key.
:type status: string
:param status: Either Active or Inactive.
:type user_name: string
:param user_name: The username of user (optional).
"""
params = {'AccessKeyId' : access_key_id,
'Status' : status}
if user_name:
params['UserName'] = user_name
return self.get_response('UpdateAccessKey', params)
def delete_access_key(self, access_key_id, user_name=None):
"""
Delete an access key associated with a user.
If the user_name is not specified, it is determined implicitly based
on the AWS Access Key ID used to sign the request.
:type access_key_id: string
:param access_key_id: The ID of the access key to be deleted.
:type user_name: string
:param user_name: The username of the new user
"""
params = {'AccessKeyId' : access_key_id}
if user_name:
params['UserName'] = user_name
return self.get_response('DeleteAccessKey', params)
#
# Signing Certificates
#
def get_all_signing_certs(self, marker=None, max_items=None,
user_name=None):
"""
Get all signing certificates associated with an account.
If the user_name is not specified, it is determined implicitly based
on the AWS Access Key ID used to sign the request.
:type marker: string
:param marker: Use this only when paginating results and only in
follow-up request after you've received a response
where the results are truncated. Set this to the
value of the Marker element in the response you
just received.
:type max_items: int
:param max_items: Use this only when paginating results to indicate
the maximum number of groups you want in the
response.
:type user_name: string
:param user_name: The username of the user
"""
params = {}
if marker:
params['Marker'] = marker
if max_items:
params['MaxItems'] = max_items
if user_name:
params['UserName'] = user_name
return self.get_response('ListSigningCertificates',
params, list_marker='Certificates')
def update_signing_cert(self, cert_id, status, user_name=None):
"""
Change the status of the specified signing certificate from
Active to Inactive or vice versa.
If the user_name is not specified, it is determined implicitly based
on the AWS Access Key ID used to sign the request.
:type cert_id: string
:param cert_id: The ID of the signing certificate
:type status: string
:param status: Either Active or Inactive.
:type user_name: string
:param user_name: The username of the user
"""
params = {'CertificateId' : cert_id,
'Status' : status}
if user_name:
params['UserName'] = user_name
return self.get_response('UpdateSigningCertificate', params)
def upload_signing_cert(self, cert_body, user_name=None):
"""
Uploads an X.509 signing certificate and associates it with
the specified user.
If the user_name is not specified, it is determined implicitly based
on the AWS Access Key ID used to sign the request.
:type cert_body: string
:param cert_body: The body of the signing certificate.
:type user_name: string
:param user_name: The username of the new user
"""
params = {'CertificateBody' : cert_body}
if user_name:
params['UserName'] = user_name
return self.get_response('UploadSigningCertificate', params,
verb='POST')
def delete_signing_cert(self, cert_id, user_name=None):
"""
Delete a signing certificate associated with a user.
If the user_name is not specified, it is determined implicitly based
on the AWS Access Key ID used to sign the request.
:type user_name: string
:param user_name: The username of the new user
:type cert_id: string
:param cert_id: The ID of the certificate.
"""
params = {'CertificateId' : cert_id}
if user_name:
params['UserName'] = user_name
return self.get_response('DeleteSigningCertificate', params)
#
# MFA Devices
#
def get_all_mfa_devices(self, marker=None, max_items=None,
user_name=None):
"""
Get all MFA devices associated with an account.
If the user_name is not specified, it is determined implicitly based
on the AWS Access Key ID used to sign the request.
:type marker: string
:param marker: Use this only when paginating results and only in
follow-up request after you've received a response
where the results are truncated. Set this to the
value of the Marker element in the response you
just received.
:type max_items: int
:param max_items: Use this only when paginating results to indicate
the maximum number of groups you want in the
response.
:type user_name: string
:param user_name: The username of the user
"""
params = {}
if marker:
params['Marker'] = marker
if max_items:
params['MaxItems'] = max_items
if user_name:
params['UserName'] = user_name
return self.get_response('ListMFADevices',
params, list_marker='MFADevices')
def enable_mfa_device(self, user_name, serial_number,
auth_code_1, auth_code_2):
"""
Enables the specified MFA device and associates it with the
specified user.
:type user_name: string
:param user_name: The username of the user
:type serial_number: string
:param seriasl_number: The serial number which uniquely identifies
the MFA device.
:type auth_code_1: string
:param auth_code_1: An authentication code emitted by the device.
:type auth_code_2: string
:param auth_code_2: A subsequent authentication code emitted
by the device.
"""
params = {'UserName' : user_name,
'SerialNumber' : serial_number,
'AuthenticationCode1' : auth_code_1,
'AuthenticationCode2' : auth_code_2}
return self.get_response('EnableMFADevice', params)
def deactivate_mfa_device(self, user_name, serial_number):
"""
Deactivates the specified MFA device and removes it from
association with the user.
:type user_name: string
:param user_name: The username of the user
:type serial_number: string
:param seriasl_number: The serial number which uniquely identifies
the MFA device.
"""
params = {'UserName' : user_name,
'SerialNumber' : serial_number}
return self.get_response('DeactivateMFADevice', params)
def resync_mfa_device(self, user_name, serial_number,
auth_code_1, auth_code_2):
"""
Syncronizes the specified MFA device with the AWS servers.
:type user_name: string
:param user_name: The username of the user
:type serial_number: string
:param seriasl_number: The serial number which uniquely identifies
the MFA device.
:type auth_code_1: string
:param auth_code_1: An authentication code emitted by the device.
:type auth_code_2: string
:param auth_code_2: A subsequent authentication code emitted
by the device.
"""
params = {'UserName' : user_name,
'SerialNumber' : serial_number,
'AuthenticationCode1' : auth_code_1,
'AuthenticationCode2' : auth_code_2}
return self.get_response('ResyncMFADevice', params)
#
# Login Profiles
#
def create_login_profile(self, user_name, password):
"""
Creates a login profile for the specified user, give the user the
ability to access AWS services and the AWS Management Console.
:type user_name: string
:param user_name: The name of the new user
:type password: string
:param password: The new password for the user
"""
params = {'UserName' : user_name,
'Password' : password}
return self.get_response('CreateLoginProfile', params)
def delete_login_profile(self, user_name):
"""
Deletes the login profile associated with the specified user.
:type user_name: string
:param user_name: The name of the user to delete.
"""
params = {'UserName' : user_name}
return self.get_response('DeleteLoginProfile', params)
def update_login_profile(self, user_name, password):
"""
Resets the password associated with the user's login profile.
:type user_name: string
:param user_name: The name of the user
:type password: string
:param password: The new password for the user
"""
params = {'UserName' : user_name,
'Password' : password}
return self.get_response('UpdateLoginProfile', params)
| Python |
# Copyright (c) 2006,2007 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
class Question(object):
QUESTION_XML_TEMPLATE = """<Question><QuestionIdentifier>%s</QuestionIdentifier>%s<IsRequired>%s</IsRequired>%s%s</Question>"""
DISPLAY_NAME_XML_TEMPLATE = """<DisplayName>%s</DisplayName>"""
def __init__(self, identifier, content, answer_spec, is_required=False, display_name=None): #amount=0.0, currency_code='USD'):
self.identifier = identifier
self.content = content
self.answer_spec = answer_spec
self.is_required = is_required
self.display_name = display_name
def get_as_params(self, label='Question', identifier=None):
if identifier is None:
raise ValueError("identifier (QuestionIdentifier) is required per MTurk spec.")
return { label : self.get_as_xml() }
def get_as_xml(self):
# add the display name if required
display_name_xml = ''
if self.display_name:
display_name_xml = self.DISPLAY_NAME_XML_TEMPLATE %(self.display_name)
ret = Question.QUESTION_XML_TEMPLATE % (self.identifier,
display_name_xml,
str(self.is_required).lower(),
self.content.get_as_xml(),
self.answer_spec.get_as_xml())
return ret
class ExternalQuestion(object):
EXTERNAL_QUESTIONFORM_SCHEMA_LOCATION = "http://mechanicalturk.amazonaws.com/AWSMechanicalTurkDataSchemas/2006-07-14/ExternalQuestion.xsd"
EXTERNAL_QUESTION_XML_TEMPLATE = """<ExternalQuestion xmlns="%s"><ExternalURL>%s</ExternalURL><FrameHeight>%s</FrameHeight></ExternalQuestion>"""
def __init__(self, external_url, frame_height):
self.external_url = external_url
self.frame_height = frame_height
def get_as_params(self, label='ExternalQuestion'):
return { label : self.get_as_xml() }
def get_as_xml(self):
ret = ExternalQuestion.EXTERNAL_QUESTION_XML_TEMPLATE % (ExternalQuestion.EXTERNAL_QUESTIONFORM_SCHEMA_LOCATION,
self.external_url,
self.frame_height)
return ret
class OrderedContent(object):
def __init__(self):
self.items = []
def append(self, field, value):
"Expects field type and value"
self.items.append((field, value))
def get_binary_xml(self, field, value):
return """
<Binary>
<MimeType>
<Type>%s</Type>
<SubType>%s</SubType>
</MimeType>
<DataURL>%s</DataURL>
<AltText>%s</AltText>
</Binary>""" % (value['type'],
value['subtype'],
value['dataurl'],
value['alttext'])
def get_application_xml(self, field, value):
raise NotImplementedError("Application question content is not yet supported.")
def get_as_xml(self):
default_handler = lambda f,v: '<%s>%s</%s>' % (f,v,f)
bulleted_list_handler = lambda _,list: '<List>%s</List>' % ''.join([('<ListItem>%s</ListItem>' % item) for item in list])
formatted_content_handler = lambda _,content: "<FormattedContent><![CDATA[%s]]></FormattedContent>" % content
application_handler = self.get_application_xml
binary_handler = self.get_binary_xml
children = ''
for (field,value) in self.items:
handler = default_handler
if field == 'List':
handler = bulleted_list_handler
elif field == 'Application':
handler = application_handler
elif field == 'Binary':
handler = binary_handler
elif field == 'FormattedContent':
handler = formatted_content_handler
children = children + handler(field, value)
return children
class Overview(object):
OVERVIEW_XML_TEMPLATE = """<Overview>%s</Overview>"""
def __init__(self):
self.ordered_content = OrderedContent()
def append(self, field, value):
self.ordered_content.append(field,value)
def get_as_params(self, label='Overview'):
return { label : self.get_as_xml() }
def get_as_xml(self):
ret = Overview.OVERVIEW_XML_TEMPLATE % (self.ordered_content.get_as_xml())
return ret
class QuestionForm(object):
QUESTIONFORM_SCHEMA_LOCATION = "http://mechanicalturk.amazonaws.com/AWSMechanicalTurkDataSchemas/2005-10-01/QuestionForm.xsd"
QUESTIONFORM_XML_TEMPLATE = """<QuestionForm xmlns="%s">%s</QuestionForm>"""
def __init__(self):
self.items = []
def append(self, item):
"Expects field type and value"
self.items.append(item)
def get_as_xml(self):
xml = ''
for item in self.items:
xml = xml + item.get_as_xml()
return QuestionForm.QUESTIONFORM_XML_TEMPLATE % (QuestionForm.QUESTIONFORM_SCHEMA_LOCATION, xml)
class QuestionContent(object):
QUESTIONCONTENT_XML_TEMPLATE = """<QuestionContent>%s</QuestionContent>"""
def __init__(self):
self.ordered_content = OrderedContent()
def append(self, field, value):
self.ordered_content.append(field,value)
def get_as_xml(self):
ret = QuestionContent.QUESTIONCONTENT_XML_TEMPLATE % (self.ordered_content.get_as_xml())
return ret
class AnswerSpecification(object):
ANSWERSPECIFICATION_XML_TEMPLATE = """<AnswerSpecification>%s</AnswerSpecification>"""
def __init__(self, spec):
self.spec = spec
def get_as_xml(self):
values = () # TODO
return AnswerSpecification.ANSWERSPECIFICATION_XML_TEMPLATE % self.spec.get_as_xml()
class FreeTextAnswer(object):
FREETEXTANSWER_XML_TEMPLATE = """<FreeTextAnswer>%s%s</FreeTextAnswer>""" # (constraints, default)
FREETEXTANSWER_CONSTRAINTS_XML_TEMPLATE = """<Constraints>%s%s%s</Constraints>""" # (is_numeric_xml, length_xml, regex_xml)
FREETEXTANSWER_LENGTH_XML_TEMPLATE = """<Length %s %s />""" # (min_length_attr, max_length_attr)
FREETEXTANSWER_ISNUMERIC_XML_TEMPLATE = """<IsNumeric %s %s />""" # (min_value_attr, max_value_attr)
FREETEXTANSWER_DEFAULTTEXT_XML_TEMPLATE = """<DefaultText>%s</DefaultText>""" # (default)
def __init__(self, default=None, min_length=None, max_length=None, is_numeric=False, min_value=None, max_value=None, format_regex=None):
self.default = default
self.min_length = min_length
self.max_length = max_length
self.is_numeric = is_numeric
self.min_value = min_value
self.max_value = max_value
self.format_regex = format_regex
def get_as_xml(self):
is_numeric_xml = ""
if self.is_numeric:
min_value_attr = ""
max_value_attr = ""
if self.min_value:
min_value_attr = """minValue="%d" """ % self.min_value
if self.max_value:
max_value_attr = """maxValue="%d" """ % self.max_value
is_numeric_xml = FreeTextAnswer.FREETEXTANSWER_ISNUMERIC_XML_TEMPLATE % (min_value_attr, max_value_attr)
length_xml = ""
if self.min_length or self.max_length:
min_length_attr = ""
max_length_attr = ""
if self.min_length:
min_length_attr = """minLength="%d" """
if self.max_length:
max_length_attr = """maxLength="%d" """
length_xml = FreeTextAnswer.FREETEXTANSWER_LENGTH_XML_TEMPLATE % (min_length_attr, max_length_attr)
regex_xml = ""
if self.format_regex:
format_regex_attribs = '''regex="%s"''' %self.format_regex['regex']
error_text = self.format_regex.get('error_text', None)
if error_text:
format_regex_attribs += ' errorText="%s"' %error_text
flags = self.format_regex.get('flags', None)
if flags:
format_regex_attribs += ' flags="%s"' %flags
regex_xml = """<AnswerFormatRegex %s/>""" %format_regex_attribs
constraints_xml = ""
if is_numeric_xml or length_xml or regex_xml:
constraints_xml = FreeTextAnswer.FREETEXTANSWER_CONSTRAINTS_XML_TEMPLATE % (is_numeric_xml, length_xml, regex_xml)
default_xml = ""
if self.default is not None:
default_xml = FreeTextAnswer.FREETEXTANSWER_DEFAULTTEXT_XML_TEMPLATE % self.default
return FreeTextAnswer.FREETEXTANSWER_XML_TEMPLATE % (constraints_xml, default_xml)
class FileUploadAnswer(object):
FILEUPLOADANSWER_XML_TEMLPATE = """<FileUploadAnswer><MinFileSizeInBytes>%d</MinFileSizeInBytes><MaxFileSizeInBytes>%d</MaxFileSizeInBytes></FileUploadAnswer>""" # (min, max)
DEFAULT_MIN_SIZE = 1024 # 1K (completely arbitrary!)
DEFAULT_MAX_SIZE = 5 * 1024 * 1024 # 5MB (completely arbitrary!)
def __init__(self, min=None, max=None):
self.min = min
self.max = max
if self.min is None:
self.min = FileUploadAnswer.DEFAULT_MIN_SIZE
if self.max is None:
self.max = FileUploadAnswer.DEFAULT_MAX_SIZE
def get_as_xml(self):
return FileUploadAnswer.FILEUPLOADANSWER_XML_TEMLPATE % (self.min, self.max)
class SelectionAnswer(object):
"""
A class to generate SelectionAnswer XML data structures.
Does not yet implement Binary selection options.
"""
SELECTIONANSWER_XML_TEMPLATE = """<SelectionAnswer>%s%s<Selections>%s</Selections></SelectionAnswer>""" # % (count_xml, style_xml, selections_xml)
SELECTION_XML_TEMPLATE = """<Selection><SelectionIdentifier>%s</SelectionIdentifier>%s</Selection>""" # (identifier, value_xml)
SELECTION_VALUE_XML_TEMPLATE = """<%s>%s</%s>""" # (type, value, type)
STYLE_XML_TEMPLATE = """<StyleSuggestion>%s</StyleSuggestion>""" # (style)
MIN_SELECTION_COUNT_XML_TEMPLATE = """<MinSelectionCount>%s</MinSelectionCount>""" # count
MAX_SELECTION_COUNT_XML_TEMPLATE = """<MaxSelectionCount>%s</MaxSelectionCount>""" # count
ACCEPTED_STYLES = ['radiobutton', 'dropdown', 'checkbox', 'list', 'combobox', 'multichooser']
OTHER_SELECTION_ELEMENT_NAME = 'OtherSelection'
def __init__(self, min=1, max=1, style=None, selections=None, type='text', other=False):
if style is not None:
if style in SelectionAnswer.ACCEPTED_STYLES:
self.style_suggestion = style
else:
raise ValueError("style '%s' not recognized; should be one of %s" % (style, ', '.join(SelectionAnswer.ACCEPTED_STYLES)))
else:
self.style_suggestion = None
if selections is None:
raise ValueError("SelectionAnswer.__init__(): selections must be a non-empty list of (content, identifier) tuples")
else:
self.selections = selections
self.min_selections = min
self.max_selections = max
assert len(selections) >= self.min_selections, "# of selections is less than minimum of %d" % self.min_selections
#assert len(selections) <= self.max_selections, "# of selections exceeds maximum of %d" % self.max_selections
self.type = type
self.other = other
def get_as_xml(self):
if self.type == 'text':
TYPE_TAG = "Text"
elif self.type == 'binary':
TYPE_TAG = "Binary"
else:
raise ValueError("illegal type: %s; must be either 'text' or 'binary'" % str(self.type))
# build list of <Selection> elements
selections_xml = ""
for tpl in self.selections:
value_xml = SelectionAnswer.SELECTION_VALUE_XML_TEMPLATE % (TYPE_TAG, tpl[0], TYPE_TAG)
selection_xml = SelectionAnswer.SELECTION_XML_TEMPLATE % (tpl[1], value_xml)
selections_xml += selection_xml
if self.other:
# add OtherSelection element as xml if available
if hasattr(self.other, 'get_as_xml'):
assert type(self.other) == FreeTextAnswer, 'OtherSelection can only be a FreeTextAnswer'
selections_xml += self.other.get_as_xml().replace('FreeTextAnswer', 'OtherSelection')
else:
selections_xml += "<OtherSelection />"
if self.style_suggestion is not None:
style_xml = SelectionAnswer.STYLE_XML_TEMPLATE % self.style_suggestion
else:
style_xml = ""
if self.style_suggestion != 'radiobutton':
count_xml = SelectionAnswer.MIN_SELECTION_COUNT_XML_TEMPLATE %self.min_selections
count_xml += SelectionAnswer.MAX_SELECTION_COUNT_XML_TEMPLATE %self.max_selections
else:
count_xml = ""
ret = SelectionAnswer.SELECTIONANSWER_XML_TEMPLATE % (count_xml, style_xml, selections_xml)
# return XML
return ret
| Python |
# Copyright (c) 2006,2007 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
import xml.sax
import datetime
from boto import handler
from boto.mturk.price import Price
import boto.mturk.notification
from boto.connection import AWSQueryConnection
from boto.exception import EC2ResponseError
from boto.resultset import ResultSet
class MTurkConnection(AWSQueryConnection):
APIVersion = '2008-08-02'
SignatureVersion = '1'
def __init__(self, aws_access_key_id=None, aws_secret_access_key=None,
is_secure=False, port=None, proxy=None, proxy_port=None,
proxy_user=None, proxy_pass=None,
host='mechanicalturk.amazonaws.com', debug=0,
https_connection_factory=None):
AWSQueryConnection.__init__(self, aws_access_key_id,
aws_secret_access_key,
is_secure, port, proxy, proxy_port,
proxy_user, proxy_pass, host, debug,
https_connection_factory)
def get_account_balance(self):
"""
"""
params = {}
return self._process_request('GetAccountBalance', params,
[('AvailableBalance', Price),
('OnHoldBalance', Price)])
def register_hit_type(self, title, description, reward, duration,
keywords=None, approval_delay=None, qual_req=None):
"""
Register a new HIT Type
\ttitle, description are strings
\treward is a Price object
\tduration can be an integer or string
"""
params = {'Title' : title,
'Description' : description,
'AssignmentDurationInSeconds' : duration}
params.update(MTurkConnection.get_price_as_price(reward).get_as_params('Reward'))
params.update(qual_req.get_as_params())
if keywords:
params['Keywords'] = keywords
if approval_delay is not None:
params['AutoApprovalDelayInSeconds']= approval_delay
return self._process_request('RegisterHITType', params)
def set_email_notification(self, hit_type, email, event_types=None):
"""
Performs a SetHITTypeNotification operation to set email
notification for a specified HIT type
"""
return self._set_notification(hit_type, 'Email', email, event_types)
def set_rest_notification(self, hit_type, url, event_types=None):
"""
Performs a SetHITTypeNotification operation to set REST notification
for a specified HIT type
"""
return self._set_notification(hit_type, 'REST', url, event_types)
def _set_notification(self, hit_type, transport, destination, event_types=None):
"""
Common SetHITTypeNotification operation to set notification for a
specified HIT type
"""
assert type(hit_type) is str, "hit_type argument should be a string."
params = {'HITTypeId': hit_type}
# from the Developer Guide:
# The 'Active' parameter is optional. If omitted, the active status of
# the HIT type's notification specification is unchanged. All HIT types
# begin with their notification specifications in the "inactive" status.
notification_params = {'Destination': destination,
'Transport': transport,
'Version': boto.mturk.notification.NotificationMessage.NOTIFICATION_VERSION,
'Active': True,
}
# add specific event types if required
if event_types:
self.build_list_params(notification_params, event_types, 'EventType')
# Set up dict of 'Notification.1.Transport' etc. values
notification_rest_params = {}
num = 1
for key in notification_params:
notification_rest_params['Notification.%d.%s' % (num, key)] = notification_params[key]
# Update main params dict
params.update(notification_rest_params)
# Execute operation
return self._process_request('SetHITTypeNotification', params)
def create_hit(self, hit_type=None, question=None, lifetime=60*60*24*7, max_assignments=1,
title=None, description=None, keywords=None, reward=None,
duration=60*60*24*7, approval_delay=None, annotation=None,
questions=None, qualifications=None, response_groups=None):
"""
Creates a new HIT.
Returns a ResultSet
See: http://docs.amazonwebservices.com/AWSMechanicalTurkRequester/2006-10-31/ApiReference_CreateHITOperation.html
"""
# handle single or multiple questions
if question is not None and questions is not None:
raise ValueError("Must specify either question (single Question instance) or questions (list), but not both")
if question is not None and questions is None:
questions = [question]
# Handle basic required arguments and set up params dict
params = {'Question': question.get_as_xml(),
'LifetimeInSeconds' : lifetime,
'MaxAssignments' : max_assignments,
}
# if hit type specified then add it
# else add the additional required parameters
if hit_type:
params['HITTypeId'] = hit_type
else:
# Handle keywords
final_keywords = MTurkConnection.get_keywords_as_string(keywords)
# Handle price argument
final_price = MTurkConnection.get_price_as_price(reward)
additional_params = {'Title': title,
'Description' : description,
'Keywords': final_keywords,
'AssignmentDurationInSeconds' : duration,
}
additional_params.update(final_price.get_as_params('Reward'))
if approval_delay is not None:
additional_params['AutoApprovalDelayInSeconds'] = approval_delay
# add these params to the others
params.update(additional_params)
# add the annotation if specified
if annotation is not None:
params['RequesterAnnotation'] = annotation
# Add the Qualifications if specified
if qualifications is not None:
params.update(qualifications.get_as_params())
# Handle optional response groups argument
if response_groups:
self.build_list_params(params, response_groups, 'ResponseGroup')
# Submit
return self._process_request('CreateHIT', params, [('HIT', HIT),])
def change_hit_type_of_hit(self, hit_id, hit_type):
"""
Change the HIT type of an existing HIT. Note that the reward associated
with the new HIT type must match the reward of the current HIT type in
order for the operation to be valid.
\thit_id is a string
\thit_type is a string
"""
params = {'HITId' : hit_id,
'HITTypeId': hit_type}
return self._process_request('ChangeHITTypeOfHIT', params)
def get_reviewable_hits(self, hit_type=None, status='Reviewable',
sort_by='Expiration', sort_direction='Ascending',
page_size=10, page_number=1):
"""
Retrieve the HITs that have a status of Reviewable, or HITs that
have a status of Reviewing, and that belong to the Requester
calling the operation.
"""
params = {'Status' : status,
'SortProperty' : sort_by,
'SortDirection' : sort_direction,
'PageSize' : page_size,
'PageNumber' : page_number}
# Handle optional hit_type argument
if hit_type is not None:
params.update({'HITTypeId': hit_type})
return self._process_request('GetReviewableHITs', params, [('HIT', HIT),])
def search_hits(self, sort_by='CreationTime', sort_direction='Ascending',
page_size=10, page_number=1, response_groups=None):
"""
Return all of a Requester's HITs, on behalf of the Requester.
The operation returns HITs of any status, except for HITs that have been
disposed with the DisposeHIT operation.
Note:
The SearchHITs operation does not accept any search parameters that
filter the results.
"""
params = {'SortProperty' : sort_by,
'SortDirection' : sort_direction,
'PageSize' : page_size,
'PageNumber' : page_number}
# Handle optional response groups argument
if response_groups:
self.build_list_params(params, response_groups, 'ResponseGroup')
return self._process_request('SearchHITs', params, [('HIT', HIT),])
def get_assignments(self, hit_id, status=None,
sort_by='SubmitTime', sort_direction='Ascending',
page_size=10, page_number=1, response_groups=None):
"""
Retrieves completed assignments for a HIT.
Use this operation to retrieve the results for a HIT.
The returned ResultSet will have the following attributes:
NumResults
The number of assignments on the page in the filtered results
list, equivalent to the number of assignments being returned
by this call.
A non-negative integer
PageNumber
The number of the page in the filtered results list being
returned.
A positive integer
TotalNumResults
The total number of HITs in the filtered results list based
on this call.
A non-negative integer
The ResultSet will contain zero or more Assignment objects
"""
params = {'HITId' : hit_id,
'SortProperty' : sort_by,
'SortDirection' : sort_direction,
'PageSize' : page_size,
'PageNumber' : page_number}
if status is not None:
params['AssignmentStatus'] = status
# Handle optional response groups argument
if response_groups:
self.build_list_params(params, response_groups, 'ResponseGroup')
return self._process_request('GetAssignmentsForHIT', params,
[('Assignment', Assignment),])
def approve_assignment(self, assignment_id, feedback=None):
"""
"""
params = {'AssignmentId' : assignment_id,}
if feedback:
params['RequesterFeedback'] = feedback
return self._process_request('ApproveAssignment', params)
def reject_assignment(self, assignment_id, feedback=None):
"""
"""
params = {'AssignmentId' : assignment_id,}
if feedback:
params['RequesterFeedback'] = feedback
return self._process_request('RejectAssignment', params)
def get_hit(self, hit_id, response_groups=None):
"""
"""
params = {'HITId' : hit_id,}
# Handle optional response groups argument
if response_groups:
self.build_list_params(params, response_groups, 'ResponseGroup')
return self._process_request('GetHIT', params, [('HIT', HIT),])
def set_reviewing(self, hit_id, revert=None):
"""
Update a HIT with a status of Reviewable to have a status of Reviewing,
or reverts a Reviewing HIT back to the Reviewable status.
Only HITs with a status of Reviewable can be updated with a status of
Reviewing. Similarly, only Reviewing HITs can be reverted back to a
status of Reviewable.
"""
params = {'HITId' : hit_id,}
if revert:
params['Revert'] = revert
return self._process_request('SetHITAsReviewing', params)
def disable_hit(self, hit_id, response_groups=None):
"""
Remove a HIT from the Mechanical Turk marketplace, approves all
submitted assignments that have not already been approved or rejected,
and disposes of the HIT and all assignment data.
Assignments for the HIT that have already been submitted, but not yet
approved or rejected, will be automatically approved. Assignments in
progress at the time of the call to DisableHIT will be approved once
the assignments are submitted. You will be charged for approval of
these assignments. DisableHIT completely disposes of the HIT and
all submitted assignment data. Assignment results data cannot be
retrieved for a HIT that has been disposed.
It is not possible to re-enable a HIT once it has been disabled.
To make the work from a disabled HIT available again, create a new HIT.
"""
params = {'HITId' : hit_id,}
# Handle optional response groups argument
if response_groups:
self.build_list_params(params, response_groups, 'ResponseGroup')
return self._process_request('DisableHIT', params)
def dispose_hit(self, hit_id):
"""
Dispose of a HIT that is no longer needed.
Only HITs in the "reviewable" state, with all submitted
assignments approved or rejected, can be disposed. A Requester
can call GetReviewableHITs to determine which HITs are
reviewable, then call GetAssignmentsForHIT to retrieve the
assignments. Disposing of a HIT removes the HIT from the
results of a call to GetReviewableHITs. """
params = {'HITId' : hit_id,}
return self._process_request('DisposeHIT', params)
def expire_hit(self, hit_id):
"""
Expire a HIT that is no longer needed.
The effect is identical to the HIT expiring on its own. The
HIT no longer appears on the Mechanical Turk web site, and no
new Workers are allowed to accept the HIT. Workers who have
accepted the HIT prior to expiration are allowed to complete
it or return it, or allow the assignment duration to elapse
(abandon the HIT). Once all remaining assignments have been
submitted, the expired HIT becomes"reviewable", and will be
returned by a call to GetReviewableHITs.
"""
params = {'HITId' : hit_id,}
return self._process_request('ForceExpireHIT', params)
def extend_hit(self, hit_id, assignments_increment=None, expiration_increment=None):
"""
Increase the maximum number of assignments, or extend the
expiration date, of an existing HIT.
NOTE: If a HIT has a status of Reviewable and the HIT is
extended to make it Available, the HIT will not be returned by
GetReviewableHITs, and its submitted assignments will not be
returned by GetAssignmentsForHIT, until the HIT is Reviewable
again. Assignment auto-approval will still happen on its
original schedule, even if the HIT has been extended. Be sure
to retrieve and approve (or reject) submitted assignments
before extending the HIT, if so desired.
"""
# must provide assignment *or* expiration increment
if (assignments_increment is None and expiration_increment is None) or \
(assignments_increment is not None and expiration_increment is not None):
raise ValueError("Must specify either assignments_increment or expiration_increment, but not both")
params = {'HITId' : hit_id,}
if assignments_increment:
params['MaxAssignmentsIncrement'] = assignments_increment
if expiration_increment:
params['ExpirationIncrementInSeconds'] = expiration_increment
return self._process_request('ExtendHIT', params)
def get_help(self, about, help_type='Operation'):
"""
Return information about the Mechanical Turk Service
operations and response group NOTE - this is basically useless
as it just returns the URL of the documentation
help_type: either 'Operation' or 'ResponseGroup'
"""
params = {'About': about, 'HelpType': help_type,}
return self._process_request('Help', params)
def grant_bonus(self, worker_id, assignment_id, bonus_price, reason):
"""
Issues a payment of money from your account to a Worker. To
be eligible for a bonus, the Worker must have submitted
results for one of your HITs, and have had those results
approved or rejected. This payment happens separately from the
reward you pay to the Worker when you approve the Worker's
assignment. The Bonus must be passed in as an instance of the
Price object.
"""
params = bonus_price.get_as_params('BonusAmount', 1)
params['WorkerId'] = worker_id
params['AssignmentId'] = assignment_id
params['Reason'] = reason
return self._process_request('GrantBonus', params)
def block_worker(self, worker_id, reason):
"""
Block a worker from working on my tasks.
"""
params = {'WorkerId': worker_id, 'Reason': reason}
return self._process_request('BlockWorker', params)
def unblock_worker(self, worker_id, reason):
"""
Unblock a worker from working on my tasks.
"""
params = {'WorkerId': worker_id, 'Reason': reason}
return self._process_request('UnblockWorker', params)
def _process_request(self, request_type, params, marker_elems=None):
"""
Helper to process the xml response from AWS
"""
response = self.make_request(request_type, params, verb='POST')
return self._process_response(response, marker_elems)
def _process_response(self, response, marker_elems=None):
"""
Helper to process the xml response from AWS
"""
body = response.read()
#print body
if '<Errors>' not in body:
rs = ResultSet(marker_elems)
h = handler.XmlHandler(rs, self)
xml.sax.parseString(body, h)
return rs
else:
raise EC2ResponseError(response.status, response.reason, body)
@staticmethod
def get_keywords_as_string(keywords):
"""
Returns a comma+space-separated string of keywords from either
a list or a string
"""
if type(keywords) is list:
keywords = ', '.join(keywords)
if type(keywords) is str:
final_keywords = keywords
elif type(keywords) is unicode:
final_keywords = keywords.encode('utf-8')
elif keywords is None:
final_keywords = ""
else:
raise TypeError("keywords argument must be a string or a list of strings; got a %s" % type(keywords))
return final_keywords
@staticmethod
def get_price_as_price(reward):
"""
Returns a Price data structure from either a float or a Price
"""
if isinstance(reward, Price):
final_price = reward
else:
final_price = Price(reward)
return final_price
class BaseAutoResultElement:
"""
Base class to automatically add attributes when parsing XML
"""
def __init__(self, connection):
self.connection = connection
def startElement(self, name, attrs, connection):
return None
def endElement(self, name, value, connection):
setattr(self, name, value)
class HIT(BaseAutoResultElement):
"""
Class to extract a HIT structure from a response (used in ResultSet)
Will have attributes named as per the Developer Guide,
e.g. HITId, HITTypeId, CreationTime
"""
# property helper to determine if HIT has expired
def _has_expired(self):
""" Has this HIT expired yet? """
expired = False
if hasattr(self, 'Expiration'):
now = datetime.datetime.utcnow()
expiration = datetime.datetime.strptime(self.Expiration, '%Y-%m-%dT%H:%M:%SZ')
expired = (now >= expiration)
else:
raise ValueError("ERROR: Request for expired property, but no Expiration in HIT!")
return expired
# are we there yet?
expired = property(_has_expired)
class Assignment(BaseAutoResultElement):
"""
Class to extract an Assignment structure from a response (used in
ResultSet)
Will have attributes named as per the Developer Guide,
e.g. AssignmentId, WorkerId, HITId, Answer, etc
"""
def __init__(self, connection):
BaseAutoResultElement.__init__(self, connection)
self.answers = []
def endElement(self, name, value, connection):
# the answer consists of embedded XML, so it needs to be parsed independantly
if name == 'Answer':
answer_rs = ResultSet([('Answer', QuestionFormAnswer),])
h = handler.XmlHandler(answer_rs, connection)
value = self.connection.get_utf8_value(value)
xml.sax.parseString(value, h)
self.answers.append(answer_rs)
else:
BaseAutoResultElement.endElement(self, name, value, connection)
class QuestionFormAnswer(BaseAutoResultElement):
"""
Class to extract Answers from inside the embedded XML
QuestionFormAnswers element inside the Answer element which is
part of the Assignment structure
A QuestionFormAnswers element contains an Answer element for each
question in the HIT or Qualification test for which the Worker
provided an answer. Each Answer contains a QuestionIdentifier
element whose value corresponds to the QuestionIdentifier of a
Question in the QuestionForm. See the QuestionForm data structure
for more information about questions and answer specifications.
If the question expects a free-text answer, the Answer element
contains a FreeText element. This element contains the Worker's
answer
*NOTE* - currently really only supports free-text answers
"""
def __init__(self, connection):
BaseAutoResultElement.__init__(self, connection)
self.fields = []
self.qid = None
def endElement(self, name, value, connection):
if name == 'QuestionIdentifier':
self.qid = value
elif name == 'FreeText' and self.qid:
self.fields.append((self.qid,value))
elif name == 'Answer':
self.qid = None
| Python |
# Copyright (c) 2006,2007 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
"""
Provides NotificationMessage and Event classes, with utility methods, for
implementations of the Mechanical Turk Notification API.
"""
import hmac
try:
from hashlib import sha1 as sha
except ImportError:
import sha
import base64
import re
class NotificationMessage:
NOTIFICATION_WSDL = "http://mechanicalturk.amazonaws.com/AWSMechanicalTurk/2006-05-05/AWSMechanicalTurkRequesterNotification.wsdl"
NOTIFICATION_VERSION = '2006-05-05'
SERVICE_NAME = "AWSMechanicalTurkRequesterNotification"
OPERATION_NAME = "Notify"
EVENT_PATTERN = r"Event\.(?P<n>\d+)\.(?P<param>\w+)"
EVENT_RE = re.compile(EVENT_PATTERN)
def __init__(self, d):
"""
Constructor; expects parameter d to be a dict of string parameters from a REST transport notification message
"""
self.signature = d['Signature'] # vH6ZbE0NhkF/hfNyxz2OgmzXYKs=
self.timestamp = d['Timestamp'] # 2006-05-23T23:22:30Z
self.version = d['Version'] # 2006-05-05
assert d['method'] == NotificationMessage.OPERATION_NAME, "Method should be '%s'" % NotificationMessage.OPERATION_NAME
# Build Events
self.events = []
events_dict = {}
if 'Event' in d:
# TurboGears surprised me by 'doing the right thing' and making { 'Event': { '1': { 'EventType': ... } } } etc.
events_dict = d['Event']
else:
for k in d:
v = d[k]
if k.startswith('Event.'):
ed = NotificationMessage.EVENT_RE.search(k).groupdict()
n = int(ed['n'])
param = str(ed['param'])
if n not in events_dict:
events_dict[n] = {}
events_dict[n][param] = v
for n in events_dict:
self.events.append(Event(events_dict[n]))
def verify(self, secret_key):
"""
Verifies the authenticity of a notification message.
"""
verification_input = NotificationMessage.SERVICE_NAME + NotificationMessage.OPERATION_NAME + self.timestamp
h = hmac.new(key=secret_key, digestmod=sha)
h.update(verification_input)
signature_calc = base64.b64encode(h.digest())
return self.signature == signature_calc
class Event:
def __init__(self, d):
self.event_type = d['EventType']
self.event_time_str = d['EventTime']
self.hit_type = d['HITTypeId']
self.hit_id = d['HITId']
self.assignment_id = d['AssignmentId']
#TODO: build self.event_time datetime from string self.event_time_str
def __repr__(self):
return "<boto.mturk.notification.Event: %s for HIT # %s>" % (self.event_type, self.hit_id)
| Python |
# Copyright (c) 2006,2007 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
class Price:
def __init__(self, amount=0.0, currency_code='USD'):
self.amount = amount
self.currency_code = currency_code
self.formatted_price = ''
def __repr__(self):
if self.formatted_price:
return self.formatted_price
else:
return str(self.amount)
def startElement(self, name, attrs, connection):
return None
def endElement(self, name, value, connection):
if name == 'Amount':
self.amount = float(value)
elif name == 'CurrencyCode':
self.currency_code = value
elif name == 'FormattedPrice':
self.formatted_price = value
def get_as_params(self, label, ord=1):
return {'%s.%d.Amount'%(label, ord) : str(self.amount),
'%s.%d.CurrencyCode'%(label, ord) : self.currency_code}
| Python |
# Copyright (c) 2006,2007 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
| Python |
# Copyright (c) 2008 Chris Moyer http://coredumped.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
class Qualifications:
def __init__(self, requirements=None):
if requirements == None:
requirements = []
self.requirements = requirements
def add(self, req):
self.requirements.append(req)
def get_as_params(self):
params = {}
assert(len(self.requirements) <= 10)
for n, req in enumerate(self.requirements):
reqparams = req.get_as_params()
for rp in reqparams:
params['QualificationRequirement.%s.%s' % ((n+1),rp) ] = reqparams[rp]
return params
class Requirement(object):
"""
Representation of a single requirement
"""
def __init__(self, qualification_type_id, comparator, integer_value, required_to_preview=False):
self.qualification_type_id = qualification_type_id
self.comparator = comparator
self.integer_value = integer_value
self.required_to_preview = required_to_preview
def get_as_params(self):
params = {
"QualificationTypeId": self.qualification_type_id,
"Comparator": self.comparator,
"IntegerValue": self.integer_value,
}
if self.required_to_preview:
params['RequiredToPreview'] = "true"
return params
class PercentAssignmentsSubmittedRequirement(Requirement):
"""
The percentage of assignments the Worker has submitted, over all assignments the Worker has accepted. The value is an integer between 0 and 100.
"""
def __init__(self, comparator, integer_value, required_to_preview=False):
Requirement.__init__(self, qualification_type_id="00000000000000000000", comparator=comparator, integer_value=integer_value, required_to_preview=required_to_preview)
class PercentAssignmentsAbandonedRequirement(Requirement):
"""
The percentage of assignments the Worker has abandoned (allowed the deadline to elapse), over all assignments the Worker has accepted. The value is an integer between 0 and 100.
"""
def __init__(self, comparator, integer_value, required_to_preview=False):
Requirement.__init__(self, qualification_type_id="00000000000000000070", comparator=comparator, integer_value=integer_value, required_to_preview=required_to_preview)
class PercentAssignmentsReturnedRequirement(Requirement):
"""
The percentage of assignments the Worker has returned, over all assignments the Worker has accepted. The value is an integer between 0 and 100.
"""
def __init__(self, comparator, integer_value, required_to_preview=False):
Requirement.__init__(self, qualification_type_id="000000000000000000E0", comparator=comparator, integer_value=integer_value, required_to_preview=required_to_preview)
class PercentAssignmentsApprovedRequirement(Requirement):
"""
The percentage of assignments the Worker has submitted that were subsequently approved by the Requester, over all assignments the Worker has submitted. The value is an integer between 0 and 100.
"""
def __init__(self, comparator, integer_value, required_to_preview=False):
Requirement.__init__(self, qualification_type_id="000000000000000000L0", comparator=comparator, integer_value=integer_value, required_to_preview=required_to_preview)
class PercentAssignmentsRejectedRequirement(Requirement):
"""
The percentage of assignments the Worker has submitted that were subsequently rejected by the Requester, over all assignments the Worker has submitted. The value is an integer between 0 and 100.
"""
def __init__(self, comparator, integer_value, required_to_preview=False):
Requirement.__init__(self, qualification_type_id="000000000000000000S0", comparator=comparator, integer_value=integer_value, required_to_preview=required_to_preview)
class LocaleRequirement(Requirement):
"""
A Qualification requirement based on the Worker's location. The Worker's location is specified by the Worker to Mechanical Turk when the Worker creates his account.
"""
def __init__(self, comparator, locale, required_to_preview=False):
Requirement.__init__(self, qualification_type_id="00000000000000000071", comparator=comparator, integer_value=None, required_to_preview=required_to_preview)
self.locale = locale
def get_as_params(self):
params = {
"QualificationTypeId": self.qualification_type_id,
"Comparator": self.comparator,
'LocaleValue.Country': self.locale,
}
if self.required_to_preview:
params['RequiredToPreview'] = "true"
return params
| Python |
from boto.mturk.connection import MTurkConnection
from boto.mturk.question import ExternalQuestion
def test():
q = ExternalQuestion(external_url="http://websort.net/s/F3481C", frame_height=800)
conn = MTurkConnection(host='mechanicalturk.sandbox.amazonaws.com')
keywords=['boto', 'test', 'doctest']
create_hit_rs = conn.create_hit(question=q, lifetime=60*65,max_assignments=2,title="Boto External Question Test", keywords=keywords,reward = 0.05, duration=60*6,approval_delay=60*60, annotation='An annotation from boto external question test', response_groups=['Minimal','HITDetail','HITQuestion','HITAssignmentSummary',])
assert(create_hit_rs.status == True)
if __name__ == "__main__":
test()
| Python |
import doctest
# doctest.testfile("create_hit.doctest")
# doctest.testfile("create_hit_binary.doctest")
doctest.testfile("create_free_text_question_regex.doctest")
# doctest.testfile("create_hit_from_hit_type.doctest")
# doctest.testfile("search_hits.doctest")
# doctest.testfile("reviewable_hits.doctest")
| Python |
from boto.mturk.connection import MTurkConnection
from boto.mturk.question import ExternalQuestion
from boto.mturk.qualification import Qualifications, PercentAssignmentsApprovedRequirement
def test():
q = ExternalQuestion(external_url="http://websort.net/s/F3481C", frame_height=800)
conn = MTurkConnection(host='mechanicalturk.sandbox.amazonaws.com')
keywords=['boto', 'test', 'doctest']
qualifications = Qualifications()
qualifications.add(PercentAssignmentsApprovedRequirement(comparator="GreaterThan", integer_value="95"))
create_hit_rs = conn.create_hit(question=q, lifetime=60*65,max_assignments=2,title="Boto External Question Test", keywords=keywords,reward = 0.05, duration=60*6,approval_delay=60*60, annotation='An annotation from boto external question test', qualifications=qualifications)
assert(create_hit_rs.status == True)
print create_hit_rs.HITTypeId
if __name__ == "__main__":
test()
| Python |
from boto.mturk.connection import MTurkConnection
def cleanup():
"""Remove any boto test related HIT's"""
conn = MTurkConnection(host='mechanicalturk.sandbox.amazonaws.com')
current_page = 1
page_size = 10
total_disabled = 0
ignored = []
while True:
# reset the total for this loop
disabled_count = 0
# search all the hits in the sandbox
search_rs = conn.search_hits(page_size=page_size, page_number=current_page)
# success?
if search_rs.status:
for hit in search_rs:
# delete any with Boto in the description
print 'hit id:%s Status:%s, desc:%s' %(hit.HITId, hit.HITStatus, hit.Description)
if hit.Description.find('Boto') != -1:
if hit.HITStatus != 'Reviewable':
print 'Disabling hit id:%s %s' %(hit.HITId, hit.Description)
disable_rs = conn.disable_hit(hit.HITId)
if disable_rs.status:
disabled_count += 1
# update the running total
total_disabled += 1
else:
print 'Error when disabling, code:%s, message:%s' %(disable_rs.Code, disable_rs.Message)
else:
print 'Disposing hit id:%s %s' %(hit.HITId, hit.Description)
dispose_rs = conn.dispose_hit(hit.HITId)
if dispose_rs.status:
disabled_count += 1
# update the running total
total_disabled += 1
else:
print 'Error when disposing, code:%s, message:%s' %(dispose_rs.Code, dispose_rs.Message)
else:
if hit.HITId not in ignored:
print 'ignored:%s' %hit.HITId
ignored.append(hit.HITId)
# any more results?
if int(search_rs.TotalNumResults) > current_page*page_size:
# if we have disabled any HITs on this page
# then we don't need to go to a new page
# otherwise we do
if not disabled_count:
current_page += 1
else:
# no, we're done
break
else:
print 'Error performing search, code:%s, message:%s' %(search_rs.Code, search_rs.Message)
break
total_ignored = len(ignored)
print 'Processed: %d HITs, disabled/disposed: %d, ignored: %d' %(total_ignored + total_disabled, total_disabled, total_ignored)
if __name__ == '__main__':
cleanup()
| Python |
# Copyright (c) 2010 Spotify AB
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
class BootstrapAction(object):
def __init__(self, name, path, bootstrap_action_args):
self.name = name
self.path = path
if isinstance(bootstrap_action_args, basestring):
bootstrap_action_args = [bootstrap_action_args]
self.bootstrap_action_args = bootstrap_action_args
def args(self):
args = []
if self.bootstrap_action_args:
args.extend(self.bootstrap_action_args)
return args
| Python |
# Copyright (c) 2010 Spotify AB
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
class Step(object):
"""
Jobflow Step base class
"""
def jar(self):
"""
:rtype: str
:return: URI to the jar
"""
raise NotImplemented()
def args(self):
"""
:rtype: list(str)
:return: List of arguments for the step
"""
raise NotImplemented()
def main_class(self):
"""
:rtype: str
:return: The main class name
"""
raise NotImplemented()
class JarStep(Step):
"""
Custom jar step
"""
def __init__(self, name, jar, main_class=None,
action_on_failure='TERMINATE_JOB_FLOW', step_args=None):
"""
A elastic mapreduce step that executes a jar
:type name: str
:param name: The name of the step
:type jar: str
:param jar: S3 URI to the Jar file
:type main_class: str
:param main_class: The class to execute in the jar
:type action_on_failure: str
:param action_on_failure: An action, defined in the EMR docs to take on failure.
:type step_args: list(str)
:param step_args: A list of arguments to pass to the step
"""
self.name = name
self._jar = jar
self._main_class = main_class
self.action_on_failure = action_on_failure
if isinstance(step_args, basestring):
step_args = [step_args]
self.step_args = step_args
def jar(self):
return self._jar
def args(self):
args = []
if self.step_args:
args.extend(self.step_args)
return args
def main_class(self):
return self._main_class
class StreamingStep(Step):
"""
Hadoop streaming step
"""
def __init__(self, name, mapper, reducer,
action_on_failure='TERMINATE_JOB_FLOW',
cache_files=None, cache_archives=None,
step_args=None, input=None, output=None):
"""
A hadoop streaming elastic mapreduce step
:type name: str
:param name: The name of the step
:type mapper: str
:param mapper: The mapper URI
:type reducer: str
:param reducer: The reducer URI
:type action_on_failure: str
:param action_on_failure: An action, defined in the EMR docs to take on failure.
:type cache_files: list(str)
:param cache_files: A list of cache files to be bundled with the job
:type cache_archives: list(str)
:param cache_archives: A list of jar archives to be bundled with the job
:type step_args: list(str)
:param step_args: A list of arguments to pass to the step
:type input: str or a list of str
:param input: The input uri
:type output: str
:param output: The output uri
"""
self.name = name
self.mapper = mapper
self.reducer = reducer
self.action_on_failure = action_on_failure
self.cache_files = cache_files
self.cache_archives = cache_archives
self.input = input
self.output = output
if isinstance(step_args, basestring):
step_args = [step_args]
self.step_args = step_args
def jar(self):
return '/home/hadoop/contrib/streaming/hadoop-0.18-streaming.jar'
def main_class(self):
return None
def args(self):
args = ['-mapper', self.mapper,
'-reducer', self.reducer]
if self.input:
if isinstance(self.input, list):
for input in self.input:
args.extend(('-input', input))
else:
args.extend(('-input', self.input))
if self.output:
args.extend(('-output', self.output))
if self.cache_files:
for cache_file in self.cache_files:
args.extend(('-cacheFile', cache_file))
if self.cache_archives:
for cache_archive in self.cache_archives:
args.extend(('-cacheArchive', cache_archive))
if self.step_args:
args.extend(self.step_args)
return args
| Python |
# Copyright (c) 2010 Spotify AB
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
"""
Represents a connection to the EMR service
"""
import types
import boto
from boto.ec2.regioninfo import RegionInfo
from boto.emr.emrobject import JobFlow, RunJobFlowResponse
from boto.emr.step import JarStep
from boto.connection import AWSQueryConnection
from boto.exception import EmrResponseError
class EmrConnection(AWSQueryConnection):
APIVersion = boto.config.get('Boto', 'emr_version', '2009-03-31')
DefaultRegionName = boto.config.get('Boto', 'emr_region_name', 'us-east-1')
DefaultRegionEndpoint = boto.config.get('Boto', 'emr_region_endpoint',
'elasticmapreduce.amazonaws.com')
ResponseError = EmrResponseError
# Constants for AWS Console debugging
DebuggingJar = 's3n://us-east-1.elasticmapreduce/libs/script-runner/script-runner.jar'
DebuggingArgs = 's3n://us-east-1.elasticmapreduce/libs/state-pusher/0.1/fetch'
def __init__(self, aws_access_key_id=None, aws_secret_access_key=None,
is_secure=True, port=None, proxy=None, proxy_port=None,
proxy_user=None, proxy_pass=None, debug=0,
https_connection_factory=None, region=None, path='/'):
if not region:
region = RegionInfo(self, self.DefaultRegionName, self.DefaultRegionEndpoint)
self.region = region
AWSQueryConnection.__init__(self, aws_access_key_id,
aws_secret_access_key,
is_secure, port, proxy, proxy_port,
proxy_user, proxy_pass,
self.region.endpoint, debug,
https_connection_factory, path)
def describe_jobflow(self, jobflow_id):
"""
Describes a single Elastic MapReduce job flow
:type jobflow_id: str
:param jobflow_id: The job flow id of interest
"""
jobflows = self.describe_jobflows(jobflow_ids=[jobflow_id])
if jobflows:
return jobflows[0]
def describe_jobflows(self, states=None, jobflow_ids=None,
created_after=None, created_before=None):
"""
Retrieve all the Elastic MapReduce job flows on your account
:type states: list
:param states: A list of strings with job flow states wanted
:type jobflow_ids: list
:param jobflow_ids: A list of job flow IDs
:type created_after: datetime
:param created_after: Bound on job flow creation time
:type created_before: datetime
:param created_before: Bound on job flow creation time
"""
params = {}
if states:
self.build_list_params(params, states, 'JobFlowStates.member')
if jobflow_ids:
self.build_list_params(params, jobflow_ids, 'JobFlowIds.member')
if created_after:
params['CreatedAfter'] = created_after.strftime('%Y-%m-%dT%H:%M:%S')
if created_before:
params['CreatedBefore'] = created_before.strftime('%Y-%m-%dT%H:%M:%S')
return self.get_list('DescribeJobFlows', params, [('member', JobFlow)])
def terminate_jobflow(self, jobflow_id):
"""
Terminate an Elastic MapReduce job flow
:type jobflow_id: str
:param jobflow_id: A jobflow id
"""
self.terminate_jobflows([jobflow_id])
def terminate_jobflows(self, jobflow_ids):
"""
Terminate an Elastic MapReduce job flow
:type jobflow_ids: list
:param jobflow_ids: A list of job flow IDs
"""
params = {}
self.build_list_params(params, jobflow_ids, 'JobFlowIds.member')
return self.get_status('TerminateJobFlows', params)
def add_jobflow_steps(self, jobflow_id, steps):
"""
Adds steps to a jobflow
:type jobflow_id: str
:param jobflow_id: The job flow id
:type steps: list(boto.emr.Step)
:param steps: A list of steps to add to the job
"""
if type(steps) != types.ListType:
steps = [steps]
params = {}
params['JobFlowId'] = jobflow_id
# Step args
step_args = [self._build_step_args(step) for step in steps]
params.update(self._build_step_list(step_args))
return self.get_object('AddJobFlowSteps', params, RunJobFlowResponse)
def run_jobflow(self, name, log_uri, ec2_keyname=None, availability_zone=None,
master_instance_type='m1.small',
slave_instance_type='m1.small', num_instances=1,
action_on_failure='TERMINATE_JOB_FLOW', keep_alive=False,
enable_debugging=False,
hadoop_version='0.18',
steps=[],
bootstrap_actions=[]):
"""
Runs a job flow
:type name: str
:param name: Name of the job flow
:type log_uri: str
:param log_uri: URI of the S3 bucket to place logs
:type ec2_keyname: str
:param ec2_keyname: EC2 key used for the instances
:type availability_zone: str
:param availability_zone: EC2 availability zone of the cluster
:type master_instance_type: str
:param master_instance_type: EC2 instance type of the master
:type slave_instance_type: str
:param slave_instance_type: EC2 instance type of the slave nodes
:type num_instances: int
:param num_instances: Number of instances in the Hadoop cluster
:type action_on_failure: str
:param action_on_failure: Action to take if a step terminates
:type keep_alive: bool
:param keep_alive: Denotes whether the cluster should stay alive upon completion
:type enable_debugging: bool
:param enable_debugging: Denotes whether AWS console debugging should be enabled.
:type steps: list(boto.emr.Step)
:param steps: List of steps to add with the job
:rtype: str
:return: The jobflow id
"""
params = {}
if action_on_failure:
params['ActionOnFailure'] = action_on_failure
params['Name'] = name
params['LogUri'] = log_uri
# Instance args
instance_params = self._build_instance_args(ec2_keyname, availability_zone,
master_instance_type, slave_instance_type,
num_instances, keep_alive, hadoop_version)
params.update(instance_params)
# Debugging step from EMR API docs
if enable_debugging:
debugging_step = JarStep(name='Setup Hadoop Debugging',
action_on_failure='TERMINATE_JOB_FLOW',
main_class=None,
jar=self.DebuggingJar,
step_args=self.DebuggingArgs)
steps.insert(0, debugging_step)
# Step args
if steps:
step_args = [self._build_step_args(step) for step in steps]
params.update(self._build_step_list(step_args))
if bootstrap_actions:
bootstrap_action_args = [self._build_bootstrap_action_args(bootstrap_action) for bootstrap_action in bootstrap_actions]
params.update(self._build_bootstrap_action_list(bootstrap_action_args))
response = self.get_object('RunJobFlow', params, RunJobFlowResponse)
return response.jobflowid
def _build_bootstrap_action_args(self, bootstrap_action):
bootstrap_action_params = {}
bootstrap_action_params['ScriptBootstrapAction.Path'] = bootstrap_action.path
try:
bootstrap_action_params['Name'] = bootstrap_action.name
except AttributeError:
pass
args = bootstrap_action.args()
if args:
self.build_list_params(bootstrap_action_params, args, 'ScriptBootstrapAction.Args.member')
return bootstrap_action_params
def _build_step_args(self, step):
step_params = {}
step_params['ActionOnFailure'] = step.action_on_failure
step_params['HadoopJarStep.Jar'] = step.jar()
main_class = step.main_class()
if main_class:
step_params['HadoopJarStep.MainClass'] = main_class
args = step.args()
if args:
self.build_list_params(step_params, args, 'HadoopJarStep.Args.member')
step_params['Name'] = step.name
return step_params
def _build_bootstrap_action_list(self, bootstrap_actions):
if type(bootstrap_actions) != types.ListType:
bootstrap_actions = [bootstrap_actions]
params = {}
for i, bootstrap_action in enumerate(bootstrap_actions):
for key, value in bootstrap_action.iteritems():
params['BootstrapActions.memeber.%s.%s' % (i + 1, key)] = value
return params
def _build_step_list(self, steps):
if type(steps) != types.ListType:
steps = [steps]
params = {}
for i, step in enumerate(steps):
for key, value in step.iteritems():
params['Steps.memeber.%s.%s' % (i+1, key)] = value
return params
def _build_instance_args(self, ec2_keyname, availability_zone, master_instance_type,
slave_instance_type, num_instances, keep_alive, hadoop_version):
params = {
'Instances.MasterInstanceType' : master_instance_type,
'Instances.SlaveInstanceType' : slave_instance_type,
'Instances.InstanceCount' : num_instances,
'Instances.KeepJobFlowAliveWhenNoSteps' : str(keep_alive).lower(),
'Instances.HadoopVersion' : hadoop_version
}
if ec2_keyname:
params['Instances.Ec2KeyName'] = ec2_keyname
if availability_zone:
params['Placement'] = availability_zone
return params
| Python |
# Copyright (c) 2010 Spotify AB
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
"""
This module contains EMR response objects
"""
from boto.resultset import ResultSet
class EmrObject(object):
Fields = set()
def __init__(self, connection=None):
self.connection = connection
def startElement(self, name, attrs, connection):
pass
def endElement(self, name, value, connection):
if name in self.Fields:
setattr(self, name.lower(), value)
class RunJobFlowResponse(EmrObject):
Fields = set(['JobFlowId'])
class Arg(EmrObject):
def __init__(self, connection=None):
self.value = None
def endElement(self, name, value, connection):
self.value = value
class Step(EmrObject):
Fields = set(['Name',
'ActionOnFailure',
'CreationDateTime',
'StartDateTime',
'EndDateTime',
'LastStateChangeReason',
'State'])
def __init__(self, connection=None):
self.connection = connection
self.args = None
def startElement(self, name, attrs, connection):
if name == 'Args':
self.args = ResultSet([('member', Arg)])
return self.args
class JobFlow(EmrObject):
Fields = set(['CreationDateTime',
'StartDateTime',
'State',
'EndDateTime',
'Id',
'InstanceCount',
'JobFlowId',
'KeepJobAliveWhenNoSteps',
'LogUri',
'MasterPublicDnsName',
'MasterInstanceId',
'Name',
'Placement',
'RequestId',
'Type',
'Value',
'AvailabilityZone',
'SlaveInstanceType',
'MasterInstanceType',
'Ec2KeyName',
'InstanceCount',
'KeepJobFlowAliveWhenNoSteps'])
def __init__(self, connection=None):
self.connection = connection
self.steps = None
def startElement(self, name, attrs, connection):
if name == 'Steps':
self.steps = ResultSet([('member', Step)])
return self.steps
else:
return None
| Python |
# Copyright (c) 2010 Spotify AB
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
"""
This module provies an interface to the Elastic MapReduce (EMR)
service from AWS.
"""
from connection import EmrConnection
from step import Step, StreamingStep, JarStep
from bootstrap_action import BootstrapAction
| Python |
# Copyright (c) 2010 Mitch Garnaat http://garnaat.org/
# Copyright 2010 Google Inc.
# Copyright (c) 2010, Eucalyptus Systems, Inc.
# All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
"""
This class encapsulates the provider-specific header differences.
"""
import os
import boto
from boto import config
from boto.gs.acl import ACL
from boto.gs.acl import CannedACLStrings as CannedGSACLStrings
from boto.s3.acl import CannedACLStrings as CannedS3ACLStrings
from boto.s3.acl import Policy
HEADER_PREFIX_KEY = 'header_prefix'
METADATA_PREFIX_KEY = 'metadata_prefix'
AWS_HEADER_PREFIX = 'x-amz-'
GOOG_HEADER_PREFIX = 'x-goog-'
ACL_HEADER_KEY = 'acl-header'
AUTH_HEADER_KEY = 'auth-header'
COPY_SOURCE_HEADER_KEY = 'copy-source-header'
COPY_SOURCE_VERSION_ID_HEADER_KEY = 'copy-source-version-id-header'
DELETE_MARKER_HEADER_KEY = 'delete-marker-header'
DATE_HEADER_KEY = 'date-header'
METADATA_DIRECTIVE_HEADER_KEY = 'metadata-directive-header'
RESUMABLE_UPLOAD_HEADER_KEY = 'resumable-upload-header'
SECURITY_TOKEN_HEADER_KEY = 'security-token-header'
STORAGE_CLASS_HEADER_KEY = 'storage-class'
MFA_HEADER_KEY = 'mfa-header'
VERSION_ID_HEADER_KEY = 'version-id-header'
STORAGE_COPY_ERROR = 'StorageCopyError'
STORAGE_CREATE_ERROR = 'StorageCreateError'
STORAGE_DATA_ERROR = 'StorageDataError'
STORAGE_PERMISSIONS_ERROR = 'StoragePermissionsError'
STORAGE_RESPONSE_ERROR = 'StorageResponseError'
class Provider(object):
CredentialMap = {
'aws' : ('aws_access_key_id', 'aws_secret_access_key'),
'google' : ('gs_access_key_id', 'gs_secret_access_key'),
}
AclClassMap = {
'aws' : Policy,
'google' : ACL
}
CannedAclsMap = {
'aws' : CannedS3ACLStrings,
'google' : CannedGSACLStrings
}
HostKeyMap = {
'aws' : 's3',
'google' : 'gs'
}
HeaderInfoMap = {
'aws' : {
HEADER_PREFIX_KEY : AWS_HEADER_PREFIX,
METADATA_PREFIX_KEY : AWS_HEADER_PREFIX + 'meta-',
ACL_HEADER_KEY : AWS_HEADER_PREFIX + 'acl',
AUTH_HEADER_KEY : 'AWS',
COPY_SOURCE_HEADER_KEY : AWS_HEADER_PREFIX + 'copy-source',
COPY_SOURCE_VERSION_ID_HEADER_KEY : AWS_HEADER_PREFIX +
'copy-source-version-id',
DATE_HEADER_KEY : AWS_HEADER_PREFIX + 'date',
DELETE_MARKER_HEADER_KEY : AWS_HEADER_PREFIX + 'delete-marker',
METADATA_DIRECTIVE_HEADER_KEY : AWS_HEADER_PREFIX +
'metadata-directive',
RESUMABLE_UPLOAD_HEADER_KEY : None,
SECURITY_TOKEN_HEADER_KEY : AWS_HEADER_PREFIX + 'security-token',
VERSION_ID_HEADER_KEY : AWS_HEADER_PREFIX + 'version-id',
STORAGE_CLASS_HEADER_KEY : AWS_HEADER_PREFIX + 'storage-class',
MFA_HEADER_KEY : AWS_HEADER_PREFIX + 'mfa',
},
'google' : {
HEADER_PREFIX_KEY : GOOG_HEADER_PREFIX,
METADATA_PREFIX_KEY : GOOG_HEADER_PREFIX + 'meta-',
ACL_HEADER_KEY : GOOG_HEADER_PREFIX + 'acl',
AUTH_HEADER_KEY : 'GOOG1',
COPY_SOURCE_HEADER_KEY : GOOG_HEADER_PREFIX + 'copy-source',
COPY_SOURCE_VERSION_ID_HEADER_KEY : GOOG_HEADER_PREFIX +
'copy-source-version-id',
DATE_HEADER_KEY : GOOG_HEADER_PREFIX + 'date',
DELETE_MARKER_HEADER_KEY : GOOG_HEADER_PREFIX + 'delete-marker',
METADATA_DIRECTIVE_HEADER_KEY : GOOG_HEADER_PREFIX +
'metadata-directive',
RESUMABLE_UPLOAD_HEADER_KEY : GOOG_HEADER_PREFIX + 'resumable',
SECURITY_TOKEN_HEADER_KEY : GOOG_HEADER_PREFIX + 'security-token',
VERSION_ID_HEADER_KEY : GOOG_HEADER_PREFIX + 'version-id',
STORAGE_CLASS_HEADER_KEY : None,
MFA_HEADER_KEY : None,
}
}
ErrorMap = {
'aws' : {
STORAGE_COPY_ERROR : boto.exception.S3CopyError,
STORAGE_CREATE_ERROR : boto.exception.S3CreateError,
STORAGE_DATA_ERROR : boto.exception.S3DataError,
STORAGE_PERMISSIONS_ERROR : boto.exception.S3PermissionsError,
STORAGE_RESPONSE_ERROR : boto.exception.S3ResponseError,
},
'google' : {
STORAGE_COPY_ERROR : boto.exception.GSCopyError,
STORAGE_CREATE_ERROR : boto.exception.GSCreateError,
STORAGE_DATA_ERROR : boto.exception.GSDataError,
STORAGE_PERMISSIONS_ERROR : boto.exception.GSPermissionsError,
STORAGE_RESPONSE_ERROR : boto.exception.GSResponseError,
}
}
def __init__(self, name, access_key=None, secret_key=None):
self.host = None
self.access_key = access_key
self.secret_key = secret_key
self.name = name
self.acl_class = self.AclClassMap[self.name]
self.canned_acls = self.CannedAclsMap[self.name]
self.get_credentials(access_key, secret_key)
self.configure_headers()
self.configure_errors()
# allow config file to override default host
host_opt_name = '%s_host' % self.HostKeyMap[self.name]
if config.has_option('Credentials', host_opt_name):
self.host = config.get('Credentials', host_opt_name)
def get_credentials(self, access_key=None, secret_key=None):
access_key_name, secret_key_name = self.CredentialMap[self.name]
if access_key is not None:
self.access_key = access_key
elif os.environ.has_key(access_key_name.upper()):
self.access_key = os.environ[access_key_name.upper()]
elif config.has_option('Credentials', access_key_name):
self.access_key = config.get('Credentials', access_key_name)
if secret_key is not None:
self.secret_key = secret_key
elif os.environ.has_key(secret_key_name.upper()):
self.secret_key = os.environ[secret_key_name.upper()]
elif config.has_option('Credentials', secret_key_name):
self.secret_key = config.get('Credentials', secret_key_name)
def configure_headers(self):
header_info_map = self.HeaderInfoMap[self.name]
self.metadata_prefix = header_info_map[METADATA_PREFIX_KEY]
self.header_prefix = header_info_map[HEADER_PREFIX_KEY]
self.acl_header = header_info_map[ACL_HEADER_KEY]
self.auth_header = header_info_map[AUTH_HEADER_KEY]
self.copy_source_header = header_info_map[COPY_SOURCE_HEADER_KEY]
self.copy_source_version_id = header_info_map[
COPY_SOURCE_VERSION_ID_HEADER_KEY]
self.date_header = header_info_map[DATE_HEADER_KEY]
self.delete_marker = header_info_map[DELETE_MARKER_HEADER_KEY]
self.metadata_directive_header = (
header_info_map[METADATA_DIRECTIVE_HEADER_KEY])
self.security_token_header = header_info_map[SECURITY_TOKEN_HEADER_KEY]
self.resumable_upload_header = (
header_info_map[RESUMABLE_UPLOAD_HEADER_KEY])
self.storage_class_header = header_info_map[STORAGE_CLASS_HEADER_KEY]
self.version_id = header_info_map[VERSION_ID_HEADER_KEY]
self.mfa_header = header_info_map[MFA_HEADER_KEY]
def configure_errors(self):
error_map = self.ErrorMap[self.name]
self.storage_copy_error = error_map[STORAGE_COPY_ERROR]
self.storage_create_error = error_map[STORAGE_CREATE_ERROR]
self.storage_data_error = error_map[STORAGE_DATA_ERROR]
self.storage_permissions_error = error_map[STORAGE_PERMISSIONS_ERROR]
self.storage_response_error = error_map[STORAGE_RESPONSE_ERROR]
def get_provider_name(self):
return self.HostKeyMap[self.name]
# Static utility method for getting default Provider.
def get_default():
return Provider('aws')
| Python |
# Copyright (c) 2006,2007 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
"""
SQS Message
A Message represents the data stored in an SQS queue. The rules for what is allowed within an SQS
Message are here:
http://docs.amazonwebservices.com/AWSSimpleQueueService/2008-01-01/SQSDeveloperGuide/Query_QuerySendMessage.html
So, at it's simplest level a Message just needs to allow a developer to store bytes in it and get the bytes
back out. However, to allow messages to have richer semantics, the Message class must support the
following interfaces:
The constructor for the Message class must accept a keyword parameter "queue" which is an instance of a
boto Queue object and represents the queue that the message will be stored in. The default value for
this parameter is None.
The constructor for the Message class must accept a keyword parameter "body" which represents the
content or body of the message. The format of this parameter will depend on the behavior of the
particular Message subclass. For example, if the Message subclass provides dictionary-like behavior to the
user the body passed to the constructor should be a dict-like object that can be used to populate
the initial state of the message.
The Message class must provide an encode method that accepts a value of the same type as the body
parameter of the constructor and returns a string of characters that are able to be stored in an
SQS message body (see rules above).
The Message class must provide a decode method that accepts a string of characters that can be
stored (and probably were stored!) in an SQS message and return an object of a type that is consistent
with the "body" parameter accepted on the class constructor.
The Message class must provide a __len__ method that will return the size of the encoded message
that would be stored in SQS based on the current state of the Message object.
The Message class must provide a get_body method that will return the body of the message in the
same format accepted in the constructor of the class.
The Message class must provide a set_body method that accepts a message body in the same format
accepted by the constructor of the class. This method should alter to the internal state of the
Message object to reflect the state represented in the message body parameter.
The Message class must provide a get_body_encoded method that returns the current body of the message
in the format in which it would be stored in SQS.
"""
import base64
import StringIO
from boto.sqs.attributes import Attributes
from boto.exception import SQSDecodeError
class RawMessage:
"""
Base class for SQS messages. RawMessage does not encode the message
in any way. Whatever you store in the body of the message is what
will be written to SQS and whatever is returned from SQS is stored
directly into the body of the message.
"""
def __init__(self, queue=None, body=''):
self.queue = queue
self.set_body(body)
self.id = None
self.receipt_handle = None
self.md5 = None
self.attributes = Attributes(self)
def __len__(self):
return len(self.encode(self._body))
def startElement(self, name, attrs, connection):
if name == 'Attribute':
return self.attributes
return None
def endElement(self, name, value, connection):
if name == 'Body':
self.set_body(self.decode(value))
elif name == 'MessageId':
self.id = value
elif name == 'ReceiptHandle':
self.receipt_handle = value
elif name == 'MD5OfMessageBody':
self.md5 = value
else:
setattr(self, name, value)
def encode(self, value):
"""Transform body object into serialized byte array format."""
return value
def decode(self, value):
"""Transform seralized byte array into any object."""
return value
def set_body(self, body):
"""Override the current body for this object, using decoded format."""
self._body = body
def get_body(self):
return self._body
def get_body_encoded(self):
"""
This method is really a semi-private method used by the Queue.write
method when writing the contents of the message to SQS.
You probably shouldn't need to call this method in the normal course of events.
"""
return self.encode(self.get_body())
def delete(self):
if self.queue:
return self.queue.delete_message(self)
def change_visibility(self, visibility_timeout):
if self.queue:
self.queue.connection.change_message_visibility(self.queue,
self.receipt_handle,
visibility_timeout)
class Message(RawMessage):
"""
The default Message class used for SQS queues. This class automatically
encodes/decodes the message body using Base64 encoding to avoid any
illegal characters in the message body. See:
http://developer.amazonwebservices.com/connect/thread.jspa?messageID=49680%EC%88%90
for details on why this is a good idea. The encode/decode is meant to
be transparent to the end-user.
"""
def encode(self, value):
return base64.b64encode(value)
def decode(self, value):
try:
value = base64.b64decode(value)
except:
raise SQSDecodeError('Unable to decode message', self)
return value
class MHMessage(Message):
"""
The MHMessage class provides a message that provides RFC821-like
headers like this:
HeaderName: HeaderValue
The encoding/decoding of this is handled automatically and after
the message body has been read, the message instance can be treated
like a mapping object, i.e. m['HeaderName'] would return 'HeaderValue'.
"""
def __init__(self, queue=None, body=None, xml_attrs=None):
if body == None or body == '':
body = {}
Message.__init__(self, queue, body)
def decode(self, value):
try:
msg = {}
fp = StringIO.StringIO(value)
line = fp.readline()
while line:
delim = line.find(':')
key = line[0:delim]
value = line[delim+1:].strip()
msg[key.strip()] = value.strip()
line = fp.readline()
except:
raise SQSDecodeError('Unable to decode message', self)
return msg
def encode(self, value):
s = ''
for item in value.items():
s = s + '%s: %s\n' % (item[0], item[1])
return s
def __getitem__(self, key):
if self._body.has_key(key):
return self._body[key]
else:
raise KeyError(key)
def __setitem__(self, key, value):
self._body[key] = value
self.set_body(self._body)
def keys(self):
return self._body.keys()
def values(self):
return self._body.values()
def items(self):
return self._body.items()
def has_key(self, key):
return self._body.has_key(key)
def update(self, d):
self._body.update(d)
self.set_body(self._body)
def get(self, key, default=None):
return self._body.get(key, default)
class EncodedMHMessage(MHMessage):
"""
The EncodedMHMessage class provides a message that provides RFC821-like
headers like this:
HeaderName: HeaderValue
This variation encodes/decodes the body of the message in base64 automatically.
The message instance can be treated like a mapping object,
i.e. m['HeaderName'] would return 'HeaderValue'.
"""
def decode(self, value):
try:
value = base64.b64decode(value)
except:
raise SQSDecodeError('Unable to decode message', self)
return MHMessage.decode(self, value)
def encode(self, value):
value = MHMessage.encode(value)
return base64.b64encode(self, value)
| Python |
# Copyright (c) 2006-2010 Mitch Garnaat http://garnaat.org/
# Copyright (c) 2010, Eucalyptus Systems, Inc.
# All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
from boto.regioninfo import RegionInfo
class SQSRegionInfo(RegionInfo):
def __init__(self, connection=None, name=None, endpoint=None):
from boto.sqs.connection import SQSConnection
RegionInfo.__init__(self, connection, name, endpoint,
SQSConnection)
| Python |
# Copyright (c) 2006-2008 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
from boto.sqs.message import MHMessage
from boto.exception import SQSDecodeError
import base64
import simplejson
class JSONMessage(MHMessage):
"""
Acts like a dictionary but encodes it's data as a Base64 encoded JSON payload.
"""
def decode(self, value):
try:
value = base64.b64decode(value)
value = simplejson.loads(value)
except:
raise SQSDecodeError('Unable to decode message', self)
return value
def encode(self, value):
value = simplejson.dumps(value)
return base64.b64encode(value)
| Python |
# Copyright (c) 2006,2007 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
"""
Represents an SQS Attribute Name/Value set
"""
class Attributes(dict):
def __init__(self, parent):
self.parent = parent
self.current_key = None
self.current_value = None
def startElement(self, name, attrs, connection):
pass
def endElement(self, name, value, connection):
if name == 'Attribute':
self[self.current_key] = self.current_value
elif name == 'Name':
self.current_key = value
elif name == 'Value':
self.current_value = value
else:
setattr(self, name, value)
| Python |
# Copyright (c) 2006-2009 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
from boto.connection import AWSQueryConnection
from boto.sqs.regioninfo import SQSRegionInfo
from boto.sqs.queue import Queue
from boto.sqs.message import Message
from boto.sqs.attributes import Attributes
from boto.exception import SQSError
class SQSConnection(AWSQueryConnection):
"""
A Connection to the SQS Service.
"""
DefaultRegionName = 'us-east-1'
DefaultRegionEndpoint = 'queue.amazonaws.com'
APIVersion = '2009-02-01'
SignatureVersion = '2'
DefaultContentType = 'text/plain'
ResponseError = SQSError
def __init__(self, aws_access_key_id=None, aws_secret_access_key=None,
is_secure=True, port=None, proxy=None, proxy_port=None,
proxy_user=None, proxy_pass=None, debug=0,
https_connection_factory=None, region=None, path='/'):
if not region:
region = SQSRegionInfo(self, self.DefaultRegionName, self.DefaultRegionEndpoint)
self.region = region
AWSQueryConnection.__init__(self, aws_access_key_id, aws_secret_access_key,
is_secure, port, proxy, proxy_port, proxy_user, proxy_pass,
self.region.endpoint, debug, https_connection_factory, path)
def create_queue(self, queue_name, visibility_timeout=None):
"""
Create an SQS Queue.
:type queue_name: str or unicode
:param queue_name: The name of the new queue. Names are scoped to an account and need to
be unique within that account. Calling this method on an existing
queue name will not return an error from SQS unless the value for
visibility_timeout is different than the value of the existing queue
of that name. This is still an expensive operation, though, and not
the preferred way to check for the existence of a queue. See the
:func:`boto.sqs.connection.SQSConnection.lookup` method.
:type visibility_timeout: int
:param visibility_timeout: The default visibility timeout for all messages written in the
queue. This can be overridden on a per-message.
:rtype: :class:`boto.sqs.queue.Queue`
:return: The newly created queue.
"""
params = {'QueueName': queue_name}
if visibility_timeout:
params['DefaultVisibilityTimeout'] = '%d' % (visibility_timeout,)
return self.get_object('CreateQueue', params, Queue)
def delete_queue(self, queue, force_deletion=False):
"""
Delete an SQS Queue.
:type queue: A Queue object
:param queue: The SQS queue to be deleted
:type force_deletion: Boolean
:param force_deletion: Normally, SQS will not delete a queue that contains messages.
However, if the force_deletion argument is True, the
queue will be deleted regardless of whether there are messages in
the queue or not. USE WITH CAUTION. This will delete all
messages in the queue as well.
:rtype: bool
:return: True if the command succeeded, False otherwise
"""
return self.get_status('DeleteQueue', None, queue.id)
def get_queue_attributes(self, queue, attribute='All'):
"""
Gets one or all attributes of a Queue
:type queue: A Queue object
:param queue: The SQS queue to be deleted
:type attribute: str
:type attribute: The specific attribute requested. If not supplied, the default
is to return all attributes. Valid attributes are:
ApproximateNumberOfMessages,
ApproximateNumberOfMessagesNotVisible,
VisibilityTimeout,
CreatedTimestamp,
LastModifiedTimestamp,
Policy
:rtype: :class:`boto.sqs.attributes.Attributes`
:return: An Attributes object containing request value(s).
"""
params = {'AttributeName' : attribute}
return self.get_object('GetQueueAttributes', params, Attributes, queue.id)
def set_queue_attribute(self, queue, attribute, value):
params = {'Attribute.Name' : attribute, 'Attribute.Value' : value}
return self.get_status('SetQueueAttributes', params, queue.id)
def receive_message(self, queue, number_messages=1, visibility_timeout=None,
attributes=None):
"""
Read messages from an SQS Queue.
:type queue: A Queue object
:param queue: The Queue from which messages are read.
:type number_messages: int
:param number_messages: The maximum number of messages to read (default=1)
:type visibility_timeout: int
:param visibility_timeout: The number of seconds the message should remain invisible
to other queue readers (default=None which uses the Queues default)
:type attributes: str
:param attributes: The name of additional attribute to return with response
or All if you want all attributes. The default is to
return no additional attributes. Valid values:
All
SenderId
SentTimestamp
ApproximateReceiveCount
ApproximateFirstReceiveTimestamp
:rtype: list
:return: A list of :class:`boto.sqs.message.Message` objects.
"""
params = {'MaxNumberOfMessages' : number_messages}
if visibility_timeout:
params['VisibilityTimeout'] = visibility_timeout
if attributes:
self.build_list_params(params, attributes, 'AttributeName')
return self.get_list('ReceiveMessage', params, [('Message', queue.message_class)],
queue.id, queue)
def delete_message(self, queue, message):
"""
Delete a message from a queue.
:type queue: A :class:`boto.sqs.queue.Queue` object
:param queue: The Queue from which messages are read.
:type message: A :class:`boto.sqs.message.Message` object
:param message: The Message to be deleted
:rtype: bool
:return: True if successful, False otherwise.
"""
params = {'ReceiptHandle' : message.receipt_handle}
return self.get_status('DeleteMessage', params, queue.id)
def delete_message_from_handle(self, queue, receipt_handle):
"""
Delete a message from a queue, given a receipt handle.
:type queue: A :class:`boto.sqs.queue.Queue` object
:param queue: The Queue from which messages are read.
:type receipt_handle: str
:param receipt_handle: The receipt handle for the message
:rtype: bool
:return: True if successful, False otherwise.
"""
params = {'ReceiptHandle' : receipt_handle}
return self.get_status('DeleteMessage', params, queue.id)
def send_message(self, queue, message_content):
params = {'MessageBody' : message_content}
return self.get_object('SendMessage', params, Message, queue.id, verb='POST')
def change_message_visibility(self, queue, receipt_handle, visibility_timeout):
"""
Extends the read lock timeout for the specified message from the specified queue
to the specified value.
:type queue: A :class:`boto.sqs.queue.Queue` object
:param queue: The Queue from which messages are read.
:type receipt_handle: str
:param queue: The receipt handle associated with the message whose
visibility timeout will be changed.
:type visibility_timeout: int
:param visibility_timeout: The new value of the message's visibility timeout
in seconds.
"""
params = {'ReceiptHandle' : receipt_handle,
'VisibilityTimeout' : visibility_timeout}
return self.get_status('ChangeMessageVisibility', params, queue.id)
def get_all_queues(self, prefix=''):
params = {}
if prefix:
params['QueueNamePrefix'] = prefix
return self.get_list('ListQueues', params, [('QueueUrl', Queue)])
def get_queue(self, queue_name):
rs = self.get_all_queues(queue_name)
for q in rs:
if q.url.endswith(queue_name):
return q
return None
lookup = get_queue
#
# Permissions methods
#
def add_permission(self, queue, label, aws_account_id, action_name):
"""
Add a permission to a queue.
:type queue: :class:`boto.sqs.queue.Queue`
:param queue: The queue object
:type label: str or unicode
:param label: A unique identification of the permission you are setting.
Maximum of 80 characters ``[0-9a-zA-Z_-]``
Example, AliceSendMessage
:type aws_account_id: str or unicode
:param principal_id: The AWS account number of the principal who will be given
permission. The principal must have an AWS account, but
does not need to be signed up for Amazon SQS. For information
about locating the AWS account identification.
:type action_name: str or unicode
:param action_name: The action. Valid choices are:
\*|SendMessage|ReceiveMessage|DeleteMessage|
ChangeMessageVisibility|GetQueueAttributes
:rtype: bool
:return: True if successful, False otherwise.
"""
params = {'Label': label,
'AWSAccountId' : aws_account_id,
'ActionName' : action_name}
return self.get_status('AddPermission', params, queue.id)
def remove_permission(self, queue, label):
"""
Remove a permission from a queue.
:type queue: :class:`boto.sqs.queue.Queue`
:param queue: The queue object
:type label: str or unicode
:param label: The unique label associated with the permission being removed.
:rtype: bool
:return: True if successful, False otherwise.
"""
params = {'Label': label}
return self.get_status('RemovePermission', params, queue.id)
| Python |
# Copyright (c) 2006-2009 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
"""
Represents an SQS Queue
"""
import urlparse
from boto.sqs.message import Message
class Queue:
def __init__(self, connection=None, url=None, message_class=Message):
self.connection = connection
self.url = url
self.message_class = message_class
self.visibility_timeout = None
def _id(self):
if self.url:
val = urlparse.urlparse(self.url)[2]
else:
val = self.url
return val
id = property(_id)
def _name(self):
if self.url:
val = urlparse.urlparse(self.url)[2].split('/')[2]
else:
val = self.url
return val
name = property(_name)
def startElement(self, name, attrs, connection):
return None
def endElement(self, name, value, connection):
if name == 'QueueUrl':
self.url = value
elif name == 'VisibilityTimeout':
self.visibility_timeout = int(value)
else:
setattr(self, name, value)
def set_message_class(self, message_class):
"""
Set the message class that should be used when instantiating messages read
from the queue. By default, the class boto.sqs.message.Message is used but
this can be overriden with any class that behaves like a message.
:type message_class: Message-like class
:param message_class: The new Message class
"""
self.message_class = message_class
def get_attributes(self, attributes='All'):
"""
Retrieves attributes about this queue object and returns
them in an Attribute instance (subclass of a Dictionary).
:type attributes: string
:param attributes: String containing one of:
ApproximateNumberOfMessages,
ApproximateNumberOfMessagesNotVisible,
VisibilityTimeout,
CreatedTimestamp,
LastModifiedTimestamp,
Policy
:rtype: Attribute object
:return: An Attribute object which is a mapping type holding the
requested name/value pairs
"""
return self.connection.get_queue_attributes(self, attributes)
def set_attribute(self, attribute, value):
"""
Set a new value for an attribute of the Queue.
:type attribute: String
:param attribute: The name of the attribute you want to set. The
only valid value at this time is: VisibilityTimeout
:type value: int
:param value: The new value for the attribute.
For VisibilityTimeout the value must be an
integer number of seconds from 0 to 86400.
:rtype: bool
:return: True if successful, otherwise False.
"""
return self.connection.set_queue_attribute(self, attribute, value)
def get_timeout(self):
"""
Get the visibility timeout for the queue.
:rtype: int
:return: The number of seconds as an integer.
"""
a = self.get_attributes('VisibilityTimeout')
return int(a['VisibilityTimeout'])
def set_timeout(self, visibility_timeout):
"""
Set the visibility timeout for the queue.
:type visibility_timeout: int
:param visibility_timeout: The desired timeout in seconds
"""
retval = self.set_attribute('VisibilityTimeout', visibility_timeout)
if retval:
self.visibility_timeout = visibility_timeout
return retval
def add_permission(self, label, aws_account_id, action_name):
"""
Add a permission to a queue.
:type label: str or unicode
:param label: A unique identification of the permission you are setting.
Maximum of 80 characters ``[0-9a-zA-Z_-]``
Example, AliceSendMessage
:type aws_account_id: str or unicode
:param principal_id: The AWS account number of the principal who will be given
permission. The principal must have an AWS account, but
does not need to be signed up for Amazon SQS. For information
about locating the AWS account identification.
:type action_name: str or unicode
:param action_name: The action. Valid choices are:
\*|SendMessage|ReceiveMessage|DeleteMessage|
ChangeMessageVisibility|GetQueueAttributes
:rtype: bool
:return: True if successful, False otherwise.
"""
return self.connection.add_permission(self, label, aws_account_id, action_name)
def remove_permission(self, label):
"""
Remove a permission from a queue.
:type label: str or unicode
:param label: The unique label associated with the permission being removed.
:rtype: bool
:return: True if successful, False otherwise.
"""
return self.connection.remove_permission(self, label)
def read(self, visibility_timeout=None):
"""
Read a single message from the queue.
:type visibility_timeout: int
:param visibility_timeout: The timeout for this message in seconds
:rtype: :class:`boto.sqs.message.Message`
:return: A single message or None if queue is empty
"""
rs = self.get_messages(1, visibility_timeout)
if len(rs) == 1:
return rs[0]
else:
return None
def write(self, message):
"""
Add a single message to the queue.
:type message: Message
:param message: The message to be written to the queue
:rtype: :class:`boto.sqs.message.Message`
:return: The :class:`boto.sqs.message.Message` object that was written.
"""
new_msg = self.connection.send_message(self, message.get_body_encoded())
message.id = new_msg.id
message.md5 = new_msg.md5
return message
def new_message(self, body=''):
"""
Create new message of appropriate class.
:type body: message body
:param body: The body of the newly created message (optional).
:rtype: :class:`boto.sqs.message.Message`
:return: A new Message object
"""
m = self.message_class(self, body)
m.queue = self
return m
# get a variable number of messages, returns a list of messages
def get_messages(self, num_messages=1, visibility_timeout=None,
attributes=None):
"""
Get a variable number of messages.
:type num_messages: int
:param num_messages: The maximum number of messages to read from the queue.
:type visibility_timeout: int
:param visibility_timeout: The VisibilityTimeout for the messages read.
:type attributes: str
:param attributes: The name of additional attribute to return with response
or All if you want all attributes. The default is to
return no additional attributes. Valid values:
All
SenderId
SentTimestamp
ApproximateReceiveCount
ApproximateFirstReceiveTimestamp
:rtype: list
:return: A list of :class:`boto.sqs.message.Message` objects.
"""
return self.connection.receive_message(self, number_messages=num_messages,
visibility_timeout=visibility_timeout,
attributes=attributes)
def delete_message(self, message):
"""
Delete a message from the queue.
:type message: :class:`boto.sqs.message.Message`
:param message: The :class:`boto.sqs.message.Message` object to delete.
:rtype: bool
:return: True if successful, False otherwise
"""
return self.connection.delete_message(self, message)
def delete(self):
"""
Delete the queue.
"""
return self.connection.delete_queue(self)
def clear(self, page_size=10, vtimeout=10):
"""Utility function to remove all messages from a queue"""
n = 0
l = self.get_messages(page_size, vtimeout)
while l:
for m in l:
self.delete_message(m)
n += 1
l = self.get_messages(page_size, vtimeout)
return n
def count(self, page_size=10, vtimeout=10):
"""
Utility function to count the number of messages in a queue.
Note: This function now calls GetQueueAttributes to obtain
an 'approximate' count of the number of messages in a queue.
"""
a = self.get_attributes('ApproximateNumberOfMessages')
return int(a['ApproximateNumberOfMessages'])
def count_slow(self, page_size=10, vtimeout=10):
"""
Deprecated. This is the old 'count' method that actually counts
the messages by reading them all. This gives an accurate count but
is very slow for queues with non-trivial number of messasges.
Instead, use get_attribute('ApproximateNumberOfMessages') to take
advantage of the new SQS capability. This is retained only for
the unit tests.
"""
n = 0
l = self.get_messages(page_size, vtimeout)
while l:
for m in l:
n += 1
l = self.get_messages(page_size, vtimeout)
return n
def dump_(self, file_name, page_size=10, vtimeout=10, sep='\n'):
"""Utility function to dump the messages in a queue to a file
NOTE: Page size must be < 10 else SQS errors"""
fp = open(file_name, 'wb')
n = 0
l = self.get_messages(page_size, vtimeout)
while l:
for m in l:
fp.write(m.get_body())
if sep:
fp.write(sep)
n += 1
l = self.get_messages(page_size, vtimeout)
fp.close()
return n
def save_to_file(self, fp, sep='\n'):
"""
Read all messages from the queue and persist them to file-like object.
Messages are written to the file and the 'sep' string is written
in between messages. Messages are deleted from the queue after
being written to the file.
Returns the number of messages saved.
"""
n = 0
m = self.read()
while m:
n += 1
fp.write(m.get_body())
if sep:
fp.write(sep)
self.delete_message(m)
m = self.read()
return n
def save_to_filename(self, file_name, sep='\n'):
"""
Read all messages from the queue and persist them to local file.
Messages are written to the file and the 'sep' string is written
in between messages. Messages are deleted from the queue after
being written to the file.
Returns the number of messages saved.
"""
fp = open(file_name, 'wb')
n = self.save_to_file(fp, sep)
fp.close()
return n
# for backwards compatibility
save = save_to_filename
def save_to_s3(self, bucket):
"""
Read all messages from the queue and persist them to S3.
Messages are stored in the S3 bucket using a naming scheme of::
<queue_id>/<message_id>
Messages are deleted from the queue after being saved to S3.
Returns the number of messages saved.
"""
n = 0
m = self.read()
while m:
n += 1
key = bucket.new_key('%s/%s' % (self.id, m.id))
key.set_contents_from_string(m.get_body())
self.delete_message(m)
m = self.read()
return n
def load_from_s3(self, bucket, prefix=None):
"""
Load messages previously saved to S3.
"""
n = 0
if prefix:
prefix = '%s/' % prefix
else:
prefix = '%s/' % self.id[1:]
rs = bucket.list(prefix=prefix)
for key in rs:
n += 1
m = self.new_message(key.get_contents_as_string())
self.write(m)
return n
def load_from_file(self, fp, sep='\n'):
"""Utility function to load messages from a file-like object to a queue"""
n = 0
body = ''
l = fp.readline()
while l:
if l == sep:
m = Message(self, body)
self.write(m)
n += 1
print 'writing message %d' % n
body = ''
else:
body = body + l
l = fp.readline()
return n
def load_from_filename(self, file_name, sep='\n'):
"""Utility function to load messages from a local filename to a queue"""
fp = open(file_name, 'rb')
n = self.load_file_file(fp, sep)
fp.close()
return n
# for backward compatibility
load = load_from_filename
| Python |
# Copyright (c) 2006,2007 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
from regioninfo import SQSRegionInfo
def regions():
"""
Get all available regions for the SQS service.
:rtype: list
:return: A list of :class:`boto.ec2.regioninfo.RegionInfo`
"""
return [SQSRegionInfo(name='us-east-1',
endpoint='queue.amazonaws.com'),
SQSRegionInfo(name='eu-west-1',
endpoint='eu-west-1.queue.amazonaws.com'),
SQSRegionInfo(name='us-west-1',
endpoint='us-west-1.queue.amazonaws.com'),
SQSRegionInfo(name='ap-southeast-1',
endpoint='ap-southeast-1.queue.amazonaws.com')
]
def connect_to_region(region_name):
for region in regions():
if region.name == region_name:
return region.connect()
return None
| Python |
# Copyright 2010 Google Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
from boto.s3.key import Key as S3Key
class Key(S3Key):
def add_email_grant(self, permission, email_address):
"""
Convenience method that provides a quick way to add an email grant to a
key. This method retrieves the current ACL, creates a new grant based on
the parameters passed in, adds that grant to the ACL and then PUT's the
new ACL back to GS.
:type permission: string
:param permission: The permission being granted. Should be one of:
READ|FULL_CONTROL
See http://code.google.com/apis/storage/docs/developer-guide.html#authorization
for more details on permissions.
:type email_address: string
:param email_address: The email address associated with the Google
account to which you are granting the permission.
"""
acl = self.get_acl()
acl.add_email_grant(permission, email_address)
self.set_acl(acl)
def add_user_grant(self, permission, user_id):
"""
Convenience method that provides a quick way to add a canonical user
grant to a key. This method retrieves the current ACL, creates a new
grant based on the parameters passed in, adds that grant to the ACL and
then PUT's the new ACL back to GS.
:type permission: string
:param permission: The permission being granted. Should be one of:
READ|FULL_CONTROL
See http://code.google.com/apis/storage/docs/developer-guide.html#authorization
for more details on permissions.
:type user_id: string
:param user_id: The canonical user id associated with the GS account to
which you are granting the permission.
"""
acl = self.get_acl()
acl.add_user_grant(permission, user_id)
self.set_acl(acl)
def add_group_email_grant(self, permission, email_address):
"""
Convenience method that provides a quick way to add an email group
grant to a key. This method retrieves the current ACL, creates a new
grant based on the parameters passed in, adds that grant to the ACL and
then PUT's the new ACL back to GS.
:type permission: string
:param permission: The permission being granted. Should be one of:
READ|FULL_CONTROL
See http://code.google.com/apis/storage/docs/developer-guide.html#authorization
for more details on permissions.
:type email_address: string
:param email_address: The email address associated with the Google
Group to which you are granting the permission.
"""
acl = self.get_acl()
acl.add_group_email_grant(permission, email_address)
self.set_acl(acl)
def add_group_grant(self, permission, group_id):
"""
Convenience method that provides a quick way to add a canonical group
grant to a key. This method retrieves the current ACL, creates a new
grant based on the parameters passed in, adds that grant to the ACL and
then PUT's the new ACL back to GS.
:type permission: string
:param permission: The permission being granted. Should be one of:
READ|FULL_CONTROL
See http://code.google.com/apis/storage/docs/developer-guide.html#authorization
for more details on permissions.
:type group_id: string
:param group_id: The canonical group id associated with the Google
Groups account you are granting the permission to.
"""
acl = self.get_acl()
acl.add_group_grant(permission, group_id)
self.set_acl(acl)
def set_contents_from_file(self, fp, headers={}, replace=True,
cb=None, num_cb=10, policy=None, md5=None,
res_upload_handler=None):
"""
Store an object in GS using the name of the Key object as the
key in GS and the contents of the file pointed to by 'fp' as the
contents.
:type fp: file
:param fp: the file whose contents are to be uploaded
:type headers: dict
:param headers: additional HTTP headers to be sent with the PUT request.
:type replace: bool
:param replace: If this parameter is False, the method will first check
to see if an object exists in the bucket with the same key. If it
does, it won't overwrite it. The default value is True which will
overwrite the object.
:type cb: function
:param cb: a callback function that will be called to report
progress on the upload. The callback should accept two integer
parameters, the first representing the number of bytes that have
been successfully transmitted to GS and the second representing the
total number of bytes that need to be transmitted.
:type num_cb: int
:param num_cb: (optional) If a callback is specified with the cb
parameter, this parameter determines the granularity of the callback
by defining the maximum number of times the callback will be called
during the file transfer.
:type policy: :class:`boto.gs.acl.CannedACLStrings`
:param policy: A canned ACL policy that will be applied to the new key
in GS.
:type md5: A tuple containing the hexdigest version of the MD5 checksum
of the file as the first element and the Base64-encoded version of
the plain checksum as the second element. This is the same format
returned by the compute_md5 method.
:param md5: If you need to compute the MD5 for any reason prior to
upload, it's silly to have to do it twice so this param, if present,
will be used as the MD5 values of the file. Otherwise, the checksum
will be computed.
:type res_upload_handler: ResumableUploadHandler
:param res_upload_handler: If provided, this handler will perform the
upload.
TODO: At some point we should refactor the Bucket and Key classes,
to move functionality common to all providers into a parent class,
and provider-specific functionality into subclasses (rather than
just overriding/sharing code the way it currently works).
"""
provider = self.bucket.connection.provider
if policy:
headers[provider.acl_header] = policy
if hasattr(fp, 'name'):
self.path = fp.name
if self.bucket != None:
if not md5:
md5 = self.compute_md5(fp)
else:
# Even if md5 is provided, still need to set size of content.
fp.seek(0, 2)
self.size = fp.tell()
fp.seek(0)
self.md5 = md5[0]
self.base64md5 = md5[1]
if self.name == None:
self.name = self.md5
if not replace:
k = self.bucket.lookup(self.name)
if k:
return
if res_upload_handler:
res_upload_handler.send_file(self, fp, headers, cb, num_cb)
else:
# Not a resumable transfer so use basic send_file mechanism.
self.send_file(fp, headers, cb, num_cb)
def set_contents_from_filename(self, filename, headers=None, replace=True,
cb=None, num_cb=10, policy=None, md5=None,
reduced_redundancy=None,
res_upload_handler=None):
"""
Store an object in GS using the name of the Key object as the
key in GS and the contents of the file named by 'filename'.
See set_contents_from_file method for details about the
parameters.
:type filename: string
:param filename: The name of the file that you want to put onto GS
:type headers: dict
:param headers: Additional headers to pass along with the request to GS.
:type replace: bool
:param replace: If True, replaces the contents of the file if it
already exists.
:type cb: function
:param cb: (optional) a callback function that will be called to report
progress on the download. The callback should accept two integer
parameters, the first representing the number of bytes that have
been successfully transmitted from GS and the second representing
the total number of bytes that need to be transmitted.
:type cb: int
:param num_cb: (optional) If a callback is specified with the cb
parameter this parameter determines the granularity of the callback
by defining the maximum number of times the callback will be called
during the file transfer.
:type policy: :class:`boto.gs.acl.CannedACLStrings`
:param policy: A canned ACL policy that will be applied to the new key
in GS.
:type md5: A tuple containing the hexdigest version of the MD5 checksum
of the file as the first element and the Base64-encoded version of
the plain checksum as the second element. This is the same format
returned by the compute_md5 method.
:param md5: If you need to compute the MD5 for any reason prior to
upload, it's silly to have to do it twice so this param, if present,
will be used as the MD5 values of the file. Otherwise, the checksum
will be computed.
:type res_upload_handler: ResumableUploadHandler
:param res_upload_handler: If provided, this handler will perform the
upload.
"""
fp = open(filename, 'rb')
self.set_contents_from_file(fp, headers, replace, cb, num_cb,
policy, md5, res_upload_handler)
fp.close()
| Python |
# Copyright 2010 Google Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
from boto.s3.connection import S3Connection
from boto.s3.connection import SubdomainCallingFormat
from boto.gs.bucket import Bucket
class GSConnection(S3Connection):
DefaultHost = 'commondatastorage.googleapis.com'
QueryString = 'Signature=%s&Expires=%d&AWSAccessKeyId=%s'
def __init__(self, gs_access_key_id=None, gs_secret_access_key=None,
is_secure=True, port=None, proxy=None, proxy_port=None,
proxy_user=None, proxy_pass=None,
host=DefaultHost, debug=0, https_connection_factory=None,
calling_format=SubdomainCallingFormat(), path='/'):
S3Connection.__init__(self, gs_access_key_id, gs_secret_access_key,
is_secure, port, proxy, proxy_port, proxy_user, proxy_pass,
host, debug, https_connection_factory, calling_format, path,
"google", Bucket)
| Python |
# Copyright 2010 Google Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
from boto.gs.user import User
from boto.exception import InvalidAclError
ACCESS_CONTROL_LIST = 'AccessControlList'
ALL_AUTHENTICATED_USERS = 'AllAuthenticatedUsers'
ALL_USERS = 'AllUsers'
DOMAIN = 'Domain'
EMAIL_ADDRESS = 'EmailAddress'
ENTRY = 'Entry'
ENTRIES = 'Entries'
GROUP_BY_DOMAIN = 'GroupByDomain'
GROUP_BY_EMAIL = 'GroupByEmail'
GROUP_BY_ID = 'GroupById'
ID = 'ID'
NAME = 'Name'
OWNER = 'Owner'
PERMISSION = 'Permission'
SCOPE = 'Scope'
TYPE = 'type'
USER_BY_EMAIL = 'UserByEmail'
USER_BY_ID = 'UserById'
CannedACLStrings = ['private', 'public-read',
'public-read-write', 'authenticated-read',
'bucket-owner-read', 'bucket-owner-full-control']
SupportedPermissions = ['READ', 'WRITE', 'FULL_CONTROL']
class ACL:
def __init__(self, parent=None):
self.parent = parent
self.entries = []
def __repr__(self):
entries_repr = ['Owner:%s' % self.owner.__repr__()]
acl_entries = self.entries
if acl_entries:
for e in acl_entries.entry_list:
entries_repr.append(e.__repr__())
return '<%s>' % ', '.join(entries_repr)
# Method with same signature as boto.s3.acl.ACL.add_email_grant(), to allow
# polymorphic treatment at application layer.
def add_email_grant(self, permission, email_address):
entry = Entry(type=USER_BY_EMAIL, email_address=email_address,
permission=permission)
self.entries.entry_list.append(entry)
# Method with same signature as boto.s3.acl.ACL.add_user_grant(), to allow
# polymorphic treatment at application layer.
def add_user_grant(self, permission, user_id):
entry = Entry(permission=permission, type=USER_BY_ID, id=user_id)
self.entries.entry_list.append(entry)
def add_group_email_grant(self, permission, email_address):
entry = Entry(type=GROUP_BY_EMAIL, email_address=email_address,
permission=permission)
self.entries.entry_list.append(entry)
def add_group_grant(self, permission, group_id):
entry = Entry(type=GROUP_BY_ID, id=group_id, permission=permission)
self.entries.entry_list.append(entry)
def startElement(self, name, attrs, connection):
if name == OWNER:
self.owner = User(self)
return self.owner
elif name == ENTRIES:
self.entries = Entries(self)
return self.entries
else:
return None
def endElement(self, name, value, connection):
if name == OWNER:
pass
elif name == ENTRIES:
pass
else:
setattr(self, name, value)
def to_xml(self):
s = '<%s>' % ACCESS_CONTROL_LIST
s += self.owner.to_xml()
acl_entries = self.entries
if acl_entries:
s += acl_entries.to_xml()
s += '</%s>' % ACCESS_CONTROL_LIST
return s
class Entries:
def __init__(self, parent=None):
self.parent = parent
# Entries is the class that represents the same-named XML
# element. entry_list is the list within this class that holds the data.
self.entry_list = []
def __repr__(self):
entries_repr = []
for e in self.entry_list:
entries_repr.append(e.__repr__())
return '<Entries: %s>' % ', '.join(entries_repr)
def startElement(self, name, attrs, connection):
if name == ENTRY:
entry = Entry(self)
self.entry_list.append(entry)
return entry
else:
return None
def endElement(self, name, value, connection):
if name == ENTRY:
pass
else:
setattr(self, name, value)
def to_xml(self):
s = '<%s>' % ENTRIES
for entry in self.entry_list:
s += entry.to_xml()
s += '</%s>' % ENTRIES
return s
# Class that represents a single (Scope, Permission) entry in an ACL.
class Entry:
def __init__(self, scope=None, type=None, id=None, name=None,
email_address=None, domain=None, permission=None):
if not scope:
scope = Scope(self, type, id, name, email_address, domain)
self.scope = scope
self.permission = permission
def __repr__(self):
return '<%s: %s>' % (self.scope.__repr__(), self.permission.__repr__())
def startElement(self, name, attrs, connection):
if name == SCOPE:
if not TYPE in attrs:
raise InvalidAclError('Missing "%s" in "%s" part of ACL' %
(TYPE, SCOPE))
self.scope = Scope(self, attrs[TYPE])
return self.scope
elif name == PERMISSION:
pass
else:
return None
def endElement(self, name, value, connection):
if name == SCOPE:
pass
elif name == PERMISSION:
value = value.strip()
if not value in SupportedPermissions:
raise InvalidAclError('Invalid Permission "%s"' % value)
self.permission = value
else:
setattr(self, name, value)
def to_xml(self):
s = '<%s>' % ENTRY
s += self.scope.to_xml()
s += '<%s>%s</%s>' % (PERMISSION, self.permission, PERMISSION)
s += '</%s>' % ENTRY
return s
class Scope:
# Map from Scope type to list of allowed sub-elems.
ALLOWED_SCOPE_TYPE_SUB_ELEMS = {
ALL_AUTHENTICATED_USERS : [],
ALL_USERS : [],
GROUP_BY_DOMAIN : [DOMAIN],
GROUP_BY_EMAIL : [EMAIL_ADDRESS, NAME],
GROUP_BY_ID : [ID, NAME],
USER_BY_EMAIL : [EMAIL_ADDRESS, NAME],
USER_BY_ID : [ID, NAME]
}
def __init__(self, parent, type=None, id=None, name=None,
email_address=None, domain=None):
self.parent = parent
self.type = type
self.name = name
self.id = id
self.domain = domain
self.email_address = email_address
if not self.ALLOWED_SCOPE_TYPE_SUB_ELEMS.has_key(self.type):
raise InvalidAclError('Invalid %s %s "%s" ' %
(SCOPE, TYPE, self.type))
def __repr__(self):
named_entity = None
if self.id:
named_entity = self.id
elif self.email_address:
named_entity = self.email_address
elif self.domain:
named_entity = self.domain
if named_entity:
return '<%s: %s>' % (self.type, named_entity)
else:
return '<%s>' % self.type
def startElement(self, name, attrs, connection):
if not name in self.ALLOWED_SCOPE_TYPE_SUB_ELEMS[self.type]:
raise InvalidAclError('Element "%s" not allowed in %s %s "%s" ' %
(name, SCOPE, TYPE, self.type))
return None
def endElement(self, name, value, connection):
value = value.strip()
if name == DOMAIN:
self.domain = value
elif name == EMAIL_ADDRESS:
self.email_address = value
elif name == ID:
self.id = value
elif name == NAME:
self.name = value
else:
setattr(self, name, value)
def to_xml(self):
s = '<%s type="%s">' % (SCOPE, self.type)
if self.type == ALL_AUTHENTICATED_USERS or self.type == ALL_USERS:
pass
elif self.type == GROUP_BY_DOMAIN:
s += '<%s>%s</%s>' % (DOMAIN, self.domain, DOMAIN)
elif self.type == GROUP_BY_EMAIL or self.type == USER_BY_EMAIL:
s += '<%s>%s</%s>' % (EMAIL_ADDRESS, self.email_address,
EMAIL_ADDRESS)
if self.name:
s += '<%s>%s</%s>' % (NAME, self.name, NAME)
elif self.type == GROUP_BY_ID or self.type == USER_BY_ID:
s += '<%s>%s</%s>' % (ID, self.id, ID)
if self.name:
s += '<%s>%s</%s>' % (NAME, self.name, NAME)
else:
raise InvalidAclError('Invalid scope type "%s" ', self.type)
s += '</%s>' % SCOPE
return s
| Python |
# Copyright 2010 Google Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
import cgi
import errno
import httplib
import os
import re
import socket
import time
import urlparse
import boto
from boto import config
from boto.connection import AWSAuthConnection
from boto.exception import InvalidUriError
from boto.exception import ResumableTransferDisposition
from boto.exception import ResumableUploadException
"""
Handler for Google Storage resumable uploads. See
http://code.google.com/apis/storage/docs/developer-guide.html#resumable
for details.
Resumable uploads will retry failed uploads, resuming at the byte
count completed by the last upload attempt. If too many retries happen with
no progress (per configurable num_retries param), the upload will be aborted.
The caller can optionally specify a tracker_file_name param in the
ResumableUploadHandler constructor. If you do this, that file will
save the state needed to allow retrying later, in a separate process
(e.g., in a later run of gsutil).
"""
class ResumableUploadHandler(object):
BUFFER_SIZE = 8192
RETRYABLE_EXCEPTIONS = (httplib.HTTPException, IOError, socket.error,
socket.gaierror)
# (start, end) response indicating server has nothing (upload protocol uses
# inclusive numbering).
SERVER_HAS_NOTHING = (0, -1)
def __init__(self, tracker_file_name=None, num_retries=None):
"""
Constructor. Instantiate once for each uploaded file.
:type tracker_file_name: string
:param tracker_file_name: optional file name to save tracker URI.
If supplied and the current process fails the upload, it can be
retried in a new process. If called with an existing file containing
a valid tracker URI, we'll resume the upload from this URI; else
we'll start a new resumable upload (and write the URI to this
tracker file).
:type num_retries: int
:param num_retries: the number of times we'll re-try a resumable upload
making no progress. (Count resets every time we get progress, so
upload can span many more than this number of retries.)
"""
self.tracker_file_name = tracker_file_name
self.num_retries = num_retries
self.server_has_bytes = 0 # Byte count at last server check.
self.tracker_uri = None
if tracker_file_name:
self._load_tracker_uri_from_file()
# Save upload_start_point in instance state so caller can find how
# much was transferred by this ResumableUploadHandler (across retries).
self.upload_start_point = None
def _load_tracker_uri_from_file(self):
f = None
try:
f = open(self.tracker_file_name, 'r')
uri = f.readline().strip()
self._set_tracker_uri(uri)
except IOError, e:
# Ignore non-existent file (happens first time an upload
# is attempted on a file), but warn user for other errors.
if e.errno != errno.ENOENT:
# Will restart because self.tracker_uri == None.
print('Couldn\'t read URI tracker file (%s): %s. Restarting '
'upload from scratch.' %
(self.tracker_file_name, e.strerror))
except InvalidUriError, e:
# Warn user, but proceed (will restart because
# self.tracker_uri == None).
print('Invalid tracker URI (%s) found in URI tracker file '
'(%s). Restarting upload from scratch.' %
(uri, self.tracker_file_name))
finally:
if f:
f.close()
def _save_tracker_uri_to_file(self):
"""
Saves URI to tracker file if one was passed to constructor.
"""
if not self.tracker_file_name:
return
f = None
try:
f = open(self.tracker_file_name, 'w')
f.write(self.tracker_uri)
except IOError, e:
raise ResumableUploadException(
'Couldn\'t write URI tracker file (%s): %s.\nThis can happen'
'if you\'re using an incorrectly configured upload tool\n'
'(e.g., gsutil configured to save tracker files to an '
'unwritable directory)' %
(self.tracker_file_name, e.strerror),
ResumableTransferDisposition.ABORT)
finally:
if f:
f.close()
def _set_tracker_uri(self, uri):
"""
Called when we start a new resumable upload or get a new tracker
URI for the upload. Saves URI and resets upload state.
Raises InvalidUriError if URI is syntactically invalid.
"""
parse_result = urlparse.urlparse(uri)
if (parse_result.scheme.lower() not in ['http', 'https'] or
not parse_result.netloc or not parse_result.query):
raise InvalidUriError('Invalid tracker URI (%s)' % uri)
qdict = cgi.parse_qs(parse_result.query)
if not qdict or not 'upload_id' in qdict:
raise InvalidUriError('Invalid tracker URI (%s)' % uri)
self.tracker_uri = uri
self.tracker_uri_host = parse_result.netloc
self.tracker_uri_path = '/?%s' % parse_result.query
self.server_has_bytes = 0
def get_tracker_uri(self):
"""
Returns upload tracker URI, or None if the upload has not yet started.
"""
return self.tracker_uri
def _remove_tracker_file(self):
if (self.tracker_file_name and
os.path.exists(self.tracker_file_name)):
os.unlink(self.tracker_file_name)
def _build_content_range_header(self, range_spec='*', length_spec='*'):
return 'bytes %s/%s' % (range_spec, length_spec)
def _query_server_state(self, conn, file_length):
"""
Queries server to find out what bytes it currently has.
Note that this method really just makes special case use of the
fact that the upload server always returns the current start/end
state whenever a PUT doesn't complete.
Returns (server_start, server_end), where the values are inclusive.
For example, (0, 2) would mean that the server has bytes 0, 1, *and* 2.
Raises ResumableUploadException if problem querying server.
"""
# Send an empty PUT so that server replies with this resumable
# transfer's state.
put_headers = {}
put_headers['Content-Range'] = (
self._build_content_range_header('*', file_length))
put_headers['Content-Length'] = '0'
resp = AWSAuthConnection.make_request(conn, 'PUT',
path=self.tracker_uri_path,
headers=put_headers,
host=self.tracker_uri_host)
if resp.status == 200:
return (0, file_length) # Completed upload.
if resp.status != 308:
# This means the server didn't have any state for the given
# upload ID, which can happen (for example) if the caller saved
# the tracker URI to a file and then tried to restart the transfer
# after that upload ID has gone stale. In that case we need to
# start a new transfer (and the caller will then save the new
# tracker URI to the tracker file).
raise ResumableUploadException(
'Got non-308 response (%s) from server state query' %
resp.status, ResumableTransferDisposition.START_OVER)
got_valid_response = False
range_spec = resp.getheader('range')
if range_spec:
# Parse 'bytes=<from>-<to>' range_spec.
m = re.search('bytes=(\d+)-(\d+)', range_spec)
if m:
server_start = long(m.group(1))
server_end = long(m.group(2))
got_valid_response = True
else:
# No Range header, which means the server does not yet have
# any bytes. Note that the Range header uses inclusive 'from'
# and 'to' values. Since Range 0-0 would mean that the server
# has byte 0, omitting the Range header is used to indicate that
# the server doesn't have any bytes.
return self.SERVER_HAS_NOTHING
if not got_valid_response:
raise ResumableUploadException(
'Couldn\'t parse upload server state query response (%s)' %
str(resp.getheaders()), ResumableTransferDisposition.START_OVER)
if conn.debug >= 1:
print 'Server has: Range: %d - %d.' % (server_start, server_end)
return (server_start, server_end)
def _start_new_resumable_upload(self, key, headers=None):
"""
Starts a new resumable upload.
Raises ResumableUploadException if any errors occur.
"""
conn = key.bucket.connection
if conn.debug >= 1:
print 'Starting new resumable upload.'
self.server_has_bytes = 0
# Start a new resumable upload by sending a POST request with an
# empty body and the "X-Goog-Resumable: start" header. Include any
# caller-provided headers (e.g., Content-Type) EXCEPT Content-Length
# (and raise an exception if they tried to pass one, since it's
# a semantic error to specify it at this point, and if we were to
# include one now it would cause the server to expect that many
# bytes; the POST doesn't include the actual file bytes We set
# the Content-Length in the subsequent PUT, based on the uploaded
# file size.
post_headers = {}
for k in headers:
if k.lower() == 'content-length':
raise ResumableUploadException(
'Attempt to specify Content-Length header (disallowed)',
ResumableTransferDisposition.ABORT)
post_headers[k] = headers[k]
post_headers[conn.provider.resumable_upload_header] = 'start'
resp = conn.make_request(
'POST', key.bucket.name, key.name, post_headers)
# Get tracker URI from response 'Location' header.
body = resp.read()
# Check for '201 Created' response code.
if resp.status != 201:
raise ResumableUploadException(
'Got status %d from attempt to start resumable upload' %
resp.status, ResumableTransferDisposition.WAIT_BEFORE_RETRY)
tracker_uri = resp.getheader('Location')
if not tracker_uri:
raise ResumableUploadException(
'No resumable tracker URI found in resumable initiation '
'POST response (%s)' % body,
ResumableTransferDisposition.WAIT_BEFORE_RETRY)
self._set_tracker_uri(tracker_uri)
self._save_tracker_uri_to_file()
def _upload_file_bytes(self, conn, http_conn, fp, file_length,
total_bytes_uploaded, cb, num_cb):
"""
Makes one attempt to upload file bytes, using an existing resumable
upload connection.
Returns etag from server upon success.
Raises ResumableUploadException if any problems occur.
"""
buf = fp.read(self.BUFFER_SIZE)
if cb:
if num_cb > 2:
cb_count = file_length / self.BUFFER_SIZE / (num_cb-2)
elif num_cb < 0:
cb_count = -1
else:
cb_count = 0
i = 0
cb(total_bytes_uploaded, file_length)
# Build resumable upload headers for the transfer. Don't send a
# Content-Range header if the file is 0 bytes long, because the
# resumable upload protocol uses an *inclusive* end-range (so, sending
# 'bytes 0-0/1' would actually mean you're sending a 1-byte file).
put_headers = {}
if file_length:
range_header = self._build_content_range_header(
'%d-%d' % (total_bytes_uploaded, file_length - 1),
file_length)
put_headers['Content-Range'] = range_header
# Set Content-Length to the total bytes we'll send with this PUT.
put_headers['Content-Length'] = str(file_length - total_bytes_uploaded)
(path, put_headers) = AWSAuthConnection.build_request(
conn, 'PUT', path=self.tracker_uri_path,
headers=put_headers, host=self.tracker_uri_host)
http_conn.putrequest('PUT', path)
for k in put_headers:
http_conn.putheader(k, put_headers[k])
http_conn.endheaders()
# Turn off debug on http connection so upload content isn't included
# in debug stream.
http_conn.set_debuglevel(0)
while buf:
http_conn.send(buf)
total_bytes_uploaded += len(buf)
if cb:
i += 1
if i == cb_count or cb_count == -1:
cb(total_bytes_uploaded, file_length)
i = 0
buf = fp.read(self.BUFFER_SIZE)
if cb:
cb(total_bytes_uploaded, file_length)
if total_bytes_uploaded != file_length:
raise ResumableUploadException('File changed during upload: EOF at '
'%d bytes of %d byte file.' %
(total_bytes_uploaded, file_length),
ResumableTransferDisposition.ABORT)
resp = http_conn.getresponse()
body = resp.read()
# Restore http connection debug level.
http_conn.set_debuglevel(conn.debug)
additional_note = ''
if resp.status == 200:
return resp.getheader('etag') # Success
# Retry status 503 errors after a delay.
elif resp.status == 503:
disposition = ResumableTransferDisposition.WAIT_BEFORE_RETRY
elif resp.status == 500:
disposition = ResumableTransferDisposition.ABORT
additional_note = ('This can happen if you attempt to upload a '
'different size file on a already partially '
'uploaded resumable upload')
else:
disposition = ResumableTransferDisposition.ABORT
raise ResumableUploadException('Got response code %d while attempting '
'upload (%s)%s' %
(resp.status, resp.reason,
additional_note), disposition)
def _attempt_resumable_upload(self, key, fp, file_length, headers, cb,
num_cb):
"""
Attempts a resumable upload.
Returns etag from server upon success.
Raises ResumableUploadException if any problems occur.
"""
(server_start, server_end) = self.SERVER_HAS_NOTHING
conn = key.bucket.connection
if self.tracker_uri:
# Try to resume existing resumable upload.
try:
(server_start, server_end) = (
self._query_server_state(conn, file_length))
self.server_has_bytes = server_start
if conn.debug >= 1:
print 'Resuming transfer.'
except ResumableUploadException, e:
if conn.debug >= 1:
print 'Unable to resume transfer (%s).' % e.message
self._start_new_resumable_upload(key, headers)
else:
self._start_new_resumable_upload(key, headers)
# upload_start_point allows the code that instantiated the
# ResumableUploadHandler to find out the point from which it started
# uploading (e.g., so it can correctly compute throughput).
if self.upload_start_point is None:
self.upload_start_point = server_end
if server_end == file_length:
return # Done.
total_bytes_uploaded = server_end + 1
fp.seek(total_bytes_uploaded)
conn = key.bucket.connection
# Get a new HTTP connection (vs conn.get_http_connection(), which reuses
# pool connections) because httplib requires a new HTTP connection per
# transaction. (Without this, calling http_conn.getresponse() would get
# "ResponseNotReady".)
http_conn = conn.new_http_connection(self.tracker_uri_host,
conn.is_secure)
http_conn.set_debuglevel(conn.debug)
# Make sure to close http_conn at end so if a local file read
# failure occurs partway through server will terminate current upload
# and can report that progress on next attempt.
try:
return self._upload_file_bytes(conn, http_conn, fp, file_length,
total_bytes_uploaded, cb, num_cb)
finally:
http_conn.close()
def _check_final_md5(self, key, etag):
"""
Checks that etag from server agrees with md5 computed before upload.
This is important, since the upload could have spanned a number of
hours and multiple processes (e.g., gsutil runs), and the user could
change some of the file and not realize they have inconsistent data.
"""
if key.bucket.connection.debug >= 1:
print 'Checking md5 against etag.'
if key.md5 != etag.strip('"\''):
# Call key.open_read() before attempting to delete the
# (incorrect-content) key, so we perform that request on a
# different HTTP connection. This is neededb because httplib
# will return a "Response not ready" error if you try to perform
# a second transaction on the connection.
key.open_read()
key.close()
key.delete()
raise ResumableUploadException(
'File changed during upload: md5 signature doesn\'t match etag '
'(incorrect uploaded object deleted)',
ResumableTransferDisposition.ABORT)
def send_file(self, key, fp, headers, cb=None, num_cb=10):
"""
Upload a file to a key into a bucket on GS, using GS resumable upload
protocol.
:type key: :class:`boto.s3.key.Key` or subclass
:param key: The Key object to which data is to be uploaded
:type fp: file-like object
:param fp: The file pointer to upload
:type headers: dict
:param headers: The headers to pass along with the PUT request
:type cb: function
:param cb: a callback function that will be called to report progress on
the upload. The callback should accept two integer parameters, the
first representing the number of bytes that have been successfully
transmitted to GS, and the second representing the total number of
bytes that need to be transmitted.
:type num_cb: int
:param num_cb: (optional) If a callback is specified with the cb
parameter, this parameter determines the granularity of the callback
by defining the maximum number of times the callback will be called
during the file transfer. Providing a negative integer will cause
your callback to be called with each buffer read.
Raises ResumableUploadException if a problem occurs during the transfer.
"""
if not headers:
headers = {}
fp.seek(0, os.SEEK_END)
file_length = fp.tell()
fp.seek(0)
debug = key.bucket.connection.debug
# Use num-retries from constructor if one was provided; else check
# for a value specified in the boto config file; else default to 5.
if self.num_retries is None:
self.num_retries = config.getint('Boto', 'num_retries', 5)
progress_less_iterations = 0
while True: # Retry as long as we're making progress.
server_had_bytes_before_attempt = self.server_has_bytes
try:
etag = self._attempt_resumable_upload(key, fp, file_length,
headers, cb, num_cb)
# Upload succceded, so remove the tracker file (if have one).
self._remove_tracker_file()
self._check_final_md5(key, etag)
if debug >= 1:
print 'Resumable upload complete.'
return
except self.RETRYABLE_EXCEPTIONS, e:
if debug >= 1:
print('Caught exception (%s)' % e.__repr__())
except ResumableUploadException, e:
if e.disposition == ResumableTransferDisposition.ABORT:
if debug >= 1:
print('Caught non-retryable ResumableUploadException '
'(%s)' % e.message)
raise
else:
if debug >= 1:
print('Caught ResumableUploadException (%s) - will '
'retry' % e.message)
# At this point we had a re-tryable failure; see if made progress.
if self.server_has_bytes > server_had_bytes_before_attempt:
progress_less_iterations = 0
else:
progress_less_iterations += 1
if progress_less_iterations > self.num_retries:
# Don't retry any longer in the current process.
raise ResumableUploadException(
'Too many resumable upload attempts failed without '
'progress. You might try this upload again later',
ResumableTransferDisposition.ABORT)
sleep_time_secs = 2**progress_less_iterations
if debug >= 1:
print ('Got retryable failure (%d progress-less in a row).\n'
'Sleeping %d seconds before re-trying' %
(progress_less_iterations, sleep_time_secs))
time.sleep(sleep_time_secs)
| Python |
# Copyright 2010 Google Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
| Python |
# Copyright 2010 Google Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
import boto
from boto import handler
from boto.exception import InvalidAclError
from boto.gs.acl import ACL
from boto.gs.acl import SupportedPermissions as GSPermissions
from boto.gs.key import Key as GSKey
from boto.s3.acl import Policy
from boto.s3.bucket import Bucket as S3Bucket
import xml.sax
class Bucket(S3Bucket):
def __init__(self, connection=None, name=None, key_class=GSKey):
super(Bucket, self).__init__(connection, name, key_class)
def set_acl(self, acl_or_str, key_name='', headers=None, version_id=None):
if isinstance(acl_or_str, Policy):
raise InvalidAclError('Attempt to set S3 Policy on GS ACL')
elif isinstance(acl_or_str, ACL):
self.set_xml_acl(acl_or_str.to_xml(), key_name, headers=headers)
else:
self.set_canned_acl(acl_or_str, key_name, headers=headers)
def get_acl(self, key_name='', headers=None, version_id=None):
response = self.connection.make_request('GET', self.name, key_name,
query_args='acl', headers=headers)
body = response.read()
if response.status == 200:
acl = ACL(self)
h = handler.XmlHandler(acl, self)
xml.sax.parseString(body, h)
return acl
else:
raise self.connection.provider.storage_response_error(
response.status, response.reason, body)
# Method with same signature as boto.s3.bucket.Bucket.add_email_grant(),
# to allow polymorphic treatment at application layer.
def add_email_grant(self, permission, email_address,
recursive=False, headers=None):
"""
Convenience method that provides a quick way to add an email grant
to a bucket. This method retrieves the current ACL, creates a new
grant based on the parameters passed in, adds that grant to the ACL
and then PUT's the new ACL back to GS.
:type permission: string
:param permission: The permission being granted. Should be one of:
(READ, WRITE, FULL_CONTROL).
:type email_address: string
:param email_address: The email address associated with the GS
account your are granting the permission to.
:type recursive: boolean
:param recursive: A boolean value to controls whether the command
will apply the grant to all keys within the bucket
or not. The default value is False. By passing a
True value, the call will iterate through all keys
in the bucket and apply the same grant to each key.
CAUTION: If you have a lot of keys, this could take
a long time!
"""
if permission not in GSPermissions:
raise self.connection.provider.storage_permissions_error(
'Unknown Permission: %s' % permission)
acl = self.get_acl(headers=headers)
acl.add_email_grant(permission, email_address)
self.set_acl(acl, headers=headers)
if recursive:
for key in self:
key.add_email_grant(permission, email_address, headers=headers)
# Method with same signature as boto.s3.bucket.Bucket.add_user_grant(),
# to allow polymorphic treatment at application layer.
def add_user_grant(self, permission, user_id, recursive=False, headers=None):
"""
Convenience method that provides a quick way to add a canonical user grant to a bucket.
This method retrieves the current ACL, creates a new grant based on the parameters
passed in, adds that grant to the ACL and then PUTs the new ACL back to GS.
:type permission: string
:param permission: The permission being granted. Should be one of:
(READ|WRITE|FULL_CONTROL)
:type user_id: string
:param user_id: The canonical user id associated with the GS account you are granting
the permission to.
:type recursive: bool
:param recursive: A boolean value to controls whether the command
will apply the grant to all keys within the bucket
or not. The default value is False. By passing a
True value, the call will iterate through all keys
in the bucket and apply the same grant to each key.
CAUTION: If you have a lot of keys, this could take
a long time!
"""
if permission not in GSPermissions:
raise self.connection.provider.storage_permissions_error(
'Unknown Permission: %s' % permission)
acl = self.get_acl(headers=headers)
acl.add_user_grant(permission, user_id)
self.set_acl(acl, headers=headers)
if recursive:
for key in self:
key.add_user_grant(permission, user_id, headers=headers)
# Method with same input signature as boto.s3.bucket.Bucket.list_grants()
# (but returning different object type), to allow polymorphic treatment
# at application layer.
def list_grants(self, headers=None):
acl = self.get_acl(headers=headers)
return acl.entries
| Python |
# Copyright 2010 Google Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
class User:
def __init__(self, parent=None, id='', name=''):
if parent:
parent.owner = self
self.type = None
self.id = id
self.name = name
def __repr__(self):
return self.id
def startElement(self, name, attrs, connection):
return None
def endElement(self, name, value, connection):
if name == 'Name':
self.name = value
elif name == 'ID':
self.id = value
else:
setattr(self, name, value)
def to_xml(self, element_name='Owner'):
if self.type:
s = '<%s type="%s">' % (element_name, self.type)
else:
s = '<%s>' % element_name
s += '<ID>%s</ID>' % self.id
if self.name:
s += '<Name>%s</Name>' % self.name
s += '</%s>' % element_name
return s
| Python |
# Copyright (c) 2009 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
class BlockDeviceType(object):
def __init__(self, connection=None):
self.connection = connection
self.ephemeral_name = None
self.volume_id = None
self.snapshot_id = None
self.status = None
self.attach_time = None
self.delete_on_termination = False
self.size = None
def startElement(self, name, attrs, connection):
pass
def endElement(self, name, value, connection):
if name =='volumeId':
self.volume_id = value
elif name == 'virtualName':
self.ephemeral_name = value
elif name =='snapshotId':
self.snapshot_id = value
elif name == 'volumeSize':
self.size = int(value)
elif name == 'status':
self.status = value
elif name == 'attachTime':
self.attach_time = value
elif name == 'deleteOnTermination':
if value == 'true':
self.delete_on_termination = True
else:
self.delete_on_termination = False
else:
setattr(self, name, value)
# for backwards compatibility
EBSBlockDeviceType = BlockDeviceType
class BlockDeviceMapping(dict):
def __init__(self, connection=None):
dict.__init__(self)
self.connection = connection
self.current_name = None
self.current_value = None
def startElement(self, name, attrs, connection):
if name == 'ebs':
self.current_value = BlockDeviceType(self)
return self.current_value
def endElement(self, name, value, connection):
if name == 'device' or name == 'deviceName':
self.current_name = value
elif name == 'item':
self[self.current_name] = self.current_value
def build_list_params(self, params, prefix=''):
i = 1
for dev_name in self:
pre = '%sBlockDeviceMapping.%d' % (prefix, i)
params['%s.DeviceName' % pre] = dev_name
block_dev = self[dev_name]
if block_dev.ephemeral_name:
params['%s.VirtualName' % pre] = block_dev.ephemeral_name
else:
if block_dev.snapshot_id:
params['%s.Ebs.SnapshotId' % pre] = block_dev.snapshot_id
if block_dev.size:
params['%s.Ebs.VolumeSize' % pre] = block_dev.size
if block_dev.delete_on_termination:
params['%s.Ebs.DeleteOnTermination' % pre] = 'true'
else:
params['%s.Ebs.DeleteOnTermination' % pre] = 'false'
i += 1
| Python |
# Copyright (c) 2006-2009 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
import boto.ec2
from boto.sdb.db.property import StringProperty, IntegerProperty
from boto.manage import propget
InstanceTypes = ['m1.small', 'm1.large', 'm1.xlarge',
'c1.medium', 'c1.xlarge', 'm2.xlarge',
'm2.2xlarge', 'm2.4xlarge', 'cc1.4xlarge',
't1.micro']
class BuyReservation(object):
def get_region(self, params):
if not params.get('region', None):
prop = StringProperty(name='region', verbose_name='EC2 Region',
choices=boto.ec2.regions)
params['region'] = propget.get(prop, choices=boto.ec2.regions)
def get_instance_type(self, params):
if not params.get('instance_type', None):
prop = StringProperty(name='instance_type', verbose_name='Instance Type',
choices=InstanceTypes)
params['instance_type'] = propget.get(prop)
def get_quantity(self, params):
if not params.get('quantity', None):
prop = IntegerProperty(name='quantity', verbose_name='Number of Instances')
params['quantity'] = propget.get(prop)
def get_zone(self, params):
if not params.get('zone', None):
prop = StringProperty(name='zone', verbose_name='EC2 Availability Zone',
choices=self.ec2.get_all_zones)
params['zone'] = propget.get(prop)
def get(self, params):
self.get_region(params)
self.ec2 = params['region'].connect()
self.get_instance_type(params)
self.get_zone(params)
self.get_quantity(params)
if __name__ == "__main__":
obj = BuyReservation()
params = {}
obj.get(params)
offerings = obj.ec2.get_all_reserved_instances_offerings(instance_type=params['instance_type'],
availability_zone=params['zone'].name)
print '\nThe following Reserved Instances Offerings are available:\n'
for offering in offerings:
offering.describe()
prop = StringProperty(name='offering', verbose_name='Offering',
choices=offerings)
offering = propget.get(prop)
print '\nYou have chosen this offering:'
offering.describe()
unit_price = float(offering.fixed_price)
total_price = unit_price * params['quantity']
print '!!! You are about to purchase %d of these offerings for a total of $%.2f !!!' % (params['quantity'], total_price)
answer = raw_input('Are you sure you want to do this? If so, enter YES: ')
if answer.strip().lower() == 'yes':
offering.purchase(params['quantity'])
else:
print 'Purchase cancelled'
| Python |
# Copyright (c) 2006-2010 Mitch Garnaat http://garnaat.org/
# Copyright (c) 2010, Eucalyptus Systems, Inc.
# All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
from boto.regioninfo import RegionInfo
class EC2RegionInfo(RegionInfo):
"""
Represents an EC2 Region
"""
def __init__(self, connection=None, name=None, endpoint=None):
from boto.ec2.connection import EC2Connection
RegionInfo.__init__(self, connection, name, endpoint,
EC2Connection)
| Python |
# Copyright (c) 2009 Reza Lotun http://reza.lotun.name/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
import weakref
from boto.ec2.elb.listelement import ListElement
from boto.resultset import ResultSet
from boto.ec2.autoscale.trigger import Trigger
from boto.ec2.autoscale.request import Request
class Instance(object):
def __init__(self, connection=None):
self.connection = connection
self.instance_id = ''
def __repr__(self):
return 'Instance:%s' % self.instance_id
def startElement(self, name, attrs, connection):
return None
def endElement(self, name, value, connection):
if name == 'InstanceId':
self.instance_id = value
else:
setattr(self, name, value)
class AutoScalingGroup(object):
def __init__(self, connection=None, group_name=None,
availability_zone=None, launch_config=None,
availability_zones=None,
load_balancers=None, cooldown=0,
min_size=None, max_size=None):
"""
Creates a new AutoScalingGroup with the specified name.
You must not have already used up your entire quota of
AutoScalingGroups in order for this call to be successful. Once the
creation request is completed, the AutoScalingGroup is ready to be
used in other calls.
:type name: str
:param name: Name of autoscaling group.
:type availability_zone: str
:param availability_zone: An availability zone. DEPRECATED - use the
availability_zones parameter, which expects
a list of availability zone
strings
:type availability_zone: list
:param availability_zone: List of availability zones.
:type launch_config: str
:param launch_config: Name of launch configuration name.
:type load_balancers: list
:param load_balancers: List of load balancers.
:type minsize: int
:param minsize: Minimum size of group
:type maxsize: int
:param maxsize: Maximum size of group
:type cooldown: int
:param cooldown: Amount of time after a Scaling Activity completes
before any further scaling activities can start.
:rtype: tuple
:return: Updated healthcheck for the instances.
"""
self.name = group_name
self.connection = connection
self.min_size = min_size
self.max_size = max_size
self.created_time = None
self.cooldown = cooldown
self.launch_config = launch_config
if self.launch_config:
self.launch_config_name = self.launch_config.name
else:
self.launch_config_name = None
self.desired_capacity = None
lbs = load_balancers or []
self.load_balancers = ListElement(lbs)
zones = availability_zones or []
self.availability_zone = availability_zone
self.availability_zones = ListElement(zones)
self.instances = None
def __repr__(self):
return 'AutoScalingGroup:%s' % self.name
def startElement(self, name, attrs, connection):
if name == 'Instances':
self.instances = ResultSet([('member', Instance)])
return self.instances
elif name == 'LoadBalancerNames':
return self.load_balancers
elif name == 'AvailabilityZones':
return self.availability_zones
else:
return
def endElement(self, name, value, connection):
if name == 'MinSize':
self.min_size = value
elif name == 'CreatedTime':
self.created_time = value
elif name == 'Cooldown':
self.cooldown = value
elif name == 'LaunchConfigurationName':
self.launch_config_name = value
elif name == 'DesiredCapacity':
self.desired_capacity = value
elif name == 'MaxSize':
self.max_size = value
elif name == 'AutoScalingGroupName':
self.name = value
else:
setattr(self, name, value)
def set_capacity(self, capacity):
""" Set the desired capacity for the group. """
params = {
'AutoScalingGroupName' : self.name,
'DesiredCapacity' : capacity,
}
req = self.connection.get_object('SetDesiredCapacity', params,
Request)
self.connection.last_request = req
return req
def update(self):
""" Sync local changes with AutoScaling group. """
return self.connection._update_group('UpdateAutoScalingGroup', self)
def shutdown_instances(self):
""" Convenience method which shuts down all instances associated with
this group.
"""
self.min_size = 0
self.max_size = 0
self.update()
def get_all_triggers(self):
""" Get all triggers for this auto scaling group. """
params = {'AutoScalingGroupName' : self.name}
triggers = self.connection.get_list('DescribeTriggers', params,
[('member', Trigger)])
# allow triggers to be able to access the autoscale group
for tr in triggers:
tr.autoscale_group = weakref.proxy(self)
return triggers
def delete(self):
""" Delete this auto-scaling group. """
params = {'AutoScalingGroupName' : self.name}
return self.connection.get_object('DeleteAutoScalingGroup', params,
Request)
def get_activities(self, activity_ids=None, max_records=100):
"""
Get all activies for this group.
"""
return self.connection.get_all_activities(self, activity_ids, max_records)
| Python |
# Copyright (c) 2009 Reza Lotun http://reza.lotun.name/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
from boto.ec2.autoscale.request import Request
from boto.ec2.elb.listelement import ListElement
class LaunchConfiguration(object):
def __init__(self, connection=None, name=None, image_id=None,
key_name=None, security_groups=None, user_data=None,
instance_type='m1.small', kernel_id=None,
ramdisk_id=None, block_device_mappings=None):
"""
A launch configuration.
:type name: str
:param name: Name of the launch configuration to create.
:type image_id: str
:param image_id: Unique ID of the Amazon Machine Image (AMI) which was
assigned during registration.
:type key_name: str
:param key_name: The name of the EC2 key pair.
:type security_groups: list
:param security_groups: Names of the security groups with which to
associate the EC2 instances.
"""
self.connection = connection
self.name = name
self.instance_type = instance_type
self.block_device_mappings = block_device_mappings
self.key_name = key_name
sec_groups = security_groups or []
self.security_groups = ListElement(sec_groups)
self.image_id = image_id
self.ramdisk_id = ramdisk_id
self.created_time = None
self.kernel_id = kernel_id
self.user_data = user_data
self.created_time = None
def __repr__(self):
return 'LaunchConfiguration:%s' % self.name
def startElement(self, name, attrs, connection):
if name == 'SecurityGroups':
return self.security_groups
else:
return
def endElement(self, name, value, connection):
if name == 'InstanceType':
self.instance_type = value
elif name == 'LaunchConfigurationName':
self.name = value
elif name == 'KeyName':
self.key_name = value
elif name == 'ImageId':
self.image_id = value
elif name == 'CreatedTime':
self.created_time = value
elif name == 'KernelId':
self.kernel_id = value
elif name == 'RamdiskId':
self.ramdisk_id = value
elif name == 'UserData':
self.user_data = value
else:
setattr(self, name, value)
def delete(self):
""" Delete this launch configuration. """
params = {'LaunchConfigurationName' : self.name}
return self.connection.get_object('DeleteLaunchConfiguration', params,
Request)
| Python |
# Copyright (c) 2009 Reza Lotun http://reza.lotun.name/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
class Request(object):
def __init__(self, connection=None):
self.connection = connection
self.request_id = ''
def __repr__(self):
return 'Request:%s' % self.request_id
def startElement(self, name, attrs, connection):
return None
def endElement(self, name, value, connection):
if name == 'RequestId':
self.request_id = value
else:
setattr(self, name, value)
| Python |
# Copyright (c) 2009 Reza Lotun http://reza.lotun.name/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
class Activity(object):
def __init__(self, connection=None):
self.connection = connection
self.start_time = None
self.activity_id = None
self.progress = None
self.status_code = None
self.cause = None
self.description = None
def __repr__(self):
return 'Activity:%s status:%s progress:%s' % (self.description,
self.status_code,
self.progress)
def startElement(self, name, attrs, connection):
return None
def endElement(self, name, value, connection):
if name == 'ActivityId':
self.activity_id = value
elif name == 'StartTime':
self.start_time = value
elif name == 'Progress':
self.progress = value
elif name == 'Cause':
self.cause = value
elif name == 'Description':
self.description = value
elif name == 'StatusCode':
self.status_code = value
else:
setattr(self, name, value)
| Python |
# Copyright (c) 2009 Reza Lotun http://reza.lotun.name/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
import weakref
from boto.ec2.autoscale.request import Request
class Trigger(object):
"""
An auto scaling trigger.
"""
def __init__(self, connection=None, name=None, autoscale_group=None,
dimensions=None, measure_name=None,
statistic=None, unit=None, period=60,
lower_threshold=None,
lower_breach_scale_increment=None,
upper_threshold=None,
upper_breach_scale_increment=None,
breach_duration=None):
"""
Initialize an auto-scaling trigger object.
:type name: str
:param name: The name for this trigger
:type autoscale_group: str
:param autoscale_group: The name of the AutoScalingGroup that will be
associated with the trigger. The AutoScalingGroup
that will be affected by the trigger when it is
activated.
:type dimensions: list
:param dimensions: List of tuples, i.e.
('ImageId', 'i-13lasde') etc.
:type measure_name: str
:param measure_name: The measure name associated with the metric used by
the trigger to determine when to activate, for
example, CPU, network I/O, or disk I/O.
:type statistic: str
:param statistic: The particular statistic used by the trigger when
fetching metric statistics to examine.
:type period: int
:param period: The period associated with the metric statistics in
seconds. Valid Values: 60 or a multiple of 60.
:type unit: str
:param unit: The unit of measurement.
"""
self.name = name
self.connection = connection
self.dimensions = dimensions
self.breach_duration = breach_duration
self.upper_breach_scale_increment = upper_breach_scale_increment
self.created_time = None
self.upper_threshold = upper_threshold
self.status = None
self.lower_threshold = lower_threshold
self.period = period
self.lower_breach_scale_increment = lower_breach_scale_increment
self.statistic = statistic
self.unit = unit
self.namespace = None
if autoscale_group:
self.autoscale_group = weakref.proxy(autoscale_group)
else:
self.autoscale_group = None
self.measure_name = measure_name
def __repr__(self):
return 'Trigger:%s' % (self.name)
def startElement(self, name, attrs, connection):
return None
def endElement(self, name, value, connection):
if name == 'BreachDuration':
self.breach_duration = value
elif name == 'TriggerName':
self.name = value
elif name == 'Period':
self.period = value
elif name == 'CreatedTime':
self.created_time = value
elif name == 'Statistic':
self.statistic = value
elif name == 'Unit':
self.unit = value
elif name == 'Namespace':
self.namespace = value
elif name == 'AutoScalingGroupName':
self.autoscale_group_name = value
elif name == 'MeasureName':
self.measure_name = value
else:
setattr(self, name, value)
def update(self):
""" Write out differences to trigger. """
self.connection.create_trigger(self)
def delete(self):
""" Delete this trigger. """
params = {
'TriggerName' : self.name,
'AutoScalingGroupName' : self.autoscale_group_name,
}
req =self.connection.get_object('DeleteTrigger', params,
Request)
self.connection.last_request = req
return req
| Python |
# Copyright (c) 2009 Reza Lotun http://reza.lotun.name/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
class Instance(object):
def __init__(self, connection=None):
self.connection = connection
self.instance_id = ''
self.lifecycle_state = None
self.availability_zone = ''
def __repr__(self):
return 'Instance:%s' % self.instance_id
def startElement(self, name, attrs, connection):
return None
def endElement(self, name, value, connection):
if name == 'InstanceId':
self.instance_id = value
elif name == 'LifecycleState':
self.lifecycle_state = value
elif name == 'AvailabilityZone':
self.availability_zone = value
else:
setattr(self, name, value)
| Python |
# Copyright (c) 2009 Reza Lotun http://reza.lotun.name/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
"""
This module provides an interface to the Elastic Compute Cloud (EC2)
Auto Scaling service.
"""
import boto
from boto.connection import AWSQueryConnection
from boto.ec2.regioninfo import RegionInfo
from boto.ec2.autoscale.request import Request
from boto.ec2.autoscale.trigger import Trigger
from boto.ec2.autoscale.launchconfig import LaunchConfiguration
from boto.ec2.autoscale.group import AutoScalingGroup
from boto.ec2.autoscale.activity import Activity
class AutoScaleConnection(AWSQueryConnection):
APIVersion = boto.config.get('Boto', 'autoscale_version', '2009-05-15')
Endpoint = boto.config.get('Boto', 'autoscale_endpoint',
'autoscaling.amazonaws.com')
DefaultRegionName = 'us-east-1'
DefaultRegionEndpoint = 'autoscaling.amazonaws.com'
SignatureVersion = '2'
def __init__(self, aws_access_key_id=None, aws_secret_access_key=None,
is_secure=True, port=None, proxy=None, proxy_port=None,
proxy_user=None, proxy_pass=None, debug=1,
https_connection_factory=None, region=None, path='/'):
"""
Init method to create a new connection to the AutoScaling service.
B{Note:} The host argument is overridden by the host specified in the
boto configuration file.
"""
if not region:
region = RegionInfo(self, self.DefaultRegionName,
self.DefaultRegionEndpoint,
AutoScaleConnection)
self.region = region
AWSQueryConnection.__init__(self, aws_access_key_id,
aws_secret_access_key,
is_secure, port, proxy, proxy_port,
proxy_user, proxy_pass,
self.region.endpoint, debug,
https_connection_factory, path=path)
def build_list_params(self, params, items, label):
""" items is a list of dictionaries or strings:
[{'Protocol' : 'HTTP',
'LoadBalancerPort' : '80',
'InstancePort' : '80'},..] etc.
or
['us-east-1b',...]
"""
# different from EC2 list params
for i in xrange(1, len(items)+1):
if isinstance(items[i-1], dict):
for k, v in items[i-1].iteritems():
params['%s.member.%d.%s' % (label, i, k)] = v
elif isinstance(items[i-1], basestring):
params['%s.member.%d' % (label, i)] = items[i-1]
def _update_group(self, op, as_group):
params = {
'AutoScalingGroupName' : as_group.name,
'Cooldown' : as_group.cooldown,
'LaunchConfigurationName' : as_group.launch_config_name,
'MinSize' : as_group.min_size,
'MaxSize' : as_group.max_size,
}
if op.startswith('Create'):
if as_group.availability_zones:
zones = as_group.availability_zones
else:
zones = [as_group.availability_zone]
self.build_list_params(params, as_group.load_balancers,
'LoadBalancerNames')
self.build_list_params(params, zones,
'AvailabilityZones')
return self.get_object(op, params, Request)
def create_auto_scaling_group(self, as_group):
"""
Create auto scaling group.
"""
return self._update_group('CreateAutoScalingGroup', as_group)
def create_launch_configuration(self, launch_config):
"""
Creates a new Launch Configuration.
:type launch_config: boto.ec2.autoscale.launchconfig.LaunchConfiguration
:param launch_config: LaunchConfiguraiton object.
"""
params = {
'ImageId' : launch_config.image_id,
'KeyName' : launch_config.key_name,
'LaunchConfigurationName' : launch_config.name,
'InstanceType' : launch_config.instance_type,
}
if launch_config.user_data:
params['UserData'] = launch_config.user_data
if launch_config.kernel_id:
params['KernelId'] = launch_config.kernel_id
if launch_config.ramdisk_id:
params['RamdiskId'] = launch_config.ramdisk_id
if launch_config.block_device_mappings:
self.build_list_params(params, launch_config.block_device_mappings,
'BlockDeviceMappings')
self.build_list_params(params, launch_config.security_groups,
'SecurityGroups')
return self.get_object('CreateLaunchConfiguration', params,
Request)
def create_trigger(self, trigger):
"""
"""
params = {'TriggerName' : trigger.name,
'AutoScalingGroupName' : trigger.autoscale_group.name,
'MeasureName' : trigger.measure_name,
'Statistic' : trigger.statistic,
'Period' : trigger.period,
'Unit' : trigger.unit,
'LowerThreshold' : trigger.lower_threshold,
'LowerBreachScaleIncrement' : trigger.lower_breach_scale_increment,
'UpperThreshold' : trigger.upper_threshold,
'UpperBreachScaleIncrement' : trigger.upper_breach_scale_increment,
'BreachDuration' : trigger.breach_duration}
# dimensions should be a list of tuples
dimensions = []
for dim in trigger.dimensions:
name, value = dim
dimensions.append(dict(Name=name, Value=value))
self.build_list_params(params, dimensions, 'Dimensions')
req = self.get_object('CreateOrUpdateScalingTrigger', params,
Request)
return req
def get_all_groups(self, names=None):
"""
"""
params = {}
if names:
self.build_list_params(params, names, 'AutoScalingGroupNames')
return self.get_list('DescribeAutoScalingGroups', params,
[('member', AutoScalingGroup)])
def get_all_launch_configurations(self, names=None):
"""
"""
params = {}
if names:
self.build_list_params(params, names, 'LaunchConfigurationNames')
return self.get_list('DescribeLaunchConfigurations', params,
[('member', LaunchConfiguration)])
def get_all_activities(self, autoscale_group,
activity_ids=None,
max_records=100):
"""
Get all activities for the given autoscaling group.
:type autoscale_group: str or AutoScalingGroup object
:param autoscale_group: The auto scaling group to get activities on.
@max_records: int
:param max_records: Maximum amount of activities to return.
"""
name = autoscale_group
if isinstance(autoscale_group, AutoScalingGroup):
name = autoscale_group.name
params = {'AutoScalingGroupName' : name}
if activity_ids:
self.build_list_params(params, activity_ids, 'ActivityIds')
return self.get_list('DescribeScalingActivities', params,
[('member', Activity)])
def get_all_triggers(self, autoscale_group):
params = {'AutoScalingGroupName' : autoscale_group}
return self.get_list('DescribeTriggers', params,
[('member', Trigger)])
def terminate_instance(self, instance_id, decrement_capacity=True):
params = {
'InstanceId' : instance_id,
'ShouldDecrementDesiredCapacity' : decrement_capacity
}
return self.get_object('TerminateInstanceInAutoScalingGroup', params,
Activity)
| Python |
# Copyright (c) 2010 Mitch Garnaat http://garnaat.org/
# Copyright (c) 2010, Eucalyptus Systems, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
class TagSet(dict):
"""
A TagSet is used to collect the tags associated with a particular
EC2 resource. Not all resources can be tagged but for those that
can, this dict object will be used to collect those values. See
:class:`boto.ec2.ec2object.TaggedEC2Object` for more details.
"""
def __init__(self, connection=None):
self.connection = connection
self._current_key = None
self._current_value = None
def startElement(self, name, attrs, connection):
if name == 'item':
self._current_key = None
self._current_value = None
return None
def endElement(self, name, value, connection):
if name == 'key':
self._current_key = value
elif name == 'value':
self._current_value = value
elif name == 'item':
self[self._current_key] = self._current_value
class Tag(object):
"""
A Tag is used when creating or listing all tags related to
an AWS account. It records not only the key and value but
also the ID of the resource to which the tag is attached
as well as the type of the resource.
"""
def __init__(self, connection=None, res_id=None, res_type=None,
name=None, value=None):
self.connection = connection
self.res_id = res_id
self.res_type = res_type
self.name = name
self.value = value
def __repr__(self):
return 'Tag:%s' % self.name
def startElement(self, name, attrs, connection):
return None
def endElement(self, name, value, connection):
if name == 'resourceId':
self.res_id = value
elif name == 'resourceType':
self.res_type = value
elif name == 'key':
self.name = value
elif name == 'value':
self.value = value
else:
setattr(self, name, value)
| Python |
# Copyright (c) 2006-2008 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
"""
Represents an EC2 Availability Zone
"""
from boto.ec2.ec2object import EC2Object
class Zone(EC2Object):
def __init__(self, connection=None):
EC2Object.__init__(self, connection)
self.name = None
self.state = None
def __repr__(self):
return 'Zone:%s' % self.name
def endElement(self, name, value, connection):
if name == 'zoneName':
self.name = value
elif name == 'zoneState':
self.state = value
else:
setattr(self, name, value)
| Python |
# Copyright (c) 2006-2010 Mitch Garnaat http://garnaat.org/
# Copyright (c) 2010, Eucalyptus Systems, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
"""
Represents an EC2 Elastic IP Snapshot
"""
from boto.ec2.ec2object import TaggedEC2Object
class Snapshot(TaggedEC2Object):
def __init__(self, connection=None):
TaggedEC2Object.__init__(self, connection)
self.id = None
self.volume_id = None
self.status = None
self.progress = None
self.start_time = None
self.owner_id = None
self.volume_size = None
self.description = None
def __repr__(self):
return 'Snapshot:%s' % self.id
def endElement(self, name, value, connection):
if name == 'snapshotId':
self.id = value
elif name == 'volumeId':
self.volume_id = value
elif name == 'status':
self.status = value
elif name == 'startTime':
self.start_time = value
elif name == 'ownerId':
self.owner_id = value
elif name == 'volumeSize':
try:
self.volume_size = int(value)
except:
self.volume_size = value
elif name == 'description':
self.description = value
else:
setattr(self, name, value)
def _update(self, updated):
self.progress = updated.progress
self.status = updated.status
def update(self, validate=False):
"""
Update the data associated with this snapshot by querying EC2.
:type validate: bool
:param validate: By default, if EC2 returns no data about the
snapshot the update method returns quietly. If
the validate param is True, however, it will
raise a ValueError exception if no data is
returned from EC2.
"""
rs = self.connection.get_all_snapshots([self.id])
if len(rs) > 0:
self._update(rs[0])
elif validate:
raise ValueError('%s is not a valid Snapshot ID' % self.id)
return self.progress
def delete(self):
return self.connection.delete_snapshot(self.id)
def get_permissions(self):
attrs = self.connection.get_snapshot_attribute(self.id,
attribute='createVolumePermission')
return attrs.attrs
def share(self, user_ids=None, groups=None):
return self.connection.modify_snapshot_attribute(self.id,
'createVolumePermission',
'add',
user_ids,
groups)
def unshare(self, user_ids=None, groups=None):
return self.connection.modify_snapshot_attribute(self.id,
'createVolumePermission',
'remove',
user_ids,
groups)
def reset_permissions(self):
return self.connection.reset_snapshot_attribute(self.id, 'createVolumePermission')
class SnapshotAttribute:
def __init__(self, parent=None):
self.snapshot_id = None
self.attrs = {}
def startElement(self, name, attrs, connection):
return None
def endElement(self, name, value, connection):
if name == 'createVolumePermission':
self.name = 'create_volume_permission'
elif name == 'group':
if self.attrs.has_key('groups'):
self.attrs['groups'].append(value)
else:
self.attrs['groups'] = [value]
elif name == 'userId':
if self.attrs.has_key('user_ids'):
self.attrs['user_ids'].append(value)
else:
self.attrs['user_ids'] = [value]
elif name == 'snapshotId':
self.snapshot_id = value
else:
setattr(self, name, value)
| Python |
# Copyright (c) 2006-2009 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
"""
Represents an EC2 Elastic IP Address
"""
from boto.ec2.ec2object import EC2Object
class Address(EC2Object):
def __init__(self, connection=None, public_ip=None, instance_id=None):
EC2Object.__init__(self, connection)
self.connection = connection
self.public_ip = public_ip
self.instance_id = instance_id
def __repr__(self):
return 'Address:%s' % self.public_ip
def endElement(self, name, value, connection):
if name == 'publicIp':
self.public_ip = value
elif name == 'instanceId':
self.instance_id = value
else:
setattr(self, name, value)
def release(self):
return self.connection.release_address(self.public_ip)
delete = release
def associate(self, instance_id):
return self.connection.associate_address(instance_id, self.public_ip)
def disassociate(self):
return self.connection.disassociate_address(self.public_ip)
| Python |
# Copyright (c) 2006-2010 Mitch Garnaat http://garnaat.org/
# Copyright (c) 2010, Eucalyptus Systems, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
"""
Represents a connection to the EC2 service.
"""
import urllib
import base64
import hmac
import boto
from hashlib import sha1 as sha
from boto.connection import AWSQueryConnection
from boto.resultset import ResultSet
from boto.ec2.image import Image, ImageAttribute
from boto.ec2.instance import Reservation, Instance, ConsoleOutput, InstanceAttribute
from boto.ec2.keypair import KeyPair
from boto.ec2.address import Address
from boto.ec2.volume import Volume
from boto.ec2.snapshot import Snapshot
from boto.ec2.snapshot import SnapshotAttribute
from boto.ec2.zone import Zone
from boto.ec2.securitygroup import SecurityGroup
from boto.ec2.regioninfo import RegionInfo
from boto.ec2.instanceinfo import InstanceInfo
from boto.ec2.reservedinstance import ReservedInstancesOffering, ReservedInstance
from boto.ec2.spotinstancerequest import SpotInstanceRequest
from boto.ec2.spotpricehistory import SpotPriceHistory
from boto.ec2.spotdatafeedsubscription import SpotDatafeedSubscription
from boto.ec2.bundleinstance import BundleInstanceTask
from boto.ec2.placementgroup import PlacementGroup
from boto.ec2.tag import Tag
from boto.exception import EC2ResponseError
#boto.set_stream_logger('ec2')
class EC2Connection(AWSQueryConnection):
APIVersion = boto.config.get('Boto', 'ec2_version', '2010-08-31')
DefaultRegionName = boto.config.get('Boto', 'ec2_region_name', 'us-east-1')
DefaultRegionEndpoint = boto.config.get('Boto', 'ec2_region_endpoint',
'ec2.amazonaws.com')
SignatureVersion = '2'
ResponseError = EC2ResponseError
def __init__(self, aws_access_key_id=None, aws_secret_access_key=None,
is_secure=True, host=None, port=None, proxy=None, proxy_port=None,
proxy_user=None, proxy_pass=None, debug=0,
https_connection_factory=None, region=None, path='/'):
"""
Init method to create a new connection to EC2.
B{Note:} The host argument is overridden by the host specified in the
boto configuration file.
"""
if not region:
region = RegionInfo(self, self.DefaultRegionName,
self.DefaultRegionEndpoint)
self.region = region
AWSQueryConnection.__init__(self, aws_access_key_id,
aws_secret_access_key,
is_secure, port, proxy, proxy_port,
proxy_user, proxy_pass,
self.region.endpoint, debug,
https_connection_factory, path)
def get_params(self):
"""
Returns a dictionary containing the value of of all of the keyword
arguments passed when constructing this connection.
"""
param_names = ['aws_access_key_id', 'aws_secret_access_key', 'is_secure',
'port', 'proxy', 'proxy_port', 'proxy_user', 'proxy_pass',
'debug', 'https_connection_factory']
params = {}
for name in param_names:
params[name] = getattr(self, name)
return params
def build_filter_params(self, params, filters):
i = 1
for name in filters:
aws_name = name.replace('_', '-')
params['Filter.%d.Name' % i] = aws_name
value = filters[name]
if not isinstance(value, list):
value = [value]
j = 1
for v in value:
params['Filter.%d.Value.%d' % (i,j)] = v
j += 1
i += 1
# Image methods
def get_all_images(self, image_ids=None, owners=None,
executable_by=None, filters=None):
"""
Retrieve all the EC2 images available on your account.
:type image_ids: list
:param image_ids: A list of strings with the image IDs wanted
:type owners: list
:param owners: A list of owner IDs
:type executable_by: list
:param executable_by: Returns AMIs for which the specified
user ID has explicit launch permissions
:type filters: dict
:param filters: Optional filters that can be used to limit
the results returned. Filters are provided
in the form of a dictionary consisting of
filter names as the key and filter values
as the value. The set of allowable filter
names/values is dependent on the request
being performed. Check the EC2 API guide
for details.
:rtype: list
:return: A list of :class:`boto.ec2.image.Image`
"""
params = {}
if image_ids:
self.build_list_params(params, image_ids, 'ImageId')
if owners:
self.build_list_params(params, owners, 'Owner')
if executable_by:
self.build_list_params(params, executable_by, 'ExecutableBy')
if filters:
self.build_filter_params(params, filters)
return self.get_list('DescribeImages', params, [('item', Image)])
def get_all_kernels(self, kernel_ids=None, owners=None):
"""
Retrieve all the EC2 kernels available on your account.
Constructs a filter to allow the processing to happen server side.
:type kernel_ids: list
:param kernel_ids: A list of strings with the image IDs wanted
:type owners: list
:param owners: A list of owner IDs
:rtype: list
:return: A list of :class:`boto.ec2.image.Image`
"""
params = {}
if kernel_ids:
self.build_list_params(params, kernel_ids, 'ImageId')
if owners:
self.build_list_params(params, owners, 'Owner')
filter = {'image-type' : 'kernel'}
self.build_filter_params(params, filter)
return self.get_list('DescribeImages', params, [('item', Image)])
def get_all_ramdisks(self, ramdisk_ids=None, owners=None):
"""
Retrieve all the EC2 ramdisks available on your account.
Constructs a filter to allow the processing to happen server side.
:type ramdisk_ids: list
:param ramdisk_ids: A list of strings with the image IDs wanted
:type owners: list
:param owners: A list of owner IDs
:rtype: list
:return: A list of :class:`boto.ec2.image.Image`
"""
params = {}
if ramdisk_ids:
self.build_list_params(params, ramdisk_ids, 'ImageId')
if owners:
self.build_list_params(params, owners, 'Owner')
filter = {'image-type' : 'ramdisk'}
self.build_filter_params(params, filter)
return self.get_list('DescribeImages', params, [('item', Image)])
def get_image(self, image_id):
"""
Shortcut method to retrieve a specific image (AMI).
:type image_id: string
:param image_id: the ID of the Image to retrieve
:rtype: :class:`boto.ec2.image.Image`
:return: The EC2 Image specified or None if the image is not found
"""
try:
return self.get_all_images(image_ids=[image_id])[0]
except IndexError: # None of those images available
return None
def register_image(self, name=None, description=None, image_location=None,
architecture=None, kernel_id=None, ramdisk_id=None,
root_device_name=None, block_device_map=None):
"""
Register an image.
:type name: string
:param name: The name of the AMI. Valid only for EBS-based images.
:type description: string
:param description: The description of the AMI.
:type image_location: string
:param image_location: Full path to your AMI manifest in Amazon S3 storage.
Only used for S3-based AMI's.
:type architecture: string
:param architecture: The architecture of the AMI. Valid choices are:
i386 | x86_64
:type kernel_id: string
:param kernel_id: The ID of the kernel with which to launch the instances
:type root_device_name: string
:param root_device_name: The root device name (e.g. /dev/sdh)
:type block_device_map: :class:`boto.ec2.blockdevicemapping.BlockDeviceMapping`
:param block_device_map: A BlockDeviceMapping data structure
describing the EBS volumes associated
with the Image.
:rtype: string
:return: The new image id
"""
params = {}
if name:
params['Name'] = name
if description:
params['Description'] = description
if architecture:
params['Architecture'] = architecture
if kernel_id:
params['KernelId'] = kernel_id
if ramdisk_id:
params['RamdiskId'] = ramdisk_id
if image_location:
params['ImageLocation'] = image_location
if root_device_name:
params['RootDeviceName'] = root_device_name
if block_device_map:
block_device_map.build_list_params(params)
rs = self.get_object('RegisterImage', params, ResultSet)
image_id = getattr(rs, 'imageId', None)
return image_id
def deregister_image(self, image_id):
"""
Unregister an AMI.
:type image_id: string
:param image_id: the ID of the Image to unregister
:rtype: bool
:return: True if successful
"""
return self.get_status('DeregisterImage', {'ImageId':image_id})
def create_image(self, instance_id, name, description=None, no_reboot=False):
"""
Will create an AMI from the instance in the running or stopped
state.
:type instance_id: string
:param instance_id: the ID of the instance to image.
:type name: string
:param name: The name of the new image
:type description: string
:param description: An optional human-readable string describing
the contents and purpose of the AMI.
:type no_reboot: bool
:param no_reboot: An optional flag indicating that the bundling process
should not attempt to shutdown the instance before
bundling. If this flag is True, the responsibility
of maintaining file system integrity is left to the
owner of the instance.
:rtype: string
:return: The new image id
"""
params = {'InstanceId' : instance_id,
'Name' : name}
if description:
params['Description'] = description
if no_reboot:
params['NoReboot'] = 'true'
img = self.get_object('CreateImage', params, Image)
return img.id
# ImageAttribute methods
def get_image_attribute(self, image_id, attribute='launchPermission'):
"""
Gets an attribute from an image.
:type image_id: string
:param image_id: The Amazon image id for which you want info about
:type attribute: string
:param attribute: The attribute you need information about.
Valid choices are:
* launchPermission
* productCodes
* blockDeviceMapping
:rtype: :class:`boto.ec2.image.ImageAttribute`
:return: An ImageAttribute object representing the value of the
attribute requested
"""
params = {'ImageId' : image_id,
'Attribute' : attribute}
return self.get_object('DescribeImageAttribute', params, ImageAttribute)
def modify_image_attribute(self, image_id, attribute='launchPermission',
operation='add', user_ids=None, groups=None,
product_codes=None):
"""
Changes an attribute of an image.
:type image_id: string
:param image_id: The image id you wish to change
:type attribute: string
:param attribute: The attribute you wish to change
:type operation: string
:param operation: Either add or remove (this is required for changing
launchPermissions)
:type user_ids: list
:param user_ids: The Amazon IDs of users to add/remove attributes
:type groups: list
:param groups: The groups to add/remove attributes
:type product_codes: list
:param product_codes: Amazon DevPay product code. Currently only one
product code can be associated with an AMI. Once
set, the product code cannot be changed or reset.
"""
params = {'ImageId' : image_id,
'Attribute' : attribute,
'OperationType' : operation}
if user_ids:
self.build_list_params(params, user_ids, 'UserId')
if groups:
self.build_list_params(params, groups, 'UserGroup')
if product_codes:
self.build_list_params(params, product_codes, 'ProductCode')
return self.get_status('ModifyImageAttribute', params)
def reset_image_attribute(self, image_id, attribute='launchPermission'):
"""
Resets an attribute of an AMI to its default value.
:type image_id: string
:param image_id: ID of the AMI for which an attribute will be described
:type attribute: string
:param attribute: The attribute to reset
:rtype: bool
:return: Whether the operation succeeded or not
"""
params = {'ImageId' : image_id,
'Attribute' : attribute}
return self.get_status('ResetImageAttribute', params)
# Instance methods
def get_all_instances(self, instance_ids=None, filters=None):
"""
Retrieve all the instances associated with your account.
:type instance_ids: list
:param instance_ids: A list of strings of instance IDs
:type filters: dict
:param filters: Optional filters that can be used to limit
the results returned. Filters are provided
in the form of a dictionary consisting of
filter names as the key and filter values
as the value. The set of allowable filter
names/values is dependent on the request
being performed. Check the EC2 API guide
for details.
:rtype: list
:return: A list of :class:`boto.ec2.instance.Reservation`
"""
params = {}
if instance_ids:
self.build_list_params(params, instance_ids, 'InstanceId')
if filters:
self.build_filter_params(params, filters)
return self.get_list('DescribeInstances', params,
[('item', Reservation)])
def run_instances(self, image_id, min_count=1, max_count=1,
key_name=None, security_groups=None,
user_data=None, addressing_type=None,
instance_type='m1.small', placement=None,
kernel_id=None, ramdisk_id=None,
monitoring_enabled=False, subnet_id=None,
block_device_map=None,
disable_api_termination=False,
instance_initiated_shutdown_behavior=None,
private_ip_address=None,
placement_group=None):
"""
Runs an image on EC2.
:type image_id: string
:param image_id: The ID of the image to run
:type min_count: int
:param min_count: The minimum number of instances to launch
:type max_count: int
:param max_count: The maximum number of instances to launch
:type key_name: string
:param key_name: The name of the key pair with which to launch instances
:type security_groups: list of strings
:param security_groups: The names of the security groups with which to
associate instances
:type user_data: string
:param user_data: The user data passed to the launched instances
:type instance_type: string
:param instance_type: The type of instance to run:
* m1.small
* m1.large
* m1.xlarge
* c1.medium
* c1.xlarge
* m2.xlarge
* m2.2xlarge
* m2.4xlarge
* cc1.4xlarge
* t1.micro
:type placement: string
:param placement: The availability zone in which to launch the instances
:type kernel_id: string
:param kernel_id: The ID of the kernel with which to launch the
instances
:type ramdisk_id: string
:param ramdisk_id: The ID of the RAM disk with which to launch the
instances
:type monitoring_enabled: bool
:param monitoring_enabled: Enable CloudWatch monitoring on the instance.
:type subnet_id: string
:param subnet_id: The subnet ID within which to launch the instances
for VPC.
:type private_ip_address: string
:param private_ip_address: If you're using VPC, you can optionally use
this parameter to assign the instance a
specific available IP address from the
subnet (e.g., 10.0.0.25).
:type block_device_map: :class:`boto.ec2.blockdevicemapping.BlockDeviceMapping`
:param block_device_map: A BlockDeviceMapping data structure
describing the EBS volumes associated
with the Image.
:type disable_api_termination: bool
:param disable_api_termination: If True, the instances will be locked
and will not be able to be terminated
via the API.
:type instance_initiated_shutdown_behavior: string
:param instance_initiated_shutdown_behavior: Specifies whether the
instance's EBS volues are
stopped (i.e. detached) or
terminated (i.e. deleted)
when the instance is
shutdown by the
owner. Valid values are:
* stop
* terminate
:type placement_group: string
:param placement_group: If specified, this is the name of the placement
group in which the instance(s) will be launched.
:rtype: Reservation
:return: The :class:`boto.ec2.instance.Reservation` associated with
the request for machines
"""
params = {'ImageId':image_id,
'MinCount':min_count,
'MaxCount': max_count}
if key_name:
params['KeyName'] = key_name
if security_groups:
l = []
for group in security_groups:
if isinstance(group, SecurityGroup):
l.append(group.name)
else:
l.append(group)
self.build_list_params(params, l, 'SecurityGroup')
if user_data:
params['UserData'] = base64.b64encode(user_data)
if addressing_type:
params['AddressingType'] = addressing_type
if instance_type:
params['InstanceType'] = instance_type
if placement:
params['Placement.AvailabilityZone'] = placement
if placement_group:
params['Placement.GroupName'] = placement_group
if kernel_id:
params['KernelId'] = kernel_id
if ramdisk_id:
params['RamdiskId'] = ramdisk_id
if monitoring_enabled:
params['Monitoring.Enabled'] = 'true'
if subnet_id:
params['SubnetId'] = subnet_id
if private_ip_address:
params['PrivateIpAddress'] = private_ip_address
if block_device_map:
block_device_map.build_list_params(params)
if disable_api_termination:
params['DisableApiTermination'] = 'true'
if instance_initiated_shutdown_behavior:
val = instance_initiated_shutdown_behavior
params['InstanceInitiatedShutdownBehavior'] = val
return self.get_object('RunInstances', params, Reservation, verb='POST')
def terminate_instances(self, instance_ids=None):
"""
Terminate the instances specified
:type instance_ids: list
:param instance_ids: A list of strings of the Instance IDs to terminate
:rtype: list
:return: A list of the instances terminated
"""
params = {}
if instance_ids:
self.build_list_params(params, instance_ids, 'InstanceId')
return self.get_list('TerminateInstances', params, [('item', Instance)])
def stop_instances(self, instance_ids=None, force=False):
"""
Stop the instances specified
:type instance_ids: list
:param instance_ids: A list of strings of the Instance IDs to stop
:type force: bool
:param force: Forces the instance to stop
:rtype: list
:return: A list of the instances stopped
"""
params = {}
if force:
params['Force'] = 'true'
if instance_ids:
self.build_list_params(params, instance_ids, 'InstanceId')
return self.get_list('StopInstances', params, [('item', Instance)])
def start_instances(self, instance_ids=None):
"""
Start the instances specified
:type instance_ids: list
:param instance_ids: A list of strings of the Instance IDs to start
:rtype: list
:return: A list of the instances started
"""
params = {}
if instance_ids:
self.build_list_params(params, instance_ids, 'InstanceId')
return self.get_list('StartInstances', params, [('item', Instance)])
def get_console_output(self, instance_id):
"""
Retrieves the console output for the specified instance.
:type instance_id: string
:param instance_id: The instance ID of a running instance on the cloud.
:rtype: :class:`boto.ec2.instance.ConsoleOutput`
:return: The console output as a ConsoleOutput object
"""
params = {}
self.build_list_params(params, [instance_id], 'InstanceId')
return self.get_object('GetConsoleOutput', params, ConsoleOutput)
def reboot_instances(self, instance_ids=None):
"""
Reboot the specified instances.
:type instance_ids: list
:param instance_ids: The instances to terminate and reboot
"""
params = {}
if instance_ids:
self.build_list_params(params, instance_ids, 'InstanceId')
return self.get_status('RebootInstances', params)
def confirm_product_instance(self, product_code, instance_id):
params = {'ProductCode' : product_code,
'InstanceId' : instance_id}
rs = self.get_object('ConfirmProductInstance', params, ResultSet)
return (rs.status, rs.ownerId)
# InstanceAttribute methods
def get_instance_attribute(self, instance_id, attribute):
"""
Gets an attribute from an instance.
:type instance_id: string
:param instance_id: The Amazon id of the instance
:type attribute: string
:param attribute: The attribute you need information about
Valid choices are:
* instanceType|kernel|ramdisk|userData|
* disableApiTermination|
* instanceInitiatedShutdownBehavior|
* rootDeviceName|blockDeviceMapping
:rtype: :class:`boto.ec2.image.InstanceAttribute`
:return: An InstanceAttribute object representing the value of the
attribute requested
"""
params = {'InstanceId' : instance_id}
if attribute:
params['Attribute'] = attribute
return self.get_object('DescribeInstanceAttribute', params,
InstanceAttribute)
def modify_instance_attribute(self, instance_id, attribute, value):
"""
Changes an attribute of an instance
:type instance_id: string
:param instance_id: The instance id you wish to change
:type attribute: string
:param attribute: The attribute you wish to change.
* AttributeName - Expected value (default)
* instanceType - A valid instance type (m1.small)
* kernel - Kernel ID (None)
* ramdisk - Ramdisk ID (None)
* userData - Base64 encoded String (None)
* disableApiTermination - Boolean (true)
* instanceInitiatedShutdownBehavior - stop|terminate
* rootDeviceName - device name (None)
:type value: string
:param value: The new value for the attribute
:rtype: bool
:return: Whether the operation succeeded or not
"""
# Allow a bool to be passed in for value of disableApiTermination
if attribute == 'disableApiTermination':
if isinstance(value, bool):
if value:
value = 'true'
else:
value = 'false'
params = {'InstanceId' : instance_id,
'Attribute' : attribute,
'Value' : value}
return self.get_status('ModifyInstanceAttribute', params)
def reset_instance_attribute(self, instance_id, attribute):
"""
Resets an attribute of an instance to its default value.
:type instance_id: string
:param instance_id: ID of the instance
:type attribute: string
:param attribute: The attribute to reset. Valid values are:
kernel|ramdisk
:rtype: bool
:return: Whether the operation succeeded or not
"""
params = {'InstanceId' : instance_id,
'Attribute' : attribute}
return self.get_status('ResetInstanceAttribute', params)
# Spot Instances
def get_all_spot_instance_requests(self, request_ids=None,
filters=None):
"""
Retrieve all the spot instances requests associated with your account.
:type request_ids: list
:param request_ids: A list of strings of spot instance request IDs
:type filters: dict
:param filters: Optional filters that can be used to limit
the results returned. Filters are provided
in the form of a dictionary consisting of
filter names as the key and filter values
as the value. The set of allowable filter
names/values is dependent on the request
being performed. Check the EC2 API guide
for details.
:rtype: list
:return: A list of
:class:`boto.ec2.spotinstancerequest.SpotInstanceRequest`
"""
params = {}
if request_ids:
self.build_list_params(params, request_ids, 'SpotInstanceRequestId')
if filters:
self.build_filter_params(params, filters)
return self.get_list('DescribeSpotInstanceRequests', params,
[('item', SpotInstanceRequest)])
def get_spot_price_history(self, start_time=None, end_time=None,
instance_type=None, product_description=None):
"""
Retrieve the recent history of spot instances pricing.
:type start_time: str
:param start_time: An indication of how far back to provide price
changes for. An ISO8601 DateTime string.
:type end_time: str
:param end_time: An indication of how far forward to provide price
changes for. An ISO8601 DateTime string.
:type instance_type: str
:param instance_type: Filter responses to a particular instance type.
:type product_description: str
:param product_descripton: Filter responses to a particular platform.
Valid values are currently: Linux
:rtype: list
:return: A list tuples containing price and timestamp.
"""
params = {}
if start_time:
params['StartTime'] = start_time
if end_time:
params['EndTime'] = end_time
if instance_type:
params['InstanceType'] = instance_type
if product_description:
params['ProductDescription'] = product_description
return self.get_list('DescribeSpotPriceHistory', params,
[('item', SpotPriceHistory)])
def request_spot_instances(self, price, image_id, count=1, type=None,
valid_from=None, valid_until=None,
launch_group=None, availability_zone_group=None,
key_name=None, security_groups=None,
user_data=None, addressing_type=None,
instance_type='m1.small', placement=None,
kernel_id=None, ramdisk_id=None,
monitoring_enabled=False, subnet_id=None,
block_device_map=None):
"""
Request instances on the spot market at a particular price.
:type price: str
:param price: The maximum price of your bid
:type image_id: string
:param image_id: The ID of the image to run
:type count: int
:param count: The of instances to requested
:type type: str
:param type: Type of request. Can be 'one-time' or 'persistent'.
Default is one-time.
:type valid_from: str
:param valid_from: Start date of the request. An ISO8601 time string.
:type valid_until: str
:param valid_until: End date of the request. An ISO8601 time string.
:type launch_group: str
:param launch_group: If supplied, all requests will be fulfilled
as a group.
:type availability_zone_group: str
:param availability_zone_group: If supplied, all requests will be
fulfilled within a single
availability zone.
:type key_name: string
:param key_name: The name of the key pair with which to launch instances
:type security_groups: list of strings
:param security_groups: The names of the security groups with which to
associate instances
:type user_data: string
:param user_data: The user data passed to the launched instances
:type instance_type: string
:param instance_type: The type of instance to run:
* m1.small
* m1.large
* m1.xlarge
* c1.medium
* c1.xlarge
* m2.xlarge
* m2.2xlarge
* m2.4xlarge
* cc1.4xlarge
* t1.micro
:type placement: string
:param placement: The availability zone in which to launch the instances
:type kernel_id: string
:param kernel_id: The ID of the kernel with which to launch the
instances
:type ramdisk_id: string
:param ramdisk_id: The ID of the RAM disk with which to launch the
instances
:type monitoring_enabled: bool
:param monitoring_enabled: Enable CloudWatch monitoring on the instance.
:type subnet_id: string
:param subnet_id: The subnet ID within which to launch the instances
for VPC.
:type block_device_map: :class:`boto.ec2.blockdevicemapping.BlockDeviceMapping`
:param block_device_map: A BlockDeviceMapping data structure
describing the EBS volumes associated
with the Image.
:rtype: Reservation
:return: The :class:`boto.ec2.spotinstancerequest.SpotInstanceRequest`
associated with the request for machines
"""
params = {'LaunchSpecification.ImageId':image_id,
'SpotPrice' : price}
if count:
params['InstanceCount'] = count
if valid_from:
params['ValidFrom'] = valid_from
if valid_until:
params['ValidUntil'] = valid_until
if launch_group:
params['LaunchGroup'] = launch_group
if availability_zone_group:
params['AvailabilityZoneGroup'] = availability_zone_group
if key_name:
params['LaunchSpecification.KeyName'] = key_name
if security_groups:
l = []
for group in security_groups:
if isinstance(group, SecurityGroup):
l.append(group.name)
else:
l.append(group)
self.build_list_params(params, l,
'LaunchSpecification.SecurityGroup')
if user_data:
params['LaunchSpecification.UserData'] = base64.b64encode(user_data)
if addressing_type:
params['LaunchSpecification.AddressingType'] = addressing_type
if instance_type:
params['LaunchSpecification.InstanceType'] = instance_type
if placement:
params['LaunchSpecification.Placement.AvailabilityZone'] = placement
if kernel_id:
params['LaunchSpecification.KernelId'] = kernel_id
if ramdisk_id:
params['LaunchSpecification.RamdiskId'] = ramdisk_id
if monitoring_enabled:
params['LaunchSpecification.Monitoring.Enabled'] = 'true'
if subnet_id:
params['LaunchSpecification.SubnetId'] = subnet_id
if block_device_map:
block_device_map.build_list_params(params, 'LaunchSpecification.')
return self.get_list('RequestSpotInstances', params,
[('item', SpotInstanceRequest)],
verb='POST')
def cancel_spot_instance_requests(self, request_ids):
"""
Cancel the specified Spot Instance Requests.
:type request_ids: list
:param request_ids: A list of strings of the Request IDs to terminate
:rtype: list
:return: A list of the instances terminated
"""
params = {}
if request_ids:
self.build_list_params(params, request_ids, 'SpotInstanceRequestId')
return self.get_list('CancelSpotInstanceRequests', params,
[('item', Instance)])
def get_spot_datafeed_subscription(self):
"""
Return the current spot instance data feed subscription
associated with this account, if any.
:rtype: :class:`boto.ec2.spotdatafeedsubscription.SpotDatafeedSubscription`
:return: The datafeed subscription object or None
"""
return self.get_object('DescribeSpotDatafeedSubscription',
None, SpotDatafeedSubscription)
def create_spot_datafeed_subscription(self, bucket, prefix):
"""
Create a spot instance datafeed subscription for this account.
:type bucket: str or unicode
:param bucket: The name of the bucket where spot instance data
will be written. The account issuing this request
must have FULL_CONTROL access to the bucket
specified in the request.
:type prefix: str or unicode
:param prefix: An optional prefix that will be pre-pended to all
data files written to the bucket.
:rtype: :class:`boto.ec2.spotdatafeedsubscription.SpotDatafeedSubscription`
:return: The datafeed subscription object or None
"""
params = {'Bucket' : bucket}
if prefix:
params['Prefix'] = prefix
return self.get_object('CreateSpotDatafeedSubscription',
params, SpotDatafeedSubscription)
def delete_spot_datafeed_subscription(self):
"""
Delete the current spot instance data feed subscription
associated with this account
:rtype: bool
:return: True if successful
"""
return self.get_status('DeleteSpotDatafeedSubscription', None)
# Zone methods
def get_all_zones(self, zones=None, filters=None):
"""
Get all Availability Zones associated with the current region.
:type zones: list
:param zones: Optional list of zones. If this list is present,
only the Zones associated with these zone names
will be returned.
:type filters: dict
:param filters: Optional filters that can be used to limit
the results returned. Filters are provided
in the form of a dictionary consisting of
filter names as the key and filter values
as the value. The set of allowable filter
names/values is dependent on the request
being performed. Check the EC2 API guide
for details.
:rtype: list of :class:`boto.ec2.zone.Zone`
:return: The requested Zone objects
"""
params = {}
if zones:
self.build_list_params(params, zones, 'ZoneName')
if filters:
self.build_filter_params(params, filters)
return self.get_list('DescribeAvailabilityZones', params, [('item', Zone)])
# Address methods
def get_all_addresses(self, addresses=None, filters=None):
"""
Get all EIP's associated with the current credentials.
:type addresses: list
:param addresses: Optional list of addresses. If this list is present,
only the Addresses associated with these addresses
will be returned.
:type filters: dict
:param filters: Optional filters that can be used to limit
the results returned. Filters are provided
in the form of a dictionary consisting of
filter names as the key and filter values
as the value. The set of allowable filter
names/values is dependent on the request
being performed. Check the EC2 API guide
for details.
:rtype: list of :class:`boto.ec2.address.Address`
:return: The requested Address objects
"""
params = {}
if addresses:
self.build_list_params(params, addresses, 'PublicIp')
if filters:
self.build_filter_params(params, filters)
return self.get_list('DescribeAddresses', params, [('item', Address)])
def allocate_address(self):
"""
Allocate a new Elastic IP address and associate it with your account.
:rtype: :class:`boto.ec2.address.Address`
:return: The newly allocated Address
"""
return self.get_object('AllocateAddress', None, Address)
def associate_address(self, instance_id, public_ip):
"""
Associate an Elastic IP address with a currently running instance.
:type instance_id: string
:param instance_id: The ID of the instance
:type public_ip: string
:param public_ip: The public IP address
:rtype: bool
:return: True if successful
"""
params = {'InstanceId' : instance_id, 'PublicIp' : public_ip}
return self.get_status('AssociateAddress', params)
def disassociate_address(self, public_ip):
"""
Disassociate an Elastic IP address from a currently running instance.
:type public_ip: string
:param public_ip: The public IP address
:rtype: bool
:return: True if successful
"""
params = {'PublicIp' : public_ip}
return self.get_status('DisassociateAddress', params)
def release_address(self, public_ip):
"""
Free up an Elastic IP address
:type public_ip: string
:param public_ip: The public IP address
:rtype: bool
:return: True if successful
"""
params = {'PublicIp' : public_ip}
return self.get_status('ReleaseAddress', params)
# Volume methods
def get_all_volumes(self, volume_ids=None, filters=None):
"""
Get all Volumes associated with the current credentials.
:type volume_ids: list
:param volume_ids: Optional list of volume ids. If this list is present,
only the volumes associated with these volume ids
will be returned.
:type filters: dict
:param filters: Optional filters that can be used to limit
the results returned. Filters are provided
in the form of a dictionary consisting of
filter names as the key and filter values
as the value. The set of allowable filter
names/values is dependent on the request
being performed. Check the EC2 API guide
for details.
:rtype: list of :class:`boto.ec2.volume.Volume`
:return: The requested Volume objects
"""
params = {}
if volume_ids:
self.build_list_params(params, volume_ids, 'VolumeId')
if filters:
self.build_filter_params(params, filters)
return self.get_list('DescribeVolumes', params, [('item', Volume)])
def create_volume(self, size, zone, snapshot=None):
"""
Create a new EBS Volume.
:type size: int
:param size: The size of the new volume, in GiB
:type zone: string or :class:`boto.ec2.zone.Zone`
:param zone: The availability zone in which the Volume will be created.
:type snapshot: string or :class:`boto.ec2.snapshot.Snapshot`
:param snapshot: The snapshot from which the new Volume will be created.
"""
if isinstance(zone, Zone):
zone = zone.name
params = {'AvailabilityZone' : zone}
if size:
params['Size'] = size
if snapshot:
if isinstance(snapshot, Snapshot):
snapshot = snapshot.id
params['SnapshotId'] = snapshot
return self.get_object('CreateVolume', params, Volume)
def delete_volume(self, volume_id):
"""
Delete an EBS volume.
:type volume_id: str
:param volume_id: The ID of the volume to be delete.
:rtype: bool
:return: True if successful
"""
params = {'VolumeId': volume_id}
return self.get_status('DeleteVolume', params)
def attach_volume(self, volume_id, instance_id, device):
"""
Attach an EBS volume to an EC2 instance.
:type volume_id: str
:param volume_id: The ID of the EBS volume to be attached.
:type instance_id: str
:param instance_id: The ID of the EC2 instance to which it will
be attached.
:type device: str
:param device: The device on the instance through which the
volume will be exposted (e.g. /dev/sdh)
:rtype: bool
:return: True if successful
"""
params = {'InstanceId' : instance_id,
'VolumeId' : volume_id,
'Device' : device}
return self.get_status('AttachVolume', params)
def detach_volume(self, volume_id, instance_id=None,
device=None, force=False):
"""
Detach an EBS volume from an EC2 instance.
:type volume_id: str
:param volume_id: The ID of the EBS volume to be attached.
:type instance_id: str
:param instance_id: The ID of the EC2 instance from which it will
be detached.
:type device: str
:param device: The device on the instance through which the
volume is exposted (e.g. /dev/sdh)
:type force: bool
:param force: Forces detachment if the previous detachment attempt did
not occur cleanly. This option can lead to data loss or
a corrupted file system. Use this option only as a last
resort to detach a volume from a failed instance. The
instance will not have an opportunity to flush file system
caches nor file system meta data. If you use this option,
you must perform file system check and repair procedures.
:rtype: bool
:return: True if successful
"""
params = {'VolumeId' : volume_id}
if instance_id:
params['InstanceId'] = instance_id
if device:
params['Device'] = device
if force:
params['Force'] = 'true'
return self.get_status('DetachVolume', params)
# Snapshot methods
def get_all_snapshots(self, snapshot_ids=None,
owner=None, restorable_by=None,
filters=None):
"""
Get all EBS Snapshots associated with the current credentials.
:type snapshot_ids: list
:param snapshot_ids: Optional list of snapshot ids. If this list is
present, only the Snapshots associated with
these snapshot ids will be returned.
:type owner: str
:param owner: If present, only the snapshots owned by the specified user
will be returned. Valid values are:
* self
* amazon
* AWS Account ID
:type restorable_by: str
:param restorable_by: If present, only the snapshots that are restorable
by the specified account id will be returned.
:type filters: dict
:param filters: Optional filters that can be used to limit
the results returned. Filters are provided
in the form of a dictionary consisting of
filter names as the key and filter values
as the value. The set of allowable filter
names/values is dependent on the request
being performed. Check the EC2 API guide
for details.
:rtype: list of :class:`boto.ec2.snapshot.Snapshot`
:return: The requested Snapshot objects
"""
params = {}
if snapshot_ids:
self.build_list_params(params, snapshot_ids, 'SnapshotId')
if owner:
params['Owner'] = owner
if restorable_by:
params['RestorableBy'] = restorable_by
if filters:
self.build_filter_params(params, filters)
return self.get_list('DescribeSnapshots', params, [('item', Snapshot)])
def create_snapshot(self, volume_id, description=None):
"""
Create a snapshot of an existing EBS Volume.
:type volume_id: str
:param volume_id: The ID of the volume to be snapshot'ed
:type description: str
:param description: A description of the snapshot.
Limited to 255 characters.
:rtype: bool
:return: True if successful
"""
params = {'VolumeId' : volume_id}
if description:
params['Description'] = description[0:255]
return self.get_object('CreateSnapshot', params, Snapshot)
def delete_snapshot(self, snapshot_id):
params = {'SnapshotId': snapshot_id}
return self.get_status('DeleteSnapshot', params)
def get_snapshot_attribute(self, snapshot_id,
attribute='createVolumePermission'):
"""
Get information about an attribute of a snapshot. Only one attribute
can be specified per call.
:type snapshot_id: str
:param snapshot_id: The ID of the snapshot.
:type attribute: str
:param attribute: The requested attribute. Valid values are:
* createVolumePermission
:rtype: list of :class:`boto.ec2.snapshotattribute.SnapshotAttribute`
:return: The requested Snapshot attribute
"""
params = {'Attribute' : attribute}
if snapshot_id:
params['SnapshotId'] = snapshot_id
return self.get_object('DescribeSnapshotAttribute', params,
SnapshotAttribute)
def modify_snapshot_attribute(self, snapshot_id,
attribute='createVolumePermission',
operation='add', user_ids=None, groups=None):
"""
Changes an attribute of an image.
:type snapshot_id: string
:param snapshot_id: The snapshot id you wish to change
:type attribute: string
:param attribute: The attribute you wish to change. Valid values are:
createVolumePermission
:type operation: string
:param operation: Either add or remove (this is required for changing
snapshot ermissions)
:type user_ids: list
:param user_ids: The Amazon IDs of users to add/remove attributes
:type groups: list
:param groups: The groups to add/remove attributes. The only valid
value at this time is 'all'.
"""
params = {'SnapshotId' : snapshot_id,
'Attribute' : attribute,
'OperationType' : operation}
if user_ids:
self.build_list_params(params, user_ids, 'UserId')
if groups:
self.build_list_params(params, groups, 'UserGroup')
return self.get_status('ModifySnapshotAttribute', params)
def reset_snapshot_attribute(self, snapshot_id,
attribute='createVolumePermission'):
"""
Resets an attribute of a snapshot to its default value.
:type snapshot_id: string
:param snapshot_id: ID of the snapshot
:type attribute: string
:param attribute: The attribute to reset
:rtype: bool
:return: Whether the operation succeeded or not
"""
params = {'SnapshotId' : snapshot_id,
'Attribute' : attribute}
return self.get_status('ResetSnapshotAttribute', params)
# Keypair methods
def get_all_key_pairs(self, keynames=None, filters=None):
"""
Get all key pairs associated with your account.
:type keynames: list
:param keynames: A list of the names of keypairs to retrieve.
If not provided, all key pairs will be returned.
:type filters: dict
:param filters: Optional filters that can be used to limit
the results returned. Filters are provided
in the form of a dictionary consisting of
filter names as the key and filter values
as the value. The set of allowable filter
names/values is dependent on the request
being performed. Check the EC2 API guide
for details.
:rtype: list
:return: A list of :class:`boto.ec2.keypair.KeyPair`
"""
params = {}
if keynames:
self.build_list_params(params, keynames, 'KeyName')
if filters:
self.build_filter_params(params, filters)
return self.get_list('DescribeKeyPairs', params, [('item', KeyPair)])
def get_key_pair(self, keyname):
"""
Convenience method to retrieve a specific keypair (KeyPair).
:type image_id: string
:param image_id: the ID of the Image to retrieve
:rtype: :class:`boto.ec2.keypair.KeyPair`
:return: The KeyPair specified or None if it is not found
"""
try:
return self.get_all_key_pairs(keynames=[keyname])[0]
except IndexError: # None of those key pairs available
return None
def create_key_pair(self, key_name):
"""
Create a new key pair for your account.
This will create the key pair within the region you
are currently connected to.
:type key_name: string
:param key_name: The name of the new keypair
:rtype: :class:`boto.ec2.keypair.KeyPair`
:return: The newly created :class:`boto.ec2.keypair.KeyPair`.
The material attribute of the new KeyPair object
will contain the the unencrypted PEM encoded RSA private key.
"""
params = {'KeyName':key_name}
return self.get_object('CreateKeyPair', params, KeyPair)
def delete_key_pair(self, key_name):
"""
Delete a key pair from your account.
:type key_name: string
:param key_name: The name of the keypair to delete
"""
params = {'KeyName':key_name}
return self.get_status('DeleteKeyPair', params)
def import_key_pair(self, key_name, public_key_material):
"""
mports the public key from an RSA key pair that you created
with a third-party tool.
Supported formats:
* OpenSSH public key format (e.g., the format
in ~/.ssh/authorized_keys)
* Base64 encoded DER format
* SSH public key file format as specified in RFC4716
DSA keys are not supported. Make sure your key generator is
set up to create RSA keys.
Supported lengths: 1024, 2048, and 4096.
:type key_name: string
:param key_name: The name of the new keypair
:type public_key_material: string
:param public_key_material: The public key. You must base64 encode
the public key material before sending
it to AWS.
:rtype: :class:`boto.ec2.keypair.KeyPair`
:return: The newly created :class:`boto.ec2.keypair.KeyPair`.
The material attribute of the new KeyPair object
will contain the the unencrypted PEM encoded RSA private key.
"""
params = {'KeyName' : key_name,
'PublicKeyMaterial' : public_key_material}
return self.get_object('ImportKeyPair', params, KeyPair, verb='POST')
# SecurityGroup methods
def get_all_security_groups(self, groupnames=None, filters=None):
"""
Get all security groups associated with your account in a region.
:type groupnames: list
:param groupnames: A list of the names of security groups to retrieve.
If not provided, all security groups will be
returned.
:type filters: dict
:param filters: Optional filters that can be used to limit
the results returned. Filters are provided
in the form of a dictionary consisting of
filter names as the key and filter values
as the value. The set of allowable filter
names/values is dependent on the request
being performed. Check the EC2 API guide
for details.
:rtype: list
:return: A list of :class:`boto.ec2.securitygroup.SecurityGroup`
"""
params = {}
if groupnames:
self.build_list_params(params, groupnames, 'GroupName')
if filters:
self.build_filter_params(params, filters)
return self.get_list('DescribeSecurityGroups', params,
[('item', SecurityGroup)])
def create_security_group(self, name, description):
"""
Create a new security group for your account.
This will create the security group within the region you
are currently connected to.
:type name: string
:param name: The name of the new security group
:type description: string
:param description: The description of the new security group
:rtype: :class:`boto.ec2.securitygroup.SecurityGroup`
:return: The newly created :class:`boto.ec2.keypair.KeyPair`.
"""
params = {'GroupName':name, 'GroupDescription':description}
group = self.get_object('CreateSecurityGroup', params, SecurityGroup)
group.name = name
group.description = description
return group
def delete_security_group(self, name):
"""
Delete a security group from your account.
:type key_name: string
:param key_name: The name of the keypair to delete
"""
params = {'GroupName':name}
return self.get_status('DeleteSecurityGroup', params)
def authorize_security_group(self, group_name, src_security_group_name=None,
src_security_group_owner_id=None,
ip_protocol=None, from_port=None, to_port=None,
cidr_ip=None):
"""
Add a new rule to an existing security group.
You need to pass in either src_security_group_name and
src_security_group_owner_id OR ip_protocol, from_port, to_port,
and cidr_ip. In other words, either you are authorizing another
group or you are authorizing some ip-based rule.
:type group_name: string
:param group_name: The name of the security group you are adding
the rule to.
:type src_security_group_name: string
:param src_security_group_name: The name of the security group you are
granting access to.
:type src_security_group_owner_id: string
:param src_security_group_owner_id: The ID of the owner of the security
group you are granting access to.
:type ip_protocol: string
:param ip_protocol: Either tcp | udp | icmp
:type from_port: int
:param from_port: The beginning port number you are enabling
:type to_port: int
:param to_port: The ending port number you are enabling
:type to_port: string
:param to_port: The CIDR block you are providing access to.
See http://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing
:rtype: bool
:return: True if successful.
"""
params = {'GroupName':group_name}
if src_security_group_name:
params['SourceSecurityGroupName'] = src_security_group_name
if src_security_group_owner_id:
params['SourceSecurityGroupOwnerId'] = src_security_group_owner_id
if ip_protocol:
params['IpProtocol'] = ip_protocol
if from_port:
params['FromPort'] = from_port
if to_port:
params['ToPort'] = to_port
if cidr_ip:
params['CidrIp'] = urllib.quote(cidr_ip)
return self.get_status('AuthorizeSecurityGroupIngress', params)
def revoke_security_group(self, group_name, src_security_group_name=None,
src_security_group_owner_id=None,
ip_protocol=None, from_port=None, to_port=None,
cidr_ip=None):
"""
Remove an existing rule from an existing security group.
You need to pass in either src_security_group_name and
src_security_group_owner_id OR ip_protocol, from_port, to_port,
and cidr_ip. In other words, either you are revoking another
group or you are revoking some ip-based rule.
:type group_name: string
:param group_name: The name of the security group you are removing
the rule from.
:type src_security_group_name: string
:param src_security_group_name: The name of the security group you are
revoking access to.
:type src_security_group_owner_id: string
:param src_security_group_owner_id: The ID of the owner of the security
group you are revoking access to.
:type ip_protocol: string
:param ip_protocol: Either tcp | udp | icmp
:type from_port: int
:param from_port: The beginning port number you are disabling
:type to_port: int
:param to_port: The ending port number you are disabling
:type to_port: string
:param to_port: The CIDR block you are revoking access to.
See http://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing
:rtype: bool
:return: True if successful.
"""
params = {'GroupName':group_name}
if src_security_group_name:
params['SourceSecurityGroupName'] = src_security_group_name
if src_security_group_owner_id:
params['SourceSecurityGroupOwnerId'] = src_security_group_owner_id
if ip_protocol:
params['IpProtocol'] = ip_protocol
if from_port:
params['FromPort'] = from_port
if to_port:
params['ToPort'] = to_port
if cidr_ip:
params['CidrIp'] = cidr_ip
return self.get_status('RevokeSecurityGroupIngress', params)
#
# Regions
#
def get_all_regions(self, filters=None):
"""
Get all available regions for the EC2 service.
:type filters: dict
:param filters: Optional filters that can be used to limit
the results returned. Filters are provided
in the form of a dictionary consisting of
filter names as the key and filter values
as the value. The set of allowable filter
names/values is dependent on the request
being performed. Check the EC2 API guide
for details.
:rtype: list
:return: A list of :class:`boto.ec2.regioninfo.RegionInfo`
"""
params = {}
if filters:
self.build_filter_params(params, filters)
regions = self.get_list('DescribeRegions', params, [('item', RegionInfo)])
for region in regions:
region.connection_cls = EC2Connection
return regions
#
# Reservation methods
#
def get_all_reserved_instances_offerings(self, reserved_instances_id=None,
instance_type=None,
availability_zone=None,
product_description=None,
filters=None):
"""
Describes Reserved Instance offerings that are available for purchase.
:type reserved_instances_id: str
:param reserved_instances_id: Displays Reserved Instances with the
specified offering IDs.
:type instance_type: str
:param instance_type: Displays Reserved Instances of the specified
instance type.
:type availability_zone: str
:param availability_zone: Displays Reserved Instances within the
specified Availability Zone.
:type product_description: str
:param product_description: Displays Reserved Instances with the
specified product description.
:type filters: dict
:param filters: Optional filters that can be used to limit
the results returned. Filters are provided
in the form of a dictionary consisting of
filter names as the key and filter values
as the value. The set of allowable filter
names/values is dependent on the request
being performed. Check the EC2 API guide
for details.
:rtype: list
:return: A list of :class:`boto.ec2.reservedinstance.ReservedInstancesOffering`
"""
params = {}
if reserved_instances_id:
params['ReservedInstancesId'] = reserved_instances_id
if instance_type:
params['InstanceType'] = instance_type
if availability_zone:
params['AvailabilityZone'] = availability_zone
if product_description:
params['ProductDescription'] = product_description
if filters:
self.build_filter_params(params, filters)
return self.get_list('DescribeReservedInstancesOfferings',
params, [('item', ReservedInstancesOffering)])
def get_all_reserved_instances(self, reserved_instances_id=None,
filters=None):
"""
Describes Reserved Instance offerings that are available for purchase.
:type reserved_instance_ids: list
:param reserved_instance_ids: A list of the reserved instance ids that
will be returned. If not provided, all
reserved instances will be returned.
:type filters: dict
:param filters: Optional filters that can be used to limit
the results returned. Filters are provided
in the form of a dictionary consisting of
filter names as the key and filter values
as the value. The set of allowable filter
names/values is dependent on the request
being performed. Check the EC2 API guide
for details.
:rtype: list
:return: A list of :class:`boto.ec2.reservedinstance.ReservedInstance`
"""
params = {}
if reserved_instances_id:
self.build_list_params(params, reserved_instances_id,
'ReservedInstancesId')
if filters:
self.build_filter_params(params, filters)
return self.get_list('DescribeReservedInstances',
params, [('item', ReservedInstance)])
def purchase_reserved_instance_offering(self, reserved_instances_offering_id,
instance_count=1):
"""
Purchase a Reserved Instance for use with your account.
** CAUTION **
This request can result in large amounts of money being charged to your
AWS account. Use with caution!
:type reserved_instances_offering_id: string
:param reserved_instances_offering_id: The offering ID of the Reserved
Instance to purchase
:type instance_count: int
:param instance_count: The number of Reserved Instances to purchase.
Default value is 1.
:rtype: :class:`boto.ec2.reservedinstance.ReservedInstance`
:return: The newly created Reserved Instance
"""
params = {'ReservedInstancesOfferingId' : reserved_instances_offering_id,
'InstanceCount' : instance_count}
return self.get_object('PurchaseReservedInstancesOffering', params,
ReservedInstance)
#
# Monitoring
#
def monitor_instance(self, instance_id):
"""
Enable CloudWatch monitoring for the supplied instance.
:type instance_id: string
:param instance_id: The instance id
:rtype: list
:return: A list of :class:`boto.ec2.instanceinfo.InstanceInfo`
"""
params = {'InstanceId' : instance_id}
return self.get_list('MonitorInstances', params,
[('item', InstanceInfo)])
def unmonitor_instance(self, instance_id):
"""
Disable CloudWatch monitoring for the supplied instance.
:type instance_id: string
:param instance_id: The instance id
:rtype: list
:return: A list of :class:`boto.ec2.instanceinfo.InstanceInfo`
"""
params = {'InstanceId' : instance_id}
return self.get_list('UnmonitorInstances', params,
[('item', InstanceInfo)])
#
# Bundle Windows Instances
#
def bundle_instance(self, instance_id,
s3_bucket,
s3_prefix,
s3_upload_policy):
"""
Bundle Windows instance.
:type instance_id: string
:param instance_id: The instance id
:type s3_bucket: string
:param s3_bucket: The bucket in which the AMI should be stored.
:type s3_prefix: string
:param s3_prefix: The beginning of the file name for the AMI.
:type s3_upload_policy: string
:param s3_upload_policy: Base64 encoded policy that specifies condition
and permissions for Amazon EC2 to upload the
user's image into Amazon S3.
"""
params = {'InstanceId' : instance_id,
'Storage.S3.Bucket' : s3_bucket,
'Storage.S3.Prefix' : s3_prefix,
'Storage.S3.UploadPolicy' : s3_upload_policy}
params['Storage.S3.AWSAccessKeyId'] = self.aws_access_key_id
local_hmac = self.hmac.copy()
local_hmac.update(s3_upload_policy)
s3_upload_policy_signature = base64.b64encode(local_hmac.digest())
params['Storage.S3.UploadPolicySignature'] = s3_upload_policy_signature
return self.get_object('BundleInstance', params, BundleInstanceTask)
def get_all_bundle_tasks(self, bundle_ids=None, filters=None):
"""
Retrieve current bundling tasks. If no bundle id is specified, all
tasks are retrieved.
:type bundle_ids: list
:param bundle_ids: A list of strings containing identifiers for
previously created bundling tasks.
:type filters: dict
:param filters: Optional filters that can be used to limit
the results returned. Filters are provided
in the form of a dictionary consisting of
filter names as the key and filter values
as the value. The set of allowable filter
names/values is dependent on the request
being performed. Check the EC2 API guide
for details.
"""
params = {}
if bundle_ids:
self.build_list_params(params, bundle_ids, 'BundleId')
if filters:
self.build_filter_params(params, filters)
return self.get_list('DescribeBundleTasks', params,
[('item', BundleInstanceTask)])
def cancel_bundle_task(self, bundle_id):
"""
Cancel a previously submitted bundle task
:type bundle_id: string
:param bundle_id: The identifier of the bundle task to cancel.
"""
params = {'BundleId' : bundle_id}
return self.get_object('CancelBundleTask', params, BundleInstanceTask)
def get_password_data(self, instance_id):
"""
Get encrypted administrator password for a Windows instance.
:type instance_id: string
:param instance_id: The identifier of the instance to retrieve the
password for.
"""
params = {'InstanceId' : instance_id}
rs = self.get_object('GetPasswordData', params, ResultSet)
return rs.passwordData
#
# Cluster Placement Groups
#
def get_all_placement_groups(self, groupnames=None, filters=None):
"""
Get all placement groups associated with your account in a region.
:type groupnames: list
:param groupnames: A list of the names of placement groups to retrieve.
If not provided, all placement groups will be
returned.
:type filters: dict
:param filters: Optional filters that can be used to limit
the results returned. Filters are provided
in the form of a dictionary consisting of
filter names as the key and filter values
as the value. The set of allowable filter
names/values is dependent on the request
being performed. Check the EC2 API guide
for details.
:rtype: list
:return: A list of :class:`boto.ec2.placementgroup.PlacementGroup`
"""
params = {}
if groupnames:
self.build_list_params(params, groupnames, 'GroupName')
if filters:
self.build_filter_params(params, filters)
return self.get_list('DescribePlacementGroups', params,
[('item', PlacementGroup)])
def create_placement_group(self, name, strategy='cluster'):
"""
Create a new placement group for your account.
This will create the placement group within the region you
are currently connected to.
:type name: string
:param name: The name of the new placement group
:type strategy: string
:param strategy: The placement strategy of the new placement group.
Currently, the only acceptable value is "cluster".
:rtype: :class:`boto.ec2.placementgroup.PlacementGroup`
:return: The newly created :class:`boto.ec2.keypair.KeyPair`.
"""
params = {'GroupName':name, 'Strategy':strategy}
group = self.get_status('CreatePlacementGroup', params)
return group
def delete_placement_group(self, name):
"""
Delete a placement group from your account.
:type key_name: string
:param key_name: The name of the keypair to delete
"""
params = {'GroupName':name}
return self.get_status('DeletePlacementGroup', params)
# Tag methods
def build_tag_param_list(self, params, tags):
keys = tags.keys()
keys.sort()
i = 1
for key in keys:
value = tags[key]
params['Tag.%d.Key'%i] = key
if value is not None:
params['Tag.%d.Value'%i] = value
i += 1
def get_all_tags(self, tags=None, filters=None):
"""
Retrieve all the metadata tags associated with your account.
:type tags: list
:param tags: A list of mumble
:type filters: dict
:param filters: Optional filters that can be used to limit
the results returned. Filters are provided
in the form of a dictionary consisting of
filter names as the key and filter values
as the value. The set of allowable filter
names/values is dependent on the request
being performed. Check the EC2 API guide
for details.
:rtype: dict
:return: A dictionary containing metadata tags
"""
params = {}
if tags:
self.build_list_params(params, instance_ids, 'InstanceId')
if filters:
self.build_filter_params(params, filters)
return self.get_list('DescribeTags', params, [('item', Tag)])
def create_tags(self, resource_ids, tags):
"""
Create new metadata tags for the specified resource ids.
:type resource_ids: list
:param resource_ids: List of strings
:type tags: dict
:param tags: A dictionary containing the name/value pairs
"""
params = {}
self.build_list_params(params, resource_ids, 'ResourceId')
self.build_tag_param_list(params, tags)
return self.get_status('CreateTags', params)
def delete_tags(self, resource_ids, tags):
"""
Delete metadata tags for the specified resource ids.
:type resource_ids: list
:param resource_ids: List of strings
:type tags: dict or list
:param tags: Either a dictionary containing name/value pairs
or a list containing just tag names.
If you pass in a dictionary, the values must
match the actual tag values or the tag will
not be deleted.
"""
if isinstance(tags, list):
tags = {}.fromkeys(tags, None)
params = {}
self.build_list_params(params, resource_ids, 'ResourceId')
self.build_tag_param_list(params, tags)
return self.get_status('DeleteTags', params)
| Python |
# Copyright (c) 2006-2010 Mitch Garnaat http://garnaat.org/
# Copyright (c) 2010, Eucalyptus Systems, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
"""
Represents an EC2 Spot Instance Request
"""
from boto.ec2.ec2object import TaggedEC2Object
from boto.ec2.launchspecification import LaunchSpecification
class SpotInstanceStateFault(object):
def __init__(self, code=None, message=None):
self.code = code
self.message = message
def __repr__(self):
return '(%s, %s)' % (self.code, self.message)
def startElement(self, name, attrs, connection):
return None
def endElement(self, name, value, connection):
if name == 'code':
self.code = value
elif name == 'message':
self.message = value
setattr(self, name, value)
class SpotInstanceRequest(TaggedEC2Object):
def __init__(self, connection=None):
TaggedEC2Object.__init__(self, connection)
self.id = None
self.price = None
self.type = None
self.state = None
self.fault = None
self.valid_from = None
self.valid_until = None
self.launch_group = None
self.product_description = None
self.availability_zone_group = None
self.create_time = None
self.launch_specification = None
self.instance_id = None
def __repr__(self):
return 'SpotInstanceRequest:%s' % self.id
def startElement(self, name, attrs, connection):
retval = TaggedEC2Object.startElement(self, name, attrs, connection)
if retval is not None:
return retval
if name == 'launchSpecification':
self.launch_specification = LaunchSpecification(connection)
return self.launch_specification
elif name == 'fault':
self.fault = SpotInstanceStateFault()
return self.fault
else:
return None
def endElement(self, name, value, connection):
if name == 'spotInstanceRequestId':
self.id = value
elif name == 'spotPrice':
self.price = float(value)
elif name == 'type':
self.type = value
elif name == 'state':
self.state = value
elif name == 'productDescription':
self.product_description = value
elif name == 'validFrom':
self.valid_from = value
elif name == 'validUntil':
self.valid_until = value
elif name == 'launchGroup':
self.launch_group = value
elif name == 'availabilityZoneGroup':
self.availability_zone_group = value
elif name == 'createTime':
self.create_time = value
elif name == 'instanceId':
self.instance_id = value
else:
setattr(self, name, value)
def cancel(self):
self.connection.cancel_spot_instance_requests([self.id])
| Python |
# Copyright (c) 2006-2009 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
"""
Represents a launch specification for Spot instances.
"""
from boto.ec2.ec2object import EC2Object
from boto.resultset import ResultSet
from boto.ec2.blockdevicemapping import BlockDeviceMapping
from boto.ec2.instance import Group
class GroupList(list):
def startElement(self, name, attrs, connection):
pass
def endElement(self, name, value, connection):
if name == 'groupId':
self.append(value)
class LaunchSpecification(EC2Object):
def __init__(self, connection=None):
EC2Object.__init__(self, connection)
self.key_name = None
self.instance_type = None
self.image_id = None
self.groups = []
self.placement = None
self.kernel = None
self.ramdisk = None
self.monitored = False
self.subnet_id = None
self._in_monitoring_element = False
self.block_device_mapping = None
def __repr__(self):
return 'LaunchSpecification(%s)' % self.image_id
def startElement(self, name, attrs, connection):
if name == 'groupSet':
self.groups = ResultSet([('item', Group)])
return self.groups
elif name == 'monitoring':
self._in_monitoring_element = True
elif name == 'blockDeviceMapping':
self.block_device_mapping = BlockDeviceMapping()
return self.block_device_mapping
else:
return None
def endElement(self, name, value, connection):
if name == 'imageId':
self.image_id = value
elif name == 'keyName':
self.key_name = value
elif name == 'instanceType':
self.instance_type = value
elif name == 'availabilityZone':
self.placement = value
elif name == 'placement':
pass
elif name == 'kernelId':
self.kernel = value
elif name == 'ramdiskId':
self.ramdisk = value
elif name == 'subnetId':
self.subnet_id = value
elif name == 'state':
if self._in_monitoring_element:
if value == 'enabled':
self.monitored = True
self._in_monitoring_element = False
else:
setattr(self, name, value)
| Python |
# Copyright (c) 2006-2009 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
"""
Represents an EC2 Spot Instance Request
"""
from boto.ec2.ec2object import EC2Object
class SpotPriceHistory(EC2Object):
def __init__(self, connection=None):
EC2Object.__init__(self, connection)
self.price = 0.0
self.instance_type = None
self.product_description = None
self.timestamp = None
def __repr__(self):
return 'SpotPriceHistory(%s):%2f' % (self.instance_type, self.price)
def endElement(self, name, value, connection):
if name == 'instanceType':
self.instance_type = value
elif name == 'spotPrice':
self.price = float(value)
elif name == 'productDescription':
self.product_description = value
elif name == 'timestamp':
self.timestamp = value
else:
setattr(self, name, value)
| Python |
# Copyright (c) 2010 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
"""
Represents an EC2 Bundle Task
"""
from boto.ec2.ec2object import EC2Object
class BundleInstanceTask(EC2Object):
def __init__(self, connection=None):
EC2Object.__init__(self, connection)
self.id = None
self.instance_id = None
self.progress = None
self.start_time = None
self.state = None
self.bucket = None
self.prefix = None
self.upload_policy = None
self.upload_policy_signature = None
self.update_time = None
self.code = None
self.message = None
def __repr__(self):
return 'BundleInstanceTask:%s' % self.id
def startElement(self, name, attrs, connection):
return None
def endElement(self, name, value, connection):
if name == 'bundleId':
self.id = value
elif name == 'instanceId':
self.instance_id = value
elif name == 'progress':
self.progress = value
elif name == 'startTime':
self.start_time = value
elif name == 'state':
self.state = value
elif name == 'bucket':
self.bucket = value
elif name == 'prefix':
self.prefix = value
elif name == 'uploadPolicy':
self.upload_policy = value
elif name == 'uploadPolicySignature':
self.upload_policy_signature = value
elif name == 'updateTime':
self.update_time = value
elif name == 'code':
self.code = value
elif name == 'message':
self.message = value
else:
setattr(self, name, value)
| Python |
# Copyright (c) 2006-2010 Mitch Garnaat http://garnaat.org/
# Copyright (c) 2010, Eucalyptus Systems, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
"""
Represents an EC2 Elastic Block Storage Volume
"""
from boto.ec2.ec2object import TaggedEC2Object
class Volume(TaggedEC2Object):
def __init__(self, connection=None):
TaggedEC2Object.__init__(self, connection)
self.id = None
self.create_time = None
self.status = None
self.size = None
self.snapshot_id = None
self.attach_data = None
self.zone = None
def __repr__(self):
return 'Volume:%s' % self.id
def startElement(self, name, attrs, connection):
retval = TaggedEC2Object.startElement(self, name, attrs, connection)
if retval is not None:
return retval
if name == 'attachmentSet':
self.attach_data = AttachmentSet()
return self.attach_data
elif name == 'tagSet':
self.tags = boto.resultset.ResultSet([('item', Tag)])
return self.tags
else:
return None
def endElement(self, name, value, connection):
if name == 'volumeId':
self.id = value
elif name == 'createTime':
self.create_time = value
elif name == 'status':
if value != '':
self.status = value
elif name == 'size':
self.size = int(value)
elif name == 'snapshotId':
self.snapshot_id = value
elif name == 'availabilityZone':
self.zone = value
else:
setattr(self, name, value)
def _update(self, updated):
self.__dict__.update(updated.__dict__)
def update(self, validate=False):
"""
Update the data associated with this volume by querying EC2.
:type validate: bool
:param validate: By default, if EC2 returns no data about the
volume the update method returns quietly. If
the validate param is True, however, it will
raise a ValueError exception if no data is
returned from EC2.
"""
rs = self.connection.get_all_volumes([self.id])
if len(rs) > 0:
self._update(rs[0])
elif validate:
raise ValueError('%s is not a valid Volume ID' % self.id)
return self.status
def delete(self):
"""
Delete this EBS volume.
:rtype: bool
:return: True if successful
"""
return self.connection.delete_volume(self.id)
def attach(self, instance_id, device):
"""
Attach this EBS volume to an EC2 instance.
:type instance_id: str
:param instance_id: The ID of the EC2 instance to which it will
be attached.
:type device: str
:param device: The device on the instance through which the
volume will be exposted (e.g. /dev/sdh)
:rtype: bool
:return: True if successful
"""
return self.connection.attach_volume(self.id, instance_id, device)
def detach(self, force=False):
"""
Detach this EBS volume from an EC2 instance.
:type force: bool
:param force: Forces detachment if the previous detachment attempt did
not occur cleanly. This option can lead to data loss or
a corrupted file system. Use this option only as a last
resort to detach a volume from a failed instance. The
instance will not have an opportunity to flush file system
caches nor file system meta data. If you use this option,
you must perform file system check and repair procedures.
:rtype: bool
:return: True if successful
"""
instance_id = None
if self.attach_data:
instance_id = self.attach_data.instance_id
device = None
if self.attach_data:
device = self.attach_data.device
return self.connection.detach_volume(self.id, instance_id, device, force)
def create_snapshot(self, description=None):
"""
Create a snapshot of this EBS Volume.
:type description: str
:param description: A description of the snapshot. Limited to 256 characters.
:rtype: bool
:return: True if successful
"""
return self.connection.create_snapshot(self.id, description)
def volume_state(self):
"""
Returns the state of the volume. Same value as the status attribute.
"""
return self.status
def attachment_state(self):
"""
Get the attachment state.
"""
state = None
if self.attach_data:
state = self.attach_data.status
return state
def snapshots(self, owner=None, restorable_by=None):
"""
Get all snapshots related to this volume. Note that this requires
that all available snapshots for the account be retrieved from EC2
first and then the list is filtered client-side to contain only
those for this volume.
:type owner: str
:param owner: If present, only the snapshots owned by the specified user
will be returned. Valid values are:
self | amazon | AWS Account ID
:type restorable_by: str
:param restorable_by: If present, only the snapshots that are restorable
by the specified account id will be returned.
:rtype: list of L{boto.ec2.snapshot.Snapshot}
:return: The requested Snapshot objects
"""
rs = self.connection.get_all_snapshots(owner=owner,
restorable_by=restorable_by)
mine = []
for snap in rs:
if snap.volume_id == self.id:
mine.append(snap)
return mine
class AttachmentSet(object):
def __init__(self):
self.id = None
self.instance_id = None
self.status = None
self.attach_time = None
self.device = None
def __repr__(self):
return 'AttachmentSet:%s' % self.id
def startElement(self, name, attrs, connection):
pass
def endElement(self, name, value, connection):
if name == 'volumeId':
self.id = value
elif name == 'instanceId':
self.instance_id = value
elif name == 'status':
self.status = value
elif name == 'attachTime':
self.attach_time = value
elif name == 'device':
self.device = value
else:
setattr(self, name, value)
| Python |
# Copyright (c) 2006-2009 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
class Dimensions(dict):
def startElement(self, name, attrs, connection):
pass
def endElement(self, name, value, connection):
if name == 'Name':
self._name = value
elif name == 'Value':
self[self._name] = value
elif name != 'Dimensions' and name != 'member':
self[name] = value
class Metric(object):
Statistics = ['Minimum', 'Maximum', 'Sum', 'Average', 'Samples']
Units = ['Seconds', 'Percent', 'Bytes', 'Bits', 'Count',
'Bytes/Second', 'Bits/Second', 'Count/Second']
def __init__(self, connection=None):
self.connection = connection
self.name = None
self.namespace = None
self.dimensions = None
def __repr__(self):
s = 'Metric:%s' % self.name
if self.dimensions:
for name,value in self.dimensions.items():
s += '(%s,%s)' % (name, value)
return s
def startElement(self, name, attrs, connection):
if name == 'Dimensions':
self.dimensions = Dimensions()
return self.dimensions
def endElement(self, name, value, connection):
if name == 'MeasureName':
self.name = value
elif name == 'Namespace':
self.namespace = value
else:
setattr(self, name, value)
def query(self, start_time, end_time, statistic, unit, period=60):
return self.connection.get_metric_statistics(period, start_time, end_time,
self.name, self.namespace, [statistic],
self.dimensions, unit)
| Python |
# Copyright (c) 2006-2009 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
class Datapoint(dict):
def __init__(self, connection=None):
dict.__init__(self)
self.connection = connection
def startElement(self, name, attrs, connection):
pass
def endElement(self, name, value, connection):
if name in ['Average', 'Maximum', 'Minimum', 'Samples', 'Sum']:
self[name] = float(value)
elif name != 'member':
self[name] = value
| Python |
# Copyright (c) 2006-2009 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
"""
This module provides an interface to the Elastic Compute Cloud (EC2)
CloudWatch service from AWS.
The 5 Minute How-To Guide
-------------------------
First, make sure you have something to monitor. You can either create a
LoadBalancer or enable monitoring on an existing EC2 instance. To enable
monitoring, you can either call the monitor_instance method on the
EC2Connection object or call the monitor method on the Instance object.
It takes a while for the monitoring data to start accumulating but once
it does, you can do this:
>>> import boto
>>> c = boto.connect_cloudwatch()
>>> metrics = c.list_metrics()
>>> metrics
[Metric:NetworkIn,
Metric:NetworkOut,
Metric:NetworkOut(InstanceType,m1.small),
Metric:NetworkIn(InstanceId,i-e573e68c),
Metric:CPUUtilization(InstanceId,i-e573e68c),
Metric:DiskWriteBytes(InstanceType,m1.small),
Metric:DiskWriteBytes(ImageId,ami-a1ffb63),
Metric:NetworkOut(ImageId,ami-a1ffb63),
Metric:DiskWriteOps(InstanceType,m1.small),
Metric:DiskReadBytes(InstanceType,m1.small),
Metric:DiskReadOps(ImageId,ami-a1ffb63),
Metric:CPUUtilization(InstanceType,m1.small),
Metric:NetworkIn(ImageId,ami-a1ffb63),
Metric:DiskReadOps(InstanceType,m1.small),
Metric:DiskReadBytes,
Metric:CPUUtilization,
Metric:DiskWriteBytes(InstanceId,i-e573e68c),
Metric:DiskWriteOps(InstanceId,i-e573e68c),
Metric:DiskWriteOps,
Metric:DiskReadOps,
Metric:CPUUtilization(ImageId,ami-a1ffb63),
Metric:DiskReadOps(InstanceId,i-e573e68c),
Metric:NetworkOut(InstanceId,i-e573e68c),
Metric:DiskReadBytes(ImageId,ami-a1ffb63),
Metric:DiskReadBytes(InstanceId,i-e573e68c),
Metric:DiskWriteBytes,
Metric:NetworkIn(InstanceType,m1.small),
Metric:DiskWriteOps(ImageId,ami-a1ffb63)]
The list_metrics call will return a list of all of the available metrics
that you can query against. Each entry in the list is a Metric object.
As you can see from the list above, some of the metrics are generic metrics
and some have Dimensions associated with them (e.g. InstanceType=m1.small).
The Dimension can be used to refine your query. So, for example, I could
query the metric Metric:CPUUtilization which would create the desired statistic
by aggregating cpu utilization data across all sources of information available
or I could refine that by querying the metric
Metric:CPUUtilization(InstanceId,i-e573e68c) which would use only the data
associated with the instance identified by the instance ID i-e573e68c.
Because for this example, I'm only monitoring a single instance, the set
of metrics available to me are fairly limited. If I was monitoring many
instances, using many different instance types and AMI's and also several
load balancers, the list of available metrics would grow considerably.
Once you have the list of available metrics, you can actually
query the CloudWatch system for that metric. Let's choose the CPU utilization
metric for our instance.
>>> m = metrics[5]
>>> m
Metric:CPUUtilization(InstanceId,i-e573e68c)
The Metric object has a query method that lets us actually perform
the query against the collected data in CloudWatch. To call that,
we need a start time and end time to control the time span of data
that we are interested in. For this example, let's say we want the
data for the previous hour:
>>> import datetime
>>> end = datetime.datetime.now()
>>> start = end - datetime.timedelta(hours=1)
We also need to supply the Statistic that we want reported and
the Units to use for the results. The Statistic can be one of these
values:
['Minimum', 'Maximum', 'Sum', 'Average', 'Samples']
And Units must be one of the following:
['Seconds', 'Percent', 'Bytes', 'Bits', 'Count',
'Bytes/Second', 'Bits/Second', 'Count/Second']
The query method also takes an optional parameter, period. This
parameter controls the granularity (in seconds) of the data returned.
The smallest period is 60 seconds and the value must be a multiple
of 60 seconds. So, let's ask for the average as a percent:
>>> datapoints = m.query(start, end, 'Average', 'Percent')
>>> len(datapoints)
60
Our period was 60 seconds and our duration was one hour so
we should get 60 data points back and we can see that we did.
Each element in the datapoints list is a DataPoint object
which is a simple subclass of a Python dict object. Each
Datapoint object contains all of the information available
about that particular data point.
>>> d = datapoints[0]
>>> d
{u'Average': 0.0,
u'Samples': 1.0,
u'Timestamp': u'2009-05-21T19:55:00Z',
u'Unit': u'Percent'}
My server obviously isn't very busy right now!
"""
from boto.connection import AWSQueryConnection
from boto.ec2.cloudwatch.metric import Metric
from boto.ec2.cloudwatch.datapoint import Datapoint
import boto
class CloudWatchConnection(AWSQueryConnection):
APIVersion = boto.config.get('Boto', 'cloudwatch_version', '2009-05-15')
Endpoint = boto.config.get('Boto', 'cloudwatch_endpoint', 'monitoring.amazonaws.com')
SignatureVersion = '2'
def __init__(self, aws_access_key_id=None, aws_secret_access_key=None,
is_secure=True, port=None, proxy=None, proxy_port=None,
proxy_user=None, proxy_pass=None, host=Endpoint, debug=0,
https_connection_factory=None, path='/'):
"""
Init method to create a new connection to EC2 Monitoring Service.
B{Note:} The host argument is overridden by the host specified in the boto configuration file.
"""
AWSQueryConnection.__init__(self, aws_access_key_id, aws_secret_access_key,
is_secure, port, proxy, proxy_port, proxy_user, proxy_pass,
host, debug, https_connection_factory, path)
def build_list_params(self, params, items, label):
if isinstance(items, str):
items = [items]
for i in range(1, len(items)+1):
params[label % i] = items[i-1]
def get_metric_statistics(self, period, start_time, end_time, measure_name,
namespace, statistics=None, dimensions=None, unit=None):
"""
Get time-series data for one or more statistics of a given metric.
:type measure_name: string
:param measure_name: CPUUtilization|NetworkIO-in|NetworkIO-out|DiskIO-ALL-read|
DiskIO-ALL-write|DiskIO-ALL-read-bytes|DiskIO-ALL-write-bytes
:rtype: list
:return: A list of :class:`boto.ec2.image.Image`
"""
params = {'Period' : period,
'MeasureName' : measure_name,
'Namespace' : namespace,
'StartTime' : start_time.isoformat(),
'EndTime' : end_time.isoformat()}
if dimensions:
i = 1
for name in dimensions:
params['Dimensions.member.%d.Name' % i] = name
params['Dimensions.member.%d.Value' % i] = dimensions[name]
i += 1
if statistics:
self.build_list_params(params, statistics, 'Statistics.member.%d')
return self.get_list('GetMetricStatistics', params, [('member', Datapoint)])
def list_metrics(self, next_token=None):
"""
Returns a list of the valid metrics for which there is recorded data available.
:type next_token: string
:param next_token: A maximum of 500 metrics will be returned at one time.
If more results are available, the ResultSet returned
will contain a non-Null next_token attribute. Passing
that token as a parameter to list_metrics will retrieve
the next page of metrics.
"""
params = {}
if next_token:
params['NextToken'] = next_token
return self.get_list('ListMetrics', params, [('member', Metric)])
| Python |
# Copyright (c) 2006-2010 Mitch Garnaat http://garnaat.org/
# Copyright (c) 2010, Eucalyptus Systems, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
"""
Represents an EC2 Instance
"""
import boto
from boto.ec2.ec2object import EC2Object, TaggedEC2Object
from boto.resultset import ResultSet
from boto.ec2.address import Address
from boto.ec2.blockdevicemapping import BlockDeviceMapping
from boto.ec2.image import ProductCodes
import base64
class Reservation(EC2Object):
def __init__(self, connection=None):
EC2Object.__init__(self, connection)
self.id = None
self.owner_id = None
self.groups = []
self.instances = []
def __repr__(self):
return 'Reservation:%s' % self.id
def startElement(self, name, attrs, connection):
if name == 'instancesSet':
self.instances = ResultSet([('item', Instance)])
return self.instances
elif name == 'groupSet':
self.groups = ResultSet([('item', Group)])
return self.groups
else:
return None
def endElement(self, name, value, connection):
if name == 'reservationId':
self.id = value
elif name == 'ownerId':
self.owner_id = value
else:
setattr(self, name, value)
def stop_all(self):
for instance in self.instances:
instance.stop()
class Instance(TaggedEC2Object):
def __init__(self, connection=None):
TaggedEC2Object.__init__(self, connection)
self.id = None
self.dns_name = None
self.public_dns_name = None
self.private_dns_name = None
self.state = None
self.state_code = None
self.key_name = None
self.shutdown_state = None
self.previous_state = None
self.instance_type = None
self.instance_class = None
self.launch_time = None
self.image_id = None
self.placement = None
self.kernel = None
self.ramdisk = None
self.product_codes = ProductCodes()
self.ami_launch_index = None
self.monitored = False
self.instance_class = None
self.spot_instance_request_id = None
self.subnet_id = None
self.vpc_id = None
self.private_ip_address = None
self.ip_address = None
self.requester_id = None
self._in_monitoring_element = False
self.persistent = False
self.root_device_name = None
self.root_device_type = None
self.block_device_mapping = None
self.state_reason = None
self.group_name = None
def __repr__(self):
return 'Instance:%s' % self.id
def startElement(self, name, attrs, connection):
retval = TaggedEC2Object.startElement(self, name, attrs, connection)
if retval is not None:
return retval
if name == 'monitoring':
self._in_monitoring_element = True
elif name == 'blockDeviceMapping':
self.block_device_mapping = BlockDeviceMapping()
return self.block_device_mapping
elif name == 'productCodes':
return self.product_codes
elif name == 'stateReason':
self.state_reason = StateReason()
return self.state_reason
return None
def endElement(self, name, value, connection):
if name == 'instanceId':
self.id = value
elif name == 'imageId':
self.image_id = value
elif name == 'dnsName' or name == 'publicDnsName':
self.dns_name = value # backwards compatibility
self.public_dns_name = value
elif name == 'privateDnsName':
self.private_dns_name = value
elif name == 'keyName':
self.key_name = value
elif name == 'amiLaunchIndex':
self.ami_launch_index = value
elif name == 'shutdownState':
self.shutdown_state = value
elif name == 'previousState':
self.previous_state = value
elif name == 'name':
self.state = value
elif name == 'code':
try:
self.state_code = int(value)
except ValueError:
boto.log.warning('Error converting code (%s) to int' % value)
self.state_code = value
elif name == 'instanceType':
self.instance_type = value
elif name == 'instanceClass':
self.instance_class = value
elif name == 'rootDeviceName':
self.root_device_name = value
elif name == 'rootDeviceType':
self.root_device_type = value
elif name == 'launchTime':
self.launch_time = value
elif name == 'availabilityZone':
self.placement = value
elif name == 'placement':
pass
elif name == 'kernelId':
self.kernel = value
elif name == 'ramdiskId':
self.ramdisk = value
elif name == 'state':
if self._in_monitoring_element:
if value == 'enabled':
self.monitored = True
self._in_monitoring_element = False
elif name == 'instanceClass':
self.instance_class = value
elif name == 'spotInstanceRequestId':
self.spot_instance_request_id = value
elif name == 'subnetId':
self.subnet_id = value
elif name == 'vpcId':
self.vpc_id = value
elif name == 'privateIpAddress':
self.private_ip_address = value
elif name == 'ipAddress':
self.ip_address = value
elif name == 'requesterId':
self.requester_id = value
elif name == 'persistent':
if value == 'true':
self.persistent = True
else:
self.persistent = False
elif name == 'groupName':
if self._in_monitoring_element:
self.group_name = value
else:
setattr(self, name, value)
def _update(self, updated):
self.__dict__.update(updated.__dict__)
def update(self, validate=False):
"""
Update the instance's state information by making a call to fetch
the current instance attributes from the service.
:type validate: bool
:param validate: By default, if EC2 returns no data about the
instance the update method returns quietly. If
the validate param is True, however, it will
raise a ValueError exception if no data is
returned from EC2.
"""
rs = self.connection.get_all_instances([self.id])
if len(rs) > 0:
r = rs[0]
for i in r.instances:
if i.id == self.id:
self._update(i)
elif validate:
raise ValueError('%s is not a valid Instance ID' % self.id)
return self.state
def terminate(self):
"""
Terminate the instance
"""
rs = self.connection.terminate_instances([self.id])
self._update(rs[0])
def stop(self, force=False):
"""
Stop the instance
:type force: bool
:param force: Forces the instance to stop
:rtype: list
:return: A list of the instances stopped
"""
rs = self.connection.stop_instances([self.id])
self._update(rs[0])
def start(self):
"""
Start the instance.
"""
rs = self.connection.start_instances([self.id])
self._update(rs[0])
def reboot(self):
return self.connection.reboot_instances([self.id])
def get_console_output(self):
"""
Retrieves the console output for the instance.
:rtype: :class:`boto.ec2.instance.ConsoleOutput`
:return: The console output as a ConsoleOutput object
"""
return self.connection.get_console_output(self.id)
def confirm_product(self, product_code):
return self.connection.confirm_product_instance(self.id, product_code)
def use_ip(self, ip_address):
if isinstance(ip_address, Address):
ip_address = ip_address.public_ip
return self.connection.associate_address(self.id, ip_address)
def monitor(self):
return self.connection.monitor_instance(self.id)
def unmonitor(self):
return self.connection.unmonitor_instance(self.id)
def get_attribute(self, attribute):
"""
Gets an attribute from this instance.
:type attribute: string
:param attribute: The attribute you need information about
Valid choices are:
instanceType|kernel|ramdisk|userData|
disableApiTermination|
instanceInitiatedShutdownBehavior|
rootDeviceName|blockDeviceMapping
:rtype: :class:`boto.ec2.image.InstanceAttribute`
:return: An InstanceAttribute object representing the value of the
attribute requested
"""
return self.connection.describe_attribute(self.id, attribute)
def modify_attribute(self, attribute, value):
"""
Changes an attribute of this instance
:type attribute: string
:param attribute: The attribute you wish to change.
AttributeName - Expected value (default)
instanceType - A valid instance type (m1.small)
kernel - Kernel ID (None)
ramdisk - Ramdisk ID (None)
userData - Base64 encoded String (None)
disableApiTermination - Boolean (true)
instanceInitiatedShutdownBehavior - stop|terminate
rootDeviceName - device name (None)
:type value: string
:param value: The new value for the attribute
:rtype: bool
:return: Whether the operation succeeded or not
"""
return self.connection.modify_instance_attribute(self.id, attribute,
value)
def reset_attribute(self, attribute):
"""
Resets an attribute of this instance to its default value.
:type attribute: string
:param attribute: The attribute to reset. Valid values are:
kernel|ramdisk
:rtype: bool
:return: Whether the operation succeeded or not
"""
return self.connection.reset_instance_attribute(self.id, attribute)
class Group:
def __init__(self, parent=None):
self.id = None
def startElement(self, name, attrs, connection):
return None
def endElement(self, name, value, connection):
if name == 'groupId':
self.id = value
else:
setattr(self, name, value)
class ConsoleOutput:
def __init__(self, parent=None):
self.parent = parent
self.instance_id = None
self.timestamp = None
self.comment = None
def startElement(self, name, attrs, connection):
return None
def endElement(self, name, value, connection):
if name == 'instanceId':
self.instance_id = value
elif name == 'output':
self.output = base64.b64decode(value)
else:
setattr(self, name, value)
class InstanceAttribute(dict):
def __init__(self, parent=None):
dict.__init__(self)
self._current_value = None
def startElement(self, name, attrs, connection):
return None
def endElement(self, name, value, connection):
if name == 'value':
self._current_value = value
else:
self[name] = self._current_value
class StateReason(dict):
def __init__(self, parent=None):
dict.__init__(self)
def startElement(self, name, attrs, connection):
return None
def endElement(self, name, value, connection):
if name != 'stateReason':
self[name] = value
| Python |
# Copyright (c) 2006,2007 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
"""
Represents an EC2 Keypair
"""
import os
from boto.ec2.ec2object import EC2Object
from boto.exception import BotoClientError
class KeyPair(EC2Object):
def __init__(self, connection=None):
EC2Object.__init__(self, connection)
self.name = None
self.fingerprint = None
self.material = None
def __repr__(self):
return 'KeyPair:%s' % self.name
def endElement(self, name, value, connection):
if name == 'keyName':
self.name = value
elif name == 'keyFingerprint':
self.fingerprint = value
elif name == 'keyMaterial':
self.material = value
else:
setattr(self, name, value)
def delete(self):
"""
Delete the KeyPair.
:rtype: bool
:return: True if successful, otherwise False.
"""
return self.connection.delete_key_pair(self.name)
def save(self, directory_path):
"""
Save the material (the unencrypted PEM encoded RSA private key)
of a newly created KeyPair to a local file.
:type directory_path: string
:param directory_path: The fully qualified path to the directory
in which the keypair will be saved. The
keypair file will be named using the name
of the keypair as the base name and .pem
for the file extension. If a file of that
name already exists in the directory, an
exception will be raised and the old file
will not be overwritten.
:rtype: bool
:return: True if successful.
"""
if self.material:
file_path = os.path.join(directory_path, '%s.pem' % self.name)
if os.path.exists(file_path):
raise BotoClientError('%s already exists, it will not be overwritten' % file_path)
fp = open(file_path, 'wb')
fp.write(self.material)
fp.close()
return True
else:
raise BotoClientError('KeyPair contains no material')
def copy_to_region(self, region):
"""
Create a new key pair of the same new in another region.
Note that the new key pair will use a different ssh
cert than the this key pair. After doing the copy,
you will need to save the material associated with the
new key pair (use the save method) to a local file.
:type region: :class:`boto.ec2.regioninfo.RegionInfo`
:param region: The region to which this security group will be copied.
:rtype: :class:`boto.ec2.keypair.KeyPair`
:return: The new key pair
"""
if region.name == self.region:
raise BotoClientError('Unable to copy to the same Region')
conn_params = self.connection.get_params()
rconn = region.connect(**conn_params)
kp = rconn.create_key_pair(self.name)
return kp
| Python |
# Copyright (c) 2006-2009 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
"""
Represents an EC2 Spot Instance Datafeed Subscription
"""
from boto.ec2.ec2object import EC2Object
from boto.ec2.spotinstancerequest import SpotInstanceStateFault
class SpotDatafeedSubscription(EC2Object):
def __init__(self, connection=None, owner_id=None,
bucket=None, prefix=None, state=None,fault=None):
EC2Object.__init__(self, connection)
self.owner_id = owner_id
self.bucket = bucket
self.prefix = prefix
self.state = state
self.fault = fault
def __repr__(self):
return 'SpotDatafeedSubscription:%s' % self.bucket
def startElement(self, name, attrs, connection):
if name == 'fault':
self.fault = SpotInstanceStateFault()
return self.fault
else:
return None
def endElement(self, name, value, connection):
if name == 'ownerId':
self.owner_id = value
elif name == 'bucket':
self.bucket = value
elif name == 'prefix':
self.prefix = value
elif name == 'state':
self.state = value
else:
setattr(self, name, value)
def delete(self):
return self.connection.delete_spot_datafeed_subscription()
| Python |
# Copyright (c) 2006-2009 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
from boto.ec2.elb.healthcheck import HealthCheck
from boto.ec2.elb.listener import Listener
from boto.ec2.elb.listelement import ListElement
from boto.ec2.instanceinfo import InstanceInfo
from boto.resultset import ResultSet
class LoadBalancer(object):
"""
Represents an EC2 Load Balancer
"""
def __init__(self, connection=None, name=None, endpoints=None):
self.connection = connection
self.name = name
self.listeners = None
self.health_check = None
self.dns_name = None
self.created_time = None
self.instances = None
self.availability_zones = ListElement()
def __repr__(self):
return 'LoadBalancer:%s' % self.name
def startElement(self, name, attrs, connection):
if name == 'HealthCheck':
self.health_check = HealthCheck(self)
return self.health_check
elif name == 'Listeners':
self.listeners = ResultSet([('member', Listener)])
return self.listeners
elif name == 'AvailabilityZones':
return self.availability_zones
elif name == 'Instances':
self.instances = ResultSet([('member', InstanceInfo)])
return self.instances
else:
return None
def endElement(self, name, value, connection):
if name == 'LoadBalancerName':
self.name = value
elif name == 'DNSName':
self.dns_name = value
elif name == 'CreatedTime':
self.created_time = value
elif name == 'InstanceId':
self.instances.append(value)
else:
setattr(self, name, value)
def enable_zones(self, zones):
"""
Enable availability zones to this Access Point.
All zones must be in the same region as the Access Point.
:type zones: string or List of strings
:param zones: The name of the zone(s) to add.
"""
if isinstance(zones, str) or isinstance(zones, unicode):
zones = [zones]
new_zones = self.connection.enable_availability_zones(self.name, zones)
self.availability_zones = new_zones
def disable_zones(self, zones):
"""
Disable availability zones from this Access Point.
:type zones: string or List of strings
:param zones: The name of the zone(s) to add.
"""
if isinstance(zones, str) or isinstance(zones, unicode):
zones = [zones]
new_zones = self.connection.disable_availability_zones(self.name, zones)
self.availability_zones = new_zones
def register_instances(self, instances):
"""
Add instances to this Load Balancer
All instances must be in the same region as the Load Balancer.
Adding endpoints that are already registered with the Load Balancer
has no effect.
:type zones: string or List of instance id's
:param zones: The name of the endpoint(s) to add.
"""
if isinstance(instances, str) or isinstance(instances, unicode):
instances = [instances]
new_instances = self.connection.register_instances(self.name, instances)
self.instances = new_instances
def deregister_instances(self, instances):
"""
Remove instances from this Load Balancer.
Removing instances that are not registered with the Load Balancer
has no effect.
:type zones: string or List of instance id's
:param zones: The name of the endpoint(s) to add.
"""
if isinstance(instances, str) or isinstance(instances, unicode):
instances = [instances]
new_instances = self.connection.deregister_instances(self.name, instances)
self.instances = new_instances
def delete(self):
"""
Delete this load balancer
"""
return self.connection.delete_load_balancer(self.name)
def configure_health_check(self, health_check):
return self.connection.configure_health_check(self.name, health_check)
def get_instance_health(self, instances=None):
return self.connection.describe_instance_health(self.name, instances)
| Python |
# Copyright (c) 2006-2009 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
class Listener(object):
"""
Represents an EC2 Load Balancer Listener tuple
"""
def __init__(self, load_balancer=None, load_balancer_port=0,
instance_port=0, protocol=''):
self.load_balancer = load_balancer
self.load_balancer_port = load_balancer_port
self.instance_port = instance_port
self.protocol = protocol
def __repr__(self):
return "(%d, %d, '%s')" % (self.load_balancer_port, self.instance_port, self.protocol)
def startElement(self, name, attrs, connection):
return None
def endElement(self, name, value, connection):
if name == 'LoadBalancerPort':
self.load_balancer_port = int(value)
elif name == 'InstancePort':
self.instance_port = int(value)
elif name == 'Protocol':
self.protocol = value
else:
setattr(self, name, value)
def get_tuple(self):
return self.load_balancer_port, self.instance_port, self.protocol
def __getitem__(self, key):
if key == 0:
return self.load_balancer_port
if key == 1:
return self.instance_port
if key == 2:
return self.protocol
raise KeyError
| Python |
# Copyright (c) 2006-2009 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
class InstanceState(object):
"""
Represents the state of an EC2 Load Balancer Instance
"""
def __init__(self, load_balancer=None, description=None,
state=None, instance_id=None, reason_code=None):
self.load_balancer = load_balancer
self.description = description
self.state = state
self.instance_id = instance_id
self.reason_code = reason_code
def __repr__(self):
return 'InstanceState:(%s,%s)' % (self.instance_id, self.state)
def startElement(self, name, attrs, connection):
return None
def endElement(self, name, value, connection):
if name == 'Description':
self.description = value
elif name == 'State':
self.state = value
elif name == 'InstanceId':
self.instance_id = value
elif name == 'ReasonCode':
self.reason_code = value
else:
setattr(self, name, value)
| Python |
# Copyright (c) 2006-2009 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
class ListElement(list):
def startElement(self, name, attrs, connection):
pass
def endElement(self, name, value, connection):
if name == 'member':
self.append(value)
| Python |
# Copyright (c) 2006-2009 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
"""
This module provides an interface to the Elastic Compute Cloud (EC2)
load balancing service from AWS.
"""
from boto.connection import AWSQueryConnection
from boto.ec2.instanceinfo import InstanceInfo
from boto.ec2.elb.loadbalancer import LoadBalancer
from boto.ec2.elb.instancestate import InstanceState
from boto.ec2.elb.healthcheck import HealthCheck
import boto
class ELBConnection(AWSQueryConnection):
APIVersion = boto.config.get('Boto', 'elb_version', '2009-05-15')
Endpoint = boto.config.get('Boto', 'elb_endpoint', 'elasticloadbalancing.amazonaws.com')
SignatureVersion = '1'
#ResponseError = EC2ResponseError
def __init__(self, aws_access_key_id=None, aws_secret_access_key=None,
is_secure=False, port=None, proxy=None, proxy_port=None,
proxy_user=None, proxy_pass=None, host=Endpoint, debug=0,
https_connection_factory=None, path='/'):
"""
Init method to create a new connection to EC2 Load Balancing Service.
B{Note:} The host argument is overridden by the host specified in the boto configuration file.
"""
AWSQueryConnection.__init__(self, aws_access_key_id, aws_secret_access_key,
is_secure, port, proxy, proxy_port, proxy_user, proxy_pass,
host, debug, https_connection_factory, path)
def build_list_params(self, params, items, label):
if isinstance(items, str):
items = [items]
for i in range(1, len(items)+1):
params[label % i] = items[i-1]
def get_all_load_balancers(self, load_balancer_names=None):
"""
Retrieve all load balancers associated with your account.
:type load_balancer_names: list
:param load_balancer_names: An optional list of load balancer names
:rtype: list
:return: A list of :class:`boto.ec2.elb.loadbalancer.LoadBalancer`
"""
params = {}
if load_balancer_names:
self.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d')
return self.get_list('DescribeLoadBalancers', params, [('member', LoadBalancer)])
def create_load_balancer(self, name, zones, listeners):
"""
Create a new load balancer for your account.
:type name: string
:param name: The mnemonic name associated with the new load balancer
:type zones: List of strings
:param zones: The names of the availability zone(s) to add.
:type listeners: List of tuples
:param listeners: Each tuple contains three values.
(LoadBalancerPortNumber, InstancePortNumber, Protocol)
where LoadBalancerPortNumber and InstancePortNumber are
integer values between 1 and 65535 and Protocol is a
string containing either 'TCP' or 'HTTP'.
:rtype: :class:`boto.ec2.elb.loadbalancer.LoadBalancer`
:return: The newly created :class:`boto.ec2.elb.loadbalancer.LoadBalancer`
"""
params = {'LoadBalancerName' : name}
for i in range(0, len(listeners)):
params['Listeners.member.%d.LoadBalancerPort' % (i+1)] = listeners[i][0]
params['Listeners.member.%d.InstancePort' % (i+1)] = listeners[i][1]
params['Listeners.member.%d.Protocol' % (i+1)] = listeners[i][2]
self.build_list_params(params, zones, 'AvailabilityZones.member.%d')
load_balancer = self.get_object('CreateLoadBalancer', params, LoadBalancer)
load_balancer.name = name
load_balancer.listeners = listeners
load_balancer.availability_zones = zones
return load_balancer
def delete_load_balancer(self, name):
"""
Delete a Load Balancer from your account.
:type name: string
:param name: The name of the Load Balancer to delete
"""
params = {'LoadBalancerName': name}
return self.get_status('DeleteLoadBalancer', params)
def enable_availability_zones(self, load_balancer_name, zones_to_add):
"""
Add availability zones to an existing Load Balancer
All zones must be in the same region as the Load Balancer
Adding zones that are already registered with the Load Balancer
has no effect.
:type load_balancer_name: string
:param load_balancer_name: The name of the Load Balancer
:type zones: List of strings
:param zones: The name of the zone(s) to add.
:rtype: List of strings
:return: An updated list of zones for this Load Balancer.
"""
params = {'LoadBalancerName' : load_balancer_name}
self.build_list_params(params, zones_to_add, 'AvailabilityZones.member.%d')
return self.get_list('EnableAvailabilityZonesForLoadBalancer', params, None)
def disable_availability_zones(self, load_balancer_name, zones_to_remove):
"""
Remove availability zones from an existing Load Balancer.
All zones must be in the same region as the Load Balancer.
Removing zones that are not registered with the Load Balancer
has no effect.
You cannot remove all zones from an Load Balancer.
:type load_balancer_name: string
:param load_balancer_name: The name of the Load Balancer
:type zones: List of strings
:param zones: The name of the zone(s) to remove.
:rtype: List of strings
:return: An updated list of zones for this Load Balancer.
"""
params = {'LoadBalancerName' : load_balancer_name}
self.build_list_params(params, zones_to_remove, 'AvailabilityZones.member.%d')
return self.get_list('DisableAvailabilityZonesForLoadBalancer', params, None)
def register_instances(self, load_balancer_name, instances):
"""
Add new Instances to an existing Load Balancer.
:type load_balancer_name: string
:param load_balancer_name: The name of the Load Balancer
:type instances: List of strings
:param instances: The instance ID's of the EC2 instances to add.
:rtype: List of strings
:return: An updated list of instances for this Load Balancer.
"""
params = {'LoadBalancerName' : load_balancer_name}
self.build_list_params(params, instances, 'Instances.member.%d.InstanceId')
return self.get_list('RegisterInstancesWithLoadBalancer', params, [('member', InstanceInfo)])
def deregister_instances(self, load_balancer_name, instances):
"""
Remove Instances from an existing Load Balancer.
:type load_balancer_name: string
:param load_balancer_name: The name of the Load Balancer
:type instances: List of strings
:param instances: The instance ID's of the EC2 instances to remove.
:rtype: List of strings
:return: An updated list of instances for this Load Balancer.
"""
params = {'LoadBalancerName' : load_balancer_name}
self.build_list_params(params, instances, 'Instances.member.%d.InstanceId')
return self.get_list('DeregisterInstancesFromLoadBalancer', params, [('member', InstanceInfo)])
def describe_instance_health(self, load_balancer_name, instances=None):
"""
Get current state of all Instances registered to an Load Balancer.
:type load_balancer_name: string
:param load_balancer_name: The name of the Load Balancer
:type instances: List of strings
:param instances: The instance ID's of the EC2 instances
to return status for. If not provided,
the state of all instances will be returned.
:rtype: List of :class:`boto.ec2.elb.instancestate.InstanceState`
:return: list of state info for instances in this Load Balancer.
"""
params = {'LoadBalancerName' : load_balancer_name}
if instances:
self.build_list_params(params, instances, 'Instances.member.%d')
return self.get_list('DescribeInstanceHealth', params, [('member', InstanceState)])
def configure_health_check(self, name, health_check):
"""
Define a health check for the EndPoints.
:type name: string
:param name: The mnemonic name associated with the new access point
:type health_check: :class:`boto.ec2.elb.healthcheck.HealthCheck`
:param health_check: A HealthCheck object populated with the desired
values.
:rtype: :class:`boto.ec2.elb.healthcheck.HealthCheck`
:return: The updated :class:`boto.ec2.elb.healthcheck.HealthCheck`
"""
params = {'LoadBalancerName' : name,
'HealthCheck.Timeout' : health_check.timeout,
'HealthCheck.Target' : health_check.target,
'HealthCheck.Interval' : health_check.interval,
'HealthCheck.UnhealthyThreshold' : health_check.unhealthy_threshold,
'HealthCheck.HealthyThreshold' : health_check.healthy_threshold}
return self.get_object('ConfigureHealthCheck', params, HealthCheck)
| Python |
# Copyright (c) 2006-2009 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
class HealthCheck(object):
"""
Represents an EC2 Access Point Health Check
"""
def __init__(self, access_point=None, interval=30, target=None,
healthy_threshold=3, timeout=5, unhealthy_threshold=5):
self.access_point = access_point
self.interval = interval
self.target = target
self.healthy_threshold = healthy_threshold
self.timeout = timeout
self.unhealthy_threshold = unhealthy_threshold
def __repr__(self):
return 'HealthCheck:%s' % self.target
def startElement(self, name, attrs, connection):
return None
def endElement(self, name, value, connection):
if name == 'Interval':
self.interval = int(value)
elif name == 'Target':
self.target = value
elif name == 'HealthyThreshold':
self.healthy_threshold = int(value)
elif name == 'Timeout':
self.timeout = int(value)
elif name == 'UnhealthyThreshold':
self.unhealthy_threshold = int(value)
else:
setattr(self, name, value)
def update(self):
if not self.access_point:
return
new_hc = self.connection.configure_health_check(self.access_point,
self)
self.interval = new_hc.interval
self.target = new_hc.target
self.healthy_threshold = new_hc.healthy_threshold
self.unhealthy_threshold = new_hc.unhealthy_threshold
self.timeout = new_hc.timeout
| Python |
# Copyright (c) 2006-2008 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
"""
This module provides an interface to the Elastic Compute Cloud (EC2)
service from AWS.
"""
from boto.ec2.connection import EC2Connection
def regions(**kw_params):
"""
Get all available regions for the EC2 service.
You may pass any of the arguments accepted by the EC2Connection
object's constructor as keyword arguments and they will be
passed along to the EC2Connection object.
:rtype: list
:return: A list of :class:`boto.ec2.regioninfo.RegionInfo`
"""
c = EC2Connection(**kw_params)
return c.get_all_regions()
def connect_to_region(region_name, **kw_params):
for region in regions(**kw_params):
if region.name == region_name:
return region.connect(**kw_params)
return None
def get_region(region_name, **kw_params):
for region in regions(**kw_params):
if region.name == region_name:
return region
return None
| Python |
# Copyright (c) 2006,2007 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
"""
Represents an EC2 Security Group
"""
from boto.ec2.ec2object import EC2Object
from boto.exception import BotoClientError
class SecurityGroup(EC2Object):
def __init__(self, connection=None, owner_id=None,
name=None, description=None):
EC2Object.__init__(self, connection)
self.owner_id = owner_id
self.name = name
self.description = description
self.rules = []
def __repr__(self):
return 'SecurityGroup:%s' % self.name
def startElement(self, name, attrs, connection):
if name == 'item':
self.rules.append(IPPermissions(self))
return self.rules[-1]
else:
return None
def endElement(self, name, value, connection):
if name == 'ownerId':
self.owner_id = value
elif name == 'groupName':
self.name = value
elif name == 'groupDescription':
self.description = value
elif name == 'ipRanges':
pass
elif name == 'return':
if value == 'false':
self.status = False
elif value == 'true':
self.status = True
else:
raise Exception(
'Unexpected value of status %s for group %s'%(
value,
self.name
)
)
else:
setattr(self, name, value)
def delete(self):
return self.connection.delete_security_group(self.name)
def add_rule(self, ip_protocol, from_port, to_port,
src_group_name, src_group_owner_id, cidr_ip):
"""
Add a rule to the SecurityGroup object. Note that this method
only changes the local version of the object. No information
is sent to EC2.
"""
rule = IPPermissions(self)
rule.ip_protocol = ip_protocol
rule.from_port = from_port
rule.to_port = to_port
self.rules.append(rule)
rule.add_grant(src_group_name, src_group_owner_id, cidr_ip)
def remove_rule(self, ip_protocol, from_port, to_port,
src_group_name, src_group_owner_id, cidr_ip):
"""
Remove a rule to the SecurityGroup object. Note that this method
only changes the local version of the object. No information
is sent to EC2.
"""
target_rule = None
for rule in self.rules:
if rule.ip_protocol == ip_protocol:
if rule.from_port == from_port:
if rule.to_port == to_port:
target_rule = rule
target_grant = None
for grant in rule.grants:
if grant.name == src_group_name:
if grant.owner_id == src_group_owner_id:
if grant.cidr_ip == cidr_ip:
target_grant = grant
if target_grant:
rule.grants.remove(target_grant)
if len(rule.grants) == 0:
self.rules.remove(target_rule)
def authorize(self, ip_protocol=None, from_port=None, to_port=None,
cidr_ip=None, src_group=None):
"""
Add a new rule to this security group.
You need to pass in either src_group_name
OR ip_protocol, from_port, to_port,
and cidr_ip. In other words, either you are authorizing another
group or you are authorizing some ip-based rule.
:type ip_protocol: string
:param ip_protocol: Either tcp | udp | icmp
:type from_port: int
:param from_port: The beginning port number you are enabling
:type to_port: int
:param to_port: The ending port number you are enabling
:type to_port: string
:param to_port: The CIDR block you are providing access to.
See http://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing
:type src_group: :class:`boto.ec2.securitygroup.SecurityGroup` or
:class:`boto.ec2.securitygroup.GroupOrCIDR`
:rtype: bool
:return: True if successful.
"""
if src_group:
from_port = None
to_port = None
cidr_ip = None
ip_protocol = None
src_group_name = src_group.name
src_group_owner_id = src_group.owner_id
else:
src_group_name = None
src_group_owner_id = None
status = self.connection.authorize_security_group(self.name,
src_group_name,
src_group_owner_id,
ip_protocol,
from_port,
to_port,
cidr_ip)
if status:
self.add_rule(ip_protocol, from_port, to_port, src_group_name,
src_group_owner_id, cidr_ip)
return status
def revoke(self, ip_protocol=None, from_port=None, to_port=None,
cidr_ip=None, src_group=None):
if src_group:
from_port=None
to_port=None
cidr_ip=None
ip_protocol = None
src_group_name = src_group.name
src_group_owner_id = src_group.owner_id
else:
src_group_name = None
src_group_owner_id = None
status = self.connection.revoke_security_group(self.name,
src_group_name,
src_group_owner_id,
ip_protocol,
from_port,
to_port,
cidr_ip)
if status:
self.remove_rule(ip_protocol, from_port, to_port, src_group_name,
src_group_owner_id, cidr_ip)
return status
def copy_to_region(self, region, name=None):
"""
Create a copy of this security group in another region.
Note that the new security group will be a separate entity
and will not stay in sync automatically after the copy
operation.
:type region: :class:`boto.ec2.regioninfo.RegionInfo`
:param region: The region to which this security group will be copied.
:type name: string
:param name: The name of the copy. If not supplied, the copy
will have the same name as this security group.
:rtype: :class:`boto.ec2.securitygroup.SecurityGroup`
:return: The new security group.
"""
if region.name == self.region:
raise BotoClientError('Unable to copy to the same Region')
conn_params = self.connection.get_params()
rconn = region.connect(**conn_params)
sg = rconn.create_security_group(name or self.name, self.description)
source_groups = []
for rule in self.rules:
grant = rule.grants[0]
if grant.name:
if grant.name not in source_groups:
source_groups.append(grant.name)
sg.authorize(None, None, None, None, grant)
else:
sg.authorize(rule.ip_protocol, rule.from_port, rule.to_port,
grant.cidr_ip)
return sg
def instances(self):
instances = []
rs = self.connection.get_all_instances()
for reservation in rs:
uses_group = [g.id for g in reservation.groups if g.id == self.name]
if uses_group:
instances.extend(reservation.instances)
return instances
class IPPermissions:
def __init__(self, parent=None):
self.parent = parent
self.ip_protocol = None
self.from_port = None
self.to_port = None
self.grants = []
def __repr__(self):
return 'IPPermissions:%s(%s-%s)' % (self.ip_protocol,
self.from_port, self.to_port)
def startElement(self, name, attrs, connection):
if name == 'item':
self.grants.append(GroupOrCIDR(self))
return self.grants[-1]
return None
def endElement(self, name, value, connection):
if name == 'ipProtocol':
self.ip_protocol = value
elif name == 'fromPort':
self.from_port = value
elif name == 'toPort':
self.to_port = value
else:
setattr(self, name, value)
def add_grant(self, name=None, owner_id=None, cidr_ip=None):
grant = GroupOrCIDR(self)
grant.owner_id = owner_id
grant.name = name
grant.cidr_ip = cidr_ip
self.grants.append(grant)
return grant
class GroupOrCIDR:
def __init__(self, parent=None):
self.owner_id = None
self.name = None
self.cidr_ip = None
def __repr__(self):
if self.cidr_ip:
return '%s' % self.cidr_ip
else:
return '%s-%s' % (self.name, self.owner_id)
def startElement(self, name, attrs, connection):
return None
def endElement(self, name, value, connection):
if name == 'userId':
self.owner_id = value
elif name == 'groupName':
self.name = value
if name == 'cidrIp':
self.cidr_ip = value
else:
setattr(self, name, value)
| Python |
# Copyright (c) 2010 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
"""
Represents an EC2 Placement Group
"""
from boto.ec2.ec2object import EC2Object
from boto.exception import BotoClientError
class PlacementGroup(EC2Object):
def __init__(self, connection=None, name=None, strategy=None, state=None):
EC2Object.__init__(self, connection)
self.name = name
self.strategy = strategy
self.state = state
def __repr__(self):
return 'PlacementGroup:%s' % self.name
def endElement(self, name, value, connection):
if name == 'groupName':
self.name = value
elif name == 'strategy':
self.strategy = value
elif name == 'state':
self.state = value
else:
setattr(self, name, value)
def delete(self):
return self.connection.delete_placement_group(self.name)
| Python |
# Copyright (c) 2006-2010 Mitch Garnaat http://garnaat.org/
# Copyright (c) 2010, Eucalyptus Systems, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
from boto.ec2.ec2object import EC2Object, TaggedEC2Object
from boto.ec2.blockdevicemapping import BlockDeviceMapping
class ProductCodes(list):
def startElement(self, name, attrs, connection):
pass
def endElement(self, name, value, connection):
if name == 'productCode':
self.append(value)
class Image(TaggedEC2Object):
"""
Represents an EC2 Image
"""
def __init__(self, connection=None):
TaggedEC2Object.__init__(self, connection)
self.id = None
self.location = None
self.state = None
self.ownerId = None
self.owner_alias = None
self.is_public = False
self.architecture = None
self.platform = None
self.type = None
self.kernel_id = None
self.ramdisk_id = None
self.name = None
self.description = None
self.product_codes = ProductCodes()
self.block_device_mapping = None
self.root_device_type = None
self.root_device_name = None
def __repr__(self):
return 'Image:%s' % self.id
def startElement(self, name, attrs, connection):
retval = TaggedEC2Object.startElement(self, name, attrs, connection)
if retval is not None:
return retval
if name == 'blockDeviceMapping':
self.block_device_mapping = BlockDeviceMapping()
return self.block_device_mapping
elif name == 'productCodes':
return self.product_codes
else:
return None
def endElement(self, name, value, connection):
if name == 'imageId':
self.id = value
elif name == 'imageLocation':
self.location = value
elif name == 'imageState':
self.state = value
elif name == 'imageOwnerId':
self.ownerId = value
elif name == 'isPublic':
if value == 'false':
self.is_public = False
elif value == 'true':
self.is_public = True
else:
raise Exception(
'Unexpected value of isPublic %s for image %s'%(
value,
self.id
)
)
elif name == 'architecture':
self.architecture = value
elif name == 'imageType':
self.type = value
elif name == 'kernelId':
self.kernel_id = value
elif name == 'ramdiskId':
self.ramdisk_id = value
elif name == 'imageOwnerAlias':
self.owner_alias = value
elif name == 'platform':
self.platform = value
elif name == 'name':
self.name = value
elif name == 'description':
self.description = value
elif name == 'rootDeviceType':
self.root_device_type = value
elif name == 'rootDeviceName':
self.root_device_name = value
else:
setattr(self, name, value)
def _update(self, updated):
self.__dict__.update(updated.__dict__)
def update(self, validate=False):
"""
Update the image's state information by making a call to fetch
the current image attributes from the service.
:type validate: bool
:param validate: By default, if EC2 returns no data about the
image the update method returns quietly. If
the validate param is True, however, it will
raise a ValueError exception if no data is
returned from EC2.
"""
rs = self.connection.get_all_images([self.id])
if len(rs) > 0:
img = rs[0]
if img.id == self.id:
self._update(img)
elif validate:
raise ValueError('%s is not a valid Image ID' % self.id)
return self.state
def run(self, min_count=1, max_count=1, key_name=None,
security_groups=None, user_data=None,
addressing_type=None, instance_type='m1.small', placement=None,
kernel_id=None, ramdisk_id=None,
monitoring_enabled=False, subnet_id=None,
block_device_map=None,
disable_api_termination=False,
instance_initiated_shutdown_behavior=None,
private_ip_address=None,
placement_group=None):
"""
Runs this instance.
:type min_count: int
:param min_count: The minimum number of instances to start
:type max_count: int
:param max_count: The maximum number of instances to start
:type key_name: string
:param key_name: The name of the keypair to run this instance with.
:type security_groups:
:param security_groups:
:type user_data:
:param user_data:
:type addressing_type:
:param daddressing_type:
:type instance_type: string
:param instance_type: The type of instance to run. Current choices are:
m1.small | m1.large | m1.xlarge | c1.medium |
c1.xlarge | m2.xlarge | m2.2xlarge |
m2.4xlarge | cc1.4xlarge
:type placement: string
:param placement: The availability zone in which to launch the instances
:type kernel_id: string
:param kernel_id: The ID of the kernel with which to launch the instances
:type ramdisk_id: string
:param ramdisk_id: The ID of the RAM disk with which to launch the instances
:type monitoring_enabled: bool
:param monitoring_enabled: Enable CloudWatch monitoring on the instance.
:type subnet_id: string
:param subnet_id: The subnet ID within which to launch the instances for VPC.
:type private_ip_address: string
:param private_ip_address: If you're using VPC, you can optionally use
this parameter to assign the instance a
specific available IP address from the
subnet (e.g., 10.0.0.25).
:type block_device_map: :class:`boto.ec2.blockdevicemapping.BlockDeviceMapping`
:param block_device_map: A BlockDeviceMapping data structure
describing the EBS volumes associated
with the Image.
:type disable_api_termination: bool
:param disable_api_termination: If True, the instances will be locked
and will not be able to be terminated
via the API.
:type instance_initiated_shutdown_behavior: string
:param instance_initiated_shutdown_behavior: Specifies whether the instance's
EBS volues are stopped (i.e. detached)
or terminated (i.e. deleted) when
the instance is shutdown by the
owner. Valid values are:
stop | terminate
:type placement_group: string
:param placement_group: If specified, this is the name of the placement
group in which the instance(s) will be launched.
:rtype: Reservation
:return: The :class:`boto.ec2.instance.Reservation` associated with the request for machines
"""
return self.connection.run_instances(self.id, min_count, max_count,
key_name, security_groups,
user_data, addressing_type,
instance_type, placement,
kernel_id, ramdisk_id,
monitoring_enabled, subnet_id,
block_device_map, disable_api_termination,
instance_initiated_shutdown_behavior,
private_ip_address,
placement_group)
def deregister(self):
return self.connection.deregister_image(self.id)
def get_launch_permissions(self):
img_attrs = self.connection.get_image_attribute(self.id,
'launchPermission')
return img_attrs.attrs
def set_launch_permissions(self, user_ids=None, group_names=None):
return self.connection.modify_image_attribute(self.id,
'launchPermission',
'add',
user_ids,
group_names)
def remove_launch_permissions(self, user_ids=None, group_names=None):
return self.connection.modify_image_attribute(self.id,
'launchPermission',
'remove',
user_ids,
group_names)
def reset_launch_attributes(self):
return self.connection.reset_image_attribute(self.id,
'launchPermission')
def get_kernel(self):
img_attrs =self.connection.get_image_attribute(self.id, 'kernel')
return img_attrs.kernel
def get_ramdisk(self):
img_attrs = self.connection.get_image_attribute(self.id, 'ramdisk')
return img_attrs.ramdisk
class ImageAttribute:
def __init__(self, parent=None):
self.name = None
self.kernel = None
self.ramdisk = None
self.attrs = {}
def startElement(self, name, attrs, connection):
if name == 'blockDeviceMapping':
self.attrs['block_device_mapping'] = BlockDeviceMapping()
return self.attrs['block_device_mapping']
else:
return None
def endElement(self, name, value, connection):
if name == 'launchPermission':
self.name = 'launch_permission'
elif name == 'group':
if self.attrs.has_key('groups'):
self.attrs['groups'].append(value)
else:
self.attrs['groups'] = [value]
elif name == 'userId':
if self.attrs.has_key('user_ids'):
self.attrs['user_ids'].append(value)
else:
self.attrs['user_ids'] = [value]
elif name == 'productCode':
if self.attrs.has_key('product_codes'):
self.attrs['product_codes'].append(value)
else:
self.attrs['product_codes'] = [value]
elif name == 'imageId':
self.image_id = value
elif name == 'kernel':
self.kernel = value
elif name == 'ramdisk':
self.ramdisk = value
else:
setattr(self, name, value)
| Python |
# Copyright (c) 2006-2010 Mitch Garnaat http://garnaat.org/
# Copyright (c) 2010, Eucalyptus Systems, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
"""
Represents an EC2 Object
"""
from boto.ec2.tag import TagSet
class EC2Object(object):
def __init__(self, connection=None):
self.connection = connection
if self.connection and hasattr(self.connection, 'region'):
self.region = connection.region
else:
self.region = None
def startElement(self, name, attrs, connection):
return None
def endElement(self, name, value, connection):
setattr(self, name, value)
class TaggedEC2Object(EC2Object):
"""
Any EC2 resource that can be tagged should be represented
by a Python object that subclasses this class. This class
has the mechanism in place to handle the tagSet element in
the Describe* responses. If tags are found, it will create
a TagSet object and allow it to parse and collect the tags
into a dict that is stored in the "tags" attribute of the
object.
"""
def __init__(self, connection=None):
EC2Object.__init__(self, connection)
self.tags = TagSet()
def startElement(self, name, attrs, connection):
if name == 'tagSet':
return self.tags
else:
return None
def add_tag(self, key, value=None):
"""
Add a tag to this object. Tag's are stored by AWS and can be used
to organize and filter resources. Adding a tag involves a round-trip
to the EC2 service.
:type key: str
:param key: The key or name of the tag being stored.
:type value: str
:param value: An optional value that can be stored with the tag.
"""
status = self.connection.create_tags([self.id], {key : value})
if self.tags is None:
self.tags = TagSet()
self.tags[key] = value
def remove_tag(self, key, value=None):
"""
Remove a tag from this object. Removing a tag involves a round-trip
to the EC2 service.
:type key: str
:param key: The key or name of the tag being stored.
:type value: str
:param value: An optional value that can be stored with the tag.
If a value is provided, it must match the value
currently stored in EC2. If not, the tag will not
be removed.
"""
if value:
tags = {key : value}
else:
tags = [key]
status = self.connection.delete_tags([self.id], tags)
if key in self.tags:
del self.tags[key]
| Python |
# Copyright (c) 2006-2009 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
from boto.ec2.ec2object import EC2Object
class ReservedInstancesOffering(EC2Object):
def __init__(self, connection=None, id=None, instance_type=None,
availability_zone=None, duration=None, fixed_price=None,
usage_price=None, description=None):
EC2Object.__init__(self, connection)
self.id = id
self.instance_type = instance_type
self.availability_zone = availability_zone
self.duration = duration
self.fixed_price = fixed_price
self.usage_price = usage_price
self.description = description
def __repr__(self):
return 'ReservedInstanceOffering:%s' % self.id
def startElement(self, name, attrs, connection):
return None
def endElement(self, name, value, connection):
if name == 'reservedInstancesOfferingId':
self.id = value
elif name == 'instanceType':
self.instance_type = value
elif name == 'availabilityZone':
self.availability_zone = value
elif name == 'duration':
self.duration = value
elif name == 'fixedPrice':
self.fixed_price = value
elif name == 'usagePrice':
self.usage_price = value
elif name == 'productDescription':
self.description = value
else:
setattr(self, name, value)
def describe(self):
print 'ID=%s' % self.id
print '\tInstance Type=%s' % self.instance_type
print '\tZone=%s' % self.availability_zone
print '\tDuration=%s' % self.duration
print '\tFixed Price=%s' % self.fixed_price
print '\tUsage Price=%s' % self.usage_price
print '\tDescription=%s' % self.description
def purchase(self, instance_count=1):
return self.connection.purchase_reserved_instance_offering(self.id, instance_count)
class ReservedInstance(ReservedInstancesOffering):
def __init__(self, connection=None, id=None, instance_type=None,
availability_zone=None, duration=None, fixed_price=None,
usage_price=None, description=None,
instance_count=None, state=None):
ReservedInstancesOffering.__init__(self, connection, id, instance_type,
availability_zone, duration, fixed_price,
usage_price, description)
self.instance_count = instance_count
self.state = state
def __repr__(self):
return 'ReservedInstance:%s' % self.id
def endElement(self, name, value, connection):
if name == 'reservedInstancesId':
self.id = value
if name == 'instanceCount':
self.instance_count = int(value)
elif name == 'state':
self.state = value
else:
ReservedInstancesOffering.endElement(self, name, value, connection)
| Python |
# Copyright (c) 2006-2008 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
class InstanceInfo(object):
"""
Represents an EC2 Instance status response from CloudWatch
"""
def __init__(self, connection=None, id=None, state=None):
self.connection = connection
self.id = id
self.state = state
def __repr__(self):
return 'InstanceInfo:%s' % self.id
def startElement(self, name, attrs, connection):
return None
def endElement(self, name, value, connection):
if name == 'instanceId' or name == 'InstanceId':
self.id = value
elif name == 'state':
self.state = value
else:
setattr(self, name, value)
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Michael Liao (askxuefeng@gmail.com)'
import unittest
from google.appengine.ext import webapp
from framework.web import Dispatcher
import interceptor
class Test(unittest.TestCase):
def init_get(self, url):
self._init_http('GET', url)
def init_post(self, url):
self._init_http('POST', url)
def _init_http(self, method, url):
self.request = webapp.Request.blank(url, environ={'REQUEST_METHOD' : method})
#self.request.set_status = lambda x: self.request.status
self.response = webapp.Response() #webob.Response(request=self.request))
self.dispatcher = Dispatcher()
self.dispatcher.initialize(self.request, self.response)
interceptor.intercept = lambda kw: None
if method=='GET':
self.dispatcher.get()
else:
self.dispatcher.post()
def test_home(self):
self.init_get('/http_test/')
self.assertEquals('<h1>Home</h1>', self.response.out.getvalue())
def test_hello(self):
self.init_post('/http_test/hello/world')
self.assertEquals('<p>Hello, world!</p>', self.response.out.getvalue())
self.init_post('/http_test/hello/Michael')
self.assertEquals('<p>Hello, Michael!</p>', self.response.out.getvalue())
def test_mapping(self):
self.init_get('/http_test/hi/Michael')
self.assertEquals('<p>Hi, Michael!</p>', self.response.out.getvalue())
self.init_post('/http_test/hi/Michael')
self.assertEquals('<p>Hi, Michael!</p>', self.response.out.getvalue())
def test_redirect(self):
self.init_get('/http_test/redirect/abc')
self.assertEquals('/about/abc', self.response.headers['Location'])
def test_args(self):
self.init_get('/http_test/args?q=Express%20Me&ref=&nl=en_US&nl=zh_CN')
self.assertEquals(u'Express Me, , None, [en_US, zh_CN]', self.response.out.getvalue())
if __name__ == '__main__':
#import sys;sys.argv = ['', 'Test.testName']
unittest.main()
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Michael Liao (askxuefeng@gmail.com)'
import time
import unittest
from framework import gaeunit
from framework import cache
class Test(gaeunit.GaeTestCase):
def test_cache(self):
key1 = 'key1'
key2 = 'key2'
self.assertEquals(None, cache.get(key1))
self.assertEquals(None, cache.get(key2))
cache.set(key1, 'abc')
cache.set(key2, ['x', 'y', 'z'])
self.assertEquals('abc', cache.get(key1))
self.assertEquals(['x', 'y', 'z'], cache.get(key2))
cache.delete(key1)
cache.delete(key2)
self.assertEquals(None, cache.get(key1))
self.assertEquals(None, cache.get(key2))
def test_incr(self):
key = 'inc'
self.assertEquals(None, cache.get(key))
cache.set(key, 123)
self.assertEquals(123, cache.get(key))
cache.incr(key)
self.assertEquals(124, cache.get(key))
cache.incr(key, 10)
self.assertEquals(134, cache.get(key))
def test_expr(self):
key = 'expr'
self.assertEquals(None, cache.get(key))
cache.set(key, u'ABC', 1)
self.assertEquals(u'ABC', cache.get(key))
time.sleep(1.2)
self.assertEquals(None, cache.get(key))
if __name__ == '__main__':
#import sys;sys.argv = ['', 'Test.testName']
unittest.main()
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Michael Liao (askxuefeng@gmail.com)'
import unittest
from framework import validator
class Test(unittest.TestCase):
def test_check_email(self):
valid_emails = (
'askxuefeng@gmail.com',
'michael.liao@liaoxuefeng.com',
'michael-liao@liaoxuefeng.com',
'michael_liao@liaoxuefeng.com',
'vip@example.com.cn',
'vip@example-example.com.cn',
'vip@vip-vip.example-example.com',
'99@1234567.com',
'cc_@123-456.com.fr',
u'me@example.com.fr',
)
invalid_emails = (
'ABC@example.COM',
'im@micro$oft.com',
'55-@@example.com',
'test@example.com.',
'test@vip.vip.example.com.cn',
'test(at)example.com',
'@example.com',
'test-user@cc',
12345,
)
for email in valid_emails:
self.assertEquals(None, validator.check_email(email))
for email in invalid_emails:
self.assertRaises(ValueError, lambda: validator.check_email(email))
def check_password(self):
self.assertEquals(None, validator.check_password(''))
self.assertEquals(None, validator.check_password('01234567890123456789012345678901'))
self.assertEquals(None, validator.check_password('012345678901234567890123456789aa'))
self.assertEquals(None, validator.check_password('aaaaaaaaaa00abcdefffffabcdefffff'))
self.assertEquals(None, validator.check_password(u'aaaaaaaaaa00abcdefffffabcdefffff'))
self.assertRaises(ValueError, lambda: validator.check_password('', allow_empty=False))
self.assertRaises(ValueError, lambda: validator.check_password(' '))
self.assertRaises(ValueError, lambda: validator.check_password('012345678901234567890123456789'))
self.assertRaises(ValueError, lambda: validator.check_password('AAaaaaaaaa00abcdefffffabcdefffff'))
self.assertRaises(ValueError, lambda: validator.check_password('aaaaaaaaaa--abcdefffffabcdefffff'))
if __name__ == '__main__':
#import sys;sys.argv = ['', 'Test.testName']
unittest.main()
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Michael Liao (askxuefeng@gmail.com)'
'''
Web MVC framework for AppEngine/WebOb.
'''
import re
import time
import urllib
import inspect
import logging
from google.appengine.ext import webapp
from framework import ApplicationError
from framework import view
import interceptor
import theme
COOKIE_EXPIRES_MIN = 86400
COOKIE_EXPIRES_MAX = 31536000
class WebError(ApplicationError):
pass
class NotFoundError(WebError):
pass
class Context(dict):
'''
Web application context as a dict.
'''
def __getattr__(self, name):
if self.has_key(name):
return self[name]
raise AttributeError('\'%s\' object has no attribute \'%s\'' % (self.__class__.__name__, name))
def __setattr__(self, name, value):
self[name] = value
class Dispatcher(webapp.RequestHandler):
'''
Entry point of MVC tier. It handles URL with '/appname/apppath'.
The app name of root URL ('/') is 'index'.
'''
def get(self):
'''
Override super.get to handle GET request.
'''
self._service('get')
def post(self):
'''
Override super.post to handle POST request.
'''
self._service('post')
def _service(self, method):
'''
Handle HTTP request of 'get' or 'post'.
Args:
method: string 'get' or 'post'.
'''
path = self.request.path;
if path=='/':
return self._handle_app(method, 'index', '/')
n = path.find('/', 1)
if n==(-1):
n = len(path)
appname = path[1:n]
apppath = path[len(appname)+1:]
if not apppath.startswith('/'):
apppath = '/' + apppath
return self._handle_app(method, appname, apppath)
def _handle_app(self, method, appname, apppath):
'''
Handle request with specific app.
Args:
method: string 'get' or 'post'.
appname: app name, the same as package name.
apppath: URL that excludes the appname in prefix. For example, apppath of '/blog/view/123' is '/view/123'.
'''
logging.info(r'Handle app "%s", path=%s' % (appname, apppath))
for func in self._get_mapping(method, appname):
r = func.matches(apppath)
if r is not None:
# decode url parameter:
args = [urllib.unquote(arg) for arg in r]
# prepare environment as varkw:
kw = {
'environ' : self.request.environ,
'headers' : self.request.headers,
'cookies' : self.request.cookies,
'request' : self.request,
'response' : self.response,
'context' : Context(
get_argument=lambda argument_name, default_value=None: self.request.get(argument_name, default_value),
get_arguments=lambda argument_name: self.request.get_all(argument_name),
arguments=lambda: self.request.arguments(),
get_cookie=lambda name: self._get_cookie(name),
set_cookie=lambda name, value, max_age=-1, path='/', secure=False: self._set_cookie(name, value, max_age, path, secure),
delete_cookie=lambda name, path='/', secure=False: self._set_cookie(name, 'deleted', 0, path, secure)
)
}
# global interceptor:
interceptor.intercept(kw)
# app interceptor:
app_inter = __import__(appname, fromlist=['interceptor']).interceptor
app_inter.intercept(kw)
if func.has_varkw():
result = func(*args, **kw)
else:
result = func(*args)
return self._response(kw, appname, result);
# 404 error:
self._error(404)
def _response(self, kw, appname, result):
'''
Handle result and send response.
Args:
appname: app name.
result: result object that can be None, basestring or dict.
'''
if result is None:
return
if isinstance(result, basestring):
return self._render_string(result)
if isinstance(result, dict):
return self._render_template(kw, appname, result)
def _render_template(self, kw, appname, model):
'''
Render a template using the given model.
Args:
model: model as dict.
'''
use_theme = model.get('__theme__', False)==True
if use_theme:
t = theme.render(appname, model, **kw)
else:
t = view.render(appname, model)
content_type = model.get('__content_type__')
if content_type:
self.response.content_type = content_type
self.response.out.write(t)
def _render_string(self, result):
'''
Render string.
Args:
result: string treated as HTML or special content like 'redirect:/'.
'''
if result.startswith('redirect:'):
return self._error(301, result[9:])
if result.startswith('json:'):
self.request.headers['Content-Type'] = 'application/json'
self.response.out.write(result[5:])
return
self.response.out.write(result)
def _get_mapping(self, method, appname):
'''
Get list of functions that matches the method and appname.
Args:
method: 'get' or 'post'.
appname: name of app.
Returns:
dict, url as key, function as value.
'''
attr = 'support_' + method
mod = __import__(appname, fromlist=['controller']).controller
all = [getattr(mod, f) for f in dir(mod)]
return [func for func in all if callable(func) and getattr(func, attr, False)]
def _error(self, code, extra=None):
'''
Send HTTP error response.
Args:
code: HTTP code as int.
extra: additional message based on code.
'''
self.response.set_status(code)
if code==301 or code==302:
self.response.headers['Location'] = extra
return
if code==404:
self.response.out.write(extra or '404 Not Found')
return
if extra:
self.response.out.write(extra)
def _set_cookie(self, name, value, max_age=-1, path='/', secure=False):
'''
Set cookie by name, value, max_age, path and secure.
Args:
name: cookie name.
value: cookie value.
max_age: cookie age in seconds, if 0, cookie will be deleted immediately, if <0, ignored. Default to -1.
path: cookie path, default to '/'.
secure: if cookie is secure, default to False.
'''
cookie = name + '=' + value + '; path=' + path
if max_age>=0:
cookie += time.strftime('; expires=%a, %d-%b-%Y %H:%M:%S GMT', time.gmtime(time.time() + max_age))
if secure:
cookie += '; secure'
self.response.headers.add_header('Set-Cookie', cookie)
def _get_cookie(self, name):
'''
Get cookie value of specified cookie name.
Args:
name: cookie name.
Returns:
Cookie value.
'''
if name in self.request.cookies:
return self.request.cookies[name]
return None
def handle_exception(self, exception, debug_mode):
logging.exception('Unhandled exception caught by framework.web.Dispatcher.handle_exception()')
html = r'''<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>An error occurred</title>
</head>
<body style="font-family: 'Helvetica Neue', Arial, Helvetica, sans-serif;">
<div style="margin:3px auto; width:640px;">
<div style="padding:12px 6px; border-bottom:solid 1px #ccc">
<a href="http://www.expressme.org/" target="_blank"><img src="/static/image/expressme.gif" width="326" height="60" border="0" /></a>
</div>
<div style="padding:0px 12px">
<h3 style="line-height:40px">We are sorry but an unexpected error occurred...</h3>
</div>
<div style="padding:12px">%s: %s</div>
<div style="padding:12px">See logs for more details.</div>
<div style="line-height:40px; text-align:center; border-top:solid 1px #ccc"><a href="http://www.expressme.org/" target="_blank">ExpressMe</a> copyright©2010, all rights reserved.</div>
</div>
</body>
</html>
''' % (exception.__class__.__name__, exception.message or '(no message)')
self.response.out.write(html)
def _matches(pattern, raw_mapping, url):
'''
Return match result by given pattern and url.
Args:
pattern: pattern as string.
raw_mapping: True if using raw regular expression, otherwise False.
url: to-be-tested url.
Returns:
A tuple as matched result (maybe empty tuple), or None if not matched.
'''
if raw_mapping:
p = re.compile('^' + pattern + '$')
else:
p = re.compile('^' + re.escape(pattern).replace(r'\$', '([^/]*)') + '$')
m = p.match(url)
if m is not None:
return m.groups()
return None
def _has_varkw(func):
'''
Return True if function has kw args. False otherwise.
Args:
func: Function reference.
Returns:
True or False.
'''
# get args spec: (arg_names, varargs, varkw, defaults)
argsspec = inspect.getargspec(func)
return argsspec[2] is not None
def get(pattern):
'''
decorator of @get() that support get only
Args:
pattern: string like '/$/$.html', default value: None
Returns:
decorated function.
'''
def execute(f):
def _wrapper(*args, **kw):
return f(*args, **kw)
_wrapper.pattern = pattern
_wrapper.support_get = True
_wrapper.support_post = False
_wrapper.raw_mapping = False
_wrapper.__name__ = f.__name__
_wrapper.matches = lambda url: _matches(_wrapper.pattern, _wrapper.raw_mapping, url)
_wrapper.has_varkw = lambda: _has_varkw(f)
return _wrapper
return execute
def post(pattern):
'''
decorator of @post() that support post only
Args:
pattern: string like '/$/$.html', default value: None
Returns:
decorated function.
'''
def execute(f):
def wrapper(*args, **kw):
return f(*args, **kw)
wrapper.pattern = pattern
wrapper.support_get = False
wrapper.support_post = True
wrapper.raw_mapping = False
wrapper.__name__ = f.__name__
wrapper.matches = lambda url: _matches(wrapper.pattern, wrapper.raw_mapping, url)
wrapper.has_varkw = lambda: _has_varkw(f)
return wrapper
return execute
def mapping(pattern):
'''
decorator of @mapping() that support get and post
Args:
pattern: string like '/$/$.html', default value: None
Returns:
decorated function.
'''
def execute(f):
def wrapper(*args, **kw):
return f(*args, **kw)
wrapper.pattern = pattern
wrapper.support_get = True
wrapper.support_post = True
wrapper.raw_mapping = False
wrapper.__name__ = f.__name__
wrapper.matches = lambda url: _matches(wrapper.pattern, wrapper.raw_mapping, url)
wrapper.has_varkw = lambda: _has_varkw(f)
return wrapper
return execute
def raw_mapping(pattern):
'''
decorator of @raw_mapping() that support get and post.
WARNING: for regular express expert only!
The regular expression MUST NOT start with '^' and end with '$'.
Args:
url: regular expression string.
Returns:
decorated function.
'''
def execute(f):
def wrapper(*args, **kw):
return f(*args, **kw)
wrapper.pattern = pattern
wrapper.support_get = True
wrapper.support_post = True
wrapper.raw_mapping = True
wrapper.__name__ = f.__name__
wrapper.matches = lambda url: _matches(wrapper.pattern, wrapper.raw_mapping, url)
wrapper.has_varkw = lambda: _has_varkw(f)
return wrapper
return execute
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Michael Liao (askxuefeng@gmail.com)'
'''
Validator API.
'''
import types
import re
REGEX_EMAIL = re.compile(r'^[a-z0-9\.\_\-]+\@([a-z0-9\-]+\.){1,3}[a-z]{2,6}$')
REGEX_MD5 = re.compile(r'^[a-f0-9]{32}$')
def check_email(email):
'''
Check email if it is validated. Upper-case characters are NOT allowed.
Args:
email: email address for test.
Raises:
ValueError if not a valid email.
'''
check_str(email, 'email', False)
if REGEX_EMAIL.match(email) is None:
raise ValueError('%s is not an email' % email)
def check_str(str, name='argument', allow_empty=True):
'''
Check if it is a string.
Args:
str: object for test.
Raises:
ValueError if not a string, or too long.
'''
if not isinstance(str, types.StringTypes):
raise ValueError('%s is not a string' % name)
if not allow_empty and str=='':
raise ValueError('%s is empty' % name)
if len(str)>500:
raise ValueError('%s is too long (maximum to 500 characters)' % name)
def check_text(text, allow_empty=True):
'''
Check if text is in range.
Args:
text: a long str.
Raises:
ValueError if not a string, or too long.
'''
if not isinstance(text, types.StringTypes):
raise ValueError('not a text')
if not allow_empty and text=='':
raise ValueError('text is empty')
if len(text)>1048576:
raise ValueError('text is too long (maximum to 1048576 characters)')
def check_password(password, allow_empty=True):
'''
Check password if it is validated.
Args:
password: password for test.
allow_empty: true if skip empty password.
Raises:
ValueError if not a valid password.
'''
check_str(password, 'password', allow_empty)
if (not allow_empty) and password and (REGEX_MD5.match(password) is None):
raise ValueError('%s is not a password' % password)
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Michael Liao (askxuefeng@gmail.com)'
import unittest
from framework.gaeunit import GaeTestCase
from framework import store
class Test(GaeTestCase):
def test_set_setting(self):
name = 'email'
value = 'guest@example.com'
self.assertTrue(store.get_setting(name) is None)
self.assertEquals('default@default.com', store.get_setting(name, store.DEFAULT_GROUP, 'default@default.com'))
store.set_setting(name, value)
self.assertEquals(value, store.get_setting(name))
name2 = 'url'
value2 = 'http://guest.example.com'
store.set_setting(name2, value2)
# get settings as dict:
d = store.get_settings()
self.assertTrue(name in d)
self.assertTrue(name2 in d)
self.assertEquals(value, d[name])
self.assertEquals(value2, d[name2])
def test_delete_settings(self):
group = 'test_grp'
for i in range(10):
store.set_setting('k%s' % i, 'v%s' % i, group)
# get settings:
ss = store.get_settings(group)
for i in range(10):
self.assertTrue(('k%s' % i) in ss)
# delete settings:
store.delete_settings(group)
# get settings again:
ss = store.get_settings(group)
self.assertEquals(0, len(ss.keys()))
def test_get_settings(self):
group = 'test_grp'
for i in range(10):
store.set_setting('key-%d' % i, 'value-%d' % i, group)
ss = store.get_settings(group)
for i in range(10):
self.assertTrue('key-%d' % i in ss)
self.assertEquals('value-%d' % i, ss['key-%d' % i])
def test_error(self):
self.assertRaises(ValueError, lambda: store.set_setting(123, 'abc'))
self.assertRaises(ValueError, lambda: store.set_setting('abc', 123))
self.assertRaises(ValueError, lambda: store.get_setting(123))
self.assertRaises(ValueError, lambda: store.get_settings(9.99))
def test_delete_setting(self):
name = 'spaceship'
value = 'NCC-74656'
group = 'USS'
store.set_setting(name, value, group)
self.assertEquals('', store.get_setting(name, 'NON-USS', ''))
self.assertEquals(value, store.get_setting(name, group, ''))
store.delete_setting(name, group)
self.assertEquals(None, store.get_setting(name, group))
if __name__ == '__main__':
#import sys;sys.argv = ['', 'Test.testName']
unittest.main()
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Michael Liao (askxuefeng@gmail.com)'
'''
Base test case for Google AppEngine.
'''
import os
import sys
import unittest
def _lookup_gae_home():
'''
Return GAE home. Lookup order:
1. Environment variable 'GAE_HOME'.
2. Default path depends on OS.
'''
if 'GAE_HOME' in os.environ:
return _check_or_raise(os.environ['GAE_HOME'])
if os.name=='nt':
return _check_or_raise(r'C:\Program Files\Google\google_appengine')
if os.name=='posix':
import getpass
return _check_or_raise('/home/%s/google_appengine' % getpass.getuser())
def _get_extra_path(gae_home):
return [
gae_home,
os.path.join(gae_home, 'google', 'appengine', 'api'),
os.path.join(gae_home, 'google', 'appengine', 'ext'),
os.path.join(gae_home, 'lib', 'yaml', 'lib'),
os.path.join(gae_home, 'lib', 'webob'),
]
def _check_or_raise(path):
if not os.path.isdir(path):
raise IOError('GAE_HOME is undefined or invalid.')
return path
# init GAE env here:
def init_once():
gae_home = _lookup_gae_home()
if not gae_home in sys.path:
sys.path.extend(_get_extra_path(_lookup_gae_home()))
init_once()
class GaeTestCase(unittest.TestCase):
'''
Base GAE TestCase that prepare all GAE local environment for test.
'''
def setUp(self):
super(GaeTestCase, self).setUp()
from google.appengine.api import apiproxy_stub_map
yaml = os.path.join(os.path.split(os.path.split(__file__)[0])[0], 'app.yaml')
appid = _get_app_id(yaml)
_setup_env(appid)
apiproxy_stub_map.apiproxy = _get_dev_apiproxy(appid)
def _get_app_id(app_yaml_file):
'''
Get application id from yaml file.
Args:
app_yaml_file: full path of app.yaml file.
Returns:
appid as str.
'''
f = None
try:
f = open(app_yaml_file, 'r')
for line in f:
s = line.strip()
if s.startswith('application:'):
return s[12:].strip()
finally:
if f is not None:
f.close()
def _setup_env(appid):
os.environ['APPLICATION_ID'] = appid
os.environ['AUTH_DOMAIN'] = 'example.com'
os.environ['USER_EMAIL'] = 'test@example.com'
def _get_dev_apiproxy(appid):
from google.appengine.api import apiproxy_stub_map
from google.appengine.api import datastore_file_stub
from google.appengine.api import user_service_stub
from google.appengine.api import mail_stub
from google.appengine.api import urlfetch_stub
from google.appengine.api.memcache import memcache_stub
apiproxy = apiproxy_stub_map.APIProxyStubMap()
apiproxy.RegisterStub('datastore_v3', datastore_file_stub.DatastoreFileStub(appid, None, None))
apiproxy.RegisterStub('user', user_service_stub.UserServiceStub())
apiproxy.RegisterStub('urlfetch', urlfetch_stub.URLFetchServiceStub())
apiproxy.RegisterStub('mail', mail_stub.MailServiceStub())
apiproxy.RegisterStub('memcache', memcache_stub.MemcacheServiceStub())
return apiproxy
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Michael Liao (askxuefeng@gmail.com)'
import unittest
from framework import encode
class Test(unittest.TestCase):
def test_encode_html(self):
self.assertEquals('abc', encode.encode_html('abc'))
self.assertEquals('<h1>', encode.encode_html('<h1>'))
self.assertEquals('A&B&C', encode.encode_html('A&B&C'))
self.assertEquals('"Hi!"', encode.encode_html('"Hi!"'))
self.assertEquals('abc', encode.encode_html(u'abc'))
self.assertEquals('<h1>', encode.encode_html(u'<h1>'))
self.assertEquals('A&B&C', encode.encode_html(u'A&B&C'))
self.assertEquals('"Hi!"', encode.encode_html(u'"Hi!"'))
def test_encode_json(self):
self.assertEquals('abc', encode.encode_json('abc'))
self.assertEquals(r'abc\r\nxyz', encode.encode_json('abc\r\nxyz'))
self.assertEquals(r'hello, \"world\"', encode.encode_json('hello, "world"'))
if __name__ == '__main__':
#import sys;sys.argv = ['', 'Test.testName']
unittest.main()
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Michael Liao (askxuefeng@gmail.com)'
import unittest
from google.appengine.ext import db as db
from framework.gaeunit import GaeTestCase
from framework.store import BaseModel
class TestModel(BaseModel):
name = db.StringProperty()
class Test(GaeTestCase):
def test_raw_field(self):
input = 'Howto & Style'
m = TestModel(name=input)
self.assertEquals(input, m.name)
self.assertEquals(input, m.name__raw__)
self.assertRaises(AttributeError, lambda: m.location)
self.assertRaises(AttributeError, lambda: m.location__raw__)
delta = m.creation_date - m.modified_date
self.assertEquals(0, delta.days)
self.assertEquals(0, delta.seconds)
self.assertTrue(m.id is None)
m.put()
self.assertFalse(m.id is None)
self.assertEquals(m.id, str(m.key()))
if __name__ == '__main__':
#import sys;sys.argv = ['', 'Test.testName']
unittest.main()
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Michael Liao (askxuefeng@gmail.com)'
import unittest
from framework.gaeunit import GaeTestCase
from framework import store
class Test(GaeTestCase):
def test_create_comment(self):
ref = 'key123456789'
email = 'guest@example.com'
c = store.create_comment(ref, email, 'Guest', 'Hello!', '127.0.0.1', True)
self.assertTrue(c.approval)
c = store.create_comment(ref, email, 'Guest', 'Hi!', '127.0.0.1', False)
self.assertFalse(c.approval)
def test_get_comments(self):
ref = 'key-ABC-999-KDE-010-USS'
email = 'guest-%s@example.com'
for i in range(10):
store.create_comment(ref, email % i, 'Guest-%s' % i, 'No. %s' % i, '127.0.0.1', True)
all = store.get_all_comments(ref)
self.assertEquals(10, len(all))
for i in range(10):
self.assertEquals(email % i, all[i].email)
def test_delete_comment(self):
ref = 'NCC-74656'
email = 'guest@example.com'
c = store.create_comment(ref, email, 'Guest', 'Hello!', '127.0.0.1', True)
self.assertEquals(email, c.email)
# delete by reference key:
store.delete_all_comments(ref)
# comment still here:
cs = store.get_all_comments(ref)
self.assertEquals(1, len(cs))
self.assertEquals(c.id, cs[0].id)
# cron-delete is a real deletion:
store.cron_delete_all_comments(ref)
self.assertEquals(0, len(store.get_all_comments(ref)))
if __name__ == '__main__':
#import sys;sys.argv = ['', 'Test.testName']
unittest.main()
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Michael Liao (askxuefeng@gmail.com)'
import unittest
import threading
from framework import gaeunit
from framework import store
class CounterThread(threading.Thread):
'''
Test thread for updating counter.
'''
def __init__(self, name, delta=1):
super(CounterThread, self).__init__()
self.name = name
self.delta = delta
def run(self):
store.incr_count(self.name, self.delta)
class Test(gaeunit.GaeTestCase):
def test_new_counter(self):
name = 'test'
self.assertEquals(0, store.get_count(name))
for i in range(10):
store.incr_count(name)
self.assertEquals(10, store.get_count(name))
for i in range(10):
store.incr_count(name, 100)
self.assertEquals(1010, store.get_count(name))
def test_incr_shards(self):
name = 'incr'
self.assertEquals(0, store.get_count(name))
for i in range(10):
store.incr_count(name)
store.incr_counter_shards(name, 100)
self.assertEquals(10, store.get_count(name))
for i in range(10):
store.incr_count(name, 100)
self.assertEquals(1010, store.get_count(name))
def test_multithreads(self):
name = 'multi'
self.assertEquals(0, store.get_count(name))
ts = []
for i in range(1, 10):
ts.append(CounterThread(name, i))
for t in ts:
t.start()
for t in ts:
t.join()
self.assertEquals(1+2+3+4+5+6+7+8+9, store.get_count(name))
if __name__ == '__main__':
#import sys;sys.argv = ['', 'Test.testName']
unittest.main()
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Michael Liao (askxuefeng@gmail.com)'
import unittest
from framework.web import _matches
from framework.web import get
from framework.web import post
from framework.web import raw_mapping
@get('/say')
def say():
return 'hello'
@get('/product')
def get_product():
return 'product'
@post('/create_order')
def create_order():
return 'order'
@get('/$/$')
def get_category(manufacturer, category):
return '%s,%s' % (manufacturer, category)
@raw_mapping('/(.+)/([0-9]+)')
def save_category(name, id):
return '%s-%s' % (name, id)
class Test(unittest.TestCase):
def test_matches(self):
# matched, not raw mapping:
self.assertEquals((), _matches('/', False, '/'))
self.assertEquals((), _matches('/abc', False, '/abc'))
self.assertEquals((), _matches('/a/b/c', False, '/a/b/c'))
self.assertEquals((), _matches('/a/', False, '/a/'))
self.assertEquals(('123',), _matches('/$', False, '/123'))
self.assertEquals(('abc',), _matches('/$', False, '/abc'))
self.assertEquals(('xyz',), _matches('/$/', False, '/xyz/'))
self.assertEquals(('a', 'b', 'c'), _matches('/$/$/$/', False, '/a/b/c/'))
self.assertEquals(('a', 'b', 'c'), _matches('/$-$-$/', False, '/a-b-c/'))
self.assertEquals(('a', 'b', 'c'), _matches('/pro-$/$/$/', False, '/pro-a/b/c/'))
# not matched, not raw mapping:
self.assertEquals(None, _matches('/', False, ''))
self.assertEquals(None, _matches('/', False, '/abc'))
self.assertEquals(None, _matches('/$', False, '/abc/'))
self.assertEquals(None, _matches('/$/$/', False, '/a/b/c/'))
self.assertEquals(None, _matches('/abc-$', False, '/abc.xyz'))
# matched, raw mapping:
self.assertEquals((), _matches('/', True, '/'))
self.assertEquals(('abc',), _matches('/(.*)', True, '/abc'))
self.assertEquals(('abc/xyz',), _matches('/(.*)', True, '/abc/xyz'))
self.assertEquals(('abc', 'xyz'), _matches('/(.*)/(.*)', True, '/abc/xyz'))
self.assertEquals(('a', 'b', ''), _matches('/(.+)/(.+)/(.*)', True, '/a/b/'))
# not matched, raw mapping:
self.assertEquals(None, _matches('/', True, ''))
self.assertEquals(None, _matches('/abc(.+)', True, '/abc'))
self.assertEquals(None, _matches('/(.+)/(.+)/(.+)', True, '/a/b/'))
def test_say(self):
f = say
self.assertTrue(f.support_get)
self.assertFalse(f.support_post)
self.assertFalse(f.raw_mapping)
self.assertEquals('/say', f.pattern)
self.assertEquals('say', f.__name__)
self.assertEquals('hello', f())
self.assertEquals((), f.matches('/say'))
self.assertEquals(None, f.matches('/say/'))
def test_get_product(self):
f = get_product
self.assertTrue(f.support_get)
self.assertFalse(f.support_post)
self.assertFalse(f.raw_mapping)
self.assertEquals('/product', f.pattern)
self.assertEquals('get_product', f.__name__)
self.assertEquals('product', f())
self.assertEquals((), f.matches('/product'))
self.assertEquals(None, f.matches('/product/'))
def test_create_order(self):
f = create_order
self.assertFalse(f.support_get)
self.assertTrue(f.support_post)
self.assertFalse(f.raw_mapping)
self.assertEquals('/create_order', f.pattern)
self.assertEquals('create_order', f.__name__)
self.assertEquals('order', f())
self.assertEquals((), f.matches('/create_order'))
self.assertEquals(None, f.matches('/create_order/'))
def test_get_category(self):
f = get_category
self.assertTrue(f.support_get)
self.assertFalse(f.support_post)
self.assertFalse(f.raw_mapping)
self.assertEquals('/$/$', f.pattern)
self.assertEquals('a,b', f('a', 'b'))
self.assertEquals('get_category', f.__name__)
self.assertEquals(('a', 'b'), f.matches('/a/b'))
self.assertEquals(None, f.matches('/a/b/'))
def test_save_category(self):
f = save_category
self.assertTrue(f.support_get)
self.assertTrue(f.support_post)
self.assertTrue(f.raw_mapping)
self.assertEquals('/(.+)/([0-9]+)', f.pattern)
self.assertEquals('a-b', f('a', 'b'))
self.assertEquals('save_category', f.__name__)
self.assertEquals(('a', '123'), f.matches('/a/123'))
self.assertEquals(None, f.matches('/a/b'))
self.assertEquals(None, f.matches('//123'))
if __name__ == '__main__':
#import sys;sys.argv = ['', 'Test.testName']
unittest.main()
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Michael Liao (askxuefeng@gmail.com)'
import hashlib
import unittest
from framework.gaeunit import GaeTestCase
from framework import ValidationError
from framework import store
class Test(GaeTestCase):
def test_create_and_get_user(self):
email = 'admin@expressme.org'
password = hashlib.md5('admin-password').hexdigest()
nicename = 'Admin'
admin = store.create_user(store.ROLE_ADMINISTRATOR, email, password, nicename)
self.assertFalse(admin is None)
self.assertEquals(store.ROLE_ADMINISTRATOR, admin.role)
self.assertEquals(email, admin.email)
self.assertEquals(password, admin.password)
self.assertEquals(nicename, admin.nicename)
# get by email:
u = store.get_user_by_email(email)
self.assertFalse(u is None)
self.assertEquals(store.ROLE_ADMINISTRATOR, u.role)
self.assertEquals(email, u.email)
self.assertEquals(password, u.password)
self.assertEquals(nicename, u.nicename)
# get by key:
u = store.get_user_by_key(admin.id)
self.assertFalse(u is None)
self.assertEquals(store.ROLE_ADMINISTRATOR, u.role)
self.assertEquals(email, u.email)
self.assertEquals(password, u.password)
self.assertEquals(nicename, u.nicename)
# load non-exist user:
u = store.get_user_by_email('nobody@expressme.org')
self.assertTrue(u is None)
def test_create_duplicate_users(self):
email = 'howto@expressme.org'
password = hashlib.md5('random-password').hexdigest()
bob1 = store.create_user(store.ROLE_EDITOR, email, password, 'Bob1')
self.assertFalse(bob1 is None)
func = lambda: store.create_user(store.ROLE_CONTRIBUTOR, email, password, 'Bob2')
self.assertRaises(ValidationError, func)
self.assertRaises(ValidationError, func)
# get by email, should be only one: Bob1
us = store.User.all().filter('email =', email).fetch(100)
self.assertEquals(1, len(us))
u = store.get_user_by_email(email)
self.assertEquals(store.ROLE_EDITOR, u.role)
self.assertEquals(email, u.email)
self.assertEquals('Bob1', u.nicename)
if __name__ == '__main__':
#import sys;sys.argv = ['', 'Test.testName']
unittest.main()
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Michael Liao (askxuefeng@gmail.com)'
'''
Simple anti-bot API for Google reCaptcha service.
'''
import logging
import urllib
RECAPTCHA_URL = 'http://www.google.com/recaptcha/api/verify'
TEST_DOMAIN = 'localhost'
TEST_PUB_KEY = '6LeAOr0SAAAAALQX_KWv_JhJpXrHNE5Xo0Z-UJwe'
TEST_PRI_KEY = '6LeAOr0SAAAAAAftuAAf6hI7McUzejjY2qLy4ukC'
def _encode(s):
if isinstance(s, unicode):
return s.encode('utf-8')
return s
def get_public_key():
return TEST_PUB_KEY
def get_private_key():
return TEST_PRI_KEY
def verify_captcha(recaptcha_challenge_field, recaptcha_response_field, private_key, remote_ip):
if not (recaptcha_challenge_field and recaptcha_response_field and private_key):
return False, 'Invalid captcha data'
params = urllib.urlencode ({
'privatekey': _encode(private_key),
'remoteip' : _encode(remote_ip),
'challenge': _encode(recaptcha_challenge_field),
'response' : _encode(recaptcha_response_field),
})
f = None
try:
f = urllib.urlopen(RECAPTCHA_URL, params)
resp = f.read()
logging.info('Get recaptcha result: %s' % resp)
if resp.splitlines()[0]=='true':
return True, 'Correct captcha'
return False, 'Incorrect captcha words'
except:
logging.exception('Error when open url: %s' % RECAPTCHA_URL)
return False, 'Network error'
finally:
if f is not None:
f.close()
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Michael Liao (askxuefeng@gmail.com)'
'''
Encoding utils for HTML, XML, JavaScript, etc.
'''
def encode_html(str):
'''
Encode html.
Args:
str: string to encode.
Returns:
str encoded with utf-8.
'''
if isinstance(str, unicode):
str = str.encode('utf-8')
return str.replace('&', '&') \
.replace('<', '<') \
.replace('>', '>') \
.replace('"', '"')
def encode_json(str):
'''
Encode json.
Args:
str: string to encode.
Returns:
str encoded with utf-8.
'''
if isinstance(str, unicode):
str = str.encode('utf-8')
return str.replace('\\', r'\\') \
.replace('"', r'\"') \
.replace('/', r'\/') \
.replace('\n', r'\n') \
.replace('\r', r'\r')
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Michael Liao (askxuefeng@gmail.com)'
'''
All storage-related class and functions.
'''
import datetime
import random
from google.appengine.ext import db as db
from framework import cache
from framework import ValidationError
from framework import validator
class BaseModel(db.Model):
'''
Base model for storage which has basic properties.
'''
creation_date = db.DateTimeProperty(required=True, auto_now_add=True)
modified_date = db.DateTimeProperty(required=True, auto_now=True)
def __getattr__(self, name):
if name=='id':
try:
return str(self.key())
except db.NotSavedError:
return None
if name.endswith('__raw__'):
return getattr(self, name[:-7])
raise AttributeError('\'%s\' object has no attribute \'%s\'' % (self.__class__.__name__, name))
# def __str__(self):
# buffer = []
# attr_names = dir(self)
# for attr_name in attr_names:
# if not attr_name.startswith('__') and not attr_name.endswith('__'):
# attr_value = getattr(self, attr_name)
# buffer.append('%s=%s' % (attr_name, str(attr_value),))
# return '%s (%s)' % (self.__class__.__name__, ', '.join(buffer))
#
# __repr__ = __str__
MAX_METADATA = 100
def query_metadata(ref, name=None):
'''
Query meta data of specific reference (key of Model).
Args:
ref: key of owner object.
name: mata data name, default to None.
Returns:
dict contains meta data name-value pairs. If name is not None, all names will return.
'''
query = MetaData.all().filter('ref =', ref)
if name is not None:
query.filter('name =', name)
map = {}
for meta in query.fetch(MAX_METADATA):
map[str(meta.name)] = meta.value
return map
def save_metadata(ref, **kw):
'''
Save new meta data for specific reference.
'''
for name, value in kw:
MetaData(ref=ref, name=name, value=value).put()
def delete_metadata(ref, names):
'''
Delete meta data by names.
'''
for meta in MetaData.all().filter('ref =', ref).fetch(MAX_METADATA):
if str(meta.name) in names:
meta.delete()
class MetaData(db.Model):
'''
Store meta data such as web site, twitter, settings, etc.
'''
ref = db.StringProperty(required=True)
name = db.StringProperty(required=True)
value = db.StringProperty(required=True)
###############################################################################
# User operation
###############################################################################
# role constants:
ROLE_ADMINISTRATOR = 0
ROLE_EDITOR = 10
ROLE_AUTHOR = 20
ROLE_CONTRIBUTOR = 30
ROLE_SUBSCRIBER = 40
ROLES = (ROLE_ADMINISTRATOR, ROLE_EDITOR, ROLE_AUTHOR, ROLE_CONTRIBUTOR, ROLE_SUBSCRIBER)
ROLE_NAMES = ('Administrator', 'Editor', 'Author', 'Contributor', 'Subscriber')
class UserAlreadyExistError(ValidationError):
pass
def get_user_by_key(key):
'''
Get user by key, or None if not found.
'''
return User.get(key)
def lock_or_unlock_users(keys, lock=True):
'''
Lock users by given keys or a single key.
Args:
keys: a list of str-key, or a single str-key.
Returns:
Number of users updated.
'''
users = []
if not isinstance(keys, list):
keys = [keys]
for key in keys:
user = get_user_by_key(key)
if (user is not None) and (lock!=user.locked) and (not user.is_admin()):
user.locked = lock
users.append(user)
for user in users:
user.put()
return len(users)
def get_user_by_email(email):
'''
Get user by email, or None if not found.
'''
return User.get_by_key_name(email)
def get_users(limit, cursor=None, role=None, order='-creation_date'):
'''
Get next users with current cursor.
Args:
limit: limit of returned users.
cursor: current cursor position, or None if no cursor.
role: filter by role, default to None (do not filter by role).
order: default to '-creation_date'.
Returns:
results as list and cursor for next fetch position, or None if reach the end of results.
'''
q = User.all()
if role is not None:
q = q.filter('role =', role)
q = q.order(order)
result, next_cursor = get_by_cursor(q, cursor, limit)
if not has_more(q, next_cursor):
next_cursor = None
return result, next_cursor
def create_user(role, email, password, nicename):
if role not in ROLES:
raise ValueError('invalid role.')
validator.check_email(email)
validator.check_password(password)
def tx():
if User.get_by_key_name(email) is None:
u = User(key_name=email, role=role, email=email, password=password, nicename=nicename)
u.put()
return u
return None
user = db.run_in_transaction(tx)
if user is None:
raise UserAlreadyExistError('User create failed.')
return user
def get_user_role_name(role):
'''
Get role display name by role number.
Args:
role: role number, constants defined as USER_ROLE_XXX.
Returns:
Role name as string.
'''
return ROLE_NAMES[role//10]
class User(BaseModel):
'''
Store a single user
'''
role = db.IntegerProperty(required=True, default=ROLE_SUBSCRIBER)
email = db.EmailProperty(required=True)
password = db.StringProperty(default='')
nicename = db.StringProperty(default='')
locked = db.BooleanProperty(required=True, default=False)
def is_admin(self):
return self.role==ROLE_ADMINISTRATOR
def get_role_name(self):
return get_user_role_name(self.role)
###############################################################################
# Counter operation
###############################################################################
CACHE_KEY_PREFIX = '_sharded_counter_'
def get_count(name):
'''
Retrieve the value for a given sharded counter.
Args:
name: the name of the counter
Returns:
Integer value
'''
total = cache.get(CACHE_KEY_PREFIX + name)
if total is None:
total = 0
for counter in ShardedCounter.all().filter('name =', name).fetch(1000):
total += counter.count
cache.set(CACHE_KEY_PREFIX + name, str(total))
return total
return int(total)
def incr_count(name, delta=1):
'''
Increment the value for a given sharded counter.
Args:
name: the name of the counter
'''
config = ShardedCounterConfig.get_or_insert(name, name=name)
def tx():
index = random.randint(0, config.shards-1)
shard_name = name + str(index)
counter = ShardedCounter.get_by_key_name(shard_name)
if counter is None:
counter = ShardedCounter(key_name=shard_name, name=name)
counter.count += delta
counter.put()
db.run_in_transaction(tx)
cache.incr(CACHE_KEY_PREFIX + name, delta=delta)
def incr_counter_shards(name, num):
'''
Increase the number of shards for a given sharded counter.
Will never decrease the number of shards.
Args:
name: the name of the counter
num: how many shards to use
'''
config = ShardedCounterConfig.get_or_insert(name, name=name)
def tx():
if config.shards < num:
config.shards = num
config.put()
db.run_in_transaction(tx)
class ShardedCounterConfig(db.Model):
'''
Tracks the number of shards for each named counter.
'''
name = db.StringProperty(required=True)
shards = db.IntegerProperty(required=True, default=10)
class ShardedCounter(db.Model):
'''
Shards for each named counter
'''
name = db.StringProperty(required=True)
count = db.IntegerProperty(required=True, default=0)
###############################################################################
# Setting operation
###############################################################################
DEFAULT_GROUP = '__default__'
def _get_setting(name, group):
'''
Get setting object.
'''
return Setting.all().filter('name =', name).filter('group =', group).get()
def get_setting(name, group=DEFAULT_GROUP, default_value=None):
'''
Get a setting value for specified name and group.
Args:
name: setting name as string.
group: setting group as string, default to DEFAULT_GROUP.
default_value: default value to return if no such setting.
Returns:
Setting value as string or unicode.
'''
if not isinstance(name, basestring):
raise ValueError('Name must be basestring.')
if not isinstance(group, basestring):
raise ValueError('Group must be basestring.')
setting = _get_setting(name, group)
if setting is None:
return default_value
return setting.value
def delete_settings(group):
'''
Delete settings by group.
Args:
group: setting group as string.
'''
if not isinstance(group, basestring):
raise ValueError('Group must be basestring.')
settings = Setting.all().filter('group =', group).fetch(100)
db.delete(settings)
def delete_setting(name, group=DEFAULT_GROUP):
'''
Delete a setting value for specified name and group.
Args:
name: setting name as string.
group: setting group as string, default to DEFAULT_GROUP.
Returns:
None
'''
if not isinstance(name, basestring):
raise ValueError('Name must be basestring.')
if not isinstance(group, basestring):
raise ValueError('Group must be basestring.')
setting = _get_setting(name, group)
if setting is not None:
setting.delete()
def set_setting(name, value, group=DEFAULT_GROUP):
'''
Set new setting for a given name, value and group.
Args:
name: setting name as string.
value: setting value as string.
group: setting group as string, default to DEFAULT_GROUP.
Returns:
None
'''
if not isinstance(name, basestring):
raise ValueError('Name must be basestring.')
if not isinstance(group, basestring):
raise ValueError('Group must be basestring.')
if not isinstance(value, basestring):
raise ValueError('Value must be basestring.')
setting = _get_setting(name, group)
if setting is None:
setting = Setting(name=name, group=group, value=value)
else:
setting.value = value
setting.put()
def get_settings(group=DEFAULT_GROUP):
'''
Get settings (100 first) as dict which belongs to specific group.
Args:
group: setting group as string, default to DEFAULT_GROUP.
Returns:
Dict contains key as setting name, value as setting value.
'''
if not isinstance(group, basestring):
raise ValueError('Group must be basestring.')
settings = Setting.all().filter('group =', group).fetch(100)
d = {}
for setting in settings:
d[setting.name] = setting.value
return d
class Setting(db.Model):
'''
Settings that contains group, name and value.
'''
name = db.StringProperty(required=True)
group = db.StringProperty(required=True, default='__default__')
value = db.StringProperty()
###############################################################################
# Comment operation
###############################################################################
def get_comment(key):
'''
Get a comment by key, or None if not exist.
'''
return Comment.get(key)
def get_all_comments(ref):
'''
Get all comments by reference key.
'''
return Comment.all().filter('ref =', ref).fetch(1000)
def create_comment(ref, email, name, content, ip, approval=True, pending_days=None):
'''
Create a comment by given ref, email, name, content, ip, approval and pending_days.
Returns:
Comment object.
'''
validator.check_str(ref, 'ref', False)
validator.check_email(email)
validator.check_str(name, 'name', False)
validator.check_text(content, False)
pending_time = None
if not approval and pending_days is not None:
if pending_days<1 or pending_days>30:
raise ValueError('Invalid pending time')
pending_time = datetime.datetime.now() + datetime.timedelta(days=pending_days)
c = Comment(ref=ref, email=email, name=name, content=content, ip=ip, approval=approval, pending_time=pending_time)
c.put()
return c
def approve_comment(key):
'''
Approve a comment.
'''
c = Comment.get(key)
if (c is not None) and (not c.approval):
c.approval = True
c.put()
def reject_comment(key):
'''
Reject a comment. Reject a comment does make it hidden but not delete it.
'''
c = Comment.get(key)
if (c is not None) and c.approval:
c.approval = False
c.pending_time = None
c.put()
def delete_comment(key):
'''
Delete a comment by given key.
'''
c = Comment.get(key)
if c is not None:
c.delete()
def delete_all_comments(ref_key):
'''
Delete all comments associated with the reference key.
This does not delete all comments immediately from data store.
Instead, it add a record in PendingDeleteComment and wait
cron job to delete them.
'''
p = PendingDeleteComment(ref=ref_key)
p.put()
def cron_delete_all_comments(ref_key):
'''
Delete all comments associated with the reference key.
ONLY called by cron job!!!
'''
cs = Comment.all().filter('ref =', ref_key).fetch(1000)
for c in cs:
c.delete()
class PendingDeleteComment(BaseModel):
'''
Store reference key that need to remove comments associated with it.
'''
ref = db.StringProperty(required=True)
class Comment(BaseModel):
'''
Store a single comment
'''
ref = db.StringProperty(required=True)
email = db.StringProperty(required=True)
name = db.StringProperty(required=True)
content = db.TextProperty(required=True)
ip = db.StringProperty()
approval = db.BooleanProperty(required=True, default=True)
pending_time = db.DateTimeProperty()
###############################################################################
# Pagination operation
###############################################################################
def get_by_page(query, page_index, page_size=20):
'''
Get query results by page, located by page index (starts from 1) and page size.
Args:
query: Query object.
page_index: Page index, starts from 1.
page_size: Page size, default to 20, maximum to 100.
Returns:
A tuple contains (results as list, next cursor position).
Raises:
Value error if page index < 1, or page_size < 1, or page_size > 100, or page_index*page_size>1000.
'''
if page_index < 1:
raise ValueError('Page index must start from 1.')
if page_size < 1 or page_size > 100:
raise ValueError('Page size must be 1 to 100.')
if page_index * page_size > 1000:
raise ValueError('Results out of 1000.')
result = query.fetch(page_size, (page_index - 1) * page_size)
cursor = query.cursor()
return (result, cursor,)
def get_by_cursor(query, cursor=None, limit=20):
'''
Get query results by cursor.
Args:
query: Query object.
cursor: current cursor, default to None.
limit: maximum results returned, default to 20.
Returns:
A tuple that contains (results as list, next cursor position).
'''
if cursor:
query.with_cursor(cursor)
result = query.fetch(limit)
return (result, query.cursor(),)
def has_more(query, cursor):
'''
Get if query has more results from current cursor.
Args:
query: Query object.
cursor: current cursor.
Returns:
True if has more results, otherwise False.
'''
query.with_cursor(cursor)
return len(query.fetch(1)) > 0
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Michael Liao (askxuefeng@gmail.com)'
'''
View rendering using Cheetah.
'''
import os
import logging
from Cheetah.Template import Template
from framework import ApplicationError
class RenderError(ApplicationError):
'''
Error when rendering.
'''
pass
def get_template_path(appname, view_name, view_dir='view', ext='.html'):
'''
Get template path by app name, view name, view dir and view file extension.
'''
web_root = os.path.split(os.path.dirname(__file__))[0]
return os.path.join(web_root, appname, view_dir, '%s%s' % (view_name, ext,))
def import_compiled_template(mod_name):
'''
Try to import a compiled template, or None if no such class.
Args:
mod_name: module name.
Return:
CompiledTemplate class.
'''
try:
return __import__(mod_name, fromlist=['CompiledTemplate']).CompiledTemplate
except ImportError:
logging.warn('Import %s.%s failed.' % (mod_name, 'CompiledTemplate'))
return None
def compile_template(appname, view_name, view_dir='view'):
'''
Compile a Cheetah template to class.
Args:
app: app name
view_name: view name of template.
view_dir: view dir name, default to 'view'.
Returns:
Compiled class content as string.
'''
view_path = get_template_path(appname, view_name, view_dir=view_dir)
logging.info('Compiling view %s...' % view_path)
return Template.compile(file=view_path, source=None, returnAClass=False, moduleName='compiled.%s.%s.%s' % (appname, view_dir, view_name), className='CompiledTemplate')
def render(appname, model, view_dir='view'):
'''
Render a template using the given model.
Args:
appname: app name.
model: model as dict.
'''
view_name = model.get('__view__')
if view_name is None:
raise RenderError('View is not set.')
cc = import_compiled_template('compiled.%s.%s.%s' % (appname, view_dir, view_name))
if cc is not None:
return cc(searchList=[model], filter='WebSafe')
view_path = get_template_path(appname, view_name, view_dir=view_dir)
logging.info('Render view at runtime: %s' % view_path)
if not os.path.isfile(view_path):
raise RenderError('Template is not found: %s' % view_path)
return Template(file=view_path, searchList=[model], filter='WebSafe')
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Michael Liao (askxuefeng@gmail.com)'
class ApplicationError(StandardError):
'''
Base error for ExpressMe application.
'''
pass
class ValidationError(ApplicationError):
'''
Validation failed.
'''
pass
class PermissionError(ApplicationError):
'''
Permission denied.
'''
pass
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Michael Liao (askxuefeng@gmail.com)'
import unittest
from framework.web import Context
class Test(unittest.TestCase):
def test_context_kw(self):
ctx = Context(name='Michael', title='Engineer')
self.assertEquals('Michael', ctx['name'])
self.assertEquals('Michael', ctx.name)
self.assertEquals('Engineer', ctx['title'])
self.assertEquals('Engineer', ctx.title)
self.assertRaises(AttributeError, lambda: ctx.url)
ctx.url = 'http://www.expressme.org'
self.assertEquals('http://www.expressme.org', ctx.url)
def test_context_dict(self):
ctx = Context({'name': 'Michael', 'title': 'Engineer'})
self.assertEquals('Michael', ctx['name'])
self.assertEquals('Michael', ctx.name)
self.assertEquals('Engineer', ctx['title'])
self.assertEquals('Engineer', ctx.title)
if __name__ == '__main__':
#import sys;sys.argv = ['', 'Test.testName']
unittest.main()
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Michael Liao (askxuefeng@gmail.com)'
import os
import unittest
from framework import view
class Test(unittest.TestCase):
def test_get_template_path(self):
self.assertTrue(os.path.isfile(view.get_template_path('http_test', 'main')))
self.assertTrue(os.path.isfile(view.get_template_path('http_test', 'rss', ext='.xml')))
self.assertTrue(os.path.isfile(view.get_template_path('http_test', 'custom', view_dir='custom_view')))
def test_compile_template(self):
cls = view.compile_template('http_test', 'main')
self.assertTrue(isinstance(cls, str))
self.assertTrue(cls.find('CompiledTemplate')>=0)
def test_compile_template2(self):
cls = view.compile_template('http_test', 'custom', view_dir='custom_view')
self.assertTrue(isinstance(cls, str))
self.assertTrue(cls.find('CompiledTemplate')>=0)
def test_import_compiled_template(self):
self.assertEquals(None, view.import_compiled_template('http_test.undefined'))
def test_render(self):
model = {
'title' : 'Life & Style',
}
self.assertRaises(view.RenderError, view.render, 'http_test', model)
model['__view__'] = 'undefined'
self.assertRaises(view.RenderError, view.render, 'http_test', model)
model['__view__'] = 'main'
t = str(view.render('http_test', model))
self.assertTrue(t.find('<h1>Life & Style</h1>')>=0)
self.assertTrue(t.find('<p>Life & Style</p>')>=0)
if __name__ == '__main__':
#import sys;sys.argv = ['', 'Test.testName']
unittest.main()
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Michael Liao (askxuefeng@gmail.com)'
'''
Simple functions to send mail.
'''
from google.appengine.api import mail
def send(sender_address, to_address, subject, body, html=None):
'''
Send mail.
Args:
sender_address: sender's address
to_address: receiver's address
subject: subject of the mail
body: body of the mail
html: HTML body of the mail, default to None
'''
kw = {}
if html:
kw['html'] = html
mail.send_mail(sender_address, to_address, subject, body, **kw)
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Michael Liao (askxuefeng@gmail.com)'
'''
Simple functions to make ease of use memcache.
'''
from google.appengine.api import memcache as memcache
def set(key, value, time=0):
'''
Put the value into cache for a given key.
Args:
key: key as str.
value: value as object.
time: expires time, default to 0 (forever).
'''
memcache.set(key, value, time)
def delete(key):
'''
Delete a key from cache.
Args:
key: key as str.
'''
memcache.delete(key)
def get(key, func_or_value=None, time=0):
'''
Retrieve the value from cache for a given key.
If value is not found in cache, and func_or_value is None,
then the None will return.
If func_or_value is a function, cache will be updated with the
value returned by function.
If func_or_value is not a function, then it must be a value, and
cache will be updated with the value.
Args:
key: the key of the value.
func_or_value: a function or value.
time: expires time, default to 0 (forever).
Returns:
value stored in cache, or None if not found.
'''
value = memcache.get(key)
if value is None:
if callable(func_or_value):
value = func_or_value()
else:
value = func_or_value
memcache.set(key, value, time)
return value
def incr(key, delta=1):
memcache.incr(key, delta=delta)
| Python |
#!/usr/bin/env python
# Build CJK Font Package, in tar.bz2 for format
import sys, os, tarfile, time, re, stat
file_map = { }
INFO_FILE_NAME = "_FONTINFO"
LIST_FILE_NAME = "_FILELIST"
PKG_FILE_EXT = "fpkg"
EXTRA_INFO_FILE_NAME = "_EXTRAINFO"
file_patterns = { "uni%FONT%[0-9a-fA-F]{2,4}\.(tfm|vf|pfb)": "#1-UTF8",\
"gbk%FONT%[0-9a-fA-F]{2,4}\.(tfm|vf|pfb)": "#1-GBK", \
"\w+\.map" : "map", \
"\w+\.fd" : "fd" }
compiled_exps = { }
def add_to_map(key, file):
if not file_map.has_key(key):
file_map[key] = [ ];
file_map[key].append(file)
def die(str):
print str
sys.exit(1)
app_name = sys.argv[0]
if len(sys.argv) < 3:
die("usage: %s <dir> <font>" % app_name)
dir_name = sys.argv[1]
if dir_name.endswith("/"):
dir_name = dirname[:-1]
fnt_name = sys.argv[2]
enc_list = [ "uni", "gbk", "big5" ]
if not os.path.isdir(dir_name):
die("%s: directory %s not exist." % (app_name, dir_name))
pkg_file_name = "%s.%s" % (fnt_name, PKG_FILE_EXT)
print "building package %s from %s/ for font %s:\n" % \
(pkg_file_name, dir_name, fnt_name)
# create real mappings
for pat in file_patterns.keys():
val = file_patterns.pop(pat)
pat = pat.replace("%FONT%", fnt_name)
# print "set", pat, "as", val
file_patterns[pat] = val
exp = re.compile(pat)
compiled_exps[pat] = exp
file_list = os.listdir(dir_name)
for file in file_list:
for pat in file_patterns.keys():
m = compiled_exps[pat].match(file)
if m:
key = file_patterns[pat]
i = 1
# do replacement for #0, #1, #2, ...
for group in m.groups():
key = key.replace("#%d" % i, group)
i += 1
add_to_map(key, file)
break
# create info file
info_file = open("%s/%s" % (dir_name, INFO_FILE_NAME), "w")
time_info = time.localtime(time.time())
pkg_date = "%s-%s-%s %s:%s:%s" % (time_info[0], time_info[1], \
time_info[2], time_info[3], \
time_info[4], time_info[4])
info_file.write("font_unique_name: %s\n" % fnt_name)
info_file.write("font_packaged_on: %s\n" % pkg_date)
if os.getenv("FONTMAN_PACKAGER") != None:
info_file.write("font_packaged_by: %s\n" % os.getenv("FONTMAN_PACKAGER"))
ei_name = "%s/%s" % (dir_name, EXTRA_INFO_FILE_NAME)
if os.path.isfile(ei_name):
extra_info_file = open(ei_name)
info_file.write(extra_info_file.read())
extra_info_file.close()
info_file.close()
# show the info file to user, for make sure
info_file = open("%s/%s" % (dir_name, INFO_FILE_NAME), "r")
print info_file.read()
info_file.close()
# create list file
list_file = open("%s/%s" % (dir_name, LIST_FILE_NAME), "w")
for part in file_map.keys():
list_file.write("# %s\n" % part)
for file in file_map[part]:
list_file.write("%s\n" % file)
list_file.close()
# create final package
pkg_file = tarfile.open(pkg_file_name, "w:gz")
pkg_file.add("%s/%s" % (dir_name, LIST_FILE_NAME), LIST_FILE_NAME)
pkg_file.add("%s/%s" % (dir_name, INFO_FILE_NAME), INFO_FILE_NAME)
for part in file_map.keys():
sys.stdout.write("adding files for %-10s: " % part)
i = 0
for file in file_map[part]:
i += 1
pkg_file.add("%s/%s" % (dir_name, file), file)
print "%-4d files added" % i
pkg_file.close()
print "\nfont package %s finished, %d bytes in total." % \
(pkg_file_name, os.stat(pkg_file_name)[stat.ST_SIZE])
| Python |
#!/usr/bin/env python
# Build CJK Font Package, in tar.bz2 for format
import sys, os, tarfile, time, re, stat
file_map = { }
INFO_FILE_NAME = "_FONTINFO"
LIST_FILE_NAME = "_FILELIST"
PKG_FILE_EXT = "fpkg"
EXTRA_INFO_FILE_NAME = "_EXTRAINFO"
file_patterns = { "uni%FONT%[0-9a-fA-F]{2,4}\.(tfm|vf|pfb)": "#1-UTF8",\
"gbk%FONT%[0-9a-fA-F]{2,4}\.(tfm|vf|pfb)": "#1-GBK", \
"\w+\.map" : "map", \
"\w+\.fd" : "fd" }
compiled_exps = { }
def add_to_map(key, file):
if not file_map.has_key(key):
file_map[key] = [ ];
file_map[key].append(file)
def die(str):
print str
sys.exit(1)
app_name = sys.argv[0]
if len(sys.argv) < 3:
die("usage: %s <dir> <font>" % app_name)
dir_name = sys.argv[1]
if dir_name.endswith("/"):
dir_name = dirname[:-1]
fnt_name = sys.argv[2]
enc_list = [ "uni", "gbk", "big5" ]
if not os.path.isdir(dir_name):
die("%s: directory %s not exist." % (app_name, dir_name))
pkg_file_name = "%s.%s" % (fnt_name, PKG_FILE_EXT)
print "building package %s from %s/ for font %s:\n" % \
(pkg_file_name, dir_name, fnt_name)
# create real mappings
for pat in file_patterns.keys():
val = file_patterns.pop(pat)
pat = pat.replace("%FONT%", fnt_name)
# print "set", pat, "as", val
file_patterns[pat] = val
exp = re.compile(pat)
compiled_exps[pat] = exp
file_list = os.listdir(dir_name)
for file in file_list:
for pat in file_patterns.keys():
m = compiled_exps[pat].match(file)
if m:
key = file_patterns[pat]
i = 1
# do replacement for #0, #1, #2, ...
for group in m.groups():
key = key.replace("#%d" % i, group)
i += 1
add_to_map(key, file)
break
# create info file
info_file = open("%s/%s" % (dir_name, INFO_FILE_NAME), "w")
time_info = time.localtime(time.time())
pkg_date = "%s-%s-%s %s:%s:%s" % (time_info[0], time_info[1], \
time_info[2], time_info[3], \
time_info[4], time_info[4])
info_file.write("font_unique_name: %s\n" % fnt_name)
info_file.write("font_packaged_on: %s\n" % pkg_date)
if os.getenv("FONTMAN_PACKAGER") != None:
info_file.write("font_packaged_by: %s\n" % os.getenv("FONTMAN_PACKAGER"))
ei_name = "%s/%s" % (dir_name, EXTRA_INFO_FILE_NAME)
if os.path.isfile(ei_name):
extra_info_file = open(ei_name)
info_file.write(extra_info_file.read())
extra_info_file.close()
info_file.close()
# show the info file to user, for make sure
info_file = open("%s/%s" % (dir_name, INFO_FILE_NAME), "r")
print info_file.read()
info_file.close()
# create list file
list_file = open("%s/%s" % (dir_name, LIST_FILE_NAME), "w")
for part in file_map.keys():
list_file.write("# %s\n" % part)
for file in file_map[part]:
list_file.write("%s\n" % file)
list_file.close()
# create final package
pkg_file = tarfile.open(pkg_file_name, "w:gz")
pkg_file.add("%s/%s" % (dir_name, LIST_FILE_NAME), LIST_FILE_NAME)
pkg_file.add("%s/%s" % (dir_name, INFO_FILE_NAME), INFO_FILE_NAME)
for part in file_map.keys():
sys.stdout.write("adding files for %-10s: " % part)
i = 0
for file in file_map[part]:
i += 1
pkg_file.add("%s/%s" % (dir_name, file), file)
print "%-4d files added" % i
pkg_file.close()
print "\nfont package %s finished, %d bytes in total." % \
(pkg_file_name, os.stat(pkg_file_name)[stat.ST_SIZE])
| Python |
# -*- coding: utf-8 -*-
"""
TreeFileBrowser a tree-like gtk file browser
Copyright (C) 2006-2008 Adolfo González Blázquez <code@infinicode.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
If you find any bugs or have any suggestions email: code@infinicode.org
"""
try:
import pygtk
pygtk.require('2.0')
except:
print "PyGtk 2.0 or later required for this app to run"
raise SystemExit
try:
import gtk
import gobject
except:
raise SystemExit
from gettext import gettext as _
try:
from os import path as ospath
import dircache
except:
raise SystemExit
class TreeFileBrowser(gobject.GObject):
""" A widget that implements a tree-like file browser, like the
one used on Nautilus spatial view in list mode """
__gproperties__ = {
'show-hidden': (gobject.TYPE_BOOLEAN, 'show hidden files',
'show hidden files and folders', False, gobject.PARAM_READWRITE),
'show-only-dirs': (gobject.TYPE_BOOLEAN, 'show only directories',
'show only directories, not files', True, gobject.PARAM_READWRITE),
'rules-hint': (gobject.TYPE_BOOLEAN, 'rules hint',
'show rows background in alternate colors', True, gobject.PARAM_READWRITE),
'root': (gobject.TYPE_STRING, 'initial path',
'initial path selected on tree browser', '/', gobject.PARAM_READWRITE)
}
__gsignals__ = { 'row-expanded' : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_STRING,)),
'cursor-changed' : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_STRING,))
}
def __init__(self, root=None):
""" Path is where we wan the tree initialized """
gobject.GObject.__init__(self)
self.show_hidden = False
self.show_only_dirs = True
self.show_rules_hint = True
self.root = '/'
if root != None and ospath.isdir(root): self.root = root
#elif root != None: print "ERROR: %s doesn't exist." % root
self.view, self.scrolled = self.make_view()
self.create_new()
self.create_popup()
#####################################################
# Accessors and Mutators
def do_get_property(self, property):
""" GObject get_property method """
if property.name == 'show-hidden':
return self.show_hidden
elif property.name == 'show-only-dirs':
return self.show_only_dirs
elif property.name == 'rules-hint':
return self.show_rules_hint
elif property.name == 'path':
return self.root
else:
raise AttributeError, 'unknown property %s' % property.name
def do_set_property(self, property, value):
""" GObject set_property method """
if property.name == 'show-hidden':
self.show_hidden = value
elif property.name == 'show-only-dirs':
self.show_only_dirs = value
elif property.name == 'rules-hint':
self.show_rules_hint = value
elif property.name == 'path':
self.root = value
else:
raise AttributeError, 'unknown property %s' % property.name
def get_view(self):
return self.view
def get_scrolled(self):
return self.scrolled
def set_show_hidden(self, hidden):
self.show_hidden = hidden
activedir = self.get_selected()
self.create_new()
if activedir != None:
if "/." in activedir: self.set_active_dir(self.root)
else: self.set_active_dir(activedir)
self.hidden_check_menu.set_active(hidden)
def get_show_hidden(self):
return self.show_hidden
def set_rules_hint(self, rules):
self.show_rules_hint = rules
self.view.set_rules_hint(rules)
def get_rules_hint(self):
return self.show_rules_hint
def set_show_only_dirs(self, only_dirs):
self.show_only_dirs = only_dirs
self.create_new()
def get_show_only_dirs(self):
return self.show_only_dirs
def get_selected(self):
""" Returns selected item in browser """
model, iter = self.view.get_selection().get_selected()
if iter != None:
return model.get_value(iter, 2)
else:
return None
#####################################################
# Callbacks
def row_expanded(self, treeview, iter, path):
""" CALLBACK: a row is expanded """
model = treeview.get_model()
model.set_value(iter, 0, self.get_folder_opened_icon())
self.get_file_list(model, iter, model.get_value(iter,2))
self.remove_empty_child(model, iter)
# Send signal with path of expanded row
self.emit('row-expanded', model.get_value(iter,2))
def row_collapsed(self, treeview, iter, path):
""" CALLBACK: a row is collapsed """
model = treeview.get_model()
model.set_value(iter, 0, self.get_folder_closed_icon())
while model.iter_has_child(iter):
child = model.iter_children(iter)
model.remove(child)
self.add_empty_child(model, iter)
def row_activated(self, treeview, path, view_column):
""" CALLBACK: row activated using return, double-click, shift-right, etc. """
if treeview.row_expanded(path):
treeview.collapse_row(path)
else:
treeview.expand_row(path, False)
def cursor_changed(self, treeview):
""" CALLBACK: a new row has been selected """
model, iter = treeview.get_selection().get_selected()
# Send signal with path of expanded row
if iter == None:
path = treeview.get_cursor()[0]
iter = self.model.get_iter(path)
self.emit('cursor-changed', model.get_value(iter,2))
def button_pressed(self, widget, event):
""" CALLBACK: clicked on widget """
if event.button == 3:
x = int(event.x)
y = int(event.y)
time = event.time
pthinfo = self.view.get_path_at_pos(x, y)
if pthinfo is not None:
path, col, cellx, celly = pthinfo
#self.view.grab_focus()
#self.view.set_cursor( path, col, 0)
self.popup.popup( None, None, None, event.button, time)
return 1
def show_hidden_toggled(self, widget):
""" CALLBACK: Show hidden files on context menu toggled """
state = widget.get_active()
self.set_show_hidden(state)
#####################################################
# Directories and files, nodes and icons
def set_cursor_on_first_row(self):
model = self.view.get_model()
iter = model.get_iter_root()
path = model.get_path(iter)
self.view.set_cursor(path)
def check_active_dir(self, directory):
rootdir = self.root
if not ospath.isdir(directory):
return False
if not (rootdir in directory):
return False
if directory == rootdir:
return True
return True
def set_active_dir(self, directory):
rootdir = self.root
# Expand root
model = self.view.get_model()
iter = model.get_iter_root()
path = model.get_path(iter)
self.view.expand_row(path, False)
iter = model.iter_children(iter)
# Add trailing / to paths
if len(directory) > 1 and directory[-1] != '/': directory += '/'
if len(rootdir) > 1 and rootdir[-1] != '/': rootdir += '/'
if not ospath.isdir(directory):
#print "ERROR: %s doesn't exist." % directory
self.set_cursor_on_first_row()
return False
if not (rootdir in directory):
#print "ERROR: %s is not on root path." % directory
self.set_cursor_on_first_row()
return False
if directory == rootdir:
self.set_cursor_on_first_row()
return True
else:
# Now we check if the desired dir is valid
# Convert the given '/home/user/dir/' to ['/', 'home/', 'user/', 'dir/']
if len(directory) > 1:
dirtree = directory.split('/')
dirtree.pop(-1)
else: dirtree = ['/']
if len(dirtree) > 1:
dirtree[0] = '/'
for i in range(len(dirtree)-1): dirtree[i+1] = dirtree[i+1] + '/'
# Convert root to '/home/user/dir/' to ['/', 'home/', 'user/', 'dir/']
if len(rootdir) > 1:
roottree = rootdir.split('/')
roottree.pop(-1)
else: roottree = ['/']
if len(roottree) > 1:
roottree[0] = '/'
for i in range(len(roottree)-1): roottree[i+1] = roottree[i+1] + '/'
# Check if the dir is in the same path as the desired root
long = len(roottree)
for i in range(long):
if roottree[i] != dirtree[i]: return False
# End checking
# Star expanding
# Count how many iterations we need
depth = len(dirtree) - len(roottree)
# Expand baby expand!
exp = len(roottree)
for i in range(depth):
newpath = dirtree[i+exp]
if iter == None: continue
val = model.get_value(iter, 1).replace('/','') + '/'
while val != newpath:
iter = model.iter_next(iter)
val = model.get_value(iter, 1).replace('/','') + '/'
path = model.get_path(iter)
self.view.expand_row(path, False)
iter = model.iter_children(iter)
# Don't expand last row
self.view.collapse_row(path)
# Set the cursor
self.view.set_cursor(path)
return True
def add_empty_child(self, model, iter):
""" Adds a empty child to a node.
Used when we need a folder that have children to show the expander arrow """
model.insert_before(iter, None)
def remove_empty_child(self, model, iter):
""" Delete empty child from a node.
Used to remove the extra child used to show the expander arrow
on folders with children """
newiter = model.iter_children(iter)
model.remove(newiter)
def get_file_list(self, model, iter, dir):
""" Get the file list from a given directory """
ls = dircache.listdir(dir)
ls.sort(key=str.lower)
for i in ls:
path = ospath.join(dir,i)
if ospath.isdir(path) or not self.show_only_dirs :
if i[0] != '.' or (self.show_hidden and i[0] == '.'):
newiter = model.append(iter)
if ospath.isdir(path): icon = self.get_folder_closed_icon()
else: icon = self.get_file_icon()
model.set_value(newiter, 0, icon)
model.set_value(newiter, 1, i)
model.set_value(newiter, 2, path)
if ospath.isdir(path):
try: subdir = dircache.listdir(path)
except: subdir = []
if subdir != []:
for i in subdir:
if ospath.isdir(ospath.join(path,i)) or not self.show_only_dirs:
if i[0] != '.' or (self.show_hidden and i[0] == '.'):
self.add_empty_child(model, newiter)
break
def create_root(self):
model = self.view.get_model()
if self.root != '/':
if self.root[-1] == '/': self.root = self.root.rsplit('/',1)[0] # Remove last / if neccesary
directory = self.root.split('/')[-1]
else: directory = self.root
iter = model.insert_before(None, None)
model.set_value(iter, 0, self.get_folder_opened_icon())
model.set_value(iter, 1, directory)
model.set_value(iter, 2, self.root)
iter = model.insert_before(iter, None)
return iter
def create_new(self):
""" Create tree from scratch """
model = self.view.get_model()
model.clear()
iter = self.create_root()
self.get_file_list(self.view.get_model(), iter, self.root)
def create_popup(self):
""" Create popup menu for right click """
self.popup = gtk.Menu()
self.hidden_check_menu = gtk.CheckMenuItem(_("Show hidden files"))
self.hidden_check_menu.connect('toggled', self.show_hidden_toggled)
self.popup.add(self.hidden_check_menu)
self.popup.show_all()
def get_folder_closed_icon(self):
""" Returns a pixbuf with the current theme closed folder icon """
icon_theme = gtk.icon_theme_get_default()
try:
icon = icon_theme.load_icon("gnome-fs-directory", 16, 0)
return icon
except gobject.GError, exc:
#print "Can't load icon", exc
try:
icon = icon_theme.load_icon("gtk-directory", 16, 0)
return icon
except:
#print "Can't load default icon"
return None
def get_folder_opened_icon(self):
""" Returns a pixbuf with the current theme opened folder icon """
icon_theme = gtk.icon_theme_get_default()
try:
icon = icon_theme.load_icon("gnome-fs-directory-accept", 16, 0)
return icon
except gobject.GError, exc:
#print "Can't load icon", exc
try:
icon = icon_theme.load_icon("gtk-directory", 16, 0)
return icon
except:
#print "Can't load default icon"
return None
def get_file_icon(self):
""" Returns a pixbuf with the current theme file icon """
icon_theme = gtk.icon_theme_get_default()
try:
icon = icon_theme.load_icon("text-x-generic", gtk.ICON_SIZE_MENU, 0)
return icon
except gobject.GError, exc:
#print "Can't load icon", exc
return None
#####################################################
# Model, treeview and scrolledwindow
def make_view(self):
""" Create the view itself.
(Icon, dir name, path) """
self.model = gtk.TreeStore(gtk.gdk.Pixbuf, gobject.TYPE_STRING, gobject.TYPE_STRING)
view = gtk.TreeView(self.model)
view.set_headers_visible(False)
view.set_enable_search(True)
view.set_reorderable(False)
view.set_rules_hint(self.show_rules_hint)
view.connect('row-expanded', self.row_expanded)
view.connect('row-collapsed', self.row_collapsed)
view.connect('row-activated', self.row_activated)
view.connect('cursor-changed', self.cursor_changed)
view.connect('button_press_event', self.button_pressed)
col = gtk.TreeViewColumn()
# The icon
render_pixbuf = gtk.CellRendererPixbuf()
col.pack_start(render_pixbuf, expand=False)
col.add_attribute(render_pixbuf, 'pixbuf', 0)
# The dir name
render_text = gtk.CellRendererText()
col.pack_start(render_text, expand=True)
col.add_attribute(render_text, 'text', 1)
view.append_column(col)
view.show()
# Create scrollbars around the view
scrolled = gtk.ScrolledWindow()
scrolled.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
scrolled.set_shadow_type(gtk.SHADOW_ETCHED_IN)
scrolled.add(view)
scrolled.show()
return view, scrolled
gobject.type_register(TreeFileBrowser)
# End TreeFileBrowser
| Python |
#!/usr/bin/env python
#-*- coding: UTF-8 -*-
import gobject
import gtk
import os
import gio
import urllib
import gconf
import rb,rhythmdb
import treefilebrowser
import logging,logging.handlers
log=logging.getLogger('FolderView')
LAST_PATH_KEY = '/rhythmbox.plugin.FolderView.lastpath'
class FolderViewSource(rb.BrowserSource):
#__gproperties__ = {'plugin': (rb.Plugin, 'plugin', 'plugin', gobject.PARAM_WRITABLE|gobject.PARAM_CONSTRUCT_ONLY),}
def __init__(self):
rb.BrowserSource.__init__(self)
self.shell = None
self.g_client = gconf.client_get_default()
self.library_location = urllib.unquote(self.g_client.get_list('/apps/rhythmbox/library_locations', gconf.VALUE_STRING)[0])
def do_impl_activate(self):
log.info('Activate')
if self.shell == None:
self.shell = self.get_property('shell')
self.db = self.shell.get_property('db')
self.entry_type = self.get_property('entry-type')
self.entry_view = self.get_entry_view()
self.filebrowser.set_active_dir(gconf.client_get_default().get_without_default(LAST_PATH_KEY).get_string())
ui_browse=self.shell.get_ui_manager().get_widget('/ToolBar/Browse')
#ui_browse.set_sensitive(False)
ui_browse.hide()
#gconf.client_get_default().set_string(LAST_PATH_KEY,userName)
rb.BrowserSource.do_impl_activate(self)
def do_impl_deactivate(self):
log.info('Deactivate')
ui_browse=self.shell.get_ui_manager().get_widget('/ToolBar/Browse')
ui_browse.show()
rb.BrowserSource.do_impl_deactivate(self)
#uim.get_widget('/ToolBar/Browse').set_sensitive(False)
#def set_entry(self, uri):
# entry = self.db.entry_lookup_by_location(uri)
# if entry != None:
# if self.db.entry_get(entry, rhythmdb.PROP_DURATION) != 0:
# #self.props.query_model.add_entry(entry, 0)
# self.db.query_append(self.query, (rhythmdb.QUERY_PROP_SUFFIX, rhythmdb.PROP_LOCATION, self.db.entry_get(entry, rhythmdb.PROP_LOCATION)))
def on_treeview_cursor_changed(self, widget):
for row in self.props.query_model:
entry = row[0]
self.props.query_model.remove_entry(entry)
self.query = self.db.query_new()
song_type = self.db.entry_type_get_by_name('song')
path = self.filebrowser.get_selected()
gconf.client_get_default().set_string(LAST_PATH_KEY,path)
#for item in os.listdir(path):
# filename = os.path.join(path, item)
# if os.path.isfile(filename):
# tmp = str(path_to_uri(filename))
#self.set_entry(path_to_uri(filename))
self.db.query_append(self.query, (rhythmdb.QUERY_PROP_EQUALS, rhythmdb.PROP_TYPE, song_type))
self.db.query_append(self.query, (rhythmdb.QUERY_PROP_PREFIX, rhythmdb.PROP_LOCATION, path_to_uri(path)))
self.db.do_full_query_parsed(self.props.query_model, self.query)
if self.shell.props.shell_player.props.playing:
pass
else:
self.shell.props.shell_player.stop()
def do_impl_pack_paned (self, paned):
self.__paned_box = gtk.HPaned()
self.filebrowser = treefilebrowser.TreeFileBrowser(self.library_location[7:])
self.scrolled = self.filebrowser.get_scrolled()
self.scrolled.set_size_request(200,-1)
self.treeview = self.filebrowser.get_view()
self.treeview.connect('cursor-changed', self.on_treeview_cursor_changed)
self.pack_start(self.__paned_box)
self.__paned_box.add1(self.scrolled)
self.__paned_box.add2(paned)
def path_to_uri(path):
gfile = gio.File(path)
return gfile.get_uri()
gobject.type_register(FolderViewSource)
| Python |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.