code stringlengths 1 1.72M | language stringclasses 1 value |
|---|---|
# 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.
#
from boto.pyami.installers.ubuntu.installer import Installer
import boto
import os
class Trac(Installer):
"""
Install Trac and DAV-SVN
Sets up a Vhost pointing to [Trac]->home
Using the config parameter [Trac]->hostname
Sets up a trac environment for every directory found under [Trac]->data_dir
[Trac]
name = My Foo Server
hostname = trac.foo.com
home = /mnt/sites/trac
data_dir = /mnt/trac
svn_dir = /mnt/subversion
server_admin = root@foo.com
sdb_auth_domain = users
# Optional
SSLCertificateFile = /mnt/ssl/foo.crt
SSLCertificateKeyFile = /mnt/ssl/foo.key
SSLCertificateChainFile = /mnt/ssl/FooCA.crt
"""
def install(self):
self.run('apt-get -y install trac', notify=True, exit_on_error=True)
self.run('apt-get -y install libapache2-svn', notify=True, exit_on_error=True)
self.run("a2enmod ssl")
self.run("a2enmod mod_python")
self.run("a2enmod dav_svn")
self.run("a2enmod rewrite")
# Make sure that boto.log is writable by everyone so that subversion post-commit hooks can
# write to it.
self.run("touch /var/log/boto.log")
self.run("chmod a+w /var/log/boto.log")
def setup_vhost(self):
domain = boto.config.get("Trac", "hostname").strip()
if domain:
domain_info = domain.split('.')
cnf = open("/etc/apache2/sites-available/%s" % domain_info[0], "w")
cnf.write("NameVirtualHost *:80\n")
if boto.config.get("Trac", "SSLCertificateFile"):
cnf.write("NameVirtualHost *:443\n\n")
cnf.write("<VirtualHost *:80>\n")
cnf.write("\tServerAdmin %s\n" % boto.config.get("Trac", "server_admin").strip())
cnf.write("\tServerName %s\n" % domain)
cnf.write("\tRewriteEngine On\n")
cnf.write("\tRewriteRule ^(.*)$ https://%s$1\n" % domain)
cnf.write("</VirtualHost>\n\n")
cnf.write("<VirtualHost *:443>\n")
else:
cnf.write("<VirtualHost *:80>\n")
cnf.write("\tServerAdmin %s\n" % boto.config.get("Trac", "server_admin").strip())
cnf.write("\tServerName %s\n" % domain)
cnf.write("\tDocumentRoot %s\n" % boto.config.get("Trac", "home").strip())
cnf.write("\t<Directory %s>\n" % boto.config.get("Trac", "home").strip())
cnf.write("\t\tOptions FollowSymLinks Indexes MultiViews\n")
cnf.write("\t\tAllowOverride All\n")
cnf.write("\t\tOrder allow,deny\n")
cnf.write("\t\tallow from all\n")
cnf.write("\t</Directory>\n")
cnf.write("\t<Location />\n")
cnf.write("\t\tAuthType Basic\n")
cnf.write("\t\tAuthName \"%s\"\n" % boto.config.get("Trac", "name"))
cnf.write("\t\tRequire valid-user\n")
cnf.write("\t\tAuthUserFile /mnt/apache/passwd/passwords\n")
cnf.write("\t</Location>\n")
data_dir = boto.config.get("Trac", "data_dir")
for env in os.listdir(data_dir):
if(env[0] != "."):
cnf.write("\t<Location /trac/%s>\n" % env)
cnf.write("\t\tSetHandler mod_python\n")
cnf.write("\t\tPythonInterpreter main_interpreter\n")
cnf.write("\t\tPythonHandler trac.web.modpython_frontend\n")
cnf.write("\t\tPythonOption TracEnv %s/%s\n" % (data_dir, env))
cnf.write("\t\tPythonOption TracUriRoot /trac/%s\n" % env)
cnf.write("\t</Location>\n")
svn_dir = boto.config.get("Trac", "svn_dir")
for env in os.listdir(svn_dir):
if(env[0] != "."):
cnf.write("\t<Location /svn/%s>\n" % env)
cnf.write("\t\tDAV svn\n")
cnf.write("\t\tSVNPath %s/%s\n" % (svn_dir, env))
cnf.write("\t</Location>\n")
cnf.write("\tErrorLog /var/log/apache2/error.log\n")
cnf.write("\tLogLevel warn\n")
cnf.write("\tCustomLog /var/log/apache2/access.log combined\n")
cnf.write("\tServerSignature On\n")
SSLCertificateFile = boto.config.get("Trac", "SSLCertificateFile")
if SSLCertificateFile:
cnf.write("\tSSLEngine On\n")
cnf.write("\tSSLCertificateFile %s\n" % SSLCertificateFile)
SSLCertificateKeyFile = boto.config.get("Trac", "SSLCertificateKeyFile")
if SSLCertificateKeyFile:
cnf.write("\tSSLCertificateKeyFile %s\n" % SSLCertificateKeyFile)
SSLCertificateChainFile = boto.config.get("Trac", "SSLCertificateChainFile")
if SSLCertificateChainFile:
cnf.write("\tSSLCertificateChainFile %s\n" % SSLCertificateChainFile)
cnf.write("</VirtualHost>\n")
cnf.close()
self.run("a2ensite %s" % domain_info[0])
self.run("/etc/init.d/apache2 force-reload")
def main(self):
self.install()
self.setup_vhost()
| 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.
#
from boto.pyami.installers.ubuntu.installer import Installer
class Apache(Installer):
"""
Install apache2, mod_python, and libapache2-svn
"""
def install(self):
self.run("apt-get update")
self.run('apt-get -y install apache2', notify=True, exit_on_error=True)
self.run('apt-get -y install libapache2-mod-python', notify=True, exit_on_error=True)
self.run('a2enmod rewrite', notify=True, exit_on_error=True)
self.run('a2enmod ssl', notify=True, exit_on_error=True)
self.run('a2enmod proxy', notify=True, exit_on_error=True)
self.run('a2enmod proxy_ajp', notify=True, exit_on_error=True)
# Hard reboot the apache2 server to enable these module
self.stop("apache2")
self.start("apache2")
def main(self):
self.install()
| 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 installer will install mysql-server on an Ubuntu machine.
In addition to the normal installation done by apt-get, it will
also configure the new MySQL server to store it's data files in
a different location. By default, this is /mnt but that can be
configured in the [MySQL] section of the boto config file passed
to the instance.
"""
from boto.pyami.installers.ubuntu.installer import Installer
import os
import boto
from boto.utils import ShellCommand
from ConfigParser import SafeConfigParser
import time
ConfigSection = """
[MySQL]
root_password = <will be used as MySQL root password, default none>
data_dir = <new data dir for MySQL, default is /mnt>
"""
class MySQL(Installer):
def install(self):
self.run('apt-get update')
self.run('apt-get -y install mysql-server', notify=True, exit_on_error=True)
# def set_root_password(self, password=None):
# if not password:
# password = boto.config.get('MySQL', 'root_password')
# if password:
# self.run('mysqladmin -u root password %s' % password)
# return password
def change_data_dir(self, password=None):
data_dir = boto.config.get('MySQL', 'data_dir', '/mnt')
fresh_install = False;
is_mysql_running_command = ShellCommand('mysqladmin ping') # exit status 0 if mysql is running
is_mysql_running_command.run()
if is_mysql_running_command.getStatus() == 0:
# mysql is running. This is the state apt-get will leave it in. If it isn't running,
# that means mysql was already installed on the AMI and there's no need to stop it,
# saving 40 seconds on instance startup.
time.sleep(10) #trying to stop mysql immediately after installing it fails
# We need to wait until mysql creates the root account before we kill it
# or bad things will happen
i = 0
while self.run("echo 'quit' | mysql -u root") != 0 and i<5:
time.sleep(5)
i = i + 1
self.run('/etc/init.d/mysql stop')
self.run("pkill -9 mysql")
mysql_path = os.path.join(data_dir, 'mysql')
if not os.path.exists(mysql_path):
self.run('mkdir %s' % mysql_path)
fresh_install = True;
self.run('chown -R mysql:mysql %s' % mysql_path)
fp = open('/etc/mysql/conf.d/use_mnt.cnf', 'w')
fp.write('# created by pyami\n')
fp.write('# use the %s volume for data\n' % data_dir)
fp.write('[mysqld]\n')
fp.write('datadir = %s\n' % mysql_path)
fp.write('log_bin = %s\n' % os.path.join(mysql_path, 'mysql-bin.log'))
fp.close()
if fresh_install:
self.run('cp -pr /var/lib/mysql/* %s/' % mysql_path)
self.start('mysql')
else:
#get the password ubuntu expects to use:
config_parser = SafeConfigParser()
config_parser.read('/etc/mysql/debian.cnf')
password = config_parser.get('client', 'password')
# start the mysql deamon, then mysql with the required grant statement piped into it:
self.start('mysql')
time.sleep(10) #time for mysql to start
grant_command = "echo \"GRANT ALL PRIVILEGES ON *.* TO 'debian-sys-maint'@'localhost' IDENTIFIED BY '%s' WITH GRANT OPTION;\" | mysql" % password
while self.run(grant_command) != 0:
time.sleep(5)
# leave mysqld running
def main(self):
self.install()
# change_data_dir runs 'mysql -u root' which assumes there is no mysql password, i
# and changing that is too ugly to be worth it:
#self.set_root_password()
self.change_data_dir()
| Python |
# Copyright (c) 2006,2007,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.
#
| Python |
# Copyright (c) 2006,2007,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.pyami.scriptbase import ScriptBase
class Installer(ScriptBase):
"""
Abstract base class for installers
"""
def add_cron(self, name, minute, hour, mday, month, wday, who, command, env=None):
"""
Add an entry to the system crontab.
"""
raise NotImplementedError
def add_init_script(self, file):
"""
Add this file to the init.d directory
"""
def add_env(self, key, value):
"""
Add an environemnt variable
"""
raise NotImplementedError
def stop(self, service_name):
"""
Stop a service.
"""
raise NotImplementedError
def start(self, service_name):
"""
Start a service.
"""
raise NotImplementedError
def install(self):
"""
Do whatever is necessary to "install" the package.
"""
raise NotImplementedError
| 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 sys
import boto
from boto.utils import find_class
from boto import config
from boto.pyami.scriptbase import ScriptBase
class Startup(ScriptBase):
def run_scripts(self):
scripts = config.get('Pyami', 'scripts')
if scripts:
for script in scripts.split(','):
script = script.strip(" ")
try:
pos = script.rfind('.')
if pos > 0:
mod_name = script[0:pos]
cls_name = script[pos+1:]
cls = find_class(mod_name, cls_name)
boto.log.info('Running Script: %s' % script)
s = cls()
s.main()
else:
boto.log.warning('Trouble parsing script: %s' % script)
except Exception:
boto.log.exception('Problem Running Script: %s' % script)
def main(self):
self.run_scripts()
self.notify('Startup Completed for %s' % config.get('Instance', 'instance-id'))
if __name__ == "__main__":
if not config.has_section('loggers'):
boto.set_file_logger('startup', '/var/log/boto.log')
sys.path.append(config.get('Pyami', 'working_dir'))
su = Startup()
su.main()
| Python |
#!/usr/bin/env 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 getopt
import sys
import imp
import time
import boto
usage_string = """
SYNOPSIS
launch_ami.py -a ami_id [-b script_bucket] [-s script_name]
[-m module] [-c class_name] [-r]
[-g group] [-k key_name] [-n num_instances]
[-w] [extra_data]
Where:
ami_id - the id of the AMI you wish to launch
module - The name of the Python module containing the class you
want to run when the instance is started. If you use this
option the Python module must already be stored on the
instance in a location that is on the Python path.
script_file - The name of a local Python module that you would like
to have copied to S3 and then run on the instance
when it is started. The specified module must be
import'able (i.e. in your local Python path). It
will then be copied to the specified bucket in S3
(see the -b option). Once the new instance(s)
start up the script will be copied from S3 and then
run locally on the instance.
class_name - The name of the class to be instantiated within the
module or script file specified.
script_bucket - the name of the bucket in which the script will be
stored
group - the name of the security group the instance will run in
key_name - the name of the keypair to use when launching the AMI
num_instances - how many instances of the AMI to launch (default 1)
input_queue_name - Name of SQS to read input messages from
output_queue_name - Name of SQS to write output messages to
extra_data - additional name-value pairs that will be passed as
userdata to the newly launched instance. These should
be of the form "name=value"
The -r option reloads the Python module to S3 without launching
another instance. This can be useful during debugging to allow
you to test a new version of your script without shutting down
your instance and starting up another one.
The -w option tells the script to run synchronously, meaning to
wait until the instance is actually up and running. It then prints
the IP address and internal and external DNS names before exiting.
"""
def usage():
print usage_string
sys.exit()
def main():
try:
opts, args = getopt.getopt(sys.argv[1:], 'a:b:c:g:hi:k:m:n:o:rs:w',
['ami', 'bucket', 'class', 'group', 'help',
'inputqueue', 'keypair', 'module',
'numinstances', 'outputqueue',
'reload', 'script_name', 'wait'])
except:
usage()
params = {'module_name' : None,
'script_name' : None,
'class_name' : None,
'script_bucket' : None,
'group' : 'default',
'keypair' : None,
'ami' : None,
'num_instances' : 1,
'input_queue_name' : None,
'output_queue_name' : None}
reload = None
wait = None
for o, a in opts:
if o in ('-a', '--ami'):
params['ami'] = a
if o in ('-b', '--bucket'):
params['script_bucket'] = a
if o in ('-c', '--class'):
params['class_name'] = a
if o in ('-g', '--group'):
params['group'] = a
if o in ('-h', '--help'):
usage()
if o in ('-i', '--inputqueue'):
params['input_queue_name'] = a
if o in ('-k', '--keypair'):
params['keypair'] = a
if o in ('-m', '--module'):
params['module_name'] = a
if o in ('-n', '--num_instances'):
params['num_instances'] = int(a)
if o in ('-o', '--outputqueue'):
params['output_queue_name'] = a
if o in ('-r', '--reload'):
reload = True
if o in ('-s', '--script'):
params['script_name'] = a
if o in ('-w', '--wait'):
wait = True
# check required fields
required = ['ami']
for pname in required:
if not params.get(pname, None):
print '%s is required' % pname
usage()
if params['script_name']:
# first copy the desired module file to S3 bucket
if reload:
print 'Reloading module %s to S3' % params['script_name']
else:
print 'Copying module %s to S3' % params['script_name']
l = imp.find_module(params['script_name'])
c = boto.connect_s3()
bucket = c.get_bucket(params['script_bucket'])
key = bucket.new_key(params['script_name']+'.py')
key.set_contents_from_file(l[0])
params['script_md5'] = key.md5
# we have everything we need, now build userdata string
l = []
for k, v in params.items():
if v:
l.append('%s=%s' % (k, v))
c = boto.connect_ec2()
l.append('aws_access_key_id=%s' % c.aws_access_key_id)
l.append('aws_secret_access_key=%s' % c.aws_secret_access_key)
for kv in args:
l.append(kv)
s = '|'.join(l)
if not reload:
rs = c.get_all_images([params['ami']])
img = rs[0]
r = img.run(user_data=s, key_name=params['keypair'],
security_groups=[params['group']],
max_count=params.get('num_instances', 1))
print 'AMI: %s - %s (Started)' % (params['ami'], img.location)
print 'Reservation %s contains the following instances:' % r.id
for i in r.instances:
print '\t%s' % i.id
if wait:
running = False
while not running:
time.sleep(30)
[i.update() for i in r.instances]
status = [i.state for i in r.instances]
print status
if status.count('running') == len(r.instances):
running = True
for i in r.instances:
print 'Instance: %s' % i.ami_launch_index
print 'Public DNS Name: %s' % i.public_dns_name
print 'Private DNS Name: %s' % i.private_dns_name
if __name__ == "__main__":
main()
| Python |
import os
import sys
from boto.utils import ShellCommand, get_ts
import boto
import boto.utils
class ScriptBase:
def __init__(self, config_file=None):
self.instance_id = boto.config.get('Instance', 'instance-id', 'default')
self.name = self.__class__.__name__
self.ts = get_ts()
if config_file:
boto.config.read(config_file)
def notify(self, subject, body=''):
boto.utils.notify(subject, body)
def mkdir(self, path):
if not os.path.isdir(path):
try:
os.mkdir(path)
except:
boto.log.error('Error creating directory: %s' % path)
def umount(self, path):
if os.path.ismount(path):
self.run('umount %s' % path)
def run(self, command, notify=True, exit_on_error=False):
self.last_command = ShellCommand(command)
if self.last_command.status != 0:
boto.log.error('Error running command: "%s". Output: "%s"' % (command, self.last_command.output))
if notify:
self.notify('Error encountered', \
'Error running the following command:\n\t%s\n\nCommand output:\n\t%s' % \
(command, self.last_command.output))
if exit_on_error:
sys.exit(-1)
return self.last_command.status
def main(self):
pass
| 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) 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 boto
from boto.pyami.scriptbase import ScriptBase
import os, StringIO
class CopyBot(ScriptBase):
def __init__(self):
ScriptBase.__init__(self)
self.wdir = boto.config.get('Pyami', 'working_dir')
self.log_file = '%s.log' % self.instance_id
self.log_path = os.path.join(self.wdir, self.log_file)
boto.set_file_logger(self.name, self.log_path)
self.src_name = boto.config.get(self.name, 'src_bucket')
self.dst_name = boto.config.get(self.name, 'dst_bucket')
self.replace = boto.config.getbool(self.name, 'replace_dst', True)
s3 = boto.connect_s3()
self.src = s3.lookup(self.src_name)
if not self.src:
boto.log.error('Source bucket does not exist: %s' % self.src_name)
dest_access_key = boto.config.get(self.name, 'dest_aws_access_key_id', None)
if dest_access_key:
dest_secret_key = boto.config.get(self.name, 'dest_aws_secret_access_key', None)
s3 = boto.connect(dest_access_key, dest_secret_key)
self.dst = s3.lookup(self.dst_name)
if not self.dst:
self.dst = s3.create_bucket(self.dst_name)
def copy_bucket_acl(self):
if boto.config.get(self.name, 'copy_acls', True):
acl = self.src.get_xml_acl()
self.dst.set_xml_acl(acl)
def copy_key_acl(self, src, dst):
if boto.config.get(self.name, 'copy_acls', True):
acl = src.get_xml_acl()
dst.set_xml_acl(acl)
def copy_keys(self):
boto.log.info('src=%s' % self.src.name)
boto.log.info('dst=%s' % self.dst.name)
try:
for key in self.src:
if not self.replace:
exists = self.dst.lookup(key.name)
if exists:
boto.log.info('key=%s already exists in %s, skipping' % (key.name, self.dst.name))
continue
boto.log.info('copying %d bytes from key=%s' % (key.size, key.name))
prefix, base = os.path.split(key.name)
path = os.path.join(self.wdir, base)
key.get_contents_to_filename(path)
new_key = self.dst.new_key(key.name)
new_key.set_contents_from_filename(path)
self.copy_key_acl(key, new_key)
os.unlink(path)
except:
boto.log.exception('Error copying key: %s' % key.name)
def copy_log(self):
key = self.dst.new_key(self.log_file)
key.set_contents_from_filename(self.log_path)
def main(self):
fp = StringIO.StringIO()
boto.config.dump_safe(fp)
self.notify('%s (%s) Starting' % (self.name, self.instance_id), fp.getvalue())
if self.src and self.dst:
self.copy_keys()
if self.dst:
self.copy_log()
self.notify('%s (%s) Stopping' % (self.name, self.instance_id),
'Copy Operation Complete')
if boto.config.getbool(self.name, 'exit_on_completion', True):
ec2 = boto.connect_ec2()
ec2.terminate_instances([self.instance_id])
| 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.
class RegionInfo(object):
"""
Represents an AWS Region
"""
def __init__(self, connection=None, name=None, endpoint=None,
connection_cls=None):
self.connection = connection
self.name = name
self.endpoint = endpoint
self.connection_cls = connection_cls
def __repr__(self):
return 'RegionInfo:%s' % self.name
def startElement(self, name, attrs, connection):
return None
def endElement(self, name, value, connection):
if name == 'regionName':
self.name = value
elif name == 'regionEndpoint':
self.endpoint = value
else:
setattr(self, name, value)
def connect(self, **kw_params):
"""
Connect to this Region's endpoint. Returns an connection
object pointing to the endpoint associated with this region.
You may pass any of the arguments accepted by the connection
class's constructor as keyword arguments and they will be
passed along to the connection object.
:rtype: Connection object
:return: The connection to this regions endpoint
"""
if self.connection_cls:
return self.connection_cls(region=self, **kw_params)
| Python |
# Copyright (c) 2010 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 xml.sax
import cgi
from StringIO import StringIO
class ResponseGroup(xml.sax.ContentHandler):
"""A Generic "Response Group", which can
be anything from the entire list of Items to
specific response elements within an item"""
def __init__(self, connection=None, nodename=None):
"""Initialize this Item"""
self._connection = connection
self._nodename = nodename
self._nodepath = []
self._curobj = None
self._xml = StringIO()
def __repr__(self):
return '<%s: %s>' % (self.__class__.__name__, self.__dict__)
#
# Attribute Functions
#
def get(self, name):
return self.__dict__.get(name)
def set(self, name, value):
self.__dict__[name] = value
def to_xml(self):
return "<%s>%s</%s>" % (self._nodename, self._xml.getvalue(), self._nodename)
#
# XML Parser functions
#
def startElement(self, name, attrs, connection):
self._xml.write("<%s>" % name)
self._nodepath.append(name)
if len(self._nodepath) == 1:
obj = ResponseGroup(self._connection)
self.set(name, obj)
self._curobj = obj
elif self._curobj:
self._curobj.startElement(name, attrs, connection)
return None
def endElement(self, name, value, connection):
self._xml.write("%s</%s>" % (cgi.escape(value).replace("&amp;", "&"), name))
if len(self._nodepath) == 0:
return
obj = None
curval = self.get(name)
if len(self._nodepath) == 1:
if value or not curval:
self.set(name, value)
if self._curobj:
self._curobj = None
#elif len(self._nodepath) == 2:
#self._curobj = None
elif self._curobj:
self._curobj.endElement(name, value, connection)
self._nodepath.pop()
return None
class Item(ResponseGroup):
"""A single Item"""
def __init__(self, connection=None):
"""Initialize this Item"""
ResponseGroup.__init__(self, connection, "Item")
class ItemSet(ResponseGroup):
"""A special ResponseGroup that has built-in paging, and
only creates new Items on the "Item" tag"""
def __init__(self, connection, action, params, page=0):
ResponseGroup.__init__(self, connection, "Items")
self.objs = []
self.iter = None
self.page = page
self.action = action
self.params = params
self.curItem = None
def startElement(self, name, attrs, connection):
if name == "Item":
self.curItem = Item(self._connection)
elif self.curItem != None:
self.curItem.startElement(name, attrs, connection)
return None
def endElement(self, name, value, connection):
if name == 'TotalResults':
self.total_results = value
elif name == 'TotalPages':
self.total_pages = value
elif name == "Item":
self.objs.append(self.curItem)
self._xml.write(self.curItem.to_xml())
self.curItem = None
elif self.curItem != None:
self.curItem.endElement(name, value, connection)
return None
def next(self):
"""Special paging functionality"""
if self.iter == None:
self.iter = iter(self.objs)
try:
return self.iter.next()
except StopIteration:
self.iter = None
self.objs = []
if int(self.page) < int(self.total_pages):
self.page += 1
self._connection.get_response(self.action, self.params, self.page, self)
return self.next()
else:
raise
def __iter__(self):
return self
def to_xml(self):
"""Override to first fetch everything"""
for item in self:
pass
return ResponseGroup.to_xml(self)
| Python |
# Copyright (c) 2010 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 boto
from boto.connection import AWSQueryConnection, AWSAuthConnection
import time
import urllib
import xml.sax
from boto.ecs.item import ItemSet
from boto import handler
class ECSConnection(AWSQueryConnection):
"""ECommerse Connection"""
APIVersion = '2010-09-01'
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='ecs.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 make_request(self, action, params=None, path='/', verb='GET'):
"""Overriden because we don't do the "Action" setting here"""
headers = {}
if params == None:
params = {}
params['Version'] = self.APIVersion
params['AWSAccessKeyId'] = self.aws_access_key_id
params['SignatureVersion'] = self.SignatureVersion
params['Timestamp'] = time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime())
qs, signature = self.get_signature(params, verb, self.get_path(path))
if verb == 'POST':
headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
request_body = qs + '&Signature=' + urllib.quote(signature)
qs = path
else:
request_body = ''
qs = path + '?' + qs + '&Signature=' + urllib.quote(signature)
return AWSAuthConnection.make_request(self, verb, qs,
data=request_body,
headers=headers)
def get_response(self, action, params, page=0, itemSet=None):
"""
Utility method to handle calls to ECS and parsing of responses.
"""
params['Service'] = "AWSECommerceService"
params['Operation'] = action
if page:
params['ItemPage'] = page
response = self.make_request("GET", params, "/onca/xml")
body = response.read()
boto.log.debug(body)
if response.status != 200:
boto.log.error('%s %s' % (response.status, response.reason))
boto.log.error('%s' % body)
raise self.ResponseError(response.status, response.reason, body)
if itemSet == None:
rs = ItemSet(self, action, params, page)
else:
rs = itemSet
h = handler.XmlHandler(rs, self)
xml.sax.parseString(body, h)
return rs
#
# Group methods
#
def item_search(self, search_index, **params):
"""
Returns items that satisfy the search criteria, including one or more search
indices.
For a full list of search terms,
:see: http://docs.amazonwebservices.com/AWSECommerceService/2010-09-01/DG/index.html?ItemSearch.html
"""
params['SearchIndex'] = search_index
return self.get_response('ItemSearch', 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.
import xml.sax
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 = ''
new_node = self.nodes[-1][1].startElement(name, attrs, self.connection)
if new_node != None:
self.nodes.append((name, new_node))
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
| 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 boto.sqs.message import MHMessage
from boto.utils import get_ts
from socket import gethostname
import os, mimetypes, time
class ServiceMessage(MHMessage):
def for_key(self, key, params=None, bucket_name=None):
if params:
self.update(params)
if key.path:
t = os.path.split(key.path)
self['OriginalLocation'] = t[0]
self['OriginalFileName'] = t[1]
mime_type = mimetypes.guess_type(t[1])[0]
if mime_type == None:
mime_type = 'application/octet-stream'
self['Content-Type'] = mime_type
s = os.stat(key.path)
t = time.gmtime(s[7])
self['FileAccessedDate'] = get_ts(t)
t = time.gmtime(s[8])
self['FileModifiedDate'] = get_ts(t)
t = time.gmtime(s[9])
self['FileCreateDate'] = get_ts(t)
else:
self['OriginalFileName'] = key.name
self['OriginalLocation'] = key.bucket.name
self['ContentType'] = key.content_type
self['Host'] = gethostname()
if bucket_name:
self['Bucket'] = bucket_name
else:
self['Bucket'] = key.bucket.name
self['InputKey'] = key.name
self['Size'] = key.size
| 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 time
import os
class Submitter:
def __init__(self, sd):
self.sd = sd
self.input_bucket = self.sd.get_obj('input_bucket')
self.output_bucket = self.sd.get_obj('output_bucket')
self.output_domain = self.sd.get_obj('output_domain')
self.queue = self.sd.get_obj('input_queue')
def get_key_name(self, fullpath, prefix):
key_name = fullpath[len(prefix):]
l = key_name.split(os.sep)
return '/'.join(l)
def write_message(self, key, metadata):
if self.queue:
m = self.queue.new_message()
m.for_key(key, metadata)
if self.output_bucket:
m['OutputBucket'] = self.output_bucket.name
self.queue.write(m)
def submit_file(self, path, metadata=None, cb=None, num_cb=0, prefix='/'):
if not metadata:
metadata = {}
key_name = self.get_key_name(path, prefix)
k = self.input_bucket.new_key(key_name)
k.update_metadata(metadata)
k.set_contents_from_filename(path, replace=False, cb=cb, num_cb=num_cb)
self.write_message(k, metadata)
def submit_path(self, path, tags=None, ignore_dirs=None, cb=None, num_cb=0, status=False, prefix='/'):
path = os.path.expanduser(path)
path = os.path.expandvars(path)
path = os.path.abspath(path)
total = 0
metadata = {}
if tags:
metadata['Tags'] = tags
l = []
for t in time.gmtime():
l.append(str(t))
metadata['Batch'] = '_'.join(l)
if self.output_domain:
self.output_domain.put_attributes(metadata['Batch'], {'type' : 'Batch'})
if os.path.isdir(path):
for root, dirs, files in os.walk(path):
if ignore_dirs:
for ignore in ignore_dirs:
if ignore in dirs:
dirs.remove(ignore)
for file in files:
fullpath = os.path.join(root, file)
if status:
print 'Submitting %s' % fullpath
self.submit_file(fullpath, metadata, cb, num_cb, prefix)
total += 1
elif os.path.isfile(path):
self.submit_file(path, metadata, cb, num_cb)
total += 1
else:
print 'problem with %s' % path
return (metadata['Batch'], total)
| Python |
#!/usr/bin/env 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 optparse import OptionParser
from boto.services.servicedef import ServiceDef
from boto.services.submit import Submitter
from boto.services.result import ResultProcessor
import boto
import sys, os, StringIO
class BS(object):
Usage = "usage: %prog [options] config_file command"
Commands = {'reset' : 'Clear input queue and output bucket',
'submit' : 'Submit local files to the service',
'start' : 'Start the service',
'status' : 'Report on the status of the service buckets and queues',
'retrieve' : 'Retrieve output generated by a batch',
'batches' : 'List all batches stored in current output_domain'}
def __init__(self):
self.service_name = None
self.parser = OptionParser(usage=self.Usage)
self.parser.add_option("--help-commands", action="store_true", dest="help_commands",
help="provides help on the available commands")
self.parser.add_option("-a", "--access-key", action="store", type="string",
help="your AWS Access Key")
self.parser.add_option("-s", "--secret-key", action="store", type="string",
help="your AWS Secret Access Key")
self.parser.add_option("-p", "--path", action="store", type="string", dest="path",
help="the path to local directory for submit and retrieve")
self.parser.add_option("-k", "--keypair", action="store", type="string", dest="keypair",
help="the SSH keypair used with launched instance(s)")
self.parser.add_option("-l", "--leave", action="store_true", dest="leave",
help="leave the files (don't retrieve) files during retrieve command")
self.parser.set_defaults(leave=False)
self.parser.add_option("-n", "--num-instances", action="store", type="string", dest="num_instances",
help="the number of launched instance(s)")
self.parser.set_defaults(num_instances=1)
self.parser.add_option("-i", "--ignore-dirs", action="append", type="string", dest="ignore",
help="directories that should be ignored by submit command")
self.parser.add_option("-b", "--batch-id", action="store", type="string", dest="batch",
help="batch identifier required by the retrieve command")
def print_command_help(self):
print '\nCommands:'
for key in self.Commands.keys():
print ' %s\t\t%s' % (key, self.Commands[key])
def do_reset(self):
iq = self.sd.get_obj('input_queue')
if iq:
print 'clearing out input queue'
i = 0
m = iq.read()
while m:
i += 1
iq.delete_message(m)
m = iq.read()
print 'deleted %d messages' % i
ob = self.sd.get_obj('output_bucket')
ib = self.sd.get_obj('input_bucket')
if ob:
if ib and ob.name == ib.name:
return
print 'delete generated files in output bucket'
i = 0
for k in ob:
i += 1
k.delete()
print 'deleted %d keys' % i
def do_submit(self):
if not self.options.path:
self.parser.error('No path provided')
if not os.path.exists(self.options.path):
self.parser.error('Invalid path (%s)' % self.options.path)
s = Submitter(self.sd)
t = s.submit_path(self.options.path, None, self.options.ignore, None,
None, True, self.options.path)
print 'A total of %d files were submitted' % t[1]
print 'Batch Identifier: %s' % t[0]
def do_start(self):
ami_id = self.sd.get('ami_id')
instance_type = self.sd.get('instance_type', 'm1.small')
security_group = self.sd.get('security_group', 'default')
if not ami_id:
self.parser.error('ami_id option is required when starting the service')
ec2 = boto.connect_ec2()
if not self.sd.has_section('Credentials'):
self.sd.add_section('Credentials')
self.sd.set('Credentials', 'aws_access_key_id', ec2.aws_access_key_id)
self.sd.set('Credentials', 'aws_secret_access_key', ec2.aws_secret_access_key)
s = StringIO.StringIO()
self.sd.write(s)
rs = ec2.get_all_images([ami_id])
img = rs[0]
r = img.run(user_data=s.getvalue(), key_name=self.options.keypair,
max_count=self.options.num_instances,
instance_type=instance_type,
security_groups=[security_group])
print 'Starting AMI: %s' % ami_id
print 'Reservation %s contains the following instances:' % r.id
for i in r.instances:
print '\t%s' % i.id
def do_status(self):
iq = self.sd.get_obj('input_queue')
if iq:
print 'The input_queue (%s) contains approximately %s messages' % (iq.id, iq.count())
ob = self.sd.get_obj('output_bucket')
ib = self.sd.get_obj('input_bucket')
if ob:
if ib and ob.name == ib.name:
return
total = 0
for k in ob:
total += 1
print 'The output_bucket (%s) contains %d keys' % (ob.name, total)
def do_retrieve(self):
if not self.options.path:
self.parser.error('No path provided')
if not os.path.exists(self.options.path):
self.parser.error('Invalid path (%s)' % self.options.path)
if not self.options.batch:
self.parser.error('batch identifier is required for retrieve command')
s = ResultProcessor(self.options.batch, self.sd)
s.get_results(self.options.path, get_file=(not self.options.leave))
def do_batches(self):
d = self.sd.get_obj('output_domain')
if d:
print 'Available Batches:'
rs = d.query("['type'='Batch']")
for item in rs:
print ' %s' % item.name
else:
self.parser.error('No output_domain specified for service')
def main(self):
self.options, self.args = self.parser.parse_args()
if self.options.help_commands:
self.print_command_help()
sys.exit(0)
if len(self.args) != 2:
self.parser.error("config_file and command are required")
self.config_file = self.args[0]
self.sd = ServiceDef(self.config_file)
self.command = self.args[1]
if hasattr(self, 'do_%s' % self.command):
method = getattr(self, 'do_%s' % self.command)
method()
else:
self.parser.error('command (%s) not recognized' % self.command)
if __name__ == "__main__":
bs = BS()
bs.main()
| Python |
#!/usr/bin/env 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 os
from datetime import datetime, timedelta
from boto.utils import parse_ts
import boto
class ResultProcessor:
LogFileName = 'log.csv'
def __init__(self, batch_name, sd, mimetype_files=None):
self.sd = sd
self.batch = batch_name
self.log_fp = None
self.num_files = 0
self.total_time = 0
self.min_time = timedelta.max
self.max_time = timedelta.min
self.earliest_time = datetime.max
self.latest_time = datetime.min
self.queue = self.sd.get_obj('output_queue')
self.domain = self.sd.get_obj('output_domain')
def calculate_stats(self, msg):
start_time = parse_ts(msg['Service-Read'])
end_time = parse_ts(msg['Service-Write'])
elapsed_time = end_time - start_time
if elapsed_time > self.max_time:
self.max_time = elapsed_time
if elapsed_time < self.min_time:
self.min_time = elapsed_time
self.total_time += elapsed_time.seconds
if start_time < self.earliest_time:
self.earliest_time = start_time
if end_time > self.latest_time:
self.latest_time = end_time
def log_message(self, msg, path):
keys = msg.keys()
keys.sort()
if not self.log_fp:
self.log_fp = open(os.path.join(path, self.LogFileName), 'a')
line = ','.join(keys)
self.log_fp.write(line+'\n')
values = []
for key in keys:
value = msg[key]
if value.find(',') > 0:
value = '"%s"' % value
values.append(value)
line = ','.join(values)
self.log_fp.write(line+'\n')
def process_record(self, record, path, get_file=True):
self.log_message(record, path)
self.calculate_stats(record)
outputs = record['OutputKey'].split(',')
if record.has_key('OutputBucket'):
bucket = boto.lookup('s3', record['OutputBucket'])
else:
bucket = boto.lookup('s3', record['Bucket'])
for output in outputs:
if get_file:
key_name = output.split(';')[0]
key = bucket.lookup(key_name)
file_name = os.path.join(path, key_name)
print 'retrieving file: %s to %s' % (key_name, file_name)
key.get_contents_to_filename(file_name)
self.num_files += 1
def get_results_from_queue(self, path, get_file=True, delete_msg=True):
m = self.queue.read()
while m:
if m.has_key('Batch') and m['Batch'] == self.batch:
self.process_record(m, path, get_file)
if delete_msg:
self.queue.delete_message(m)
m = self.queue.read()
def get_results_from_domain(self, path, get_file=True):
rs = self.domain.query("['Batch'='%s']" % self.batch)
for item in rs:
self.process_record(item, path, get_file)
def get_results_from_bucket(self, path):
bucket = self.sd.get_obj('output_bucket')
if bucket:
print 'No output queue or domain, just retrieving files from output_bucket'
for key in bucket:
file_name = os.path.join(path, key)
print 'retrieving file: %s to %s' % (key, file_name)
key.get_contents_to_filename(file_name)
self.num_files + 1
def get_results(self, path, get_file=True, delete_msg=True):
if not os.path.isdir(path):
os.mkdir(path)
if self.queue:
self.get_results_from_queue(path, get_file)
elif self.domain:
self.get_results_from_domain(path, get_file)
else:
self.get_results_from_bucket(path)
if self.log_fp:
self.log_fp.close()
print '%d results successfully retrieved.' % self.num_files
if self.num_files > 0:
self.avg_time = float(self.total_time)/self.num_files
print 'Minimum Processing Time: %d' % self.min_time.seconds
print 'Maximum Processing Time: %d' % self.max_time.seconds
print 'Average Processing Time: %f' % self.avg_time
self.elapsed_time = self.latest_time-self.earliest_time
print 'Elapsed Time: %d' % self.elapsed_time.seconds
tput = 1.0 / ((self.elapsed_time.seconds/60.0) / self.num_files)
print 'Throughput: %f transactions / minute' % tput
| 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 boto
from boto.services.service import Service
from boto.services.message import ServiceMessage
import os
import mimetypes
class SonOfMMM(Service):
def __init__(self, config_file=None):
Service.__init__(self, config_file)
self.log_file = '%s.log' % self.instance_id
self.log_path = os.path.join(self.working_dir, self.log_file)
boto.set_file_logger(self.name, self.log_path)
if self.sd.has_option('ffmpeg_args'):
self.command = '/usr/local/bin/ffmpeg ' + self.sd.get('ffmpeg_args')
else:
self.command = '/usr/local/bin/ffmpeg -y -i %s %s'
self.output_mimetype = self.sd.get('output_mimetype')
if self.sd.has_option('output_ext'):
self.output_ext = self.sd.get('output_ext')
else:
self.output_ext = mimetypes.guess_extension(self.output_mimetype)
self.output_bucket = self.sd.get_obj('output_bucket')
self.input_bucket = self.sd.get_obj('input_bucket')
# check to see if there are any messages queue
# if not, create messages for all files in input_bucket
m = self.input_queue.read(1)
if not m:
self.queue_files()
def queue_files(self):
boto.log.info('Queueing files from %s' % self.input_bucket.name)
for key in self.input_bucket:
boto.log.info('Queueing %s' % key.name)
m = ServiceMessage()
if self.output_bucket:
d = {'OutputBucket' : self.output_bucket.name}
else:
d = None
m.for_key(key, d)
self.input_queue.write(m)
def process_file(self, in_file_name, msg):
base, ext = os.path.splitext(in_file_name)
out_file_name = os.path.join(self.working_dir,
base+self.output_ext)
command = self.command % (in_file_name, out_file_name)
boto.log.info('running:\n%s' % command)
status = self.run(command)
if status == 0:
return [(out_file_name, self.output_mimetype)]
else:
return []
def shutdown(self):
if os.path.isfile(self.log_path):
if self.output_bucket:
key = self.output_bucket.new_key(self.log_file)
key.set_contents_from_filename(self.log_path)
Service.shutdown(self)
| 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 boto.pyami.config import Config
from boto.services.message import ServiceMessage
import boto
class ServiceDef(Config):
def __init__(self, config_file, aws_access_key_id=None, aws_secret_access_key=None):
Config.__init__(self, config_file)
self.aws_access_key_id = aws_access_key_id
self.aws_secret_access_key = aws_secret_access_key
script = Config.get(self, 'Pyami', 'scripts')
if script:
self.name = script.split('.')[-1]
else:
self.name = None
def get(self, name, default=None):
return Config.get(self, self.name, name, default)
def has_option(self, option):
return Config.has_option(self, self.name, option)
def getint(self, option, default=0):
try:
val = Config.get(self, self.name, option)
val = int(val)
except:
val = int(default)
return val
def getbool(self, option, default=False):
try:
val = Config.get(self, self.name, option)
if val.lower() == 'true':
val = True
else:
val = False
except:
val = default
return val
def get_obj(self, name):
"""
Returns the AWS object associated with a given option.
The heuristics used are a bit lame. If the option name contains
the word 'bucket' it is assumed to be an S3 bucket, if the name
contains the word 'queue' it is assumed to be an SQS queue and
if it contains the word 'domain' it is assumed to be a SimpleDB
domain. If the option name specified does not exist in the
config file or if the AWS object cannot be retrieved this
returns None.
"""
val = self.get(name)
if not val:
return None
if name.find('queue') >= 0:
obj = boto.lookup('sqs', val)
if obj:
obj.set_message_class(ServiceMessage)
elif name.find('bucket') >= 0:
obj = boto.lookup('s3', val)
elif name.find('domain') >= 0:
obj = boto.lookup('sdb', val)
else:
obj = None
return obj
| 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) 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 boto
from boto.services.message import ServiceMessage
from boto.services.servicedef import ServiceDef
from boto.pyami.scriptbase import ScriptBase
from boto.utils import get_ts
import time
import os
import mimetypes
class Service(ScriptBase):
# Time required to process a transaction
ProcessingTime = 60
def __init__(self, config_file=None, mimetype_files=None):
ScriptBase.__init__(self, config_file)
self.name = self.__class__.__name__
self.working_dir = boto.config.get('Pyami', 'working_dir')
self.sd = ServiceDef(config_file)
self.retry_count = self.sd.getint('retry_count', 5)
self.loop_delay = self.sd.getint('loop_delay', 30)
self.processing_time = self.sd.getint('processing_time', 60)
self.input_queue = self.sd.get_obj('input_queue')
self.output_queue = self.sd.get_obj('output_queue')
self.output_domain = self.sd.get_obj('output_domain')
if mimetype_files:
mimetypes.init(mimetype_files)
def split_key(key):
if key.find(';') < 0:
t = (key, '')
else:
key, type = key.split(';')
label, mtype = type.split('=')
t = (key, mtype)
return t
def read_message(self):
boto.log.info('read_message')
message = self.input_queue.read(self.processing_time)
if message:
boto.log.info(message.get_body())
key = 'Service-Read'
message[key] = get_ts()
return message
# retrieve the source file from S3
def get_file(self, message):
bucket_name = message['Bucket']
key_name = message['InputKey']
file_name = os.path.join(self.working_dir, message.get('OriginalFileName', 'in_file'))
boto.log.info('get_file: %s/%s to %s' % (bucket_name, key_name, file_name))
bucket = boto.lookup('s3', bucket_name)
key = bucket.new_key(key_name)
key.get_contents_to_filename(os.path.join(self.working_dir, file_name))
return file_name
# process source file, return list of output files
def process_file(self, in_file_name, msg):
return []
# store result file in S3
def put_file(self, bucket_name, file_path, key_name=None):
boto.log.info('putting file %s as %s.%s' % (file_path, bucket_name, key_name))
bucket = boto.lookup('s3', bucket_name)
key = bucket.new_key(key_name)
key.set_contents_from_filename(file_path)
return key
def save_results(self, results, input_message, output_message):
output_keys = []
for file, type in results:
if input_message.has_key('OutputBucket'):
output_bucket = input_message['OutputBucket']
else:
output_bucket = input_message['Bucket']
key_name = os.path.split(file)[1]
key = self.put_file(output_bucket, file, key_name)
output_keys.append('%s;type=%s' % (key.name, type))
output_message['OutputKey'] = ','.join(output_keys)
# write message to each output queue
def write_message(self, message):
message['Service-Write'] = get_ts()
message['Server'] = self.name
if os.environ.has_key('HOSTNAME'):
message['Host'] = os.environ['HOSTNAME']
else:
message['Host'] = 'unknown'
message['Instance-ID'] = self.instance_id
if self.output_queue:
boto.log.info('Writing message to SQS queue: %s' % self.output_queue.id)
self.output_queue.write(message)
if self.output_domain:
boto.log.info('Writing message to SDB domain: %s' % self.output_domain.name)
item_name = '/'.join([message['Service-Write'], message['Bucket'], message['InputKey']])
self.output_domain.put_attributes(item_name, message)
# delete message from input queue
def delete_message(self, message):
boto.log.info('deleting message from %s' % self.input_queue.id)
self.input_queue.delete_message(message)
# to clean up any files, etc. after each iteration
def cleanup(self):
pass
def shutdown(self):
on_completion = self.sd.get('on_completion', 'shutdown')
if on_completion == 'shutdown':
if self.instance_id:
time.sleep(60)
c = boto.connect_ec2()
c.terminate_instances([self.instance_id])
def main(self, notify=False):
self.notify('Service: %s Starting' % self.name)
empty_reads = 0
while self.retry_count < 0 or empty_reads < self.retry_count:
try:
input_message = self.read_message()
if input_message:
empty_reads = 0
output_message = ServiceMessage(None, input_message.get_body())
input_file = self.get_file(input_message)
results = self.process_file(input_file, output_message)
self.save_results(results, input_message, output_message)
self.write_message(output_message)
self.delete_message(input_message)
self.cleanup()
else:
empty_reads += 1
time.sleep(self.loop_delay)
except Exception:
boto.log.exception('Service Failed')
empty_reads += 1
self.notify('Service: %s Shutting Down' % self.name)
self.shutdown()
| 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 Prefix:
def __init__(self, bucket=None, name=None):
self.bucket = bucket
self.name = name
def startElement(self, name, attrs, connection):
return None
def endElement(self, name, value, connection):
if name == 'Prefix':
self.name = value
else:
setattr(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.
def bucket_lister(bucket, prefix='', delimiter='', marker='', headers=None):
"""
A generator function for listing keys in a bucket.
"""
more_results = True
k = None
while more_results:
rs = bucket.get_all_keys(prefix=prefix, marker=marker,
delimiter=delimiter, headers=headers)
for k in rs:
yield k
if k:
marker = k.name
more_results= rs.is_truncated
class BucketListResultSet:
"""
A resultset for listing keys within a bucket. Uses the bucket_lister
generator function and implements the iterator interface. This
transparently handles the results paging from S3 so even if you have
many thousands of keys within the bucket you can iterate over all
keys in a reasonably efficient manner.
"""
def __init__(self, bucket=None, prefix='', delimiter='', marker='', headers=None):
self.bucket = bucket
self.prefix = prefix
self.delimiter = delimiter
self.marker = marker
self.headers = headers
def __iter__(self):
return bucket_lister(self.bucket, prefix=self.prefix,
delimiter=self.delimiter, marker=self.marker, headers=self.headers)
def versioned_bucket_lister(bucket, prefix='', delimiter='',
key_marker='', version_id_marker='', headers=None):
"""
A generator function for listing versions in a bucket.
"""
more_results = True
k = None
while more_results:
rs = bucket.get_all_versions(prefix=prefix, key_marker=key_marker,
version_id_marker=version_id_marker,
delimiter=delimiter, headers=headers)
for k in rs:
yield k
key_marker = rs.next_key_marker
version_id_marker = rs.next_version_id_marker
more_results= rs.is_truncated
class VersionedBucketListResultSet:
"""
A resultset for listing versions within a bucket. Uses the bucket_lister
generator function and implements the iterator interface. This
transparently handles the results paging from S3 so even if you have
many thousands of keys within the bucket you can iterate over all
keys in a reasonably efficient manner.
"""
def __init__(self, bucket=None, prefix='', delimiter='', key_marker='',
version_id_marker='', headers=None):
self.bucket = bucket
self.prefix = prefix
self.delimiter = delimiter
self.key_marker = key_marker
self.version_id_marker = version_id_marker
self.headers = headers
def __iter__(self):
return versioned_bucket_lister(self.bucket, prefix=self.prefix,
delimiter=self.delimiter,
key_marker=self.key_marker,
version_id_marker=self.version_id_marker,
headers=self.headers)
| 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 mimetypes
import os
import rfc822
import StringIO
import base64
import boto.utils
from boto.exception import BotoClientError
from boto.provider import Provider
from boto.s3.user import User
from boto import UserAgent
try:
from hashlib import md5
except ImportError:
from md5 import md5
class Key(object):
DefaultContentType = 'application/octet-stream'
BufferSize = 8192
def __init__(self, bucket=None, name=None):
self.bucket = bucket
self.name = name
self.metadata = {}
self.cache_control = None
self.content_type = self.DefaultContentType
self.content_encoding = None
self.filename = None
self.etag = None
self.last_modified = None
self.owner = None
self.storage_class = 'STANDARD'
self.md5 = None
self.base64md5 = None
self.path = None
self.resp = None
self.mode = None
self.size = None
self.version_id = None
self.source_version_id = None
self.delete_marker = False
def __repr__(self):
if self.bucket:
return '<Key: %s,%s>' % (self.bucket.name, self.name)
else:
return '<Key: None,%s>' % self.name
def __getattr__(self, name):
if name == 'key':
return self.name
else:
raise AttributeError
def __setattr__(self, name, value):
if name == 'key':
self.__dict__['name'] = value
else:
self.__dict__[name] = value
def __iter__(self):
return self
@property
def provider(self):
provider = None
if self.bucket:
if self.bucket.connection:
provider = self.bucket.connection.provider
return provider
def get_md5_from_hexdigest(self, md5_hexdigest):
"""
A utility function to create the 2-tuple (md5hexdigest, base64md5)
from just having a precalculated md5_hexdigest.
"""
import binascii
digest = binascii.unhexlify(md5_hexdigest)
base64md5 = base64.encodestring(digest)
if base64md5[-1] == '\n':
base64md5 = base64md5[0:-1]
return (md5_hexdigest, base64md5)
def handle_version_headers(self, resp, force=False):
provider = self.bucket.connection.provider
# If the Key object already has a version_id attribute value, it
# means that it represents an explicit version and the user is
# doing a get_contents_*(version_id=<foo>) to retrieve another
# version of the Key. In that case, we don't really want to
# overwrite the version_id in this Key object. Comprende?
if self.version_id is None or force:
self.version_id = resp.getheader(provider.version_id, None)
self.source_version_id = resp.getheader(provider.copy_source_version_id, None)
if resp.getheader(provider.delete_marker, 'false') == 'true':
self.delete_marker = True
else:
self.delete_marker = False
def open_read(self, headers=None, query_args=None,
override_num_retries=None):
"""
Open this key for reading
:type headers: dict
:param headers: Headers to pass in the web request
:type query_args: string
:param query_args: Arguments to pass in the query string (ie, 'torrent')
:type override_num_retries: int
:param override_num_retries: If not None will override configured
num_retries parameter for underlying GET.
"""
if self.resp == None:
self.mode = 'r'
provider = self.bucket.connection.provider
self.resp = self.bucket.connection.make_request(
'GET', self.bucket.name, self.name, headers,
query_args=query_args,
override_num_retries=override_num_retries)
if self.resp.status < 199 or self.resp.status > 299:
body = self.resp.read()
raise provider.storage_response_error(self.resp.status,
self.resp.reason, body)
response_headers = self.resp.msg
self.metadata = boto.utils.get_aws_metadata(response_headers,
provider)
for name,value in response_headers.items():
if name.lower() == 'content-length':
self.size = int(value)
elif name.lower() == 'etag':
self.etag = value
elif name.lower() == 'content-type':
self.content_type = value
elif name.lower() == 'content-encoding':
self.content_encoding = value
elif name.lower() == 'last-modified':
self.last_modified = value
elif name.lower() == 'cache-control':
self.cache_control = value
self.handle_version_headers(self.resp)
def open_write(self, headers=None, override_num_retries=None):
"""
Open this key for writing.
Not yet implemented
:type headers: dict
:param headers: Headers to pass in the write request
:type override_num_retries: int
:param override_num_retries: If not None will override configured
num_retries parameter for underlying PUT.
"""
raise BotoClientError('Not Implemented')
def open(self, mode='r', headers=None, query_args=None,
override_num_retries=None):
if mode == 'r':
self.mode = 'r'
self.open_read(headers=headers, query_args=query_args,
override_num_retries=override_num_retries)
elif mode == 'w':
self.mode = 'w'
self.open_write(headers=headers,
override_num_retries=override_num_retries)
else:
raise BotoClientError('Invalid mode: %s' % mode)
closed = False
def close(self):
if self.resp:
self.resp.read()
self.resp = None
self.mode = None
self.closed = True
def next(self):
"""
By providing a next method, the key object supports use as an iterator.
For example, you can now say:
for bytes in key:
write bytes to a file or whatever
All of the HTTP connection stuff is handled for you.
"""
self.open_read()
data = self.resp.read(self.BufferSize)
if not data:
self.close()
raise StopIteration
return data
def read(self, size=0):
if size == 0:
size = self.BufferSize
self.open_read()
data = self.resp.read(size)
if not data:
self.close()
return data
def change_storage_class(self, new_storage_class, dst_bucket=None):
"""
Change the storage class of an existing key.
Depending on whether a different destination bucket is supplied
or not, this will either move the item within the bucket, preserving
all metadata and ACL info bucket changing the storage class or it
will copy the item to the provided destination bucket, also
preserving metadata and ACL info.
:type new_storage_class: string
:param new_storage_class: The new storage class for the Key.
Possible values are:
* STANDARD
* REDUCED_REDUNDANCY
:type dst_bucket: string
:param dst_bucket: The name of a destination bucket. If not
provided the current bucket of the key
will be used.
"""
if new_storage_class == 'STANDARD':
return self.copy(self.bucket.name, self.name,
reduced_redundancy=False, preserve_acl=True)
elif new_storage_class == 'REDUCED_REDUNDANCY':
return self.copy(self.bucket.name, self.name,
reduced_redundancy=True, preserve_acl=True)
else:
raise BotoClientError('Invalid storage class: %s' %
new_storage_class)
def copy(self, dst_bucket, dst_key, metadata=None,
reduced_redundancy=False, preserve_acl=False):
"""
Copy this Key to another bucket.
:type dst_bucket: string
:param dst_bucket: The name of the destination bucket
:type dst_key: string
:param dst_key: The name of the destination key
:type metadata: dict
:param metadata: Metadata to be associated with new key.
If metadata is supplied, it will replace the
metadata of the source key being copied.
If no metadata is supplied, the source key's
metadata will be copied to the new key.
:type reduced_redundancy: bool
:param reduced_redundancy: If True, this will force the storage
class of the new Key to be
REDUCED_REDUNDANCY regardless of the
storage class of the key being copied.
The Reduced Redundancy Storage (RRS)
feature of S3, provides lower
redundancy at lower storage cost.
:type preserve_acl: bool
:param preserve_acl: If True, the ACL from the source key
will be copied to the destination
key. If False, the destination key
will have the default ACL.
Note that preserving the ACL in the
new key object will require two
additional API calls to S3, one to
retrieve the current ACL and one to
set that ACL on the new object. If
you don't care about the ACL, a value
of False will be significantly more
efficient.
:rtype: :class:`boto.s3.key.Key` or subclass
:returns: An instance of the newly created key object
"""
dst_bucket = self.bucket.connection.lookup(dst_bucket)
if reduced_redundancy:
storage_class = 'REDUCED_REDUNDANCY'
else:
storage_class = self.storage_class
return dst_bucket.copy_key(dst_key, self.bucket.name,
self.name, metadata,
storage_class=storage_class,
preserve_acl=preserve_acl)
def startElement(self, name, attrs, connection):
if name == 'Owner':
self.owner = User(self)
return self.owner
else:
return None
def endElement(self, name, value, connection):
if name == 'Key':
self.name = value.encode('utf-8')
elif name == 'ETag':
self.etag = value
elif name == 'LastModified':
self.last_modified = value
elif name == 'Size':
self.size = int(value)
elif name == 'StorageClass':
self.storage_class = value
elif name == 'Owner':
pass
elif name == 'VersionId':
self.version_id = value
else:
setattr(self, name, value)
def exists(self):
"""
Returns True if the key exists
:rtype: bool
:return: Whether the key exists on S3
"""
return bool(self.bucket.lookup(self.name))
def delete(self):
"""
Delete this key from S3
"""
return self.bucket.delete_key(self.name, version_id=self.version_id)
def get_metadata(self, name):
return self.metadata.get(name)
def set_metadata(self, name, value):
self.metadata[name] = value
def update_metadata(self, d):
self.metadata.update(d)
# convenience methods for setting/getting ACL
def set_acl(self, acl_str, headers=None):
if self.bucket != None:
self.bucket.set_acl(acl_str, self.name, headers=headers)
def get_acl(self, headers=None):
if self.bucket != None:
return self.bucket.get_acl(self.name, headers=headers)
def get_xml_acl(self, headers=None):
if self.bucket != None:
return self.bucket.get_xml_acl(self.name, headers=headers)
def set_xml_acl(self, acl_str, headers=None):
if self.bucket != None:
return self.bucket.set_xml_acl(acl_str, self.name, headers=headers)
def set_canned_acl(self, acl_str, headers=None):
return self.bucket.set_canned_acl(acl_str, self.name, headers)
def make_public(self, headers=None):
return self.bucket.set_canned_acl('public-read', self.name, headers)
def generate_url(self, expires_in, method='GET', headers=None,
query_auth=True, force_http=False):
"""
Generate a URL to access this key.
:type expires_in: int
:param expires_in: How long the url is valid for, in seconds
:type method: string
:param method: The method to use for retrieving the file (default is GET)
:type headers: dict
:param headers: Any headers to pass along in the request
:type query_auth: bool
:param query_auth:
:rtype: string
:return: The URL to access the key
"""
return self.bucket.connection.generate_url(expires_in, method,
self.bucket.name, self.name,
headers, query_auth, force_http)
def send_file(self, fp, headers=None, cb=None, num_cb=10):
"""
Upload a file to a key into a bucket on S3.
:type fp: file
: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 S3 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.
"""
provider = self.bucket.connection.provider
def sender(http_conn, method, path, data, headers):
http_conn.putrequest(method, path)
for key in headers:
http_conn.putheader(key, headers[key])
http_conn.endheaders()
fp.seek(0)
save_debug = self.bucket.connection.debug
self.bucket.connection.debug = 0
http_conn.set_debuglevel(0)
if cb:
if num_cb > 2:
cb_count = self.size / self.BufferSize / (num_cb-2)
elif num_cb < 0:
cb_count = -1
else:
cb_count = 0
i = total_bytes = 0
cb(total_bytes, self.size)
l = fp.read(self.BufferSize)
while len(l) > 0:
http_conn.send(l)
if cb:
total_bytes += len(l)
i += 1
if i == cb_count or cb_count == -1:
cb(total_bytes, self.size)
i = 0
l = fp.read(self.BufferSize)
if cb:
cb(total_bytes, self.size)
response = http_conn.getresponse()
body = response.read()
fp.seek(0)
http_conn.set_debuglevel(save_debug)
self.bucket.connection.debug = save_debug
if response.status == 500 or response.status == 503 or \
response.getheader('location'):
# we'll try again
return response
elif response.status >= 200 and response.status <= 299:
self.etag = response.getheader('etag')
if self.etag != '"%s"' % self.md5:
raise provider.storage_data_error(
'ETag from S3 did not match computed MD5')
return response
else:
raise provider.storage_response_error(
response.status, response.reason, body)
if not headers:
headers = {}
else:
headers = headers.copy()
headers['User-Agent'] = UserAgent
headers['Content-MD5'] = self.base64md5
if self.storage_class != 'STANDARD':
headers[provider.storage_class_header] = self.storage_class
if headers.has_key('Content-Encoding'):
self.content_encoding = headers['Content-Encoding']
if headers.has_key('Content-Type'):
self.content_type = headers['Content-Type']
elif self.path:
self.content_type = mimetypes.guess_type(self.path)[0]
if self.content_type == None:
self.content_type = self.DefaultContentType
headers['Content-Type'] = self.content_type
else:
headers['Content-Type'] = self.content_type
headers['Content-Length'] = str(self.size)
headers['Expect'] = '100-Continue'
headers = boto.utils.merge_meta(headers, self.metadata, provider)
resp = self.bucket.connection.make_request('PUT', self.bucket.name,
self.name, headers,
sender=sender)
self.handle_version_headers(resp, force=True)
def compute_md5(self, fp):
"""
:type fp: file
:param fp: File pointer to the file to MD5 hash. The file pointer will be
reset to the beginning of the file before the method returns.
:rtype: tuple
:return: A tuple containing the hex digest version of the MD5 hash
as the first element and the base64 encoded version of the
plain digest as the second element.
"""
m = md5()
fp.seek(0)
s = fp.read(self.BufferSize)
while s:
m.update(s)
s = fp.read(self.BufferSize)
hex_md5 = m.hexdigest()
base64md5 = base64.encodestring(m.digest())
if base64md5[-1] == '\n':
base64md5 = base64md5[0:-1]
self.size = fp.tell()
fp.seek(0)
return (hex_md5, base64md5)
def set_contents_from_file(self, fp, headers=None, replace=True,
cb=None, num_cb=10, policy=None, md5=None,
reduced_redundancy=False):
"""
Store an object in S3 using the name of the Key object as the
key in S3 and the contents of the file pointed to by 'fp' as the
contents.
:type fp: file
:param fp: the file whose contents to upload
:type headers: dict
:param headers: additional HTTP headers that will 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 S3 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.s3.acl.CannedACLStrings`
:param policy: A canned ACL policy that will be applied to the new key in S3.
: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 reduced_redundancy: bool
:param reduced_redundancy: If True, this will set the storage
class of the new Key to be
REDUCED_REDUNDANCY. The Reduced Redundancy
Storage (RRS) feature of S3, provides lower
redundancy at lower storage cost.
"""
provider = self.bucket.connection.provider
if headers is None:
headers = {}
if policy:
headers[provider.acl_header] = policy
if reduced_redundancy:
self.storage_class = 'REDUCED_REDUNDANCY'
if provider.storage_class_header:
headers[provider.storage_class_header] = self.storage_class
# TODO - What if the provider doesn't support reduced reduncancy?
# What if different providers provide different classes?
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
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=False):
"""
Store an object in S3 using the name of the Key object as the
key in S3 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 S3
:type headers: dict
:param headers: Additional headers to pass along with the request to AWS.
: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 S3 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.s3.acl.CannedACLStrings`
:param policy: A canned ACL policy that will be applied to the new key in S3.
: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 reduced_redundancy: bool
:param reduced_redundancy: If True, this will set the storage
class of the new Key to be
REDUCED_REDUNDANCY. The Reduced Redundancy
Storage (RRS) feature of S3, provides lower
redundancy at lower storage cost.
"""
fp = open(filename, 'rb')
self.set_contents_from_file(fp, headers, replace, cb, num_cb,
policy, md5, reduced_redundancy)
fp.close()
def set_contents_from_string(self, s, headers=None, replace=True,
cb=None, num_cb=10, policy=None, md5=None,
reduced_redundancy=False):
"""
Store an object in S3 using the name of the Key object as the
key in S3 and the string 's' as the contents.
See set_contents_from_file method for details about the
parameters.
:type headers: dict
:param headers: Additional headers to pass along with the request to AWS.
: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 S3 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.s3.acl.CannedACLStrings`
:param policy: A canned ACL policy that will be applied to the new key in S3.
: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 reduced_redundancy: bool
:param reduced_redundancy: If True, this will set the storage
class of the new Key to be
REDUCED_REDUNDANCY. The Reduced Redundancy
Storage (RRS) feature of S3, provides lower
redundancy at lower storage cost.
"""
fp = StringIO.StringIO(s)
r = self.set_contents_from_file(fp, headers, replace, cb, num_cb,
policy, md5, reduced_redundancy)
fp.close()
return r
def get_file(self, fp, headers=None, cb=None, num_cb=10,
torrent=False, version_id=None, override_num_retries=None):
"""
Retrieves a file from an S3 Key
:type fp: file
:param fp: File pointer to put the data into
:type headers: string
:param: headers to send when retrieving the files
: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 S3 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 torrent: bool
:param torrent: Flag for whether to get a torrent for the file
:type override_num_retries: int
:param override_num_retries: If not None will override configured
num_retries parameter for underlying GET.
"""
if cb:
if num_cb > 2:
cb_count = self.size / self.BufferSize / (num_cb-2)
elif num_cb < 0:
cb_count = -1
else:
cb_count = 0
i = total_bytes = 0
cb(total_bytes, self.size)
save_debug = self.bucket.connection.debug
if self.bucket.connection.debug == 1:
self.bucket.connection.debug = 0
query_args = ''
if torrent:
query_args = 'torrent'
# If a version_id is passed in, use that. If not, check to see
# if the Key object has an explicit version_id and, if so, use that.
# Otherwise, don't pass a version_id query param.
if version_id is None:
version_id = self.version_id
if version_id:
query_args = 'versionId=%s' % version_id
self.open('r', headers, query_args=query_args,
override_num_retries=override_num_retries)
for bytes in self:
fp.write(bytes)
if cb:
total_bytes += len(bytes)
i += 1
if i == cb_count or cb_count == -1:
cb(total_bytes, self.size)
i = 0
if cb:
cb(total_bytes, self.size)
self.close()
self.bucket.connection.debug = save_debug
def get_torrent_file(self, fp, headers=None, cb=None, num_cb=10):
"""
Get a torrent file (see to get_file)
:type fp: file
:param fp: The file pointer of where to put the torrent
:type headers: dict
:param headers: Headers to be passed
:type cb: function
:param cb: Callback function to call on retrieved data
: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.
"""
return self.get_file(fp, headers, cb, num_cb, torrent=True)
def get_contents_to_file(self, fp, headers=None,
cb=None, num_cb=10,
torrent=False,
version_id=None,
res_download_handler=None):
"""
Retrieve an object from S3 using the name of the Key object as the
key in S3. Write the contents of the object to the file pointed
to by 'fp'.
:type fp: File -like object
:param fp:
:type headers: dict
:param headers: additional HTTP headers that will be sent with the GET request.
: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 S3 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 torrent: bool
:param torrent: If True, returns the contents of a torrent file as a string.
:type res_upload_handler: ResumableDownloadHandler
:param res_download_handler: If provided, this handler will perform the
download.
"""
if self.bucket != None:
if res_download_handler:
res_download_handler.get_file(self, fp, headers, cb, num_cb,
torrent=torrent,
version_id=version_id)
else:
self.get_file(fp, headers, cb, num_cb, torrent=torrent,
version_id=version_id)
def get_contents_to_filename(self, filename, headers=None,
cb=None, num_cb=10,
torrent=False,
version_id=None,
res_download_handler=None):
"""
Retrieve an object from S3 using the name of the Key object as the
key in S3. Store contents of the object to a file named by 'filename'.
See get_contents_to_file method for details about the
parameters.
:type filename: string
:param filename: The filename of where to put the file contents
:type headers: dict
:param headers: Any additional headers to send in the request
: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 S3 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 torrent: bool
:param torrent: If True, returns the contents of a torrent file as a string.
:type res_upload_handler: ResumableDownloadHandler
:param res_download_handler: If provided, this handler will perform the
download.
"""
fp = open(filename, 'wb')
self.get_contents_to_file(fp, headers, cb, num_cb, torrent=torrent,
version_id=version_id,
res_download_handler=res_download_handler)
fp.close()
# if last_modified date was sent from s3, try to set file's timestamp
if self.last_modified != None:
try:
modified_tuple = rfc822.parsedate_tz(self.last_modified)
modified_stamp = int(rfc822.mktime_tz(modified_tuple))
os.utime(fp.name, (modified_stamp, modified_stamp))
except Exception: pass
def get_contents_as_string(self, headers=None,
cb=None, num_cb=10,
torrent=False,
version_id=None):
"""
Retrieve an object from S3 using the name of the Key object as the
key in S3. Return the contents of the object as a string.
See get_contents_to_file method for details about the
parameters.
:type headers: dict
:param headers: Any additional headers to send in the request
: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 S3 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 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 torrent: bool
:param torrent: If True, returns the contents of a torrent file as a string.
:rtype: string
:returns: The contents of the file as a string
"""
fp = StringIO.StringIO()
self.get_contents_to_file(fp, headers, cb, num_cb, torrent=torrent,
version_id=version_id)
return fp.getvalue()
def add_email_grant(self, permission, email_address, headers=None):
"""
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 S3.
:type permission: string
:param permission: The permission being granted. Should be one of:
READ|WRITE|READ_ACP|WRITE_ACP|FULL_CONTROL
See http://docs.amazonwebservices.com/AmazonS3/2006-03-01/UsingAuthAccess.html
for more details on permissions.
:type email_address: string
:param email_address: The email address associated with the AWS account your are granting
the permission to.
"""
policy = self.get_acl(headers=headers)
policy.acl.add_email_grant(permission, email_address)
self.set_acl(policy, headers=headers)
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 S3.
:type permission: string
:param permission: The permission being granted. Should be one of:
READ|WRITE|READ_ACP|WRITE_ACP|FULL_CONTROL
See http://docs.amazonwebservices.com/AmazonS3/2006-03-01/UsingAuthAccess.html
for more details on permissions.
:type user_id: string
:param user_id: The canonical user id associated with the AWS account your are granting
the permission to.
"""
policy = self.get_acl()
policy.acl.add_user_grant(permission, user_id)
self.set_acl(policy)
| 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.
import xml.sax
import urllib, base64
import time
import boto.utils
from boto.connection import AWSAuthConnection
from boto import handler
from boto.provider import Provider
from boto.s3.bucket import Bucket
from boto.s3.key import Key
from boto.resultset import ResultSet
from boto.exception import BotoClientError
def check_lowercase_bucketname(n):
"""
Bucket names must not contain uppercase characters. We check for
this by appending a lowercase character and testing with islower().
Note this also covers cases like numeric bucket names with dashes.
>>> check_lowercase_bucketname("Aaaa")
Traceback (most recent call last):
...
BotoClientError: S3Error: Bucket names cannot contain upper-case
characters when using either the sub-domain or virtual hosting calling
format.
>>> check_lowercase_bucketname("1234-5678-9123")
True
>>> check_lowercase_bucketname("abcdefg1234")
True
"""
if not (n + 'a').islower():
raise BotoClientError("Bucket names cannot contain upper-case " \
"characters when using either the sub-domain or virtual " \
"hosting calling format.")
return True
def assert_case_insensitive(f):
def wrapper(*args, **kwargs):
if len(args) == 3 and check_lowercase_bucketname(args[2]):
pass
return f(*args, **kwargs)
return wrapper
class _CallingFormat:
def build_url_base(self, connection, protocol, server, bucket, key=''):
url_base = '%s://' % protocol
url_base += self.build_host(server, bucket)
url_base += connection.get_path(self.build_path_base(bucket, key))
return url_base
def build_host(self, server, bucket):
if bucket == '':
return server
else:
return self.get_bucket_server(server, bucket)
def build_auth_path(self, bucket, key=''):
path = ''
if bucket != '':
path = '/' + bucket
return path + '/%s' % urllib.quote(key)
def build_path_base(self, bucket, key=''):
return '/%s' % urllib.quote(key)
class SubdomainCallingFormat(_CallingFormat):
@assert_case_insensitive
def get_bucket_server(self, server, bucket):
return '%s.%s' % (bucket, server)
class VHostCallingFormat(_CallingFormat):
@assert_case_insensitive
def get_bucket_server(self, server, bucket):
return bucket
class OrdinaryCallingFormat(_CallingFormat):
def get_bucket_server(self, server, bucket):
return server
def build_path_base(self, bucket, key=''):
path_base = '/'
if bucket:
path_base += "%s/" % bucket
return path_base + urllib.quote(key)
class Location:
DEFAULT = ''
EU = 'EU'
USWest = 'us-west-1'
#boto.set_stream_logger('s3')
class S3Connection(AWSAuthConnection):
DefaultHost = 's3.amazonaws.com'
QueryString = 'Signature=%s&Expires=%d&AWSAccessKeyId=%s'
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=DefaultHost, debug=0, https_connection_factory=None,
calling_format=SubdomainCallingFormat(), path='/', provider='aws',
bucket_class=Bucket):
self.calling_format = calling_format
self.bucket_class = bucket_class
AWSAuthConnection.__init__(self, host,
aws_access_key_id, aws_secret_access_key,
is_secure, port, proxy, proxy_port, proxy_user, proxy_pass,
debug=debug, https_connection_factory=https_connection_factory,
path=path, provider=provider)
def __iter__(self):
for bucket in self.get_all_buckets():
yield bucket
def __contains__(self, bucket_name):
return not (self.lookup(bucket_name) is None)
def set_bucket_class(self, bucket_class):
"""
Set the Bucket class associated with this bucket. By default, this
would be the boto.s3.key.Bucket class but if you want to subclass that
for some reason this allows you to associate your new class.
:type bucket_class: class
:param bucket_class: A subclass of Bucket that can be more specific
"""
self.bucket_class = bucket_class
def build_post_policy(self, expiration_time, conditions):
"""
Taken from the AWS book Python examples and modified for use with boto
"""
assert type(expiration_time) == time.struct_time, \
'Policy document must include a valid expiration Time object'
# Convert conditions object mappings to condition statements
return '{"expiration": "%s",\n"conditions": [%s]}' % \
(time.strftime(boto.utils.ISO8601, expiration_time), ",".join(conditions))
def build_post_form_args(self, bucket_name, key, expires_in = 6000,
acl = None, success_action_redirect = None, max_content_length = None,
http_method = "http", fields=None, conditions=None):
"""
Taken from the AWS book Python examples and modified for use with boto
This only returns the arguments required for the post form, not the actual form
This does not return the file input field which also needs to be added
:param bucket_name: Bucket to submit to
:type bucket_name: string
:param key: Key name, optionally add ${filename} to the end to attach the submitted filename
:type key: string
:param expires_in: Time (in seconds) before this expires, defaults to 6000
:type expires_in: integer
:param acl: ACL rule to use, if any
:type acl: :class:`boto.s3.acl.ACL`
:param success_action_redirect: URL to redirect to on success
:type success_action_redirect: string
:param max_content_length: Maximum size for this file
:type max_content_length: integer
:type http_method: string
:param http_method: HTTP Method to use, "http" or "https"
:rtype: dict
:return: A dictionary containing field names/values as well as a url to POST to
.. code-block:: python
{
"action": action_url_to_post_to,
"fields": [
{
"name": field_name,
"value": field_value
},
{
"name": field_name2,
"value": field_value2
}
]
}
"""
if fields == None:
fields = []
if conditions == None:
conditions = []
expiration = time.gmtime(int(time.time() + expires_in))
# Generate policy document
conditions.append('{"bucket": "%s"}' % bucket_name)
if key.endswith("${filename}"):
conditions.append('["starts-with", "$key", "%s"]' % key[:-len("${filename}")])
else:
conditions.append('{"key": "%s"}' % key)
if acl:
conditions.append('{"acl": "%s"}' % acl)
fields.append({ "name": "acl", "value": acl})
if success_action_redirect:
conditions.append('{"success_action_redirect": "%s"}' % success_action_redirect)
fields.append({ "name": "success_action_redirect", "value": success_action_redirect})
if max_content_length:
conditions.append('["content-length-range", 0, %i]' % max_content_length)
fields.append({"name":'content-length-range', "value": "0,%i" % max_content_length})
policy = self.build_post_policy(expiration, conditions)
# Add the base64-encoded policy document as the 'policy' field
policy_b64 = base64.b64encode(policy)
fields.append({"name": "policy", "value": policy_b64})
# Add the AWS access key as the 'AWSAccessKeyId' field
fields.append({"name": "AWSAccessKeyId", "value": self.aws_access_key_id})
# Add signature for encoded policy document as the 'AWSAccessKeyId' field
hmac_copy = self.hmac.copy()
hmac_copy.update(policy_b64)
signature = base64.encodestring(hmac_copy.digest()).strip()
fields.append({"name": "signature", "value": signature})
fields.append({"name": "key", "value": key})
# HTTPS protocol will be used if the secure HTTP option is enabled.
url = '%s://%s.%s/' % (http_method, bucket_name, self.host)
return {"action": url, "fields": fields}
def generate_url(self, expires_in, method, bucket='', key='',
headers=None, query_auth=True, force_http=False):
if not headers:
headers = {}
expires = int(time.time() + expires_in)
auth_path = self.calling_format.build_auth_path(bucket, key)
auth_path = self.get_path(auth_path)
canonical_str = boto.utils.canonical_string(method, auth_path,
headers, expires,
self.provider)
hmac_copy = self.hmac.copy()
hmac_copy.update(canonical_str)
b64_hmac = base64.encodestring(hmac_copy.digest()).strip()
encoded_canonical = urllib.quote_plus(b64_hmac)
self.calling_format.build_path_base(bucket, key)
if query_auth:
query_part = '?' + self.QueryString % (encoded_canonical, expires,
self.aws_access_key_id)
sec_hdr = self.provider.security_token_header
if sec_hdr in headers:
query_part += ('&%s=%s' % (sec_hdr,
urllib.quote(headers[sec_hdr])));
else:
query_part = ''
if force_http:
protocol = 'http'
port = 80
else:
protocol = self.protocol
port = self.port
return self.calling_format.build_url_base(self, protocol, self.server_name(port),
bucket, key) + query_part
def get_all_buckets(self, headers=None):
response = self.make_request('GET')
body = response.read()
if response.status > 300:
raise self.provider.storage_response_error(
response.status, response.reason, body)
rs = ResultSet([('Bucket', self.bucket_class)])
h = handler.XmlHandler(rs, self)
xml.sax.parseString(body, h)
return rs
def get_canonical_user_id(self, headers=None):
"""
Convenience method that returns the "CanonicalUserID" of the user who's credentials
are associated with the connection. The only way to get this value is to do a GET
request on the service which returns all buckets associated with the account. As part
of that response, the canonical userid is returned. This method simply does all of
that and then returns just the user id.
:rtype: string
:return: A string containing the canonical user id.
"""
rs = self.get_all_buckets(headers=headers)
return rs.ID
def get_bucket(self, bucket_name, validate=True, headers=None):
bucket = self.bucket_class(self, bucket_name)
if validate:
bucket.get_all_keys(headers, maxkeys=0)
return bucket
def lookup(self, bucket_name, validate=True, headers=None):
try:
bucket = self.get_bucket(bucket_name, validate, headers=headers)
except:
bucket = None
return bucket
def create_bucket(self, bucket_name, headers=None,
location=Location.DEFAULT, policy=None):
"""
Creates a new located bucket. By default it's in the USA. You can pass
Location.EU to create an European bucket.
:type bucket_name: string
:param bucket_name: The name of the new bucket
:type headers: dict
:param headers: Additional headers to pass along with the request to AWS.
:type location: :class:`boto.s3.connection.Location`
:param location: The location of the new bucket
:type policy: :class:`boto.s3.acl.CannedACLStrings`
:param policy: A canned ACL policy that will be applied to the new key in S3.
"""
check_lowercase_bucketname(bucket_name)
if policy:
if headers:
headers[self.provider.acl_header] = policy
else:
headers = {self.provider.acl_header : policy}
if location == Location.DEFAULT:
data = ''
else:
data = '<CreateBucketConstraint><LocationConstraint>' + \
location + '</LocationConstraint></CreateBucketConstraint>'
response = self.make_request('PUT', bucket_name, headers=headers,
data=data)
body = response.read()
if response.status == 409:
raise self.provider.storage_create_error(
response.status, response.reason, body)
if response.status == 200:
return self.bucket_class(self, bucket_name)
else:
raise self.provider.storage_response_error(
response.status, response.reason, body)
def delete_bucket(self, bucket, headers=None):
response = self.make_request('DELETE', bucket, headers=headers)
body = response.read()
if response.status != 204:
raise self.provider.storage_response_error(
response.status, response.reason, body)
def make_request(self, method, bucket='', key='', headers=None, data='',
query_args=None, sender=None, override_num_retries=None):
if isinstance(bucket, self.bucket_class):
bucket = bucket.name
if isinstance(key, Key):
key = key.name
path = self.calling_format.build_path_base(bucket, key)
auth_path = self.calling_format.build_auth_path(bucket, key)
host = self.calling_format.build_host(self.server_name(), bucket)
if query_args:
path += '?' + query_args
auth_path += '?' + query_args
return AWSAuthConnection.make_request(self, method, path, headers,
data, host, auth_path, sender,
override_num_retries=override_num_retries)
| 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 boto.s3.user import User
CannedACLStrings = ['private', 'public-read',
'public-read-write', 'authenticated-read',
'bucket-owner-read', 'bucket-owner-full-control']
class Policy:
def __init__(self, parent=None):
self.parent = parent
self.acl = None
def __repr__(self):
grants = []
for g in self.acl.grants:
if g.id == self.owner.id:
grants.append("%s (owner) = %s" % (g.display_name, g.permission))
else:
if g.type == 'CanonicalUser':
u = g.display_name
elif g.type == 'Group':
u = g.uri
else:
u = g.email
grants.append("%s = %s" % (u, g.permission))
return "<Policy: %s>" % ", ".join(grants)
def startElement(self, name, attrs, connection):
if name == 'Owner':
self.owner = User(self)
return self.owner
elif name == 'AccessControlList':
self.acl = ACL(self)
return self.acl
else:
return None
def endElement(self, name, value, connection):
if name == 'Owner':
pass
elif name == 'AccessControlList':
pass
else:
setattr(self, name, value)
def to_xml(self):
s = '<AccessControlPolicy>'
s += self.owner.to_xml()
s += self.acl.to_xml()
s += '</AccessControlPolicy>'
return s
class ACL:
def __init__(self, policy=None):
self.policy = policy
self.grants = []
def add_grant(self, grant):
self.grants.append(grant)
def add_email_grant(self, permission, email_address):
grant = Grant(permission=permission, type='AmazonCustomerByEmail',
email_address=email_address)
self.grants.append(grant)
def add_user_grant(self, permission, user_id):
grant = Grant(permission=permission, type='CanonicalUser', id=user_id)
self.grants.append(grant)
def startElement(self, name, attrs, connection):
if name == 'Grant':
self.grants.append(Grant(self))
return self.grants[-1]
else:
return None
def endElement(self, name, value, connection):
if name == 'Grant':
pass
else:
setattr(self, name, value)
def to_xml(self):
s = '<AccessControlList>'
for grant in self.grants:
s += grant.to_xml()
s += '</AccessControlList>'
return s
class Grant:
NameSpace = 'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'
def __init__(self, permission=None, type=None, id=None,
display_name=None, uri=None, email_address=None):
self.permission = permission
self.id = id
self.display_name = display_name
self.uri = uri
self.email_address = email_address
self.type = type
def startElement(self, name, attrs, connection):
if name == 'Grantee':
self.type = attrs['xsi:type']
return None
def endElement(self, name, value, connection):
if name == 'ID':
self.id = value
elif name == 'DisplayName':
self.display_name = value
elif name == 'URI':
self.uri = value
elif name == 'EmailAddress':
self.email_address = value
elif name == 'Grantee':
pass
elif name == 'Permission':
self.permission = value
else:
setattr(self, name, value)
def to_xml(self):
s = '<Grant>'
s += '<Grantee %s xsi:type="%s">' % (self.NameSpace, self.type)
if self.type == 'CanonicalUser':
s += '<ID>%s</ID>' % self.id
s += '<DisplayName>%s</DisplayName>' % self.display_name
elif self.type == 'Group':
s += '<URI>%s</URI>' % self.uri
else:
s += '<EmailAddress>%s</EmailAddress>' % self.email_address
s += '</Grantee>'
s += '<Permission>%s</Permission>' % self.permission
s += '</Grant>'
return s
| 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.
#
| 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.
import boto
from boto import handler
from boto.provider import Provider
from boto.resultset import ResultSet
from boto.s3.acl import ACL, Policy, CannedACLStrings, Grant
from boto.s3.key import Key
from boto.s3.prefix import Prefix
from boto.s3.deletemarker import DeleteMarker
from boto.s3.user import User
from boto.s3.bucketlistresultset import BucketListResultSet
from boto.s3.bucketlistresultset import VersionedBucketListResultSet
import boto.utils
import xml.sax
import urllib
import re
S3Permissions = ['READ', 'WRITE', 'READ_ACP', 'WRITE_ACP', 'FULL_CONTROL']
class Bucket(object):
BucketLoggingBody = """<?xml version="1.0" encoding="UTF-8"?>
<BucketLoggingStatus xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<LoggingEnabled>
<TargetBucket>%s</TargetBucket>
<TargetPrefix>%s</TargetPrefix>
</LoggingEnabled>
</BucketLoggingStatus>"""
EmptyBucketLoggingBody = """<?xml version="1.0" encoding="UTF-8"?>
<BucketLoggingStatus xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
</BucketLoggingStatus>"""
LoggingGroup = 'http://acs.amazonaws.com/groups/s3/LogDelivery'
BucketPaymentBody = """<?xml version="1.0" encoding="UTF-8"?>
<RequestPaymentConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<Payer>%s</Payer>
</RequestPaymentConfiguration>"""
VersioningBody = """<?xml version="1.0" encoding="UTF-8"?>
<VersioningConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<Status>%s</Status>
<MfaDelete>%s</MfaDelete>
</VersioningConfiguration>"""
VersionRE = '<Status>([A-Za-z]+)</Status>'
MFADeleteRE = '<MfaDelete>([A-Za-z]+)</MfaDelete>'
def __init__(self, connection=None, name=None, key_class=Key):
self.name = name
self.connection = connection
self.key_class = key_class
def __repr__(self):
return '<Bucket: %s>' % self.name
def __iter__(self):
return iter(BucketListResultSet(self))
def __contains__(self, key_name):
return not (self.get_key(key_name) is None)
def startElement(self, name, attrs, connection):
return None
def endElement(self, name, value, connection):
if name == 'Name':
self.name = value
elif name == 'CreationDate':
self.creation_date = value
else:
setattr(self, name, value)
def set_key_class(self, key_class):
"""
Set the Key class associated with this bucket. By default, this
would be the boto.s3.key.Key class but if you want to subclass that
for some reason this allows you to associate your new class with a
bucket so that when you call bucket.new_key() or when you get a listing
of keys in the bucket you will get an instances of your key class
rather than the default.
:type key_class: class
:param key_class: A subclass of Key that can be more specific
"""
self.key_class = key_class
def lookup(self, key_name, headers=None):
"""
Deprecated: Please use get_key method.
:type key_name: string
:param key_name: The name of the key to retrieve
:rtype: :class:`boto.s3.key.Key`
:returns: A Key object from this bucket.
"""
return self.get_key(key_name, headers=headers)
def get_key(self, key_name, headers=None, version_id=None):
"""
Check to see if a particular key exists within the bucket. This
method uses a HEAD request to check for the existance of the key.
Returns: An instance of a Key object or None
:type key_name: string
:param key_name: The name of the key to retrieve
:rtype: :class:`boto.s3.key.Key`
:returns: A Key object from this bucket.
"""
if version_id:
query_args = 'versionId=%s' % version_id
else:
query_args = None
response = self.connection.make_request('HEAD', self.name, key_name,
headers=headers,
query_args=query_args)
# Allow any success status (2xx) - for example this lets us
# support Range gets, which return status 206:
if response.status/100 == 2:
response.read()
k = self.key_class(self)
provider = self.connection.provider
k.metadata = boto.utils.get_aws_metadata(response.msg, provider)
k.etag = response.getheader('etag')
k.content_type = response.getheader('content-type')
k.content_encoding = response.getheader('content-encoding')
k.last_modified = response.getheader('last-modified')
k.size = int(response.getheader('content-length'))
k.name = key_name
k.handle_version_headers(response)
return k
else:
if response.status == 404:
response.read()
return None
else:
raise self.connection.provider.storage_response_error(
response.status, response.reason, '')
def list(self, prefix='', delimiter='', marker='', headers=None):
"""
List key objects within a bucket. This returns an instance of an
BucketListResultSet that automatically handles all of the result
paging, etc. from S3. You just need to keep iterating until
there are no more results.
Called with no arguments, this will return an iterator object across
all keys within the bucket.
The Key objects returned by the iterator are obtained by parsing
the results of a GET on the bucket, also known as the List Objects
request. The XML returned by this request contains only a subset
of the information about each key. Certain metadata fields such
as Content-Type and user metadata are not available in the XML.
Therefore, if you want these additional metadata fields you will
have to do a HEAD request on the Key in the bucket.
:type prefix: string
:param prefix: allows you to limit the listing to a particular
prefix. For example, if you call the method with
prefix='/foo/' then the iterator will only cycle
through the keys that begin with the string '/foo/'.
:type delimiter: string
:param delimiter: can be used in conjunction with the prefix
to allow you to organize and browse your keys
hierarchically. See:
http://docs.amazonwebservices.com/AmazonS3/2006-03-01/
for more details.
:type marker: string
:param marker: The "marker" of where you are in the result set
:rtype: :class:`boto.s3.bucketlistresultset.BucketListResultSet`
:return: an instance of a BucketListResultSet that handles paging, etc
"""
return BucketListResultSet(self, prefix, delimiter, marker, headers)
def list_versions(self, prefix='', delimiter='', key_marker='',
version_id_marker='', headers=None):
"""
List key objects within a bucket. This returns an instance of an
BucketListResultSet that automatically handles all of the result
paging, etc. from S3. You just need to keep iterating until
there are no more results.
Called with no arguments, this will return an iterator object across
all keys within the bucket.
:type prefix: string
:param prefix: allows you to limit the listing to a particular
prefix. For example, if you call the method with
prefix='/foo/' then the iterator will only cycle
through the keys that begin with the string '/foo/'.
:type delimiter: string
:param delimiter: can be used in conjunction with the prefix
to allow you to organize and browse your keys
hierarchically. See:
http://docs.amazonwebservices.com/AmazonS3/2006-03-01/
for more details.
:type marker: string
:param marker: The "marker" of where you are in the result set
:rtype: :class:`boto.s3.bucketlistresultset.BucketListResultSet`
:return: an instance of a BucketListResultSet that handles paging, etc
"""
return VersionedBucketListResultSet(self, prefix, delimiter, key_marker,
version_id_marker, headers)
def _get_all(self, element_map, initial_query_string='',
headers=None, **params):
l = []
for k,v in params.items():
k = k.replace('_', '-')
if k == 'maxkeys':
k = 'max-keys'
if isinstance(v, unicode):
v = v.encode('utf-8')
if v is not None and v != '':
l.append('%s=%s' % (urllib.quote(k), urllib.quote(str(v))))
if len(l):
s = initial_query_string + '&' + '&'.join(l)
else:
s = initial_query_string
response = self.connection.make_request('GET', self.name,
headers=headers, query_args=s)
body = response.read()
boto.log.debug(body)
if response.status == 200:
rs = ResultSet(element_map)
h = handler.XmlHandler(rs, self)
xml.sax.parseString(body, h)
return rs
else:
raise self.connection.provider.storage_response_error(
response.status, response.reason, body)
def get_all_keys(self, headers=None, **params):
"""
A lower-level method for listing contents of a bucket.
This closely models the actual S3 API and requires you to manually
handle the paging of results. For a higher-level method
that handles the details of paging for you, you can use the list method.
:type max_keys: int
:param max_keys: The maximum number of keys to retrieve
:type prefix: string
:param prefix: The prefix of the keys you want to retrieve
:type marker: string
:param marker: The "marker" of where you are in the result set
:type delimiter: string
:param delimiter: If this optional, Unicode string parameter
is included with your request, then keys that
contain the same string between the prefix and
the first occurrence of the delimiter will be
rolled up into a single result element in the
CommonPrefixes collection. These rolled-up keys
are not returned elsewhere in the response.
:rtype: ResultSet
:return: The result from S3 listing the keys requested
"""
return self._get_all([('Contents', self.key_class),
('CommonPrefixes', Prefix)],
'', headers, **params)
def get_all_versions(self, headers=None, **params):
"""
A lower-level, version-aware method for listing contents of a bucket.
This closely models the actual S3 API and requires you to manually
handle the paging of results. For a higher-level method
that handles the details of paging for you, you can use the list method.
:type max_keys: int
:param max_keys: The maximum number of keys to retrieve
:type prefix: string
:param prefix: The prefix of the keys you want to retrieve
:type key_marker: string
:param key_marker: The "marker" of where you are in the result set
with respect to keys.
:type version_id_marker: string
:param version_id_marker: The "marker" of where you are in the result
set with respect to version-id's.
:type delimiter: string
:param delimiter: If this optional, Unicode string parameter
is included with your request, then keys that
contain the same string between the prefix and
the first occurrence of the delimiter will be
rolled up into a single result element in the
CommonPrefixes collection. These rolled-up keys
are not returned elsewhere in the response.
:rtype: ResultSet
:return: The result from S3 listing the keys requested
"""
return self._get_all([('Version', self.key_class),
('CommonPrefixes', Prefix),
('DeleteMarker', DeleteMarker)],
'versions', headers, **params)
def new_key(self, key_name=None):
"""
Creates a new key
:type key_name: string
:param key_name: The name of the key to create
:rtype: :class:`boto.s3.key.Key` or subclass
:returns: An instance of the newly created key object
"""
return self.key_class(self, key_name)
def generate_url(self, expires_in, method='GET',
headers=None, force_http=False):
return self.connection.generate_url(expires_in, method, self.name,
headers=headers,
force_http=force_http)
def delete_key(self, key_name, headers=None,
version_id=None, mfa_token=None):
"""
Deletes a key from the bucket. If a version_id is provided,
only that version of the key will be deleted.
:type key_name: string
:param key_name: The key name to delete
:type version_id: string
:param version_id: The version ID (optional)
:type mfa_token: tuple or list of strings
:param mfa_token: A tuple or list consisting of the serial number
from the MFA device and the current value of
the six-digit token associated with the device.
This value is required anytime you are
deleting versioned objects from a bucket
that has the MFADelete option on the bucket.
"""
provider = self.connection.provider
if version_id:
query_args = 'versionId=%s' % version_id
else:
query_args = None
if mfa_token:
if not headers:
headers = {}
headers[provider.mfa_header] = ' '.join(mfa_token)
response = self.connection.make_request('DELETE', self.name, key_name,
headers=headers,
query_args=query_args)
body = response.read()
if response.status != 204:
raise provider.storage_response_error(response.status,
response.reason, body)
def copy_key(self, new_key_name, src_bucket_name,
src_key_name, metadata=None, src_version_id=None,
storage_class='STANDARD', preserve_acl=False):
"""
Create a new key in the bucket by copying another existing key.
:type new_key_name: string
:param new_key_name: The name of the new key
:type src_bucket_name: string
:param src_bucket_name: The name of the source bucket
:type src_key_name: string
:param src_key_name: The name of the source key
:type src_version_id: string
:param src_version_id: The version id for the key. This param
is optional. If not specified, the newest
version of the key will be copied.
:type metadata: dict
:param metadata: Metadata to be associated with new key.
If metadata is supplied, it will replace the
metadata of the source key being copied.
If no metadata is supplied, the source key's
metadata will be copied to the new key.
:type storage_class: string
:param storage_class: The storage class of the new key.
By default, the new key will use the
standard storage class. Possible values are:
STANDARD | REDUCED_REDUNDANCY
:type preserve_acl: bool
:param preserve_acl: If True, the ACL from the source key
will be copied to the destination
key. If False, the destination key
will have the default ACL.
Note that preserving the ACL in the
new key object will require two
additional API calls to S3, one to
retrieve the current ACL and one to
set that ACL on the new object. If
you don't care about the ACL, a value
of False will be significantly more
efficient.
:rtype: :class:`boto.s3.key.Key` or subclass
:returns: An instance of the newly created key object
"""
if preserve_acl:
acl = self.get_xml_acl(src_key_name)
src = '%s/%s' % (src_bucket_name, urllib.quote(src_key_name))
if src_version_id:
src += '?version_id=%s' % src_version_id
provider = self.connection.provider
headers = {provider.copy_source_header : src}
if storage_class != 'STANDARD':
headers[provider.storage_class_header] = storage_class
if metadata:
headers[provider.metadata_directive_header] = 'REPLACE'
headers = boto.utils.merge_meta(headers, metadata)
else:
headers[provider.metadata_directive_header] = 'COPY'
response = self.connection.make_request('PUT', self.name, new_key_name,
headers=headers)
body = response.read()
if response.status == 200:
key = self.new_key(new_key_name)
h = handler.XmlHandler(key, self)
xml.sax.parseString(body, h)
if hasattr(key, 'Error'):
raise provider.storage_copy_error(key.Code, key.Message, body)
key.handle_version_headers(response)
if preserve_acl:
self.set_xml_acl(acl, new_key_name)
return key
else:
raise provider.storage_response_error(response.status, response.reason, body)
def set_canned_acl(self, acl_str, key_name='', headers=None,
version_id=None):
assert acl_str in CannedACLStrings
if headers:
headers[self.connection.provider.acl_header] = acl_str
else:
headers={self.connection.provider.acl_header: acl_str}
query_args='acl'
if version_id:
query_args += '&versionId=%s' % version_id
response = self.connection.make_request('PUT', self.name, key_name,
headers=headers, query_args=query_args)
body = response.read()
if response.status != 200:
raise self.connection.provider.storage_response_error(
response.status, response.reason, body)
def get_xml_acl(self, key_name='', headers=None, version_id=None):
query_args = 'acl'
if version_id:
query_args += '&versionId=%s' % version_id
response = self.connection.make_request('GET', self.name, key_name,
query_args=query_args,
headers=headers)
body = response.read()
if response.status != 200:
raise self.connection.provider.storage_response_error(
response.status, response.reason, body)
return body
def set_xml_acl(self, acl_str, key_name='', headers=None, version_id=None):
query_args = 'acl'
if version_id:
query_args += '&versionId=%s' % version_id
response = self.connection.make_request('PUT', self.name, key_name,
data=acl_str,
query_args=query_args,
headers=headers)
body = response.read()
if response.status != 200:
raise self.connection.provider.storage_response_error(
response.status, response.reason, body)
def set_acl(self, acl_or_str, key_name='', headers=None, version_id=None):
if isinstance(acl_or_str, Policy):
self.set_xml_acl(acl_or_str.to_xml(), key_name,
headers, version_id)
else:
self.set_canned_acl(acl_or_str, key_name,
headers, version_id)
def get_acl(self, key_name='', headers=None, version_id=None):
query_args = 'acl'
if version_id:
query_args += '&versionId=%s' % version_id
response = self.connection.make_request('GET', self.name, key_name,
query_args=query_args,
headers=headers)
body = response.read()
if response.status == 200:
policy = Policy(self)
h = handler.XmlHandler(policy, self)
xml.sax.parseString(body, h)
return policy
else:
raise self.connection.provider.storage_response_error(
response.status, response.reason, body)
def make_public(self, recursive=False, headers=None):
self.set_canned_acl('public-read', headers=headers)
if recursive:
for key in self:
self.set_canned_acl('public-read', key.name, headers=headers)
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 S3.
:type permission: string
:param permission: The permission being granted. Should be one of:
(READ, WRITE, READ_ACP, WRITE_ACP, FULL_CONTROL).
:type email_address: string
:param email_address: The email address associated with the AWS
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 S3Permissions:
raise self.connection.provider.storage_permissions_error(
'Unknown Permission: %s' % permission)
policy = self.get_acl(headers=headers)
policy.acl.add_email_grant(permission, email_address)
self.set_acl(policy, headers=headers)
if recursive:
for key in self:
key.add_email_grant(permission, email_address, headers=headers)
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 PUT's the new ACL back to S3.
:type permission: string
:param permission: The permission being granted. Should be one of:
(READ, WRITE, READ_ACP, WRITE_ACP, FULL_CONTROL).
:type user_id: string
:param user_id: The canonical user id associated with the AWS 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 S3Permissions:
raise self.connection.provider.storage_permissions_error(
'Unknown Permission: %s' % permission)
policy = self.get_acl(headers=headers)
policy.acl.add_user_grant(permission, user_id)
self.set_acl(policy, headers=headers)
if recursive:
for key in self:
key.add_user_grant(permission, user_id, headers=headers)
def list_grants(self, headers=None):
policy = self.get_acl(headers=headers)
return policy.acl.grants
def get_location(self):
"""
Returns the LocationConstraint for the bucket.
:rtype: str
:return: The LocationConstraint for the bucket or the empty string if
no constraint was specified when bucket was created.
"""
response = self.connection.make_request('GET', self.name,
query_args='location')
body = response.read()
if response.status == 200:
rs = ResultSet(self)
h = handler.XmlHandler(rs, self)
xml.sax.parseString(body, h)
return rs.LocationConstraint
else:
raise self.connection.provider.storage_response_error(
response.status, response.reason, body)
def enable_logging(self, target_bucket, target_prefix='', headers=None):
if isinstance(target_bucket, Bucket):
target_bucket = target_bucket.name
body = self.BucketLoggingBody % (target_bucket, target_prefix)
response = self.connection.make_request('PUT', self.name, data=body,
query_args='logging', headers=headers)
body = response.read()
if response.status == 200:
return True
else:
raise self.connection.provider.storage_response_error(
response.status, response.reason, body)
def disable_logging(self, headers=None):
body = self.EmptyBucketLoggingBody
response = self.connection.make_request('PUT', self.name, data=body,
query_args='logging', headers=headers)
body = response.read()
if response.status == 200:
return True
else:
raise self.connection.provider.storage_response_error(
response.status, response.reason, body)
def get_logging_status(self, headers=None):
response = self.connection.make_request('GET', self.name,
query_args='logging', headers=headers)
body = response.read()
if response.status == 200:
return body
else:
raise self.connection.provider.storage_response_error(
response.status, response.reason, body)
def set_as_logging_target(self, headers=None):
policy = self.get_acl(headers=headers)
g1 = Grant(permission='WRITE', type='Group', uri=self.LoggingGroup)
g2 = Grant(permission='READ_ACP', type='Group', uri=self.LoggingGroup)
policy.acl.add_grant(g1)
policy.acl.add_grant(g2)
self.set_acl(policy, headers=headers)
def get_request_payment(self, headers=None):
response = self.connection.make_request('GET', self.name,
query_args='requestPayment', headers=headers)
body = response.read()
if response.status == 200:
return body
else:
raise self.connection.provider.storage_response_error(
response.status, response.reason, body)
def set_request_payment(self, payer='BucketOwner', headers=None):
body = self.BucketPaymentBody % payer
response = self.connection.make_request('PUT', self.name, data=body,
query_args='requestPayment', headers=headers)
body = response.read()
if response.status == 200:
return True
else:
raise self.connection.provider.storage_response_error(
response.status, response.reason, body)
def configure_versioning(self, versioning, mfa_delete=False,
mfa_token=None, headers=None):
"""
Configure versioning for this bucket.
Note: This feature is currently in beta release and is available
only in the Northern California region.
:type versioning: bool
:param versioning: A boolean indicating whether version is
enabled (True) or disabled (False).
:type mfa_delete: bool
:param mfa_delete: A boolean indicating whether the Multi-Factor
Authentication Delete feature is enabled (True)
or disabled (False). If mfa_delete is enabled
then all Delete operations will require the
token from your MFA device to be passed in
the request.
:type mfa_token: tuple or list of strings
:param mfa_token: A tuple or list consisting of the serial number
from the MFA device and the current value of
the six-digit token associated with the device.
This value is required when you are changing
the status of the MfaDelete property of
the bucket.
"""
if versioning:
ver = 'Enabled'
else:
ver = 'Suspended'
if mfa_delete:
mfa = 'Enabled'
else:
mfa = 'Disabled'
body = self.VersioningBody % (ver, mfa)
if mfa_token:
if not headers:
headers = {}
provider = self.connection.provider
headers[provider.mfa_header] = ' '.join(mfa_token)
response = self.connection.make_request('PUT', self.name, data=body,
query_args='versioning', headers=headers)
body = response.read()
if response.status == 200:
return True
else:
raise self.connection.provider.storage_response_error(
response.status, response.reason, body)
def get_versioning_status(self, headers=None):
"""
Returns the current status of versioning on the bucket.
:rtype: dict
:returns: A dictionary containing a key named 'Versioning'
that can have a value of either Enabled, Disabled,
or Suspended. Also, if MFADelete has ever been enabled
on the bucket, the dictionary will contain a key
named 'MFADelete' which will have a value of either
Enabled or Suspended.
"""
response = self.connection.make_request('GET', self.name,
query_args='versioning', headers=headers)
body = response.read()
boto.log.debug(body)
if response.status == 200:
d = {}
ver = re.search(self.VersionRE, body)
if ver:
d['Versioning'] = ver.group(1)
mfa = re.search(self.MFADeleteRE, body)
if mfa:
d['MfaDelete'] = mfa.group(1)
return d
else:
raise self.connection.provider.storage_response_error(
response.status, response.reason, body)
def delete(self, headers=None):
return self.connection.delete_bucket(self.name, headers=headers)
| 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 errno
import httplib
import os
import re
import socket
import time
import boto
from boto import config, storage_uri_for_key
from boto.connection import AWSAuthConnection
from boto.exception import ResumableDownloadException
from boto.exception import ResumableTransferDisposition
"""
Resumable download handler.
Resumable downloads will retry failed downloads, resuming at the byte count
completed by the last download attempt. If too many retries happen with no
progress (per configurable num_retries param), the download will be aborted.
The caller can optionally specify a tracker_file_name param in the
ResumableDownloadHandler 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).
Note that resumable downloads work across providers (they depend only
on support Range GETs), but this code is in the boto.s3 package
because it is the wrong abstraction level to go in the top-level boto
package.
TODO: At some point we should refactor the code to have a storage_service
package where all these provider-independent files go.
"""
class ByteTranslatingCallbackHandler(object):
"""
Proxy class that translates progress callbacks made by
boto.s3.Key.get_file(), taking into account that we're resuming
a download.
"""
def __init__(self, proxied_cb, download_start_point):
self.proxied_cb = proxied_cb
self.download_start_point = download_start_point
def call(self, total_bytes_uploaded, total_size):
self.proxied_cb(self.download_start_point + total_bytes_uploaded,
self.download_start_point + total_size)
def get_cur_file_size(fp, position_to_eof=False):
"""
Returns size of file, optionally leaving fp positioned at EOF.
"""
if not position_to_eof:
cur_pos = fp.tell()
fp.seek(0, os.SEEK_END)
cur_file_size = fp.tell()
if not position_to_eof:
fp.seek(cur_pos, os.SEEK_SET)
return cur_file_size
class ResumableDownloadHandler(object):
"""
Handler for resumable downloads.
"""
ETAG_REGEX = '([a-z0-9]{32})\n'
RETRYABLE_EXCEPTIONS = (httplib.HTTPException, IOError, socket.error,
socket.gaierror)
def __init__(self, tracker_file_name=None, num_retries=None):
"""
Constructor. Instantiate once for each downloaded file.
:type tracker_file_name: string
:param tracker_file_name: optional file name to save tracking info
about this download. If supplied and the current process fails
the download, it can be retried in a new process. If called
with an existing file containing an unexpired timestamp,
we'll resume the transfer for this file; else we'll start a
new resumable download.
:type num_retries: int
:param num_retries: the number of times we'll re-try a resumable
download making no progress. (Count resets every time we get
progress, so download can span many more than this number of
retries.)
"""
self.tracker_file_name = tracker_file_name
self.num_retries = num_retries
self.etag_value_for_current_download = None
if tracker_file_name:
self._load_tracker_file_etag()
# Save download_start_point in instance state so caller can
# find how much was transferred by this ResumableDownloadHandler
# (across retries).
self.download_start_point = None
def _load_tracker_file_etag(self):
f = None
try:
f = open(self.tracker_file_name, 'r')
etag_line = f.readline()
m = re.search(self.ETAG_REGEX, etag_line)
if m:
self.etag_value_for_current_download = m.group(1)
else:
print('Couldn\'t read etag in tracker file (%s). Restarting '
'download from scratch.' % self.tracker_file_name)
except IOError, e:
# Ignore non-existent file (happens first time a download
# is attempted on an object), but warn user for other errors.
if e.errno != errno.ENOENT:
# Will restart because
# self.etag_value_for_current_download == None.
print('Couldn\'t read URI tracker file (%s): %s. Restarting '
'download from scratch.' %
(self.tracker_file_name, e.strerror))
finally:
if f:
f.close()
def _save_tracker_info(self, key):
self.etag_value_for_current_download = key.etag.strip('"\'')
if not self.tracker_file_name:
return
f = None
try:
f = open(self.tracker_file_name, 'w')
f.write('%s\n' % self.etag_value_for_current_download)
except IOError, e:
raise ResumableDownloadException(
'Couldn\'t write tracker file (%s): %s.\nThis can happen'
'if you\'re using an incorrectly configured download 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 _remove_tracker_file(self):
if (self.tracker_file_name and
os.path.exists(self.tracker_file_name)):
os.unlink(self.tracker_file_name)
def _attempt_resumable_download(self, key, fp, headers, cb, num_cb,
torrent, version_id):
"""
Attempts a resumable download.
Raises ResumableDownloadException if any problems occur.
"""
cur_file_size = get_cur_file_size(fp, position_to_eof=True)
if (cur_file_size and
self.etag_value_for_current_download and
self.etag_value_for_current_download == key.etag.strip('"\'')):
# Try to resume existing transfer.
if cur_file_size > key.size:
raise ResumableDownloadException(
'%s is larger (%d) than %s (%d).\nDeleting tracker file, so '
'if you re-try this download it will start from scratch' %
(fp.name, cur_file_size, str(storage_uri_for_key(key)),
key.size), ResumableTransferDisposition.ABORT)
elif cur_file_size == key.size:
if key.bucket.connection.debug >= 1:
print 'Download complete.'
return
if key.bucket.connection.debug >= 1:
print 'Resuming download.'
headers = headers.copy()
headers['Range'] = 'bytes=%d-%d' % (cur_file_size, key.size - 1)
cb = ByteTranslatingCallbackHandler(cb, cur_file_size).call
self.download_start_point = cur_file_size
else:
if key.bucket.connection.debug >= 1:
print 'Starting new resumable download.'
self._save_tracker_info(key)
self.download_start_point = 0
# Truncate the file, in case a new resumable download is being
# started atop an existing file.
fp.truncate(0)
# Disable AWSAuthConnection-level retry behavior, since that would
# cause downloads to restart from scratch.
key.get_file(fp, headers, cb, num_cb, torrent, version_id,
override_num_retries=0)
fp.flush()
def _check_final_md5(self, key, file_name):
"""
Checks that etag from server agrees with md5 computed after the
download completes. This is important, since the download 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.
"""
fp = open(file_name, 'r')
if key.bucket.connection.debug >= 1:
print 'Checking md5 against etag.'
hex_md5 = key.compute_md5(fp)[0]
if hex_md5 != key.etag.strip('"\''):
file_name = fp.name
fp.close()
os.unlink(file_name)
raise ResumableDownloadException(
'File changed during download: md5 signature doesn\'t match '
'etag (incorrect downloaded file deleted)',
ResumableTransferDisposition.ABORT)
def get_file(self, key, fp, headers, cb=None, num_cb=10, torrent=False,
version_id=None):
"""
Retrieves a file from a Key
:type key: :class:`boto.s3.key.Key` or subclass
:param key: The Key object from which upload is to be downloaded
:type fp: file
:param fp: File pointer into which data should be downloaded
:type headers: string
:param: headers to send when retrieving the files
: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 the storage service 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 torrent: bool
:param torrent: Flag for whether to get a torrent for the file
:type version_id: string
:param version_id: The version ID (optional)
Raises ResumableDownloadException if a problem occurs during
the transfer.
"""
debug = key.bucket.connection.debug
if not headers:
headers = {}
# 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.
had_file_bytes_before_attempt = get_cur_file_size(fp)
try:
self._attempt_resumable_download(key, fp, headers, cb, num_cb,
torrent, version_id)
# Download succceded, so remove the tracker file (if have one).
self._remove_tracker_file()
self._check_final_md5(key, fp.name)
if debug >= 1:
print 'Resumable download complete.'
return
except self.RETRYABLE_EXCEPTIONS, e:
if debug >= 1:
print('Caught exception (%s)' % e.__repr__())
except ResumableDownloadException, e:
if e.disposition == ResumableTransferDisposition.ABORT:
if debug >= 1:
print('Caught non-retryable ResumableDownloadException '
'(%s)' % e.message)
raise
else:
if debug >= 1:
print('Caught ResumableDownloadException (%s) - will '
'retry' % e.message)
# At this point we had a re-tryable failure; see if made progress.
if get_cur_file_size(fp) > had_file_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 ResumableDownloadException(
'Too many resumable download attempts failed without '
'progress. You might try this download again later',
ResumableTransferDisposition.ABORT)
# Close the key, in case a previous download died partway
# through and left data in the underlying key HTTP buffer.
key.close()
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 (c) 2006-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.
from boto.s3.user import User
class DeleteMarker:
def __init__(self, bucket=None, name=None):
self.bucket = bucket
self.name = name
self.is_latest = False
self.last_modified = None
self.owner = None
def startElement(self, name, attrs, connection):
if name == 'Owner':
self.owner = User(self)
return self.owner
else:
return None
def endElement(self, name, value, connection):
if name == 'Key':
self.name = value.encode('utf-8')
elif name == 'IsLatest':
if value == 'true':
self.is_lastest = True
else:
self.is_latest = False
elif name == 'LastModified':
self.last_modified = value
elif name == 'Owner':
pass
elif name == 'VersionId':
self.version_id = value
else:
setattr(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.
class User:
def __init__(self, parent=None, id='', display_name=''):
if parent:
parent.owner = self
self.type = None
self.id = id
self.display_name = display_name
def startElement(self, name, attrs, connection):
return None
def endElement(self, name, value, connection):
if name == 'DisplayName':
self.display_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 xsi:type="%s">' % (element_name, self.type)
else:
s = '<%s>' % element_name
s += '<ID>%s</ID>' % self.id
s += '<DisplayName>%s</DisplayName>' % self.display_name
s += '</%s>' % element_name
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 os
from boto.exception import BotoClientError
from boto.exception import InvalidUriError
class StorageUri(object):
"""
Base class for representing storage provider-independent bucket and
object name with a shorthand URI-like syntax.
This is an abstract class: the constructor cannot be called (throws an
exception if you try).
"""
connection = None
def __init__(self):
"""Uncallable constructor on abstract base StorageUri class.
"""
raise BotoClientError('Attempt to instantiate abstract StorageUri '
'class')
def __repr__(self):
"""Returns string representation of URI."""
return self.uri
def equals(self, uri):
"""Returns true if two URIs are equal."""
return self.uri == uri.uri
def check_response(self, resp, level, uri):
if resp is None:
raise InvalidUriError('Attempt to get %s for "%s" failed. This '
'probably indicates the URI is invalid' %
(level, uri))
def connect(self, access_key_id=None, secret_access_key=None, **kwargs):
"""
Opens a connection to appropriate provider, depending on provider
portion of URI. Requires Credentials defined in boto config file (see
boto/pyami/config.py).
@type storage_uri: StorageUri
@param storage_uri: StorageUri specifying a bucket or a bucket+object
@rtype: L{AWSAuthConnection<boto.gs.connection.AWSAuthConnection>}
@return: A connection to storage service provider of the given URI.
"""
if not self.connection:
if self.scheme == 's3':
from boto.s3.connection import S3Connection
self.connection = S3Connection(access_key_id,
secret_access_key, **kwargs)
elif self.scheme == 'gs':
from boto.gs.connection import GSConnection
self.connection = GSConnection(access_key_id,
secret_access_key, **kwargs)
elif self.scheme == 'file':
from boto.file.connection import FileConnection
self.connection = FileConnection(self)
else:
raise InvalidUriError('Unrecognized scheme "%s"' %
self.scheme)
self.connection.debug = self.debug
return self.connection
def delete_key(self, validate=True, headers=None, version_id=None,
mfa_token=None):
if not self.object_name:
raise InvalidUriError('delete_key on object-less URI (%s)' %
self.uri)
bucket = self.get_bucket(validate, headers)
return bucket.delete_key(self.object_name, headers, version_id,
mfa_token)
def get_all_keys(self, validate=True, headers=None):
bucket = self.get_bucket(validate, headers)
return bucket.get_all_keys(headers)
def get_bucket(self, validate=True, headers=None):
if self.bucket_name is None:
raise InvalidUriError('get_bucket on bucket-less URI (%s)' %
self.uri)
conn = self.connect()
bucket = conn.get_bucket(self.bucket_name, validate, headers)
self.check_response(bucket, 'bucket', self.uri)
return bucket
def get_key(self, validate=True, headers=None, version_id=None):
if not self.object_name:
raise InvalidUriError('get_key on object-less URI (%s)' % self.uri)
bucket = self.get_bucket(validate, headers)
key = bucket.get_key(self.object_name, headers, version_id)
self.check_response(key, 'key', self.uri)
return key
def new_key(self, validate=True, headers=None):
if not self.object_name:
raise InvalidUriError('new_key on object-less URI (%s)' % self.uri)
bucket = self.get_bucket(validate, headers)
return bucket.new_key(self.object_name)
def get_contents_as_string(self, validate=True, headers=None, cb=None,
num_cb=10, torrent=False, version_id=None):
if not self.object_name:
raise InvalidUriError('get_contents_as_string on object-less URI '
'(%s)' % self.uri)
key = self.get_key(validate, headers)
return key.get_contents_as_string(headers, cb, num_cb, torrent,
version_id)
def acl_class(self):
if self.bucket_name is None:
raise InvalidUriError('acl_class on bucket-less URI (%s)' %
self.uri)
conn = self.connect()
acl_class = conn.provider.acl_class
self.check_response(acl_class, 'acl_class', self.uri)
return acl_class
def canned_acls(self):
if self.bucket_name is None:
raise InvalidUriError('canned_acls on bucket-less URI (%s)' %
self.uri)
conn = self.connect()
canned_acls = conn.provider.canned_acls
self.check_response(canned_acls, 'canned_acls', self.uri)
return canned_acls
class BucketStorageUri(StorageUri):
"""
StorageUri subclass that handles bucket storage providers.
Callers should instantiate this class by calling boto.storage_uri().
"""
def __init__(self, scheme, bucket_name=None, object_name=None,
debug=0):
"""Instantiate a BucketStorageUri from scheme,bucket,object tuple.
@type scheme: string
@param scheme: URI scheme naming the storage provider (gs, s3, etc.)
@type bucket_name: string
@param bucket_name: bucket name
@type object_name: string
@param object_name: object name
@type debug: int
@param debug: debug level to pass in to connection (range 0..2)
After instantiation the components are available in the following
fields: uri, scheme, bucket_name, object_name.
"""
self.scheme = scheme
self.bucket_name = bucket_name
self.object_name = object_name
if self.bucket_name and self.object_name:
self.uri = ('%s://%s/%s' % (self.scheme, self.bucket_name,
self.object_name))
elif self.bucket_name:
self.uri = ('%s://%s/' % (self.scheme, self.bucket_name))
else:
self.uri = ('%s://' % self.scheme)
self.debug = debug
def clone_replace_name(self, new_name):
"""Instantiate a BucketStorageUri from the current BucketStorageUri,
but replacing the object_name.
@type new_name: string
@param new_name: new object name
"""
if not self.bucket_name:
raise InvalidUriError('clone_replace_name() on bucket-less URI %s' %
self.uri)
return BucketStorageUri(self.scheme, self.bucket_name, new_name,
self.debug)
def get_acl(self, validate=True, headers=None, version_id=None):
if not self.bucket_name:
raise InvalidUriError('get_acl on bucket-less URI (%s)' % self.uri)
bucket = self.get_bucket(validate, headers)
# This works for both bucket- and object- level ACLs (former passes
# key_name=None):
acl = bucket.get_acl(self.object_name, headers, version_id)
self.check_response(acl, 'acl', self.uri)
return acl
def add_email_grant(self, permission, email_address, recursive=False,
validate=True, headers=None):
if not self.bucket_name:
raise InvalidUriError('add_email_grant on bucket-less URI (%s)' %
self.uri)
if not self.object_name:
bucket = self.get_bucket(validate, headers)
bucket.add_email_grant(permission, email_address, recursive,
headers)
else:
key = self.get_key(validate, headers)
key.add_email_grant(permission, email_address)
def add_user_grant(self, permission, user_id, recursive=False,
validate=True, headers=None):
if not self.bucket_name:
raise InvalidUriError('add_user_grant on bucket-less URI (%s)' %
self.uri)
if not self.object_name:
bucket = self.get_bucket(validate, headers)
bucket.add_user_grant(permission, user_id, recursive, headers)
else:
key = self.get_key(validate, headers)
key.add_user_grant(permission, user_id)
def list_grants(self, headers=None):
if not self.bucket_name:
raise InvalidUriError('list_grants on bucket-less URI (%s)' %
self.uri)
bucket = self.get_bucket(headers)
return bucket.list_grants(headers)
def names_container(self):
"""Returns True if this URI names a bucket (vs. an object).
"""
return not self.object_name
def names_singleton(self):
"""Returns True if this URI names an object (vs. a bucket).
"""
return self.object_name
def is_file_uri(self):
return False
def is_cloud_uri(self):
return True
def create_bucket(self, headers=None, location='', policy=None):
if self.bucket_name is None:
raise InvalidUriError('create_bucket on bucket-less URI (%s)' %
self.uri)
conn = self.connect()
return conn.create_bucket(self.bucket_name, headers, location, policy)
def delete_bucket(self, headers=None):
if self.bucket_name is None:
raise InvalidUriError('delete_bucket on bucket-less URI (%s)' %
self.uri)
conn = self.connect()
return conn.delete_bucket(self.bucket_name, headers)
def get_all_buckets(self, headers=None):
conn = self.connect()
return conn.get_all_buckets(headers)
def get_provider(self):
conn = self.connect()
provider = conn.provider
self.check_response(provider, 'provider', self.uri)
return provider
def set_acl(self, acl_or_str, key_name='', validate=True, headers=None,
version_id=None):
if not self.bucket_name:
raise InvalidUriError('set_acl on bucket-less URI (%s)' %
self.uri)
self.get_bucket(validate, headers).set_acl(acl_or_str, key_name,
headers, version_id)
def set_canned_acl(self, acl_str, validate=True, headers=None,
version_id=None):
if not self.object_name:
raise InvalidUriError('set_canned_acl on object-less URI (%s)' %
self.uri)
key = self.get_key(validate, headers)
key.set_canned_acl(acl_str, headers, version_id)
class FileStorageUri(StorageUri):
"""
StorageUri subclass that handles files in the local file system.
Callers should instantiate this class by calling boto.storage_uri().
See file/README about how we map StorageUri operations onto a file system.
"""
def __init__(self, object_name, debug):
"""Instantiate a FileStorageUri from a path name.
@type object_name: string
@param object_name: object name
@type debug: boolean
@param debug: whether to enable debugging on this StorageUri
After instantiation the components are available in the following
fields: uri, scheme, bucket_name (always blank for this "anonymous"
bucket), object_name.
"""
self.scheme = 'file'
self.bucket_name = ''
self.object_name = object_name
self.uri = 'file://' + object_name
self.debug = debug
def clone_replace_name(self, new_name):
"""Instantiate a FileStorageUri from the current FileStorageUri,
but replacing the object_name.
@type new_name: string
@param new_name: new object name
"""
return FileStorageUri(new_name, self.debug)
def names_container(self):
"""Returns True if this URI names a directory.
"""
return os.path.isdir(self.object_name)
def names_singleton(self):
"""Returns True if this URI names a file.
"""
return os.path.isfile(self.object_name)
def is_file_uri(self):
return True
def is_cloud_uri(self):
return False
| 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 SDBRegionInfo(RegionInfo):
def __init__(self, connection=None, name=None, endpoint=None):
from boto.sdb.connection import SDBConnection
RegionInfo.__init__(self, connection, name, endpoint,
SDBConnection)
| 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 SDB Item
"""
import base64
class Item(dict):
def __init__(self, domain, name='', active=False):
dict.__init__(self)
self.domain = domain
self.name = name
self.active = active
self.request_id = None
self.encoding = None
self.in_attribute = False
self.converter = self.domain.connection.converter
def startElement(self, name, attrs, connection):
if name == 'Attribute':
self.in_attribute = True
self.encoding = attrs.get('encoding', None)
return None
def decode_value(self, value):
if self.encoding == 'base64':
self.encoding = None
return base64.decodestring(value)
else:
return value
def endElement(self, name, value, connection):
if name == 'ItemName':
self.name = self.decode_value(value)
elif name == 'Name':
if self.in_attribute:
self.last_key = self.decode_value(value)
else:
self.name = self.decode_value(value)
elif name == 'Value':
if self.has_key(self.last_key):
if not isinstance(self[self.last_key], list):
self[self.last_key] = [self[self.last_key]]
value = self.decode_value(value)
if self.converter:
value = self.converter.decode(value)
self[self.last_key].append(value)
else:
value = self.decode_value(value)
if self.converter:
value = self.converter.decode(value)
self[self.last_key] = value
elif name == 'BoxUsage':
try:
connection.box_usage += float(value)
except:
pass
elif name == 'RequestId':
self.request_id = value
elif name == 'Attribute':
self.in_attribute = False
else:
setattr(self, name, value)
def load(self):
self.domain.get_attributes(self.name, item=self)
def save(self, replace=True):
self.domain.put_attributes(self.name, self, replace)
# Delete any attributes set to "None"
if replace:
del_attrs = []
for name in self:
if self[name] == None:
del_attrs.append(name)
if len(del_attrs) > 0:
self.domain.delete_attributes(self.name, del_attrs)
def add_value(self, key, value):
if key in self:
if not isinstance(self[key], list):
self[key] = [self[key]]
self[key].append(value)
else:
self[key] = value
def delete(self):
self.domain.delete_item(self)
| 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 threading
from boto import handler
from boto.connection import AWSQueryConnection
from boto.sdb.domain import Domain, DomainMetaData
from boto.sdb.item import Item
from boto.sdb.regioninfo import SDBRegionInfo
from boto.exception import SDBResponseError
class ItemThread(threading.Thread):
def __init__(self, name, domain_name, item_names):
threading.Thread.__init__(self, name=name)
print 'starting %s with %d items' % (name, len(item_names))
self.domain_name = domain_name
self.conn = SDBConnection()
self.item_names = item_names
self.items = []
def run(self):
for item_name in self.item_names:
item = self.conn.get_attributes(self.domain_name, item_name)
self.items.append(item)
#boto.set_stream_logger('sdb')
class SDBConnection(AWSQueryConnection):
DefaultRegionName = 'us-east-1'
DefaultRegionEndpoint = 'sdb.amazonaws.com'
APIVersion = '2009-04-15'
SignatureVersion = '2'
ResponseError = SDBResponseError
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='/', converter=None):
if not region:
region = SDBRegionInfo(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)
self.box_usage = 0.0
self.converter = converter
self.item_cls = Item
def set_item_cls(self, cls):
self.item_cls = cls
def build_name_value_list(self, params, attributes, replace=False,
label='Attribute'):
keys = attributes.keys()
keys.sort()
i = 1
for key in keys:
value = attributes[key]
if isinstance(value, list):
for v in value:
params['%s.%d.Name'%(label,i)] = key
if self.converter:
v = self.converter.encode(v)
params['%s.%d.Value'%(label,i)] = v
if replace:
params['%s.%d.Replace'%(label,i)] = 'true'
i += 1
else:
params['%s.%d.Name'%(label,i)] = key
if self.converter:
value = self.converter.encode(value)
params['%s.%d.Value'%(label,i)] = value
if replace:
params['%s.%d.Replace'%(label,i)] = 'true'
i += 1
def build_expected_value(self, params, expected_value):
params['Expected.1.Name'] = expected_value[0]
if expected_value[1] == True:
params['Expected.1.Exists'] = 'true'
elif expected_value[1] == False:
params['Expected.1.Exists'] = 'false'
else:
params['Expected.1.Value'] = expected_value[1]
def build_batch_list(self, params, items, replace=False):
item_names = items.keys()
i = 0
for item_name in item_names:
j = 0
item = items[item_name]
attr_names = item.keys()
params['Item.%d.ItemName' % i] = item_name
for attr_name in attr_names:
value = item[attr_name]
if isinstance(value, list):
for v in value:
if self.converter:
v = self.converter.encode(v)
params['Item.%d.Attribute.%d.Name' % (i,j)] = attr_name
params['Item.%d.Attribute.%d.Value' % (i,j)] = v
if replace:
params['Item.%d.Attribute.%d.Replace' % (i,j)] = 'true'
j += 1
else:
params['Item.%d.Attribute.%d.Name' % (i,j)] = attr_name
if self.converter:
value = self.converter.encode(value)
params['Item.%d.Attribute.%d.Value' % (i,j)] = value
if replace:
params['Item.%d.Attribute.%d.Replace' % (i,j)] = 'true'
j += 1
i += 1
def build_name_list(self, params, attribute_names):
i = 1
attribute_names.sort()
for name in attribute_names:
params['Attribute.%d.Name'%i] = name
i += 1
def get_usage(self):
"""
Returns the BoxUsage accumulated on this SDBConnection object.
:rtype: float
:return: The accumulated BoxUsage of all requests made on the connection.
"""
return self.box_usage
def print_usage(self):
"""
Print the BoxUsage and approximate costs of all requests made on this connection.
"""
print 'Total Usage: %f compute seconds' % self.box_usage
cost = self.box_usage * 0.14
print 'Approximate Cost: $%f' % cost
def get_domain(self, domain_name, validate=True):
domain = Domain(self, domain_name)
if validate:
self.select(domain, """select * from `%s` limit 1""" % domain_name)
return domain
def lookup(self, domain_name, validate=True):
"""
Lookup an existing SimpleDB domain
:type domain_name: string
:param domain_name: The name of the new domain
:rtype: :class:`boto.sdb.domain.Domain` object or None
:return: The Domain object or None if the domain does not exist.
"""
try:
domain = self.get_domain(domain_name, validate)
except:
domain = None
return domain
def get_all_domains(self, max_domains=None, next_token=None):
params = {}
if max_domains:
params['MaxNumberOfDomains'] = max_domains
if next_token:
params['NextToken'] = next_token
return self.get_list('ListDomains', params, [('DomainName', Domain)])
def create_domain(self, domain_name):
"""
Create a SimpleDB domain.
:type domain_name: string
:param domain_name: The name of the new domain
:rtype: :class:`boto.sdb.domain.Domain` object
:return: The newly created domain
"""
params = {'DomainName':domain_name}
d = self.get_object('CreateDomain', params, Domain)
d.name = domain_name
return d
def get_domain_and_name(self, domain_or_name):
if (isinstance(domain_or_name, Domain)):
return (domain_or_name, domain_or_name.name)
else:
return (self.get_domain(domain_or_name), domain_or_name)
def delete_domain(self, domain_or_name):
"""
Delete a SimpleDB domain.
:type domain_or_name: string or :class:`boto.sdb.domain.Domain` object.
:param domain_or_name: Either the name of a domain or a Domain object
:rtype: bool
:return: True if successful
B{Note:} This will delete the domain and all items within the domain.
"""
domain, domain_name = self.get_domain_and_name(domain_or_name)
params = {'DomainName':domain_name}
return self.get_status('DeleteDomain', params)
def domain_metadata(self, domain_or_name):
"""
Get the Metadata for a SimpleDB domain.
:type domain_or_name: string or :class:`boto.sdb.domain.Domain` object.
:param domain_or_name: Either the name of a domain or a Domain object
:rtype: :class:`boto.sdb.domain.DomainMetaData` object
:return: The newly created domain metadata object
"""
domain, domain_name = self.get_domain_and_name(domain_or_name)
params = {'DomainName':domain_name}
d = self.get_object('DomainMetadata', params, DomainMetaData)
d.domain = domain
return d
def put_attributes(self, domain_or_name, item_name, attributes,
replace=True, expected_value=None):
"""
Store attributes for a given item in a domain.
:type domain_or_name: string or :class:`boto.sdb.domain.Domain` object.
:param domain_or_name: Either the name of a domain or a Domain object
:type item_name: string
:param item_name: The name of the item whose attributes are being stored.
:type attribute_names: dict or dict-like object
:param attribute_names: The name/value pairs to store as attributes
:type expected_value: list
:param expected_value: If supplied, this is a list or tuple consisting
of a single attribute name and expected value.
The list can be of the form:
* ['name', 'value']
In which case the call will first verify
that the attribute "name" of this item has
a value of "value". If it does, the delete
will proceed, otherwise a ConditionalCheckFailed
error will be returned.
The list can also be of the form:
* ['name', True|False]
which will simply check for the existence (True)
or non-existencve (False) of the attribute.
:type replace: bool
:param replace: Whether the attribute values passed in will replace
existing values or will be added as addition values.
Defaults to True.
:rtype: bool
:return: True if successful
"""
domain, domain_name = self.get_domain_and_name(domain_or_name)
params = {'DomainName' : domain_name,
'ItemName' : item_name}
self.build_name_value_list(params, attributes, replace)
if expected_value:
self.build_expected_value(params, expected_value)
return self.get_status('PutAttributes', params)
def batch_put_attributes(self, domain_or_name, items, replace=True):
"""
Store attributes for multiple items in a domain.
:type domain_or_name: string or :class:`boto.sdb.domain.Domain` object.
:param domain_or_name: Either the name of a domain or a Domain object
:type items: dict or dict-like object
:param items: A dictionary-like object. The keys of the dictionary are
the item names and the values are themselves dictionaries
of attribute names/values, exactly the same as the
attribute_names parameter of the scalar put_attributes
call.
:type replace: bool
:param replace: Whether the attribute values passed in will replace
existing values or will be added as addition values.
Defaults to True.
:rtype: bool
:return: True if successful
"""
domain, domain_name = self.get_domain_and_name(domain_or_name)
params = {'DomainName' : domain_name}
self.build_batch_list(params, items, replace)
return self.get_status('BatchPutAttributes', params, verb='POST')
def get_attributes(self, domain_or_name, item_name, attribute_names=None,
consistent_read=False, item=None):
"""
Retrieve attributes for a given item in a domain.
:type domain_or_name: string or :class:`boto.sdb.domain.Domain` object.
:param domain_or_name: Either the name of a domain or a Domain object
:type item_name: string
:param item_name: The name of the item whose attributes are being retrieved.
:type attribute_names: string or list of strings
:param attribute_names: An attribute name or list of attribute names. This
parameter is optional. If not supplied, all attributes
will be retrieved for the item.
:type consistent_read: bool
:param consistent_read: When set to true, ensures that the most recent
data is returned.
:rtype: :class:`boto.sdb.item.Item`
:return: An Item mapping type containing the requested attribute name/values
"""
domain, domain_name = self.get_domain_and_name(domain_or_name)
params = {'DomainName' : domain_name,
'ItemName' : item_name}
if consistent_read:
params['ConsistentRead'] = 'true'
if attribute_names:
if not isinstance(attribute_names, list):
attribute_names = [attribute_names]
self.build_list_params(params, attribute_names, 'AttributeName')
response = self.make_request('GetAttributes', params)
body = response.read()
if response.status == 200:
if item == None:
item = self.item_cls(domain, item_name)
h = handler.XmlHandler(item, self)
xml.sax.parseString(body, h)
return item
else:
raise SDBResponseError(response.status, response.reason, body)
def delete_attributes(self, domain_or_name, item_name, attr_names=None,
expected_value=None):
"""
Delete attributes from a given item in a domain.
:type domain_or_name: string or :class:`boto.sdb.domain.Domain` object.
:param domain_or_name: Either the name of a domain or a Domain object
:type item_name: string
:param item_name: The name of the item whose attributes are being deleted.
:type attributes: dict, list or :class:`boto.sdb.item.Item`
:param attributes: Either a list containing attribute names which will cause
all values associated with that attribute name to be deleted or
a dict or Item containing the attribute names and keys and list
of values to delete as the value. If no value is supplied,
all attribute name/values for the item will be deleted.
:type expected_value: list
:param expected_value: If supplied, this is a list or tuple consisting
of a single attribute name and expected value.
The list can be of the form:
* ['name', 'value']
In which case the call will first verify
that the attribute "name" of this item has
a value of "value". If it does, the delete
will proceed, otherwise a ConditionalCheckFailed
error will be returned.
The list can also be of the form:
* ['name', True|False]
which will simply check for the existence (True)
or non-existencve (False) of the attribute.
:rtype: bool
:return: True if successful
"""
domain, domain_name = self.get_domain_and_name(domain_or_name)
params = {'DomainName':domain_name,
'ItemName' : item_name}
if attr_names:
if isinstance(attr_names, list):
self.build_name_list(params, attr_names)
elif isinstance(attr_names, dict) or isinstance(attr_names, self.item_cls):
self.build_name_value_list(params, attr_names)
if expected_value:
self.build_expected_value(params, expected_value)
return self.get_status('DeleteAttributes', params)
def select(self, domain_or_name, query='', next_token=None,
consistent_read=False):
"""
Returns a set of Attributes for item names within domain_name that match the query.
The query must be expressed in using the SELECT style syntax rather than the
original SimpleDB query language.
Even though the select request does not require a domain object, a domain
object must be passed into this method so the Item objects returned can
point to the appropriate domain.
:type domain_or_name: string or :class:`boto.sdb.domain.Domain` object.
:param domain_or_name: Either the name of a domain or a Domain object
:type query: string
:param query: The SimpleDB query to be performed.
:type consistent_read: bool
:param consistent_read: When set to true, ensures that the most recent
data is returned.
:rtype: ResultSet
:return: An iterator containing the results.
"""
domain, domain_name = self.get_domain_and_name(domain_or_name)
params = {'SelectExpression' : query}
if consistent_read:
params['ConsistentRead'] = 'true'
if next_token:
params['NextToken'] = next_token
try:
return self.get_list('Select', params, [('Item', self.item_cls)],
parent=domain)
except SDBResponseError, e:
e.body = "Query: %s\n%s" % (query, e.body)
raise e
| 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 regioninfo import SDBRegionInfo
def regions():
"""
Get all available regions for the SDB service.
:rtype: list
:return: A list of :class:`boto.sdb.regioninfo.RegionInfo`
"""
return [SDBRegionInfo(name='us-east-1',
endpoint='sdb.amazonaws.com'),
SDBRegionInfo(name='eu-west-1',
endpoint='sdb.eu-west-1.amazonaws.com'),
SDBRegionInfo(name='us-west-1',
endpoint='sdb.us-west-1.amazonaws.com'),
SDBRegionInfo(name='ap-southeast-1',
endpoint='sdb.ap-southeast-1.amazonaws.com')
]
def connect_to_region(region_name):
for region in regions():
if region.name == region_name:
return region.connect()
return None
| Python |
# Copyright (c) 2006,2007,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 Query(object):
__local_iter__ = None
def __init__(self, model_class, limit=None, next_token=None, manager=None):
self.model_class = model_class
self.limit = limit
self.offset = 0
if manager:
self.manager = manager
else:
self.manager = self.model_class._manager
self.filters = []
self.sort_by = None
self.rs = None
self.next_token = next_token
def __iter__(self):
return iter(self.manager.query(self))
def next(self):
if self.__local_iter__ == None:
self.__local_iter__ = self.__iter__()
return self.__local_iter__.next()
def filter(self, property_operator, value):
self.filters.append((property_operator, value))
return self
def fetch(self, limit, offset=0):
"""Not currently fully supported, but we can use this
to allow them to set a limit in a chainable method"""
self.limit = limit
self.offset = offset
return self
def count(self, quick=True):
return self.manager.count(self.model_class, self.filters, quick)
def get_query(self):
return self.manager._build_filter_part(self.model_class, self.filters, self.sort_by)
def order(self, key):
self.sort_by = key
return self
def to_xml(self, doc=None):
if not doc:
xmlmanager = self.model_class.get_xmlmanager()
doc = xmlmanager.new_doc()
for obj in self:
obj.to_xml(doc)
return doc
def get_next_token(self):
if self.rs:
return self.rs.next_token
if self._next_token:
return self._next_token
return None
def set_next_token(self, token):
self._next_token = token
next_token = property(get_next_token, set_next_token)
| Python |
# Copyright (c) 2006,2007,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.sdb.db.manager import get_manager
from boto.sdb.db.property import Property
from boto.sdb.db.key import Key
from boto.sdb.db.query import Query
import boto
class ModelMeta(type):
"Metaclass for all Models"
def __init__(cls, name, bases, dict):
super(ModelMeta, cls).__init__(name, bases, dict)
# Make sure this is a subclass of Model - mainly copied from django ModelBase (thanks!)
cls.__sub_classes__ = []
try:
if filter(lambda b: issubclass(b, Model), bases):
for base in bases:
base.__sub_classes__.append(cls)
cls._manager = get_manager(cls)
# look for all of the Properties and set their names
for key in dict.keys():
if isinstance(dict[key], Property):
property = dict[key]
property.__property_config__(cls, key)
prop_names = []
props = cls.properties()
for prop in props:
if not prop.__class__.__name__.startswith('_'):
prop_names.append(prop.name)
setattr(cls, '_prop_names', prop_names)
except NameError:
# 'Model' isn't defined yet, meaning we're looking at our own
# Model class, defined below.
pass
class Model(object):
__metaclass__ = ModelMeta
__consistent__ = False # Consistent is set off by default
id = None
@classmethod
def get_lineage(cls):
l = [c.__name__ for c in cls.mro()]
l.reverse()
return '.'.join(l)
@classmethod
def kind(cls):
return cls.__name__
@classmethod
def _get_by_id(cls, id, manager=None):
if not manager:
manager = cls._manager
return manager.get_object(cls, id)
@classmethod
def get_by_id(cls, ids=None, parent=None):
if isinstance(ids, list):
objs = [cls._get_by_id(id) for id in ids]
return objs
else:
return cls._get_by_id(ids)
get_by_ids = get_by_id
@classmethod
def get_by_key_name(cls, key_names, parent=None):
raise NotImplementedError, "Key Names are not currently supported"
@classmethod
def find(cls, limit=None, next_token=None, **params):
q = Query(cls, limit=limit, next_token=next_token)
for key, value in params.items():
q.filter('%s =' % key, value)
return q
@classmethod
def lookup(cls, name, value):
return cls._manager.lookup(cls, name, value)
@classmethod
def all(cls, limit=None, next_token=None):
return cls.find(limit=limit, next_token=next_token)
@classmethod
def get_or_insert(key_name, **kw):
raise NotImplementedError, "get_or_insert not currently supported"
@classmethod
def properties(cls, hidden=True):
properties = []
while cls:
for key in cls.__dict__.keys():
prop = cls.__dict__[key]
if isinstance(prop, Property):
if hidden or not prop.__class__.__name__.startswith('_'):
properties.append(prop)
if len(cls.__bases__) > 0:
cls = cls.__bases__[0]
else:
cls = None
return properties
@classmethod
def find_property(cls, prop_name):
property = None
while cls:
for key in cls.__dict__.keys():
prop = cls.__dict__[key]
if isinstance(prop, Property):
if not prop.__class__.__name__.startswith('_') and prop_name == prop.name:
property = prop
if len(cls.__bases__) > 0:
cls = cls.__bases__[0]
else:
cls = None
return property
@classmethod
def get_xmlmanager(cls):
if not hasattr(cls, '_xmlmanager'):
from boto.sdb.db.manager.xmlmanager import XMLManager
cls._xmlmanager = XMLManager(cls, None, None, None,
None, None, None, None, False)
return cls._xmlmanager
@classmethod
def from_xml(cls, fp):
xmlmanager = cls.get_xmlmanager()
return xmlmanager.unmarshal_object(fp)
def __init__(self, id=None, **kw):
self._loaded = False
# first initialize all properties to their default values
for prop in self.properties(hidden=False):
setattr(self, prop.name, prop.default_value())
if kw.has_key('manager'):
self._manager = kw['manager']
self.id = id
for key in kw:
if key != 'manager':
# We don't want any errors populating up when loading an object,
# so if it fails we just revert to it's default value
try:
setattr(self, key, kw[key])
except Exception, e:
boto.log.exception(e)
def __repr__(self):
return '%s<%s>' % (self.__class__.__name__, self.id)
def __str__(self):
return str(self.id)
def __eq__(self, other):
return other and isinstance(other, Model) and self.id == other.id
def _get_raw_item(self):
return self._manager.get_raw_item(self)
def load(self):
if self.id and not self._loaded:
self._manager.load_object(self)
def reload(self):
if self.id:
self._loaded = False
self._manager.load_object(self)
def put(self):
self._manager.save_object(self)
save = put
def delete(self):
self._manager.delete_object(self)
def key(self):
return Key(obj=self)
def set_manager(self, manager):
self._manager = manager
def to_dict(self):
props = {}
for prop in self.properties(hidden=False):
props[prop.name] = getattr(self, prop.name)
obj = {'properties' : props,
'id' : self.id}
return {self.__class__.__name__ : obj}
def to_xml(self, doc=None):
xmlmanager = self.get_xmlmanager()
doc = xmlmanager.marshal_object(self, doc)
return doc
class Expando(Model):
def __setattr__(self, name, value):
if name in self._prop_names:
object.__setattr__(self, name, value)
elif name.startswith('_'):
object.__setattr__(self, name, value)
elif name == 'id':
object.__setattr__(self, name, value)
else:
self._manager.set_key_value(self, name, value)
object.__setattr__(self, name, value)
def __getattr__(self, name):
if not name.startswith('_'):
value = self._manager.get_key_value(self, name)
if value:
object.__setattr__(self, name, value)
return value
raise AttributeError
| Python |
# Copyright (c) 2006,2007,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 Key(object):
@classmethod
def from_path(cls, *args, **kwds):
raise NotImplementedError, "Paths are not currently supported"
def __init__(self, encoded=None, obj=None):
self.name = None
if obj:
self.id = obj.id
self.kind = obj.kind()
else:
self.id = None
self.kind = None
def app(self):
raise NotImplementedError, "Applications are not currently supported"
def kind(self):
return self.kind
def id(self):
return self.id
def name(self):
raise NotImplementedError, "Key Names are not currently supported"
def id_or_name(self):
return self.id
def has_id_or_name(self):
return self.id != None
def parent(self):
raise NotImplementedError, "Key parents are not currently supported"
def __str__(self):
return self.id_or_name()
| Python |
# Copyright (c) 2006,2007,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.
import datetime
from key import Key
from boto.utils import Password
from boto.sdb.db.query import Query
import re
import boto
import boto.s3.key
from boto.sdb.db.blob import Blob
class Property(object):
data_type = str
type_name = ''
name = ''
verbose_name = ''
def __init__(self, verbose_name=None, name=None, default=None, required=False,
validator=None, choices=None, unique=False):
self.verbose_name = verbose_name
self.name = name
self.default = default
self.required = required
self.validator = validator
self.choices = choices
if self.name:
self.slot_name = '_' + self.name
else:
self.slot_name = '_'
self.unique = unique
def __get__(self, obj, objtype):
if obj:
obj.load()
return getattr(obj, self.slot_name)
else:
return None
def __set__(self, obj, value):
self.validate(value)
# Fire off any on_set functions
try:
if obj._loaded and hasattr(obj, "on_set_%s" % self.name):
fnc = getattr(obj, "on_set_%s" % self.name)
value = fnc(value)
except Exception:
boto.log.exception("Exception running on_set_%s" % self.name)
setattr(obj, self.slot_name, value)
def __property_config__(self, model_class, property_name):
self.model_class = model_class
self.name = property_name
self.slot_name = '_' + self.name
def default_validator(self, value):
if value == self.default_value():
return
if not isinstance(value, self.data_type):
raise TypeError, 'Validation Error, expecting %s, got %s' % (self.data_type, type(value))
def default_value(self):
return self.default
def validate(self, value):
if self.required and value==None:
raise ValueError, '%s is a required property' % self.name
if self.choices and value and not value in self.choices:
raise ValueError, '%s not a valid choice for %s.%s' % (value, self.model_class.__name__, self.name)
if self.validator:
self.validator(value)
else:
self.default_validator(value)
return value
def empty(self, value):
return not value
def get_value_for_datastore(self, model_instance):
return getattr(model_instance, self.name)
def make_value_from_datastore(self, value):
return value
def get_choices(self):
if callable(self.choices):
return self.choices()
return self.choices
def validate_string(value):
if value == None:
return
elif isinstance(value, str) or isinstance(value, unicode):
if len(value) > 1024:
raise ValueError, 'Length of value greater than maxlength'
else:
raise TypeError, 'Expecting String, got %s' % type(value)
class StringProperty(Property):
type_name = 'String'
def __init__(self, verbose_name=None, name=None, default='', required=False,
validator=validate_string, choices=None, unique=False):
Property.__init__(self, verbose_name, name, default, required, validator, choices, unique)
class TextProperty(Property):
type_name = 'Text'
def __init__(self, verbose_name=None, name=None, default='', required=False,
validator=None, choices=None, unique=False, max_length=None):
Property.__init__(self, verbose_name, name, default, required, validator, choices, unique)
self.max_length = max_length
def validate(self, value):
if not isinstance(value, str) and not isinstance(value, unicode):
raise TypeError, 'Expecting Text, got %s' % type(value)
if self.max_length and len(value) > self.max_length:
raise ValueError, 'Length of value greater than maxlength %s' % self.max_length
class PasswordProperty(StringProperty):
"""
Hashed property who's original value can not be
retrieved, but still can be compaired.
"""
data_type = Password
type_name = 'Password'
def __init__(self, verbose_name=None, name=None, default='', required=False,
validator=None, choices=None, unique=False):
StringProperty.__init__(self, verbose_name, name, default, required, validator, choices, unique)
def make_value_from_datastore(self, value):
p = Password(value)
return p
def get_value_for_datastore(self, model_instance):
value = StringProperty.get_value_for_datastore(self, model_instance)
if value and len(value):
return str(value)
else:
return None
def __set__(self, obj, value):
if not isinstance(value, Password):
p = Password()
p.set(value)
value = p
Property.__set__(self, obj, value)
def __get__(self, obj, objtype):
return Password(StringProperty.__get__(self, obj, objtype))
def validate(self, value):
value = Property.validate(self, value)
if isinstance(value, Password):
if len(value) > 1024:
raise ValueError, 'Length of value greater than maxlength'
else:
raise TypeError, 'Expecting Password, got %s' % type(value)
class BlobProperty(Property):
data_type = Blob
type_name = "blob"
def __set__(self, obj, value):
if value != self.default_value():
if not isinstance(value, Blob):
oldb = self.__get__(obj, type(obj))
id = None
if oldb:
id = oldb.id
b = Blob(value=value, id=id)
value = b
Property.__set__(self, obj, value)
class S3KeyProperty(Property):
data_type = boto.s3.key.Key
type_name = 'S3Key'
validate_regex = "^s3:\/\/([^\/]*)\/(.*)$"
def __init__(self, verbose_name=None, name=None, default=None,
required=False, validator=None, choices=None, unique=False):
Property.__init__(self, verbose_name, name, default, required,
validator, choices, unique)
def validate(self, value):
if value == self.default_value() or value == str(self.default_value()):
return self.default_value()
if isinstance(value, self.data_type):
return
match = re.match(self.validate_regex, value)
if match:
return
raise TypeError, 'Validation Error, expecting %s, got %s' % (self.data_type, type(value))
def __get__(self, obj, objtype):
value = Property.__get__(self, obj, objtype)
if value:
if isinstance(value, self.data_type):
return value
match = re.match(self.validate_regex, value)
if match:
s3 = obj._manager.get_s3_connection()
bucket = s3.get_bucket(match.group(1), validate=False)
k = bucket.get_key(match.group(2))
if not k:
k = bucket.new_key(match.group(2))
k.set_contents_from_string("")
return k
else:
return value
def get_value_for_datastore(self, model_instance):
value = Property.get_value_for_datastore(self, model_instance)
if value:
return "s3://%s/%s" % (value.bucket.name, value.name)
else:
return None
class IntegerProperty(Property):
data_type = int
type_name = 'Integer'
def __init__(self, verbose_name=None, name=None, default=0, required=False,
validator=None, choices=None, unique=False, max=2147483647, min=-2147483648):
Property.__init__(self, verbose_name, name, default, required, validator, choices, unique)
self.max = max
self.min = min
def validate(self, value):
value = int(value)
value = Property.validate(self, value)
if value > self.max:
raise ValueError, 'Maximum value is %d' % self.max
if value < self.min:
raise ValueError, 'Minimum value is %d' % self.min
return value
def empty(self, value):
return value is None
def __set__(self, obj, value):
if value == "" or value == None:
value = 0
return Property.__set__(self, obj, value)
class LongProperty(Property):
data_type = long
type_name = 'Long'
def __init__(self, verbose_name=None, name=None, default=0, required=False,
validator=None, choices=None, unique=False):
Property.__init__(self, verbose_name, name, default, required, validator, choices, unique)
def validate(self, value):
value = long(value)
value = Property.validate(self, value)
min = -9223372036854775808
max = 9223372036854775807
if value > max:
raise ValueError, 'Maximum value is %d' % max
if value < min:
raise ValueError, 'Minimum value is %d' % min
return value
def empty(self, value):
return value is None
class BooleanProperty(Property):
data_type = bool
type_name = 'Boolean'
def __init__(self, verbose_name=None, name=None, default=False, required=False,
validator=None, choices=None, unique=False):
Property.__init__(self, verbose_name, name, default, required, validator, choices, unique)
def empty(self, value):
return value is None
class FloatProperty(Property):
data_type = float
type_name = 'Float'
def __init__(self, verbose_name=None, name=None, default=0.0, required=False,
validator=None, choices=None, unique=False):
Property.__init__(self, verbose_name, name, default, required, validator, choices, unique)
def validate(self, value):
value = float(value)
value = Property.validate(self, value)
return value
def empty(self, value):
return value is None
class DateTimeProperty(Property):
data_type = datetime.datetime
type_name = 'DateTime'
def __init__(self, verbose_name=None, auto_now=False, auto_now_add=False, name=None,
default=None, required=False, validator=None, choices=None, unique=False):
Property.__init__(self, verbose_name, name, default, required, validator, choices, unique)
self.auto_now = auto_now
self.auto_now_add = auto_now_add
def default_value(self):
if self.auto_now or self.auto_now_add:
return self.now()
return Property.default_value(self)
def validate(self, value):
if value == None:
return
if not isinstance(value, self.data_type):
raise TypeError, 'Validation Error, expecting %s, got %s' % (self.data_type, type(value))
def get_value_for_datastore(self, model_instance):
if self.auto_now:
setattr(model_instance, self.name, self.now())
return Property.get_value_for_datastore(self, model_instance)
def now(self):
return datetime.datetime.utcnow()
class DateProperty(Property):
data_type = datetime.date
type_name = 'Date'
def __init__(self, verbose_name=None, auto_now=False, auto_now_add=False, name=None,
default=None, required=False, validator=None, choices=None, unique=False):
Property.__init__(self, verbose_name, name, default, required, validator, choices, unique)
self.auto_now = auto_now
self.auto_now_add = auto_now_add
def default_value(self):
if self.auto_now or self.auto_now_add:
return self.now()
return Property.default_value(self)
def validate(self, value):
if value == None:
return
if not isinstance(value, self.data_type):
raise TypeError, 'Validation Error, expecting %s, got %s' % (self.data_type, type(value))
def get_value_for_datastore(self, model_instance):
if self.auto_now:
setattr(model_instance, self.name, self.now())
return Property.get_value_for_datastore(self, model_instance)
def now(self):
return datetime.date.today()
class ReferenceProperty(Property):
data_type = Key
type_name = 'Reference'
def __init__(self, reference_class=None, collection_name=None,
verbose_name=None, name=None, default=None, required=False, validator=None, choices=None, unique=False):
Property.__init__(self, verbose_name, name, default, required, validator, choices, unique)
self.reference_class = reference_class
self.collection_name = collection_name
def __get__(self, obj, objtype):
if obj:
value = getattr(obj, self.slot_name)
if value == self.default_value():
return value
# If the value is still the UUID for the referenced object, we need to create
# the object now that is the attribute has actually been accessed. This lazy
# instantiation saves unnecessary roundtrips to SimpleDB
if isinstance(value, str) or isinstance(value, unicode):
value = self.reference_class(value)
setattr(obj, self.name, value)
return value
def __set__(self, obj, value):
"""Don't allow this object to be associated to itself
This causes bad things to happen"""
if value != None and (obj.id == value or (hasattr(value, "id") and obj.id == value.id)):
raise ValueError, "Can not associate an object with itself!"
return super(ReferenceProperty, self).__set__(obj,value)
def __property_config__(self, model_class, property_name):
Property.__property_config__(self, model_class, property_name)
if self.collection_name is None:
self.collection_name = '%s_%s_set' % (model_class.__name__.lower(), self.name)
if hasattr(self.reference_class, self.collection_name):
raise ValueError, 'duplicate property: %s' % self.collection_name
setattr(self.reference_class, self.collection_name,
_ReverseReferenceProperty(model_class, property_name, self.collection_name))
def check_uuid(self, value):
# This does a bit of hand waving to "type check" the string
t = value.split('-')
if len(t) != 5:
raise ValueError
def check_instance(self, value):
try:
obj_lineage = value.get_lineage()
cls_lineage = self.reference_class.get_lineage()
if obj_lineage.startswith(cls_lineage):
return
raise TypeError, '%s not instance of %s' % (obj_lineage, cls_lineage)
except:
raise ValueError, '%s is not a Model' % value
def validate(self, value):
if self.required and value==None:
raise ValueError, '%s is a required property' % self.name
if value == self.default_value():
return
if not isinstance(value, str) and not isinstance(value, unicode):
self.check_instance(value)
class _ReverseReferenceProperty(Property):
data_type = Query
type_name = 'query'
def __init__(self, model, prop, name):
self.__model = model
self.__property = prop
self.collection_name = prop
self.name = name
self.item_type = model
def __get__(self, model_instance, model_class):
"""Fetches collection of model instances of this collection property."""
if model_instance is not None:
query = Query(self.__model)
if type(self.__property) == list:
props = []
for prop in self.__property:
props.append("%s =" % prop)
return query.filter(props, model_instance)
else:
return query.filter(self.__property + ' =', model_instance)
else:
return self
def __set__(self, model_instance, value):
"""Not possible to set a new collection."""
raise ValueError, 'Virtual property is read-only'
class CalculatedProperty(Property):
def __init__(self, verbose_name=None, name=None, default=None,
required=False, validator=None, choices=None,
calculated_type=int, unique=False, use_method=False):
Property.__init__(self, verbose_name, name, default, required,
validator, choices, unique)
self.calculated_type = calculated_type
self.use_method = use_method
def __get__(self, obj, objtype):
value = self.default_value()
if obj:
try:
value = getattr(obj, self.slot_name)
if self.use_method:
value = value()
except AttributeError:
pass
return value
def __set__(self, obj, value):
"""Not possible to set a new AutoID."""
pass
def _set_direct(self, obj, value):
if not self.use_method:
setattr(obj, self.slot_name, value)
def get_value_for_datastore(self, model_instance):
if self.calculated_type in [str, int, bool]:
value = self.__get__(model_instance, model_instance.__class__)
return value
else:
return None
class ListProperty(Property):
data_type = list
type_name = 'List'
def __init__(self, item_type, verbose_name=None, name=None, default=None, **kwds):
if default is None:
default = []
self.item_type = item_type
Property.__init__(self, verbose_name, name, default=default, required=True, **kwds)
def validate(self, value):
if value is not None:
if not isinstance(value, list):
value = [value]
if self.item_type in (int, long):
item_type = (int, long)
elif self.item_type in (str, unicode):
item_type = (str, unicode)
else:
item_type = self.item_type
for item in value:
if not isinstance(item, item_type):
if item_type == (int, long):
raise ValueError, 'Items in the %s list must all be integers.' % self.name
else:
raise ValueError('Items in the %s list must all be %s instances' %
(self.name, self.item_type.__name__))
return value
def empty(self, value):
return value is None
def default_value(self):
return list(super(ListProperty, self).default_value())
def __set__(self, obj, value):
"""Override the set method to allow them to set the property to an instance of the item_type instead of requiring a list to be passed in"""
if self.item_type in (int, long):
item_type = (int, long)
elif self.item_type in (str, unicode):
item_type = (str, unicode)
else:
item_type = self.item_type
if isinstance(value, item_type):
value = [value]
elif value == None: # Override to allow them to set this to "None" to remove everything
value = []
return super(ListProperty, self).__set__(obj,value)
class MapProperty(Property):
data_type = dict
type_name = 'Map'
def __init__(self, item_type=str, verbose_name=None, name=None, default=None, **kwds):
if default is None:
default = {}
self.item_type = item_type
Property.__init__(self, verbose_name, name, default=default, required=True, **kwds)
def validate(self, value):
if value is not None:
if not isinstance(value, dict):
raise ValueError, 'Value must of type dict'
if self.item_type in (int, long):
item_type = (int, long)
elif self.item_type in (str, unicode):
item_type = (str, unicode)
else:
item_type = self.item_type
for key in value:
if not isinstance(value[key], item_type):
if item_type == (int, long):
raise ValueError, 'Values in the %s Map must all be integers.' % self.name
else:
raise ValueError('Values in the %s Map must all be %s instances' %
(self.name, self.item_type.__name__))
return value
def empty(self, value):
return value is None
def default_value(self):
return {}
| Python |
# Copyright (c) 2006,2007,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.sdb.db.key import Key
from boto.sdb.db.model import Model
import psycopg2
import psycopg2.extensions
import uuid
import os
import string
from boto.exception import SDBPersistenceError
psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)
class PGConverter:
def __init__(self, manager):
self.manager = manager
self.type_map = {Key : (self.encode_reference, self.decode_reference),
Model : (self.encode_reference, self.decode_reference)}
def encode(self, type, value):
if type in self.type_map:
encode = self.type_map[type][0]
return encode(value)
return value
def decode(self, type, value):
if type in self.type_map:
decode = self.type_map[type][1]
return decode(value)
return value
def encode_prop(self, prop, value):
if isinstance(value, list):
if hasattr(prop, 'item_type'):
s = "{"
new_value = []
for v in value:
item_type = getattr(prop, 'item_type')
if Model in item_type.mro():
item_type = Model
new_value.append('%s' % self.encode(item_type, v))
s += ','.join(new_value)
s += "}"
return s
else:
return value
return self.encode(prop.data_type, value)
def decode_prop(self, prop, value):
if prop.data_type == list:
if value != None:
if not isinstance(value, list):
value = [value]
if hasattr(prop, 'item_type'):
item_type = getattr(prop, "item_type")
if Model in item_type.mro():
if item_type != self.manager.cls:
return item_type._manager.decode_value(prop, value)
else:
item_type = Model
return [self.decode(item_type, v) for v in value]
return value
elif hasattr(prop, 'reference_class'):
ref_class = getattr(prop, 'reference_class')
if ref_class != self.manager.cls:
return ref_class._manager.decode_value(prop, value)
else:
return self.decode(prop.data_type, value)
elif hasattr(prop, 'calculated_type'):
calc_type = getattr(prop, 'calculated_type')
return self.decode(calc_type, value)
else:
return self.decode(prop.data_type, value)
def encode_reference(self, value):
if isinstance(value, str) or isinstance(value, unicode):
return value
if value == None:
return ''
else:
return value.id
def decode_reference(self, value):
if not value:
return None
try:
return self.manager.get_object_from_id(value)
except:
raise ValueError, 'Unable to convert %s to Object' % value
class PGManager(object):
def __init__(self, cls, db_name, db_user, db_passwd,
db_host, db_port, db_table, sql_dir, enable_ssl):
self.cls = cls
self.db_name = db_name
self.db_user = db_user
self.db_passwd = db_passwd
self.db_host = db_host
self.db_port = db_port
self.db_table = db_table
self.sql_dir = sql_dir
self.in_transaction = False
self.converter = PGConverter(self)
self._connect()
def _build_connect_string(self):
cs = 'dbname=%s user=%s password=%s host=%s port=%d'
return cs % (self.db_name, self.db_user, self.db_passwd,
self.db_host, self.db_port)
def _connect(self):
self.connection = psycopg2.connect(self._build_connect_string())
self.connection.set_client_encoding('UTF8')
self.cursor = self.connection.cursor()
def _object_lister(self, cursor):
try:
for row in cursor:
yield self._object_from_row(row, cursor.description)
except StopIteration:
cursor.close()
raise StopIteration
def _dict_from_row(self, row, description):
d = {}
for i in range(0, len(row)):
d[description[i][0]] = row[i]
return d
def _object_from_row(self, row, description=None):
if not description:
description = self.cursor.description
d = self._dict_from_row(row, description)
obj = self.cls(d['id'])
obj._manager = self
obj._auto_update = False
for prop in obj.properties(hidden=False):
if prop.data_type != Key:
v = self.decode_value(prop, d[prop.name])
v = prop.make_value_from_datastore(v)
if hasattr(prop, 'calculated_type'):
prop._set_direct(obj, v)
elif not prop.empty(v):
setattr(obj, prop.name, v)
else:
setattr(obj, prop.name, prop.default_value())
return obj
def _build_insert_qs(self, obj, calculated):
fields = []
values = []
templs = []
id_calculated = [p for p in calculated if p.name == 'id']
for prop in obj.properties(hidden=False):
if prop not in calculated:
value = prop.get_value_for_datastore(obj)
if value != prop.default_value() or prop.required:
value = self.encode_value(prop, value)
values.append(value)
fields.append('"%s"' % prop.name)
templs.append('%s')
qs = 'INSERT INTO "%s" (' % self.db_table
if len(id_calculated) == 0:
qs += '"id",'
qs += ','.join(fields)
qs += ") VALUES ("
if len(id_calculated) == 0:
qs += "'%s'," % obj.id
qs += ','.join(templs)
qs += ')'
if calculated:
qs += ' RETURNING '
calc_values = ['"%s"' % p.name for p in calculated]
qs += ','.join(calc_values)
qs += ';'
return qs, values
def _build_update_qs(self, obj, calculated):
fields = []
values = []
for prop in obj.properties(hidden=False):
if prop not in calculated:
value = prop.get_value_for_datastore(obj)
if value != prop.default_value() or prop.required:
value = self.encode_value(prop, value)
values.append(value)
field = '"%s"=' % prop.name
field += '%s'
fields.append(field)
qs = 'UPDATE "%s" SET ' % self.db_table
qs += ','.join(fields)
qs += """ WHERE "id" = '%s'""" % obj.id
if calculated:
qs += ' RETURNING '
calc_values = ['"%s"' % p.name for p in calculated]
qs += ','.join(calc_values)
qs += ';'
return qs, values
def _get_sql(self, mapping=None):
print '_get_sql'
sql = None
if self.sql_dir:
path = os.path.join(self.sql_dir, self.cls.__name__ + '.sql')
print path
if os.path.isfile(path):
fp = open(path)
sql = fp.read()
fp.close()
t = string.Template(sql)
sql = t.safe_substitute(mapping)
return sql
def start_transaction(self):
print 'start_transaction'
self.in_transaction = True
def end_transaction(self):
print 'end_transaction'
self.in_transaction = False
self.commit()
def commit(self):
if not self.in_transaction:
print '!!commit on %s' % self.db_table
try:
self.connection.commit()
except psycopg2.ProgrammingError, err:
self.connection.rollback()
raise err
def rollback(self):
print '!!rollback on %s' % self.db_table
self.connection.rollback()
def delete_table(self):
self.cursor.execute('DROP TABLE "%s";' % self.db_table)
self.commit()
def create_table(self, mapping=None):
self.cursor.execute(self._get_sql(mapping))
self.commit()
def encode_value(self, prop, value):
return self.converter.encode_prop(prop, value)
def decode_value(self, prop, value):
return self.converter.decode_prop(prop, value)
def execute_sql(self, query):
self.cursor.execute(query, None)
self.commit()
def query_sql(self, query, vars=None):
self.cursor.execute(query, vars)
return self.cursor.fetchall()
def lookup(self, cls, name, value):
values = []
qs = 'SELECT * FROM "%s" WHERE ' % self.db_table
found = False
for property in cls.properties(hidden=False):
if property.name == name:
found = True
value = self.encode_value(property, value)
values.append(value)
qs += "%s=" % name
qs += "%s"
if not found:
raise SDBPersistenceError('%s is not a valid field' % name)
qs += ';'
print qs
self.cursor.execute(qs, values)
if self.cursor.rowcount == 1:
row = self.cursor.fetchone()
return self._object_from_row(row, self.cursor.description)
elif self.cursor.rowcount == 0:
raise KeyError, 'Object not found'
else:
raise LookupError, 'Multiple Objects Found'
def query(self, cls, filters, limit=None, order_by=None):
parts = []
qs = 'SELECT * FROM "%s"' % self.db_table
if filters:
qs += ' WHERE '
properties = cls.properties(hidden=False)
for filter, value in filters:
name, op = filter.strip().split()
found = False
for property in properties:
if property.name == name:
found = True
value = self.encode_value(property, value)
parts.append(""""%s"%s'%s'""" % (name, op, value))
if not found:
raise SDBPersistenceError('%s is not a valid field' % name)
qs += ','.join(parts)
qs += ';'
print qs
cursor = self.connection.cursor()
cursor.execute(qs)
return self._object_lister(cursor)
def get_property(self, prop, obj, name):
qs = """SELECT "%s" FROM "%s" WHERE id='%s';""" % (name, self.db_table, obj.id)
print qs
self.cursor.execute(qs, None)
if self.cursor.rowcount == 1:
rs = self.cursor.fetchone()
for prop in obj.properties(hidden=False):
if prop.name == name:
v = self.decode_value(prop, rs[0])
return v
raise AttributeError, '%s not found' % name
def set_property(self, prop, obj, name, value):
pass
value = self.encode_value(prop, value)
qs = 'UPDATE "%s" SET ' % self.db_table
qs += "%s='%s'" % (name, self.encode_value(prop, value))
qs += " WHERE id='%s'" % obj.id
qs += ';'
print qs
self.cursor.execute(qs)
self.commit()
def get_object(self, cls, id):
qs = """SELECT * FROM "%s" WHERE id='%s';""" % (self.db_table, id)
self.cursor.execute(qs, None)
if self.cursor.rowcount == 1:
row = self.cursor.fetchone()
return self._object_from_row(row, self.cursor.description)
else:
raise SDBPersistenceError('%s object with id=%s does not exist' % (cls.__name__, id))
def get_object_from_id(self, id):
return self.get_object(self.cls, id)
def _find_calculated_props(self, obj):
return [p for p in obj.properties() if hasattr(p, 'calculated_type')]
def save_object(self, obj):
obj._auto_update = False
calculated = self._find_calculated_props(obj)
if not obj.id:
obj.id = str(uuid.uuid4())
qs, values = self._build_insert_qs(obj, calculated)
else:
qs, values = self._build_update_qs(obj, calculated)
print qs
self.cursor.execute(qs, values)
if calculated:
calc_values = self.cursor.fetchone()
print calculated
print calc_values
for i in range(0, len(calculated)):
prop = calculated[i]
prop._set_direct(obj, calc_values[i])
self.commit()
def delete_object(self, obj):
qs = """DELETE FROM "%s" WHERE id='%s';""" % (self.db_table, obj.id)
print qs
self.cursor.execute(qs)
self.commit()
| Python |
# Copyright (c) 2006,2007,2008 Mitch Garnaat http://garnaat.org/
# Copyright (c) 2010 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 boto
import re
from boto.utils import find_class
import uuid
from boto.sdb.db.key import Key
from boto.sdb.db.model import Model
from boto.sdb.db.blob import Blob
from boto.sdb.db.property import ListProperty, MapProperty
from datetime import datetime, date
from boto.exception import SDBPersistenceError
ISO8601 = '%Y-%m-%dT%H:%M:%SZ'
class SDBConverter:
"""
Responsible for converting base Python types to format compatible with underlying
database. For SimpleDB, that means everything needs to be converted to a string
when stored in SimpleDB and from a string when retrieved.
To convert a value, pass it to the encode or decode method. The encode method
will take a Python native value and convert to DB format. The decode method will
take a DB format value and convert it to Python native format. To find the appropriate
method to call, the generic encode/decode methods will look for the type-specific
method by searching for a method called "encode_<type name>" or "decode_<type name>".
"""
def __init__(self, manager):
self.manager = manager
self.type_map = { bool : (self.encode_bool, self.decode_bool),
int : (self.encode_int, self.decode_int),
long : (self.encode_long, self.decode_long),
float : (self.encode_float, self.decode_float),
Model : (self.encode_reference, self.decode_reference),
Key : (self.encode_reference, self.decode_reference),
datetime : (self.encode_datetime, self.decode_datetime),
date : (self.encode_date, self.decode_date),
Blob: (self.encode_blob, self.decode_blob),
}
def encode(self, item_type, value):
try:
if Model in item_type.mro():
item_type = Model
except:
pass
if item_type in self.type_map:
encode = self.type_map[item_type][0]
return encode(value)
return value
def decode(self, item_type, value):
if item_type in self.type_map:
decode = self.type_map[item_type][1]
return decode(value)
return value
def encode_list(self, prop, value):
if value in (None, []):
return []
if not isinstance(value, list):
# This is a little trick to avoid encoding when it's just a single value,
# since that most likely means it's from a query
item_type = getattr(prop, "item_type")
return self.encode(item_type, value)
# Just enumerate(value) won't work here because
# we need to add in some zero padding
# We support lists up to 1,000 attributes, since
# SDB technically only supports 1024 attributes anyway
values = {}
for k,v in enumerate(value):
values["%03d" % k] = v
return self.encode_map(prop, values)
def encode_map(self, prop, value):
if value == None:
return None
if not isinstance(value, dict):
raise ValueError, 'Expected a dict value, got %s' % type(value)
new_value = []
for key in value:
item_type = getattr(prop, "item_type")
if Model in item_type.mro():
item_type = Model
encoded_value = self.encode(item_type, value[key])
if encoded_value != None:
new_value.append('%s:%s' % (key, encoded_value))
return new_value
def encode_prop(self, prop, value):
if isinstance(prop, ListProperty):
return self.encode_list(prop, value)
elif isinstance(prop, MapProperty):
return self.encode_map(prop, value)
else:
return self.encode(prop.data_type, value)
def decode_list(self, prop, value):
if not isinstance(value, list):
value = [value]
if hasattr(prop, 'item_type'):
item_type = getattr(prop, "item_type")
dec_val = {}
for val in value:
if val != None:
k,v = self.decode_map_element(item_type, val)
try:
k = int(k)
except:
k = v
dec_val[k] = v
value = dec_val.values()
return value
def decode_map(self, prop, value):
if not isinstance(value, list):
value = [value]
ret_value = {}
item_type = getattr(prop, "item_type")
for val in value:
k,v = self.decode_map_element(item_type, val)
ret_value[k] = v
return ret_value
def decode_map_element(self, item_type, value):
"""Decode a single element for a map"""
key = value
if ":" in value:
key, value = value.split(':',1)
if Model in item_type.mro():
value = item_type(id=value)
else:
value = self.decode(item_type, value)
return (key, value)
def decode_prop(self, prop, value):
if isinstance(prop, ListProperty):
return self.decode_list(prop, value)
elif isinstance(prop, MapProperty):
return self.decode_map(prop, value)
else:
return self.decode(prop.data_type, value)
def encode_int(self, value):
value = int(value)
value += 2147483648
return '%010d' % value
def decode_int(self, value):
try:
value = int(value)
except:
boto.log.error("Error, %s is not an integer" % value)
value = 0
value = int(value)
value -= 2147483648
return int(value)
def encode_long(self, value):
value = long(value)
value += 9223372036854775808
return '%020d' % value
def decode_long(self, value):
value = long(value)
value -= 9223372036854775808
return value
def encode_bool(self, value):
if value == True or str(value).lower() in ("true", "yes"):
return 'true'
else:
return 'false'
def decode_bool(self, value):
if value.lower() == 'true':
return True
else:
return False
def encode_float(self, value):
"""
See http://tools.ietf.org/html/draft-wood-ldapext-float-00.
"""
s = '%e' % value
l = s.split('e')
mantissa = l[0].ljust(18, '0')
exponent = l[1]
if value == 0.0:
case = '3'
exponent = '000'
elif mantissa[0] != '-' and exponent[0] == '+':
case = '5'
exponent = exponent[1:].rjust(3, '0')
elif mantissa[0] != '-' and exponent[0] == '-':
case = '4'
exponent = 999 + int(exponent)
exponent = '%03d' % exponent
elif mantissa[0] == '-' and exponent[0] == '-':
case = '2'
mantissa = '%f' % (10 + float(mantissa))
mantissa = mantissa.ljust(18, '0')
exponent = exponent[1:].rjust(3, '0')
else:
case = '1'
mantissa = '%f' % (10 + float(mantissa))
mantissa = mantissa.ljust(18, '0')
exponent = 999 - int(exponent)
exponent = '%03d' % exponent
return '%s %s %s' % (case, exponent, mantissa)
def decode_float(self, value):
case = value[0]
exponent = value[2:5]
mantissa = value[6:]
if case == '3':
return 0.0
elif case == '5':
pass
elif case == '4':
exponent = '%03d' % (int(exponent) - 999)
elif case == '2':
mantissa = '%f' % (float(mantissa) - 10)
exponent = '-' + exponent
else:
mantissa = '%f' % (float(mantissa) - 10)
exponent = '%03d' % abs((int(exponent) - 999))
return float(mantissa + 'e' + exponent)
def encode_datetime(self, value):
if isinstance(value, str) or isinstance(value, unicode):
return value
return value.strftime(ISO8601)
def decode_datetime(self, value):
try:
return datetime.strptime(value, ISO8601)
except:
return None
def encode_date(self, value):
if isinstance(value, str) or isinstance(value, unicode):
return value
return value.isoformat()
def decode_date(self, value):
try:
value = value.split("-")
return date(int(value[0]), int(value[1]), int(value[2]))
except:
return None
def encode_reference(self, value):
if value in (None, 'None', '', ' '):
return None
if isinstance(value, str) or isinstance(value, unicode):
return value
else:
return value.id
def decode_reference(self, value):
if not value or value == "None":
return None
return value
def encode_blob(self, value):
if not value:
return None
if isinstance(value, str):
return value
if not value.id:
bucket = self.manager.get_blob_bucket()
key = bucket.new_key(str(uuid.uuid4()))
value.id = "s3://%s/%s" % (key.bucket.name, key.name)
else:
match = re.match("^s3:\/\/([^\/]*)\/(.*)$", value.id)
if match:
s3 = self.manager.get_s3_connection()
bucket = s3.get_bucket(match.group(1), validate=False)
key = bucket.get_key(match.group(2))
else:
raise SDBPersistenceError("Invalid Blob ID: %s" % value.id)
if value.value != None:
key.set_contents_from_string(value.value)
return value.id
def decode_blob(self, value):
if not value:
return None
match = re.match("^s3:\/\/([^\/]*)\/(.*)$", value)
if match:
s3 = self.manager.get_s3_connection()
bucket = s3.get_bucket(match.group(1), validate=False)
key = bucket.get_key(match.group(2))
else:
return None
if key:
return Blob(file=key, id="s3://%s/%s" % (key.bucket.name, key.name))
else:
return None
class SDBManager(object):
def __init__(self, cls, db_name, db_user, db_passwd,
db_host, db_port, db_table, ddl_dir, enable_ssl, consistent=None):
self.cls = cls
self.db_name = db_name
self.db_user = db_user
self.db_passwd = db_passwd
self.db_host = db_host
self.db_port = db_port
self.db_table = db_table
self.ddl_dir = ddl_dir
self.enable_ssl = enable_ssl
self.s3 = None
self.bucket = None
self.converter = SDBConverter(self)
self._sdb = None
self._domain = None
if consistent == None and hasattr(cls, "__consistent"):
consistent = cls.__consistent__
self.consistent = consistent
@property
def sdb(self):
if self._sdb is None:
self._connect()
return self._sdb
@property
def domain(self):
if self._domain is None:
self._connect()
return self._domain
def _connect(self):
self._sdb = boto.connect_sdb(aws_access_key_id=self.db_user,
aws_secret_access_key=self.db_passwd,
is_secure=self.enable_ssl)
# This assumes that the domain has already been created
# It's much more efficient to do it this way rather than
# having this make a roundtrip each time to validate.
# The downside is that if the domain doesn't exist, it breaks
self._domain = self._sdb.lookup(self.db_name, validate=False)
if not self._domain:
self._domain = self._sdb.create_domain(self.db_name)
def _object_lister(self, cls, query_lister):
for item in query_lister:
obj = self.get_object(cls, item.name, item)
if obj:
yield obj
def encode_value(self, prop, value):
if value == None:
return None
if not prop:
return str(value)
return self.converter.encode_prop(prop, value)
def decode_value(self, prop, value):
return self.converter.decode_prop(prop, value)
def get_s3_connection(self):
if not self.s3:
self.s3 = boto.connect_s3(self.db_user, self.db_passwd)
return self.s3
def get_blob_bucket(self, bucket_name=None):
s3 = self.get_s3_connection()
bucket_name = "%s-%s" % (s3.aws_access_key_id, self.domain.name)
bucket_name = bucket_name.lower()
try:
self.bucket = s3.get_bucket(bucket_name)
except:
self.bucket = s3.create_bucket(bucket_name)
return self.bucket
def load_object(self, obj):
if not obj._loaded:
a = self.domain.get_attributes(obj.id,consistent_read=self.consistent)
if a.has_key('__type__'):
for prop in obj.properties(hidden=False):
if a.has_key(prop.name):
value = self.decode_value(prop, a[prop.name])
value = prop.make_value_from_datastore(value)
try:
setattr(obj, prop.name, value)
except Exception, e:
boto.log.exception(e)
obj._loaded = True
def get_object(self, cls, id, a=None):
obj = None
if not a:
a = self.domain.get_attributes(id,consistent_read=self.consistent)
if a.has_key('__type__'):
if not cls or a['__type__'] != cls.__name__:
cls = find_class(a['__module__'], a['__type__'])
if cls:
params = {}
for prop in cls.properties(hidden=False):
if a.has_key(prop.name):
value = self.decode_value(prop, a[prop.name])
value = prop.make_value_from_datastore(value)
params[prop.name] = value
obj = cls(id, **params)
obj._loaded = True
else:
s = '(%s) class %s.%s not found' % (id, a['__module__'], a['__type__'])
boto.log.info('sdbmanager: %s' % s)
return obj
def get_object_from_id(self, id):
return self.get_object(None, id)
def query(self, query):
query_str = "select * from `%s` %s" % (self.domain.name, self._build_filter_part(query.model_class, query.filters, query.sort_by))
if query.limit:
query_str += " limit %s" % query.limit
rs = self.domain.select(query_str, max_items=query.limit, next_token = query.next_token)
query.rs = rs
return self._object_lister(query.model_class, rs)
def count(self, cls, filters, quick=True):
"""
Get the number of results that would
be returned in this query
"""
query = "select count(*) from `%s` %s" % (self.domain.name, self._build_filter_part(cls, filters))
count = 0
for row in self.domain.select(query):
count += int(row['Count'])
if quick:
return count
return count
def _build_filter(self, property, name, op, val):
if val == None:
if op in ('is','='):
return "`%(name)s` is null" % {"name": name}
elif op in ('is not', '!='):
return "`%s` is not null" % name
else:
val = ""
if property.__class__ == ListProperty:
if op in ("is", "="):
op = "like"
elif op in ("!=", "not"):
op = "not like"
if not(op == "like" and val.startswith("%")):
val = "%%:%s" % val
return "`%s` %s '%s'" % (name, op, val.replace("'", "''"))
def _build_filter_part(self, cls, filters, order_by=None):
"""
Build the filter part
"""
import types
query_parts = []
order_by_filtered = False
if order_by:
if order_by[0] == "-":
order_by_method = "desc";
order_by = order_by[1:]
else:
order_by_method = "asc";
for filter in filters:
filter_parts = []
filter_props = filter[0]
if type(filter_props) != list:
filter_props = [filter_props]
for filter_prop in filter_props:
(name, op) = filter_prop.strip().split(" ", 1)
value = filter[1]
property = cls.find_property(name)
if name == order_by:
order_by_filtered = True
if types.TypeType(value) == types.ListType:
filter_parts_sub = []
for val in value:
val = self.encode_value(property, val)
if isinstance(val, list):
for v in val:
filter_parts_sub.append(self._build_filter(property, name, op, v))
else:
filter_parts_sub.append(self._build_filter(property, name, op, val))
filter_parts.append("(%s)" % (" or ".join(filter_parts_sub)))
else:
val = self.encode_value(property, value)
if isinstance(val, list):
for v in val:
filter_parts.append(self._build_filter(property, name, op, v))
else:
filter_parts.append(self._build_filter(property, name, op, val))
query_parts.append("(%s)" % (" or ".join(filter_parts)))
type_query = "(`__type__` = '%s'" % cls.__name__
for subclass in self._get_all_decendents(cls).keys():
type_query += " or `__type__` = '%s'" % subclass
type_query +=")"
query_parts.append(type_query)
order_by_query = ""
if order_by:
if not order_by_filtered:
query_parts.append("`%s` like '%%'" % order_by)
order_by_query = " order by `%s` %s" % (order_by, order_by_method)
if len(query_parts) > 0:
return "where %s %s" % (" and ".join(query_parts), order_by_query)
else:
return ""
def _get_all_decendents(self, cls):
"""Get all decendents for a given class"""
decendents = {}
for sc in cls.__sub_classes__:
decendents[sc.__name__] = sc
decendents.update(self._get_all_decendents(sc))
return decendents
def query_gql(self, query_string, *args, **kwds):
raise NotImplementedError, "GQL queries not supported in SimpleDB"
def save_object(self, obj):
if not obj.id:
obj.id = str(uuid.uuid4())
attrs = {'__type__' : obj.__class__.__name__,
'__module__' : obj.__class__.__module__,
'__lineage__' : obj.get_lineage()}
del_attrs = []
for property in obj.properties(hidden=False):
value = property.get_value_for_datastore(obj)
if value is not None:
value = self.encode_value(property, value)
if value == []:
value = None
if value == None:
del_attrs.append(property.name)
continue
attrs[property.name] = value
if property.unique:
try:
args = {property.name: value}
obj2 = obj.find(**args).next()
if obj2.id != obj.id:
raise SDBPersistenceError("Error: %s must be unique!" % property.name)
except(StopIteration):
pass
self.domain.put_attributes(obj.id, attrs, replace=True)
if len(del_attrs) > 0:
self.domain.delete_attributes(obj.id, del_attrs)
return obj
def delete_object(self, obj):
self.domain.delete_attributes(obj.id)
def set_property(self, prop, obj, name, value):
value = prop.get_value_for_datastore(obj)
value = self.encode_value(prop, value)
if prop.unique:
try:
args = {prop.name: value}
obj2 = obj.find(**args).next()
if obj2.id != obj.id:
raise SDBPersistenceError("Error: %s must be unique!" % prop.name)
except(StopIteration):
pass
self.domain.put_attributes(obj.id, {name : value}, replace=True)
def get_property(self, prop, obj, name):
a = self.domain.get_attributes(obj.id,consistent_read=self.consistent)
# try to get the attribute value from SDB
if name in a:
value = self.decode_value(prop, a[name])
value = prop.make_value_from_datastore(value)
setattr(obj, prop.name, value)
return value
raise AttributeError, '%s not found' % name
def set_key_value(self, obj, name, value):
self.domain.put_attributes(obj.id, {name : value}, replace=True)
def delete_key_value(self, obj, name):
self.domain.delete_attributes(obj.id, name)
def get_key_value(self, obj, name):
a = self.domain.get_attributes(obj.id, name,consistent_read=self.consistent)
if a.has_key(name):
return a[name]
else:
return None
def get_raw_item(self, obj):
return self.domain.get_item(obj.id)
| 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.
import boto
from boto.utils import find_class, Password
from boto.sdb.db.key import Key
from boto.sdb.db.model import Model
from datetime import datetime
from xml.dom.minidom import getDOMImplementation, parse, parseString, Node
ISO8601 = '%Y-%m-%dT%H:%M:%SZ'
class XMLConverter:
"""
Responsible for converting base Python types to format compatible with underlying
database. For SimpleDB, that means everything needs to be converted to a string
when stored in SimpleDB and from a string when retrieved.
To convert a value, pass it to the encode or decode method. The encode method
will take a Python native value and convert to DB format. The decode method will
take a DB format value and convert it to Python native format. To find the appropriate
method to call, the generic encode/decode methods will look for the type-specific
method by searching for a method called "encode_<type name>" or "decode_<type name>".
"""
def __init__(self, manager):
self.manager = manager
self.type_map = { bool : (self.encode_bool, self.decode_bool),
int : (self.encode_int, self.decode_int),
long : (self.encode_long, self.decode_long),
Model : (self.encode_reference, self.decode_reference),
Key : (self.encode_reference, self.decode_reference),
Password : (self.encode_password, self.decode_password),
datetime : (self.encode_datetime, self.decode_datetime)}
def get_text_value(self, parent_node):
value = ''
for node in parent_node.childNodes:
if node.nodeType == node.TEXT_NODE:
value += node.data
return value
def encode(self, item_type, value):
if item_type in self.type_map:
encode = self.type_map[item_type][0]
return encode(value)
return value
def decode(self, item_type, value):
if item_type in self.type_map:
decode = self.type_map[item_type][1]
return decode(value)
else:
value = self.get_text_value(value)
return value
def encode_prop(self, prop, value):
if isinstance(value, list):
if hasattr(prop, 'item_type'):
new_value = []
for v in value:
item_type = getattr(prop, "item_type")
if Model in item_type.mro():
item_type = Model
new_value.append(self.encode(item_type, v))
return new_value
else:
return value
else:
return self.encode(prop.data_type, value)
def decode_prop(self, prop, value):
if prop.data_type == list:
if hasattr(prop, 'item_type'):
item_type = getattr(prop, "item_type")
if Model in item_type.mro():
item_type = Model
values = []
for item_node in value.getElementsByTagName('item'):
value = self.decode(item_type, item_node)
values.append(value)
return values
else:
return self.get_text_value(value)
else:
return self.decode(prop.data_type, value)
def encode_int(self, value):
value = int(value)
return '%d' % value
def decode_int(self, value):
value = self.get_text_value(value)
if value:
value = int(value)
else:
value = None
return value
def encode_long(self, value):
value = long(value)
return '%d' % value
def decode_long(self, value):
value = self.get_text_value(value)
return long(value)
def encode_bool(self, value):
if value == True:
return 'true'
else:
return 'false'
def decode_bool(self, value):
value = self.get_text_value(value)
if value.lower() == 'true':
return True
else:
return False
def encode_datetime(self, value):
return value.strftime(ISO8601)
def decode_datetime(self, value):
value = self.get_text_value(value)
try:
return datetime.strptime(value, ISO8601)
except:
return None
def encode_reference(self, value):
if isinstance(value, str) or isinstance(value, unicode):
return value
if value == None:
return ''
else:
val_node = self.manager.doc.createElement("object")
val_node.setAttribute('id', value.id)
val_node.setAttribute('class', '%s.%s' % (value.__class__.__module__, value.__class__.__name__))
return val_node
def decode_reference(self, value):
if not value:
return None
try:
value = value.childNodes[0]
class_name = value.getAttribute("class")
id = value.getAttribute("id")
cls = find_class(class_name)
return cls.get_by_ids(id)
except:
return None
def encode_password(self, value):
if value and len(value) > 0:
return str(value)
else:
return None
def decode_password(self, value):
value = self.get_text_value(value)
return Password(value)
class XMLManager(object):
def __init__(self, cls, db_name, db_user, db_passwd,
db_host, db_port, db_table, ddl_dir, enable_ssl):
self.cls = cls
if not db_name:
db_name = cls.__name__.lower()
self.db_name = db_name
self.db_user = db_user
self.db_passwd = db_passwd
self.db_host = db_host
self.db_port = db_port
self.db_table = db_table
self.ddl_dir = ddl_dir
self.s3 = None
self.converter = XMLConverter(self)
self.impl = getDOMImplementation()
self.doc = self.impl.createDocument(None, 'objects', None)
self.connection = None
self.enable_ssl = enable_ssl
self.auth_header = None
if self.db_user:
import base64
base64string = base64.encodestring('%s:%s' % (self.db_user, self.db_passwd))[:-1]
authheader = "Basic %s" % base64string
self.auth_header = authheader
def _connect(self):
if self.db_host:
if self.enable_ssl:
from httplib import HTTPSConnection as Connection
else:
from httplib import HTTPConnection as Connection
self.connection = Connection(self.db_host, self.db_port)
def _make_request(self, method, url, post_data=None, body=None):
"""
Make a request on this connection
"""
if not self.connection:
self._connect()
try:
self.connection.close()
except:
pass
self.connection.connect()
headers = {}
if self.auth_header:
headers["Authorization"] = self.auth_header
self.connection.request(method, url, body, headers)
resp = self.connection.getresponse()
return resp
def new_doc(self):
return self.impl.createDocument(None, 'objects', None)
def _object_lister(self, cls, doc):
for obj_node in doc.getElementsByTagName('object'):
if not cls:
class_name = obj_node.getAttribute('class')
cls = find_class(class_name)
id = obj_node.getAttribute('id')
obj = cls(id)
for prop_node in obj_node.getElementsByTagName('property'):
prop_name = prop_node.getAttribute('name')
prop = obj.find_property(prop_name)
if prop:
if hasattr(prop, 'item_type'):
value = self.get_list(prop_node, prop.item_type)
else:
value = self.decode_value(prop, prop_node)
value = prop.make_value_from_datastore(value)
setattr(obj, prop.name, value)
yield obj
def reset(self):
self._connect()
def get_doc(self):
return self.doc
def encode_value(self, prop, value):
return self.converter.encode_prop(prop, value)
def decode_value(self, prop, value):
return self.converter.decode_prop(prop, value)
def get_s3_connection(self):
if not self.s3:
self.s3 = boto.connect_s3(self.aws_access_key_id, self.aws_secret_access_key)
return self.s3
def get_list(self, prop_node, item_type):
values = []
try:
items_node = prop_node.getElementsByTagName('items')[0]
except:
return []
for item_node in items_node.getElementsByTagName('item'):
value = self.converter.decode(item_type, item_node)
values.append(value)
return values
def get_object_from_doc(self, cls, id, doc):
obj_node = doc.getElementsByTagName('object')[0]
if not cls:
class_name = obj_node.getAttribute('class')
cls = find_class(class_name)
if not id:
id = obj_node.getAttribute('id')
obj = cls(id)
for prop_node in obj_node.getElementsByTagName('property'):
prop_name = prop_node.getAttribute('name')
prop = obj.find_property(prop_name)
value = self.decode_value(prop, prop_node)
value = prop.make_value_from_datastore(value)
if value != None:
try:
setattr(obj, prop.name, value)
except:
pass
return obj
def get_props_from_doc(self, cls, id, doc):
"""
Pull out the properties from this document
Returns the class, the properties in a hash, and the id if provided as a tuple
:return: (cls, props, id)
"""
obj_node = doc.getElementsByTagName('object')[0]
if not cls:
class_name = obj_node.getAttribute('class')
cls = find_class(class_name)
if not id:
id = obj_node.getAttribute('id')
props = {}
for prop_node in obj_node.getElementsByTagName('property'):
prop_name = prop_node.getAttribute('name')
prop = cls.find_property(prop_name)
value = self.decode_value(prop, prop_node)
value = prop.make_value_from_datastore(value)
if value != None:
props[prop.name] = value
return (cls, props, id)
def get_object(self, cls, id):
if not self.connection:
self._connect()
if not self.connection:
raise NotImplementedError("Can't query without a database connection")
url = "/%s/%s" % (self.db_name, id)
resp = self._make_request('GET', url)
if resp.status == 200:
doc = parse(resp)
else:
raise Exception("Error: %s" % resp.status)
return self.get_object_from_doc(cls, id, doc)
def query(self, cls, filters, limit=None, order_by=None):
if not self.connection:
self._connect()
if not self.connection:
raise NotImplementedError("Can't query without a database connection")
from urllib import urlencode
query = str(self._build_query(cls, filters, limit, order_by))
if query:
url = "/%s?%s" % (self.db_name, urlencode({"query": query}))
else:
url = "/%s" % self.db_name
resp = self._make_request('GET', url)
if resp.status == 200:
doc = parse(resp)
else:
raise Exception("Error: %s" % resp.status)
return self._object_lister(cls, doc)
def _build_query(self, cls, filters, limit, order_by):
import types
if len(filters) > 4:
raise Exception('Too many filters, max is 4')
parts = []
properties = cls.properties(hidden=False)
for filter, value in filters:
name, op = filter.strip().split()
found = False
for property in properties:
if property.name == name:
found = True
if types.TypeType(value) == types.ListType:
filter_parts = []
for val in value:
val = self.encode_value(property, val)
filter_parts.append("'%s' %s '%s'" % (name, op, val))
parts.append("[%s]" % " OR ".join(filter_parts))
else:
value = self.encode_value(property, value)
parts.append("['%s' %s '%s']" % (name, op, value))
if not found:
raise Exception('%s is not a valid field' % name)
if order_by:
if order_by.startswith("-"):
key = order_by[1:]
type = "desc"
else:
key = order_by
type = "asc"
parts.append("['%s' starts-with ''] sort '%s' %s" % (key, key, type))
return ' intersection '.join(parts)
def query_gql(self, query_string, *args, **kwds):
raise NotImplementedError, "GQL queries not supported in XML"
def save_list(self, doc, items, prop_node):
items_node = doc.createElement('items')
prop_node.appendChild(items_node)
for item in items:
item_node = doc.createElement('item')
items_node.appendChild(item_node)
if isinstance(item, Node):
item_node.appendChild(item)
else:
text_node = doc.createTextNode(item)
item_node.appendChild(text_node)
def save_object(self, obj):
"""
Marshal the object and do a PUT
"""
doc = self.marshal_object(obj)
if obj.id:
url = "/%s/%s" % (self.db_name, obj.id)
else:
url = "/%s" % (self.db_name)
resp = self._make_request("PUT", url, body=doc.toxml())
new_obj = self.get_object_from_doc(obj.__class__, None, parse(resp))
obj.id = new_obj.id
for prop in obj.properties():
try:
propname = prop.name
except AttributeError:
propname = None
if propname:
value = getattr(new_obj, prop.name)
if value:
setattr(obj, prop.name, value)
return obj
def marshal_object(self, obj, doc=None):
if not doc:
doc = self.new_doc()
if not doc:
doc = self.doc
obj_node = doc.createElement('object')
if obj.id:
obj_node.setAttribute('id', obj.id)
obj_node.setAttribute('class', '%s.%s' % (obj.__class__.__module__,
obj.__class__.__name__))
root = doc.documentElement
root.appendChild(obj_node)
for property in obj.properties(hidden=False):
prop_node = doc.createElement('property')
prop_node.setAttribute('name', property.name)
prop_node.setAttribute('type', property.type_name)
value = property.get_value_for_datastore(obj)
if value is not None:
value = self.encode_value(property, value)
if isinstance(value, list):
self.save_list(doc, value, prop_node)
elif isinstance(value, Node):
prop_node.appendChild(value)
else:
text_node = doc.createTextNode(unicode(value).encode("ascii", "ignore"))
prop_node.appendChild(text_node)
obj_node.appendChild(prop_node)
return doc
def unmarshal_object(self, fp, cls=None, id=None):
if isinstance(fp, str) or isinstance(fp, unicode):
doc = parseString(fp)
else:
doc = parse(fp)
return self.get_object_from_doc(cls, id, doc)
def unmarshal_props(self, fp, cls=None, id=None):
"""
Same as unmarshalling an object, except it returns
from "get_props_from_doc"
"""
if isinstance(fp, str) or isinstance(fp, unicode):
doc = parseString(fp)
else:
doc = parse(fp)
return self.get_props_from_doc(cls, id, doc)
def delete_object(self, obj):
url = "/%s/%s" % (self.db_name, obj.id)
return self._make_request("DELETE", url)
def set_key_value(self, obj, name, value):
self.domain.put_attributes(obj.id, {name : value}, replace=True)
def delete_key_value(self, obj, name):
self.domain.delete_attributes(obj.id, name)
def get_key_value(self, obj, name):
a = self.domain.get_attributes(obj.id, name)
if a.has_key(name):
return a[name]
else:
return None
def get_raw_item(self, obj):
return self.domain.get_item(obj.id)
def set_property(self, prop, obj, name, value):
pass
def get_property(self, prop, obj, name):
pass
def load_object(self, obj):
if not obj._loaded:
obj = obj.get_by_id(obj.id)
obj._loaded = True
return obj
| Python |
# Copyright (c) 2006,2007,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.
import boto
def get_manager(cls):
"""
Returns the appropriate Manager class for a given Model class. It does this by
looking in the boto config for a section like this::
[DB]
db_type = SimpleDB
db_user = <aws access key id>
db_passwd = <aws secret access key>
db_name = my_domain
[DB_TestBasic]
db_type = SimpleDB
db_user = <another aws access key id>
db_passwd = <another aws secret access key>
db_name = basic_domain
db_port = 1111
The values in the DB section are "generic values" that will be used if nothing more
specific is found. You can also create a section for a specific Model class that
gives the db info for that class. In the example above, TestBasic is a Model subclass.
"""
db_user = boto.config.get('DB', 'db_user', None)
db_passwd = boto.config.get('DB', 'db_passwd', None)
db_type = boto.config.get('DB', 'db_type', 'SimpleDB')
db_name = boto.config.get('DB', 'db_name', None)
db_table = boto.config.get('DB', 'db_table', None)
db_host = boto.config.get('DB', 'db_host', "sdb.amazonaws.com")
db_port = boto.config.getint('DB', 'db_port', 443)
enable_ssl = boto.config.getbool('DB', 'enable_ssl', True)
sql_dir = boto.config.get('DB', 'sql_dir', None)
debug = boto.config.getint('DB', 'debug', 0)
# first see if there is a fully qualified section name in the Boto config file
module_name = cls.__module__.replace('.', '_')
db_section = 'DB_' + module_name + '_' + cls.__name__
if not boto.config.has_section(db_section):
db_section = 'DB_' + cls.__name__
if boto.config.has_section(db_section):
db_user = boto.config.get(db_section, 'db_user', db_user)
db_passwd = boto.config.get(db_section, 'db_passwd', db_passwd)
db_type = boto.config.get(db_section, 'db_type', db_type)
db_name = boto.config.get(db_section, 'db_name', db_name)
db_table = boto.config.get(db_section, 'db_table', db_table)
db_host = boto.config.get(db_section, 'db_host', db_host)
db_port = boto.config.getint(db_section, 'db_port', db_port)
enable_ssl = boto.config.getint(db_section, 'enable_ssl', enable_ssl)
debug = boto.config.getint(db_section, 'debug', debug)
elif hasattr(cls.__bases__[0], "_manager"):
return cls.__bases__[0]._manager
if db_type == 'SimpleDB':
from sdbmanager import SDBManager
return SDBManager(cls, db_name, db_user, db_passwd,
db_host, db_port, db_table, sql_dir, enable_ssl)
elif db_type == 'PostgreSQL':
from pgmanager import PGManager
if db_table:
return PGManager(cls, db_name, db_user, db_passwd,
db_host, db_port, db_table, sql_dir, enable_ssl)
else:
return None
elif db_type == 'XML':
from xmlmanager import XMLManager
return XMLManager(cls, db_name, db_user, db_passwd,
db_host, db_port, db_table, sql_dir, enable_ssl)
else:
raise ValueError, 'Unknown db_type: %s' % db_type
| Python |
# Copyright (c) 2006,2007,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.
| Python |
# Copyright (c) 2006,2007,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 Blob(object):
"""Blob object"""
def __init__(self, value=None, file=None, id=None):
self._file = file
self.id = id
self.value = value
@property
def file(self):
from StringIO import StringIO
if self._file:
f = self._file
else:
f = StringIO(self.value)
return f
def __str__(self):
if hasattr(self.file, "get_contents_as_string"):
value = self.file.get_contents_as_string()
else:
value = self.file.getvalue()
try:
return str(value)
except:
return unicode(value)
def read(self):
return self.file.read()
def readline(self):
return self.file.readline()
def next(self):
return self.file.next()
def __iter__(self):
return iter(self.file)
@property
def size(self):
if self._file:
return self._file.size
elif self.value:
return len(self.value)
else:
return 0
| Python |
# Copyright (c) 2010 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.
from boto.exception import SDBResponseError
class SequenceGenerator(object):
"""Generic Sequence Generator object, this takes a single
string as the "sequence" and uses that to figure out
what the next value in a string is. For example
if you give "ABC" and pass in "A" it will give you "B",
and if you give it "C" it will give you "AA".
If you set "rollover" to True in the above example, passing
in "C" would give you "A" again.
The Sequence string can be a string or any iterable
that has the "index" function and is indexable.
"""
__name__ = "SequenceGenerator"
def __init__(self, sequence_string, rollover=False):
"""Create a new SequenceGenerator using the sequence_string
as how to generate the next item.
:param sequence_string: The string or list that explains
how to generate the next item in the sequence
:type sequence_string: str,iterable
:param rollover: Rollover instead of incrementing when
we hit the end of the sequence
:type rollover: bool
"""
self.sequence_string = sequence_string
self.sequence_length = len(sequence_string[0])
self.rollover = rollover
self.last_item = sequence_string[-1]
self.__name__ = "%s('%s')" % (self.__class__.__name__, sequence_string)
def __call__(self, val, last=None):
"""Get the next value in the sequence"""
# If they pass us in a string that's not at least
# the lenght of our sequence, then return the
# first element in our sequence
if val == None or len(val) < self.sequence_length:
return self.sequence_string[0]
last_value = val[-self.sequence_length:]
if (not self.rollover) and (last_value == self.last_item):
val = "%s%s" % (self(val[:-self.sequence_length]), self._inc(last_value))
else:
val = "%s%s" % (val[:-self.sequence_length], self._inc(last_value))
return val
def _inc(self, val):
"""Increment a single value"""
assert(len(val) == self.sequence_length)
return self.sequence_string[(self.sequence_string.index(val)+1) % len(self.sequence_string)]
#
# Simple Sequence Functions
#
def increment_by_one(cv=None, lv=None):
if cv == None:
return 0
return cv + 1
def double(cv=None, lv=None):
if cv == None:
return 1
return cv * 2
def fib(cv=1, lv=0):
"""The fibonacci sequence, this incrementer uses the
last value"""
if cv == None:
cv = 1
if lv == None:
lv = 0
return cv + lv
increment_string = SequenceGenerator("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
class Sequence(object):
"""A simple Sequence using the new SDB "Consistent" features
Based largly off of the "Counter" example from mitch garnaat:
http://bitbucket.org/mitch/stupidbototricks/src/tip/counter.py"""
def __init__(self, id=None, domain_name=None, fnc=increment_by_one, init_val=None):
"""Create a new Sequence, using an optional function to
increment to the next number, by default we just increment by one.
Every parameter here is optional, if you don't specify any options
then you'll get a new SequenceGenerator with a random ID stored in the
default domain that increments by one and uses the default botoweb
environment
:param id: Optional ID (name) for this counter
:type id: str
:param domain_name: Optional domain name to use, by default we get this out of the
environment configuration
:type domain_name:str
:param fnc: Optional function to use for the incrementation, by default we just increment by one
There are several functions defined in this module.
Your function must accept "None" to get the initial value
:type fnc: function, str
:param init_val: Initial value, by default this is the first element in your sequence,
but you can pass in any value, even a string if you pass in a function that uses
strings instead of ints to increment
"""
self._db = None
self._value = None
self.last_value = None
self.domain_name = domain_name
self.id = id
if self.id == None:
import uuid
self.id = str(uuid.uuid4())
if init_val == None:
init_val = fnc(init_val)
self.val = init_val
self.item_type = type(fnc(None))
self.timestamp = None
# Allow us to pass in a full name to a function
if type(fnc) == str:
from boto.utils import find_class
fnc = find_class(fnc)
self.fnc = fnc
def set(self, val):
"""Set the value"""
import time
now = time.time()
expected_values = []
new_val = {}
new_val['timestamp'] = now
if self._value != None:
new_val['last_value'] = self._value
expected_values = ['current_value', str(self._value)]
new_val['current_value'] = val
try:
self.db.put_attributes(self.id, new_val, expected_values=expected_values)
self.timestamp = new_val['timestamp']
except SDBResponseError, e:
if e.status == 409:
raise ValueError, "Sequence out of sync"
else:
raise
def get(self):
"""Get the value"""
val = self.db.get_attributes(self.id, consistent_read=True)
if val and val.has_key('timestamp'):
self.timestamp = val['timestamp']
if val and val.has_key('current_value'):
self._value = self.item_type(val['current_value'])
if val.has_key("last_value") and val['last_value'] != None:
self.last_value = self.item_type(val['last_value'])
return self._value
val = property(get, set)
def __repr__(self):
return "%s('%s', '%s', '%s.%s', '%s')" % (
self.__class__.__name__,
self.id,
self.domain_name,
self.fnc.__module__, self.fnc.__name__,
self.val)
def _connect(self):
"""Connect to our domain"""
if not self._db:
if not self.domain_name:
import boto
sdb = boto.connect_sdb()
self.domain_name = boto.config.get("DB", "sequence_db", boto.config.get("DB", "db_name", "default"))
try:
self._db = sdb.get_domain(self.domain_name)
except SDBResponseError, e:
if e.status == 400:
self._db = sdb.create_domain(self.domain_name)
else:
raise
return self._db
db = property(_connect)
def next(self):
self.val = self.fnc(self.val, self.last_value)
return self.val
def delete(self):
"""Remove this sequence"""
self.db.delete_attributes(self.id)
def __del__(self):
self.delete()
| 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 SDB Domain
"""
from boto.sdb.queryresultset import SelectResultSet
class Domain:
def __init__(self, connection=None, name=None):
self.connection = connection
self.name = name
self._metadata = None
def __repr__(self):
return 'Domain:%s' % self.name
def __iter__(self):
return iter(self.select("SELECT * FROM `%s`" % self.name))
def startElement(self, name, attrs, connection):
return None
def endElement(self, name, value, connection):
if name == 'DomainName':
self.name = value
else:
setattr(self, name, value)
def get_metadata(self):
if not self._metadata:
self._metadata = self.connection.domain_metadata(self)
return self._metadata
def put_attributes(self, item_name, attributes,
replace=True, expected_values=None):
"""
Store attributes for a given item.
:type item_name: string
:param item_name: The name of the item whose attributes are being stored.
:type attribute_names: dict or dict-like object
:param attribute_names: The name/value pairs to store as attributes
:type expected_value: list
:param expected_value: If supplied, this is a list or tuple consisting
of a single attribute name and expected value.
The list can be of the form:
* ['name', 'value']
In which case the call will first verify
that the attribute "name" of this item has
a value of "value". If it does, the delete
will proceed, otherwise a ConditionalCheckFailed
error will be returned.
The list can also be of the form:
* ['name', True|False]
which will simply check for the existence (True)
or non-existencve (False) of the attribute.
:type replace: bool
:param replace: Whether the attribute values passed in will replace
existing values or will be added as addition values.
Defaults to True.
:rtype: bool
:return: True if successful
"""
return self.connection.put_attributes(self, item_name, attributes,
replace, expected_values)
def batch_put_attributes(self, items, replace=True):
"""
Store attributes for multiple items.
:type items: dict or dict-like object
:param items: A dictionary-like object. The keys of the dictionary are
the item names and the values are themselves dictionaries
of attribute names/values, exactly the same as the
attribute_names parameter of the scalar put_attributes
call.
:type replace: bool
:param replace: Whether the attribute values passed in will replace
existing values or will be added as addition values.
Defaults to True.
:rtype: bool
:return: True if successful
"""
return self.connection.batch_put_attributes(self, items, replace)
def get_attributes(self, item_name, attribute_name=None,
consistent_read=False, item=None):
"""
Retrieve attributes for a given item.
:type item_name: string
:param item_name: The name of the item whose attributes are being retrieved.
:type attribute_names: string or list of strings
:param attribute_names: An attribute name or list of attribute names. This
parameter is optional. If not supplied, all attributes
will be retrieved for the item.
:rtype: :class:`boto.sdb.item.Item`
:return: An Item mapping type containing the requested attribute name/values
"""
return self.connection.get_attributes(self, item_name, attribute_name,
consistent_read, item)
def delete_attributes(self, item_name, attributes=None,
expected_values=None):
"""
Delete attributes from a given item.
:type item_name: string
:param item_name: The name of the item whose attributes are being deleted.
:type attributes: dict, list or :class:`boto.sdb.item.Item`
:param attributes: Either a list containing attribute names which will cause
all values associated with that attribute name to be deleted or
a dict or Item containing the attribute names and keys and list
of values to delete as the value. If no value is supplied,
all attribute name/values for the item will be deleted.
:type expected_value: list
:param expected_value: If supplied, this is a list or tuple consisting
of a single attribute name and expected value.
The list can be of the form:
* ['name', 'value']
In which case the call will first verify
that the attribute "name" of this item has
a value of "value". If it does, the delete
will proceed, otherwise a ConditionalCheckFailed
error will be returned.
The list can also be of the form:
* ['name', True|False]
which will simply check for the existence (True)
or non-existencve (False) of the attribute.
:rtype: bool
:return: True if successful
"""
return self.connection.delete_attributes(self, item_name, attributes,
expected_values)
def select(self, query='', next_token=None, consistent_read=False, max_items=None):
"""
Returns a set of Attributes for item names within domain_name that match the query.
The query must be expressed in using the SELECT style syntax rather than the
original SimpleDB query language.
:type query: string
:param query: The SimpleDB query to be performed.
:rtype: iter
:return: An iterator containing the results. This is actually a generator
function that will iterate across all search results, not just the
first page.
"""
return SelectResultSet(self, query, max_items = max_items, next_token=next_token,
consistent_read=consistent_read)
def get_item(self, item_name):
item = self.get_attributes(item_name)
if item:
item.domain = self
return item
else:
return None
def new_item(self, item_name):
return self.connection.item_cls(self, item_name)
def delete_item(self, item):
self.delete_attributes(item.name)
def to_xml(self, f=None):
"""Get this domain as an XML DOM Document
:param f: Optional File to dump directly to
:type f: File or Stream
:return: File object where the XML has been dumped to
:rtype: file
"""
if not f:
from tempfile import TemporaryFile
f = TemporaryFile()
print >>f, '<?xml version="1.0" encoding="UTF-8"?>'
print >>f, '<Domain id="%s">' % self.name
for item in self:
print >>f, '\t<Item id="%s">' % item.name
for k in item:
print >>f, '\t\t<attribute id="%s">' % k
values = item[k]
if not isinstance(values, list):
values = [values]
for value in values:
print >>f, '\t\t\t<value><![CDATA[',
if isinstance(value, unicode):
value = value.encode('utf-8', 'replace')
else:
value = unicode(value, errors='replace').encode('utf-8', 'replace')
f.write(value)
print >>f, ']]></value>'
print >>f, '\t\t</attribute>'
print >>f, '\t</Item>'
print >>f, '</Domain>'
f.flush()
f.seek(0)
return f
def from_xml(self, doc):
"""Load this domain based on an XML document"""
import xml.sax
handler = DomainDumpParser(self)
xml.sax.parse(doc, handler)
return handler
class DomainMetaData:
def __init__(self, domain=None):
self.domain = domain
self.item_count = None
self.item_names_size = None
self.attr_name_count = None
self.attr_names_size = None
self.attr_value_count = None
self.attr_values_size = None
def startElement(self, name, attrs, connection):
return None
def endElement(self, name, value, connection):
if name == 'ItemCount':
self.item_count = int(value)
elif name == 'ItemNamesSizeBytes':
self.item_names_size = int(value)
elif name == 'AttributeNameCount':
self.attr_name_count = int(value)
elif name == 'AttributeNamesSizeBytes':
self.attr_names_size = int(value)
elif name == 'AttributeValueCount':
self.attr_value_count = int(value)
elif name == 'AttributeValuesSizeBytes':
self.attr_values_size = int(value)
elif name == 'Timestamp':
self.timestamp = value
else:
setattr(self, name, value)
import sys
from xml.sax.handler import ContentHandler
class DomainDumpParser(ContentHandler):
"""
SAX parser for a domain that has been dumped
"""
def __init__(self, domain):
self.uploader = UploaderThread(domain)
self.item_id = None
self.attrs = {}
self.attribute = None
self.value = ""
self.domain = domain
def startElement(self, name, attrs):
if name == "Item":
self.item_id = attrs['id']
self.attrs = {}
elif name == "attribute":
self.attribute = attrs['id']
elif name == "value":
self.value = ""
def characters(self, ch):
self.value += ch
def endElement(self, name):
if name == "value":
if self.value and self.attribute:
value = self.value.strip()
attr_name = self.attribute.strip()
if self.attrs.has_key(attr_name):
self.attrs[attr_name].append(value)
else:
self.attrs[attr_name] = [value]
elif name == "Item":
self.uploader.items[self.item_id] = self.attrs
# Every 20 items we spawn off the uploader
if len(self.uploader.items) >= 20:
self.uploader.start()
self.uploader = UploaderThread(self.domain)
elif name == "Domain":
# If we're done, spawn off our last Uploader Thread
self.uploader.start()
from threading import Thread
class UploaderThread(Thread):
"""Uploader Thread"""
def __init__(self, domain):
self.db = domain
self.items = {}
Thread.__init__(self)
def run(self):
try:
self.db.batch_put_attributes(self.items)
except:
print "Exception using batch put, trying regular put instead"
for item_name in self.items:
self.db.put_attributes(item_name, self.items[item_name])
print ".",
sys.stdout.flush()
| Python |
# Copyright (c) 2006,2007,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 datetime import datetime
from boto.s3.key import Key
from boto.s3.bucket import Bucket
from boto.sdb.persist import revive_object_from_id
from boto.exception import SDBPersistenceError
from boto.utils import Password
ISO8601 = '%Y-%m-%dT%H:%M:%SZ'
class ValueChecker:
def check(self, value):
"""
Checks a value to see if it is of the right type.
Should raise a TypeError exception if an in appropriate value is passed in.
"""
raise TypeError
def from_string(self, str_value, obj):
"""
Takes a string as input and returns the type-specific value represented by that string.
Should raise a ValueError if the value cannot be converted to the appropriate type.
"""
raise ValueError
def to_string(self, value):
"""
Convert a value to it's string representation.
Should raise a ValueError if the value cannot be converted to a string representation.
"""
raise ValueError
class StringChecker(ValueChecker):
def __init__(self, **params):
if params.has_key('maxlength'):
self.maxlength = params['maxlength']
else:
self.maxlength = 1024
if params.has_key('default'):
self.check(params['default'])
self.default = params['default']
else:
self.default = ''
def check(self, value):
if isinstance(value, str) or isinstance(value, unicode):
if len(value) > self.maxlength:
raise ValueError, 'Length of value greater than maxlength'
else:
raise TypeError, 'Expecting String, got %s' % type(value)
def from_string(self, str_value, obj):
return str_value
def to_string(self, value):
self.check(value)
return value
class PasswordChecker(StringChecker):
def check(self, value):
if isinstance(value, str) or isinstance(value, unicode) or isinstance(value, Password):
if len(value) > self.maxlength:
raise ValueError, 'Length of value greater than maxlength'
else:
raise TypeError, 'Expecting String, got %s' % type(value)
class IntegerChecker(ValueChecker):
__sizes__ = { 'small' : (65535, 32767, -32768, 5),
'medium' : (4294967295, 2147483647, -2147483648, 10),
'large' : (18446744073709551615, 9223372036854775807, -9223372036854775808, 20)}
def __init__(self, **params):
self.size = params.get('size', 'medium')
if self.size not in self.__sizes__.keys():
raise ValueError, 'size must be one of %s' % self.__sizes__.keys()
self.signed = params.get('signed', True)
self.default = params.get('default', 0)
self.format_string = '%%0%dd' % self.__sizes__[self.size][-1]
def check(self, value):
if not isinstance(value, int) and not isinstance(value, long):
raise TypeError, 'Expecting int or long, got %s' % type(value)
if self.signed:
min = self.__sizes__[self.size][2]
max = self.__sizes__[self.size][1]
else:
min = 0
max = self.__sizes__[self.size][0]
if value > max:
raise ValueError, 'Maximum value is %d' % max
if value < min:
raise ValueError, 'Minimum value is %d' % min
def from_string(self, str_value, obj):
val = int(str_value)
if self.signed:
val = val + self.__sizes__[self.size][2]
return val
def to_string(self, value):
self.check(value)
if self.signed:
value += -self.__sizes__[self.size][2]
return self.format_string % value
class BooleanChecker(ValueChecker):
def __init__(self, **params):
if params.has_key('default'):
self.default = params['default']
else:
self.default = False
def check(self, value):
if not isinstance(value, bool):
raise TypeError, 'Expecting bool, got %s' % type(value)
def from_string(self, str_value, obj):
if str_value.lower() == 'true':
return True
else:
return False
def to_string(self, value):
self.check(value)
if value == True:
return 'true'
else:
return 'false'
class DateTimeChecker(ValueChecker):
def __init__(self, **params):
if params.has_key('maxlength'):
self.maxlength = params['maxlength']
else:
self.maxlength = 1024
if params.has_key('default'):
self.default = params['default']
else:
self.default = datetime.now()
def check(self, value):
if not isinstance(value, datetime):
raise TypeError, 'Expecting datetime, got %s' % type(value)
def from_string(self, str_value, obj):
try:
return datetime.strptime(str_value, ISO8601)
except:
raise ValueError, 'Unable to convert %s to DateTime' % str_value
def to_string(self, value):
self.check(value)
return value.strftime(ISO8601)
class ObjectChecker(ValueChecker):
def __init__(self, **params):
self.default = None
self.ref_class = params.get('ref_class', None)
if self.ref_class == None:
raise SDBPersistenceError('ref_class parameter is required')
def check(self, value):
if value == None:
return
if isinstance(value, str) or isinstance(value, unicode):
# ugly little hack - sometimes I want to just stick a UUID string
# in here rather than instantiate an object.
# This does a bit of hand waving to "type check" the string
t = value.split('-')
if len(t) != 5:
raise ValueError
else:
try:
obj_lineage = value.get_lineage()
cls_lineage = self.ref_class.get_lineage()
if obj_lineage.startswith(cls_lineage):
return
raise TypeError, '%s not instance of %s' % (obj_lineage, cls_lineage)
except:
raise ValueError, '%s is not an SDBObject' % value
def from_string(self, str_value, obj):
if not str_value:
return None
try:
return revive_object_from_id(str_value, obj._manager)
except:
raise ValueError, 'Unable to convert %s to Object' % str_value
def to_string(self, value):
self.check(value)
if isinstance(value, str) or isinstance(value, unicode):
return value
if value == None:
return ''
else:
return value.id
class S3KeyChecker(ValueChecker):
def __init__(self, **params):
self.default = None
def check(self, value):
if value == None:
return
if isinstance(value, str) or isinstance(value, unicode):
try:
bucket_name, key_name = value.split('/', 1)
except:
raise ValueError
elif not isinstance(value, Key):
raise TypeError, 'Expecting Key, got %s' % type(value)
def from_string(self, str_value, obj):
if not str_value:
return None
if str_value == 'None':
return None
try:
bucket_name, key_name = str_value.split('/', 1)
if obj:
s3 = obj._manager.get_s3_connection()
bucket = s3.get_bucket(bucket_name)
key = bucket.get_key(key_name)
if not key:
key = bucket.new_key(key_name)
return key
except:
raise ValueError, 'Unable to convert %s to S3Key' % str_value
def to_string(self, value):
self.check(value)
if isinstance(value, str) or isinstance(value, unicode):
return value
if value == None:
return ''
else:
return '%s/%s' % (value.bucket.name, value.name)
class S3BucketChecker(ValueChecker):
def __init__(self, **params):
self.default = None
def check(self, value):
if value == None:
return
if isinstance(value, str) or isinstance(value, unicode):
return
elif not isinstance(value, Bucket):
raise TypeError, 'Expecting Bucket, got %s' % type(value)
def from_string(self, str_value, obj):
if not str_value:
return None
if str_value == 'None':
return None
try:
if obj:
s3 = obj._manager.get_s3_connection()
bucket = s3.get_bucket(str_value)
return bucket
except:
raise ValueError, 'Unable to convert %s to S3Bucket' % str_value
def to_string(self, value):
self.check(value)
if value == None:
return ''
else:
return '%s' % value.name
| Python |
# Copyright (c) 2006,2007,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.exception import SDBPersistenceError
from boto.sdb.persist.checker import StringChecker, PasswordChecker, IntegerChecker, BooleanChecker
from boto.sdb.persist.checker import DateTimeChecker, ObjectChecker, S3KeyChecker, S3BucketChecker
from boto.utils import Password
class Property(object):
def __init__(self, checker_class, **params):
self.name = ''
self.checker = checker_class(**params)
self.slot_name = '__'
def set_name(self, name):
self.name = name
self.slot_name = '__' + self.name
class ScalarProperty(Property):
def save(self, obj):
domain = obj._manager.domain
domain.put_attributes(obj.id, {self.name : self.to_string(obj)}, replace=True)
def to_string(self, obj):
return self.checker.to_string(getattr(obj, self.name))
def load(self, obj):
domain = obj._manager.domain
a = domain.get_attributes(obj.id, self.name)
# try to get the attribute value from SDB
if self.name in a:
value = self.checker.from_string(a[self.name], obj)
setattr(obj, self.slot_name, value)
# if it's not there, set the value to the default value
else:
self.__set__(obj, self.checker.default)
def __get__(self, obj, objtype):
if obj:
try:
value = getattr(obj, self.slot_name)
except AttributeError:
if obj._auto_update:
self.load(obj)
value = getattr(obj, self.slot_name)
else:
value = self.checker.default
setattr(obj, self.slot_name, self.checker.default)
return value
def __set__(self, obj, value):
self.checker.check(value)
try:
old_value = getattr(obj, self.slot_name)
except:
old_value = self.checker.default
setattr(obj, self.slot_name, value)
if obj._auto_update:
try:
self.save(obj)
except:
setattr(obj, self.slot_name, old_value)
raise
class StringProperty(ScalarProperty):
def __init__(self, **params):
ScalarProperty.__init__(self, StringChecker, **params)
class PasswordProperty(ScalarProperty):
"""
Hashed password
"""
def __init__(self, **params):
ScalarProperty.__init__(self, PasswordChecker, **params)
def __set__(self, obj, value):
p = Password()
p.set(value)
ScalarProperty.__set__(self, obj, p)
def __get__(self, obj, objtype):
return Password(ScalarProperty.__get__(self, obj, objtype))
class SmallPositiveIntegerProperty(ScalarProperty):
def __init__(self, **params):
params['size'] = 'small'
params['signed'] = False
ScalarProperty.__init__(self, IntegerChecker, **params)
class SmallIntegerProperty(ScalarProperty):
def __init__(self, **params):
params['size'] = 'small'
params['signed'] = True
ScalarProperty.__init__(self, IntegerChecker, **params)
class PositiveIntegerProperty(ScalarProperty):
def __init__(self, **params):
params['size'] = 'medium'
params['signed'] = False
ScalarProperty.__init__(self, IntegerChecker, **params)
class IntegerProperty(ScalarProperty):
def __init__(self, **params):
params['size'] = 'medium'
params['signed'] = True
ScalarProperty.__init__(self, IntegerChecker, **params)
class LargePositiveIntegerProperty(ScalarProperty):
def __init__(self, **params):
params['size'] = 'large'
params['signed'] = False
ScalarProperty.__init__(self, IntegerChecker, **params)
class LargeIntegerProperty(ScalarProperty):
def __init__(self, **params):
params['size'] = 'large'
params['signed'] = True
ScalarProperty.__init__(self, IntegerChecker, **params)
class BooleanProperty(ScalarProperty):
def __init__(self, **params):
ScalarProperty.__init__(self, BooleanChecker, **params)
class DateTimeProperty(ScalarProperty):
def __init__(self, **params):
ScalarProperty.__init__(self, DateTimeChecker, **params)
class ObjectProperty(ScalarProperty):
def __init__(self, **params):
ScalarProperty.__init__(self, ObjectChecker, **params)
class S3KeyProperty(ScalarProperty):
def __init__(self, **params):
ScalarProperty.__init__(self, S3KeyChecker, **params)
def __set__(self, obj, value):
self.checker.check(value)
try:
old_value = getattr(obj, self.slot_name)
except:
old_value = self.checker.default
if isinstance(value, str):
value = self.checker.from_string(value, obj)
setattr(obj, self.slot_name, value)
if obj._auto_update:
try:
self.save(obj)
except:
setattr(obj, self.slot_name, old_value)
raise
class S3BucketProperty(ScalarProperty):
def __init__(self, **params):
ScalarProperty.__init__(self, S3BucketChecker, **params)
def __set__(self, obj, value):
self.checker.check(value)
try:
old_value = getattr(obj, self.slot_name)
except:
old_value = self.checker.default
if isinstance(value, str):
value = self.checker.from_string(value, obj)
setattr(obj, self.slot_name, value)
if obj._auto_update:
try:
self.save(obj)
except:
setattr(obj, self.slot_name, old_value)
raise
class MultiValueProperty(Property):
def __init__(self, checker_class, **params):
Property.__init__(self, checker_class, **params)
def __get__(self, obj, objtype):
if obj:
try:
value = getattr(obj, self.slot_name)
except AttributeError:
if obj._auto_update:
self.load(obj)
value = getattr(obj, self.slot_name)
else:
value = MultiValue(self, obj, [])
setattr(obj, self.slot_name, value)
return value
def load(self, obj):
if obj != None:
_list = []
domain = obj._manager.domain
a = domain.get_attributes(obj.id, self.name)
if self.name in a:
lst = a[self.name]
if not isinstance(lst, list):
lst = [lst]
for value in lst:
value = self.checker.from_string(value, obj)
_list.append(value)
setattr(obj, self.slot_name, MultiValue(self, obj, _list))
def __set__(self, obj, value):
if not isinstance(value, list):
raise SDBPersistenceError('Value must be a list')
setattr(obj, self.slot_name, MultiValue(self, obj, value))
str_list = self.to_string(obj)
domain = obj._manager.domain
if obj._auto_update:
if len(str_list) == 1:
domain.put_attributes(obj.id, {self.name : str_list[0]}, replace=True)
else:
try:
self.__delete__(obj)
except:
pass
domain.put_attributes(obj.id, {self.name : str_list}, replace=True)
setattr(obj, self.slot_name, MultiValue(self, obj, value))
def __delete__(self, obj):
if obj._auto_update:
domain = obj._manager.domain
domain.delete_attributes(obj.id, [self.name])
setattr(obj, self.slot_name, MultiValue(self, obj, []))
def to_string(self, obj):
str_list = []
for value in self.__get__(obj, type(obj)):
str_list.append(self.checker.to_string(value))
return str_list
class StringListProperty(MultiValueProperty):
def __init__(self, **params):
MultiValueProperty.__init__(self, StringChecker, **params)
class SmallIntegerListProperty(MultiValueProperty):
def __init__(self, **params):
params['size'] = 'small'
params['signed'] = True
MultiValueProperty.__init__(self, IntegerChecker, **params)
class SmallPositiveIntegerListProperty(MultiValueProperty):
def __init__(self, **params):
params['size'] = 'small'
params['signed'] = False
MultiValueProperty.__init__(self, IntegerChecker, **params)
class IntegerListProperty(MultiValueProperty):
def __init__(self, **params):
params['size'] = 'medium'
params['signed'] = True
MultiValueProperty.__init__(self, IntegerChecker, **params)
class PositiveIntegerListProperty(MultiValueProperty):
def __init__(self, **params):
params['size'] = 'medium'
params['signed'] = False
MultiValueProperty.__init__(self, IntegerChecker, **params)
class LargeIntegerListProperty(MultiValueProperty):
def __init__(self, **params):
params['size'] = 'large'
params['signed'] = True
MultiValueProperty.__init__(self, IntegerChecker, **params)
class LargePositiveIntegerListProperty(MultiValueProperty):
def __init__(self, **params):
params['size'] = 'large'
params['signed'] = False
MultiValueProperty.__init__(self, IntegerChecker, **params)
class BooleanListProperty(MultiValueProperty):
def __init__(self, **params):
MultiValueProperty.__init__(self, BooleanChecker, **params)
class ObjectListProperty(MultiValueProperty):
def __init__(self, **params):
MultiValueProperty.__init__(self, ObjectChecker, **params)
class HasManyProperty(Property):
def set_name(self, name):
self.name = name
self.slot_name = '__' + self.name
def __get__(self, obj, objtype):
return self
class MultiValue:
"""
Special Multi Value for boto persistence layer to allow us to do
obj.list.append(foo)
"""
def __init__(self, property, obj, _list):
self.checker = property.checker
self.name = property.name
self.object = obj
self._list = _list
def __repr__(self):
return repr(self._list)
def __getitem__(self, key):
return self._list.__getitem__(key)
def __delitem__(self, key):
item = self[key]
self._list.__delitem__(key)
domain = self.object._manager.domain
domain.delete_attributes(self.object.id, {self.name: [self.checker.to_string(item)]})
def __len__(self):
return len(self._list)
def append(self, value):
self.checker.check(value)
self._list.append(value)
domain = self.object._manager.domain
domain.put_attributes(self.object.id, {self.name: self.checker.to_string(value)}, replace=False)
def index(self, value):
for x in self._list:
if x.id == value.id:
return self._list.index(x)
def remove(self, value):
del(self[self.index(value)])
| Python |
# Copyright (c) 2006,2007,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.exception import SDBPersistenceError
from boto.sdb.persist import get_manager, object_lister
from boto.sdb.persist.property import Property, ScalarProperty
import uuid
class SDBBase(type):
"Metaclass for all SDBObjects"
def __init__(cls, name, bases, dict):
super(SDBBase, cls).__init__(name, bases, dict)
# Make sure this is a subclass of SDBObject - mainly copied from django ModelBase (thanks!)
try:
if filter(lambda b: issubclass(b, SDBObject), bases):
# look for all of the Properties and set their names
for key in dict.keys():
if isinstance(dict[key], Property):
property = dict[key]
property.set_name(key)
prop_names = []
props = cls.properties()
for prop in props:
prop_names.append(prop.name)
setattr(cls, '_prop_names', prop_names)
except NameError:
# 'SDBObject' isn't defined yet, meaning we're looking at our own
# SDBObject class, defined below.
pass
class SDBObject(object):
__metaclass__ = SDBBase
_manager = get_manager()
@classmethod
def get_lineage(cls):
l = [c.__name__ for c in cls.mro()]
l.reverse()
return '.'.join(l)
@classmethod
def get(cls, id=None, **params):
if params.has_key('manager'):
manager = params['manager']
else:
manager = cls._manager
if manager.domain and id:
a = cls._manager.domain.get_attributes(id, '__type__')
if a.has_key('__type__'):
return cls(id, manager)
else:
raise SDBPersistenceError('%s object with id=%s does not exist' % (cls.__name__, id))
else:
rs = cls.find(**params)
try:
obj = rs.next()
except StopIteration:
raise SDBPersistenceError('%s object matching query does not exist' % cls.__name__)
try:
rs.next()
except StopIteration:
return obj
raise SDBPersistenceError('Query matched more than 1 item')
@classmethod
def find(cls, **params):
if params.has_key('manager'):
manager = params['manager']
del params['manager']
else:
manager = cls._manager
keys = params.keys()
if len(keys) > 4:
raise SDBPersistenceError('Too many fields, max is 4')
parts = ["['__type__'='%s'] union ['__lineage__'starts-with'%s']" % (cls.__name__, cls.get_lineage())]
properties = cls.properties()
for key in keys:
found = False
for property in properties:
if property.name == key:
found = True
if isinstance(property, ScalarProperty):
checker = property.checker
parts.append("['%s' = '%s']" % (key, checker.to_string(params[key])))
else:
raise SDBPersistenceError('%s is not a searchable field' % key)
if not found:
raise SDBPersistenceError('%s is not a valid field' % key)
query = ' intersection '.join(parts)
if manager.domain:
rs = manager.domain.query(query)
else:
rs = []
return object_lister(None, rs, manager)
@classmethod
def list(cls, max_items=None, manager=None):
if not manager:
manager = cls._manager
if manager.domain:
rs = manager.domain.query("['__type__' = '%s']" % cls.__name__, max_items=max_items)
else:
rs = []
return object_lister(cls, rs, manager)
@classmethod
def properties(cls):
properties = []
while cls:
for key in cls.__dict__.keys():
if isinstance(cls.__dict__[key], Property):
properties.append(cls.__dict__[key])
if len(cls.__bases__) > 0:
cls = cls.__bases__[0]
else:
cls = None
return properties
# for backwards compatibility
find_properties = properties
def __init__(self, id=None, manager=None):
if manager:
self._manager = manager
self.id = id
if self.id:
self._auto_update = True
if self._manager.domain:
attrs = self._manager.domain.get_attributes(self.id, '__type__')
if len(attrs.keys()) == 0:
raise SDBPersistenceError('Object %s: not found' % self.id)
else:
self.id = str(uuid.uuid4())
self._auto_update = False
def __setattr__(self, name, value):
if name in self._prop_names:
object.__setattr__(self, name, value)
elif name.startswith('_'):
object.__setattr__(self, name, value)
elif name == 'id':
object.__setattr__(self, name, value)
else:
self._persist_attribute(name, value)
object.__setattr__(self, name, value)
def __getattr__(self, name):
if not name.startswith('_'):
a = self._manager.domain.get_attributes(self.id, name)
if a.has_key(name):
object.__setattr__(self, name, a[name])
return a[name]
raise AttributeError
def __repr__(self):
return '%s<%s>' % (self.__class__.__name__, self.id)
def _persist_attribute(self, name, value):
if self.id:
self._manager.domain.put_attributes(self.id, {name : value}, replace=True)
def _get_sdb_item(self):
return self._manager.domain.get_item(self.id)
def save(self):
attrs = {'__type__' : self.__class__.__name__,
'__module__' : self.__class__.__module__,
'__lineage__' : self.get_lineage()}
for property in self.properties():
attrs[property.name] = property.to_string(self)
if self._manager.domain:
self._manager.domain.put_attributes(self.id, attrs, replace=True)
self._auto_update = True
def delete(self):
if self._manager.domain:
self._manager.domain.delete_attributes(self.id)
def get_related_objects(self, ref_name, ref_cls=None):
if self._manager.domain:
query = "['%s' = '%s']" % (ref_name, self.id)
if ref_cls:
query += " intersection ['__type__'='%s']" % ref_cls.__name__
rs = self._manager.domain.query(query)
else:
rs = []
return object_lister(ref_cls, rs, self._manager)
| Python |
# Copyright (c) 2006,2007,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.
import boto
from boto.utils import find_class
class Manager(object):
DefaultDomainName = boto.config.get('Persist', 'default_domain', None)
def __init__(self, domain_name=None, aws_access_key_id=None, aws_secret_access_key=None, debug=0):
self.domain_name = domain_name
self.aws_access_key_id = aws_access_key_id
self.aws_secret_access_key = aws_secret_access_key
self.domain = None
self.sdb = None
self.s3 = None
if not self.domain_name:
self.domain_name = self.DefaultDomainName
if self.domain_name:
boto.log.info('No SimpleDB domain set, using default_domain: %s' % self.domain_name)
else:
boto.log.warning('No SimpleDB domain set, persistance is disabled')
if self.domain_name:
self.sdb = boto.connect_sdb(aws_access_key_id=self.aws_access_key_id,
aws_secret_access_key=self.aws_secret_access_key,
debug=debug)
self.domain = self.sdb.lookup(self.domain_name)
if not self.domain:
self.domain = self.sdb.create_domain(self.domain_name)
def get_s3_connection(self):
if not self.s3:
self.s3 = boto.connect_s3(self.aws_access_key_id, self.aws_secret_access_key)
return self.s3
def get_manager(domain_name=None, aws_access_key_id=None, aws_secret_access_key=None, debug=0):
return Manager(domain_name, aws_access_key_id, aws_secret_access_key, debug=debug)
def set_domain(domain_name):
Manager.DefaultDomainName = domain_name
def get_domain():
return Manager.DefaultDomainName
def revive_object_from_id(id, manager):
if not manager.domain:
return None
attrs = manager.domain.get_attributes(id, ['__module__', '__type__', '__lineage__'])
try:
cls = find_class(attrs['__module__'], attrs['__type__'])
return cls(id, manager=manager)
except ImportError:
return None
def object_lister(cls, query_lister, manager):
for item in query_lister:
if cls:
yield cls(item.name)
else:
o = revive_object_from_id(item.name, manager)
if o:
yield o
| 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.
def query_lister(domain, query='', max_items=None, attr_names=None):
more_results = True
num_results = 0
next_token = None
while more_results:
rs = domain.connection.query_with_attributes(domain, query, attr_names,
next_token=next_token)
for item in rs:
if max_items:
if num_results == max_items:
raise StopIteration
yield item
num_results += 1
next_token = rs.next_token
more_results = next_token != None
class QueryResultSet:
def __init__(self, domain=None, query='', max_items=None, attr_names=None):
self.max_items = max_items
self.domain = domain
self.query = query
self.attr_names = attr_names
def __iter__(self):
return query_lister(self.domain, self.query, self.max_items, self.attr_names)
def select_lister(domain, query='', max_items=None):
more_results = True
num_results = 0
next_token = None
while more_results:
rs = domain.connection.select(domain, query, next_token=next_token)
for item in rs:
if max_items:
if num_results == max_items:
raise StopIteration
yield item
num_results += 1
next_token = rs.next_token
more_results = next_token != None
class SelectResultSet(object):
def __init__(self, domain=None, query='', max_items=None,
next_token=None, consistent_read=False):
self.domain = domain
self.query = query
self.consistent_read = consistent_read
self.max_items = max_items
self.next_token = next_token
def __iter__(self):
more_results = True
num_results = 0
while more_results:
rs = self.domain.connection.select(self.domain, self.query,
next_token=self.next_token,
consistent_read=self.consistent_read)
for item in rs:
if self.max_items and num_results >= self.max_items:
raise StopIteration
yield item
num_results += 1
self.next_token = rs.next_token
if self.max_items and num_results >= self.max_items:
raise StopIteration
more_results = self.next_token != None
def next(self):
return self.__iter__().next()
| Python |
# Copyright (c) 2009-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 a Customer Gateway
"""
from boto.ec2.ec2object import TaggedEC2Object
class CustomerGateway(TaggedEC2Object):
def __init__(self, connection=None):
TaggedEC2Object.__init__(self, connection)
self.id = None
self.type = None
self.state = None
self.ip_address = None
self.bgp_asn = None
def __repr__(self):
return 'CustomerGateway:%s' % self.id
def endElement(self, name, value, connection):
if name == 'customerGatewayId':
self.id = value
elif name == 'ipAddress':
self.ip_address = value
elif name == 'type':
self.type = value
elif name == 'state':
self.state = value
elif name == 'bgpAsn':
self.bgp_asn = value
else:
setattr(self, name, value)
| Python |
# Copyright (c) 2009-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 a Subnet
"""
from boto.ec2.ec2object import TaggedEC2Object
class Subnet(TaggedEC2Object):
def __init__(self, connection=None):
TaggedEC2Object.__init__(self, connection)
self.id = None
self.state = None
self.cidr_block = None
self.available_ip_address_count = 0
self.availability_zone = None
def __repr__(self):
return 'Subnet:%s' % self.id
def endElement(self, name, value, connection):
if name == 'subnetId':
self.id = value
elif name == 'state':
self.state = value
elif name == 'cidrBlock':
self.cidr_block = value
elif name == 'availableIpAddressCount':
self.available_ip_address_count = int(value)
elif name == 'availabilityZone':
self.availability_zone = value
else:
setattr(self, name, value)
| Python |
# Copyright (c) 2009-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 a DHCP Options set
"""
from boto.ec2.ec2object import TaggedEC2Object
class DhcpValueSet(list):
def startElement(self, name, attrs, connection):
pass
def endElement(self, name, value, connection):
if name == 'value':
self.append(value)
class DhcpConfigSet(dict):
def startElement(self, name, attrs, connection):
if name == 'valueSet':
if not self.has_key(self._name):
self[self._name] = DhcpValueSet()
return self[self._name]
def endElement(self, name, value, connection):
if name == 'key':
self._name = value
class DhcpOptions(TaggedEC2Object):
def __init__(self, connection=None):
TaggedEC2Object.__init__(self, connection)
self.id = None
self.options = None
def __repr__(self):
return 'DhcpOptions:%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 == 'dhcpConfigurationSet':
self.options = DhcpConfigSet()
return self.options
def endElement(self, name, value, connection):
if name == 'dhcpOptionsId':
self.id = value
else:
setattr(self, name, value)
| Python |
# Copyright (c) 2009-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 a VPN Connectionn
"""
from boto.ec2.ec2object import EC2Object
class VpnConnection(EC2Object):
def __init__(self, connection=None):
EC2Object.__init__(self, connection)
self.id = None
self.state = None
self.customer_gateway_configuration = None
self.type = None
self.customer_gateway_id = None
self.vpn_gateway_id = None
def __repr__(self):
return 'VpnConnection:%s' % self.id
def endElement(self, name, value, connection):
if name == 'vpnConnectionId':
self.id = value
elif name == 'state':
self.state = value
elif name == 'CustomerGatewayConfiguration':
self.customer_gateway_configuration = value
elif name == 'type':
self.type = value
elif name == 'customerGatewayId':
self.customer_gateway_id = value
elif name == 'vpnGatewayId':
self.vpn_gateway_id = value
else:
setattr(self, name, value)
def delete(self):
return self.connection.delete_vpn_connection(self.id)
| Python |
# Copyright (c) 2009-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 a Virtual Private Cloud.
"""
from boto.ec2.ec2object import TaggedEC2Object
class VPC(TaggedEC2Object):
def __init__(self, connection=None):
TaggedEC2Object.__init__(self, connection)
self.id = None
self.dhcp_options_id = None
self.state = None
self.cidr_block = None
def __repr__(self):
return 'VPC:%s' % self.id
def endElement(self, name, value, connection):
if name == 'vpcId':
self.id = value
elif name == 'dhcpOptionsId':
self.dhcp_options_id = value
elif name == 'state':
self.state = value
elif name == 'cidrBlock':
self.cidr_block = value
else:
setattr(self, name, value)
def delete(self):
return self.connection.delete_vpc(self.id)
| 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.
"""
Represents a connection to the EC2 service.
"""
from boto.ec2.connection import EC2Connection
from boto.vpc.vpc import VPC
from boto.vpc.customergateway import CustomerGateway
from boto.vpc.vpngateway import VpnGateway, Attachment
from boto.vpc.dhcpoptions import DhcpOptions
from boto.vpc.subnet import Subnet
from boto.vpc.vpnconnection import VpnConnection
class VPCConnection(EC2Connection):
# VPC methods
def get_all_vpcs(self, vpc_ids=None, filters=None):
"""
Retrieve information about your VPCs. You can filter results to
return information only about those VPCs that match your search
parameters. Otherwise, all VPCs associated with your account
are returned.
:type vpc_ids: list
:param vpc_ids: A list of strings with the desired VPC ID's
:type filters: list of tuples
:param filters: A list of tuples containing filters. Each tuple
consists of a filter key and a filter value.
Possible filter keys are:
- *state*, the state of the VPC (pending or available)
- *cidrBlock*, CIDR block of the VPC
- *dhcpOptionsId*, the ID of a set of DHCP options
:rtype: list
:return: A list of :class:`boto.vpc.vpc.VPC`
"""
params = {}
if vpc_ids:
self.build_list_params(params, vpc_ids, 'VpcId')
if filters:
i = 1
for filter in filters:
params[('Filter.%d.Key' % i)] = filter[0]
params[('Filter.%d.Value.1')] = filter[1]
i += 1
return self.get_list('DescribeVpcs', params, [('item', VPC)])
def create_vpc(self, cidr_block):
"""
Create a new Virtual Private Cloud.
:type cidr_block: str
:param cidr_block: A valid CIDR block
:rtype: The newly created VPC
:return: A :class:`boto.vpc.vpc.VPC` object
"""
params = {'CidrBlock' : cidr_block}
return self.get_object('CreateVpc', params, VPC)
def delete_vpc(self, vpc_id):
"""
Delete a Virtual Private Cloud.
:type vpc_id: str
:param vpc_id: The ID of the vpc to be deleted.
:rtype: bool
:return: True if successful
"""
params = {'VpcId': vpc_id}
return self.get_status('DeleteVpc', params)
# Customer Gateways
def get_all_customer_gateways(self, customer_gateway_ids=None, filters=None):
"""
Retrieve information about your CustomerGateways. You can filter results to
return information only about those CustomerGateways that match your search
parameters. Otherwise, all CustomerGateways associated with your account
are returned.
:type customer_gateway_ids: list
:param customer_gateway_ids: A list of strings with the desired CustomerGateway ID's
:type filters: list of tuples
:param filters: A list of tuples containing filters. Each tuple
consists of a filter key and a filter value.
Possible filter keys are:
- *state*, the state of the CustomerGateway
(pending,available,deleting,deleted)
- *type*, the type of customer gateway (ipsec.1)
- *ipAddress* the IP address of customer gateway's
internet-routable external inteface
:rtype: list
:return: A list of :class:`boto.vpc.customergateway.CustomerGateway`
"""
params = {}
if customer_gateway_ids:
self.build_list_params(params, customer_gateway_ids, 'CustomerGatewayId')
if filters:
i = 1
for filter in filters:
params[('Filter.%d.Key' % i)] = filter[0]
params[('Filter.%d.Value.1')] = filter[1]
i += 1
return self.get_list('DescribeCustomerGateways', params, [('item', CustomerGateway)])
def create_customer_gateway(self, type, ip_address, bgp_asn):
"""
Create a new Customer Gateway
:type type: str
:param type: Type of VPN Connection. Only valid valid currently is 'ipsec.1'
:type ip_address: str
:param ip_address: Internet-routable IP address for customer's gateway.
Must be a static address.
:type bgp_asn: str
:param bgp_asn: Customer gateway's Border Gateway Protocol (BGP)
Autonomous System Number (ASN)
:rtype: The newly created CustomerGateway
:return: A :class:`boto.vpc.customergateway.CustomerGateway` object
"""
params = {'Type' : type,
'IpAddress' : ip_address,
'BgpAsn' : bgp_asn}
return self.get_object('CreateCustomerGateway', params, CustomerGateway)
def delete_customer_gateway(self, customer_gateway_id):
"""
Delete a Customer Gateway.
:type customer_gateway_id: str
:param customer_gateway_id: The ID of the customer_gateway to be deleted.
:rtype: bool
:return: True if successful
"""
params = {'CustomerGatewayId': customer_gateway_id}
return self.get_status('DeleteCustomerGateway', params)
# VPN Gateways
def get_all_vpn_gateways(self, vpn_gateway_ids=None, filters=None):
"""
Retrieve information about your VpnGateways. You can filter results to
return information only about those VpnGateways that match your search
parameters. Otherwise, all VpnGateways associated with your account
are returned.
:type vpn_gateway_ids: list
:param vpn_gateway_ids: A list of strings with the desired VpnGateway ID's
:type filters: list of tuples
:param filters: A list of tuples containing filters. Each tuple
consists of a filter key and a filter value.
Possible filter keys are:
- *state*, the state of the VpnGateway
(pending,available,deleting,deleted)
- *type*, the type of customer gateway (ipsec.1)
- *availabilityZone*, the Availability zone the
VPN gateway is in.
:rtype: list
:return: A list of :class:`boto.vpc.customergateway.VpnGateway`
"""
params = {}
if vpn_gateway_ids:
self.build_list_params(params, vpn_gateway_ids, 'VpnGatewayId')
if filters:
i = 1
for filter in filters:
params[('Filter.%d.Key' % i)] = filter[0]
params[('Filter.%d.Value.1')] = filter[1]
i += 1
return self.get_list('DescribeVpnGateways', params, [('item', VpnGateway)])
def create_vpn_gateway(self, type, availability_zone=None):
"""
Create a new Vpn Gateway
:type type: str
:param type: Type of VPN Connection. Only valid valid currently is 'ipsec.1'
:type availability_zone: str
:param availability_zone: The Availability Zone where you want the VPN gateway.
:rtype: The newly created VpnGateway
:return: A :class:`boto.vpc.vpngateway.VpnGateway` object
"""
params = {'Type' : type}
if availability_zone:
params['AvailabilityZone'] = availability_zone
return self.get_object('CreateVpnGateway', params, VpnGateway)
def delete_vpn_gateway(self, vpn_gateway_id):
"""
Delete a Vpn Gateway.
:type vpn_gateway_id: str
:param vpn_gateway_id: The ID of the vpn_gateway to be deleted.
:rtype: bool
:return: True if successful
"""
params = {'VpnGatewayId': vpn_gateway_id}
return self.get_status('DeleteVpnGateway', params)
def attach_vpn_gateway(self, vpn_gateway_id, vpc_id):
"""
Attaches a VPN gateway to a VPC.
:type vpn_gateway_id: str
:param vpn_gateway_id: The ID of the vpn_gateway to attach
:type vpc_id: str
:param vpc_id: The ID of the VPC you want to attach the gateway to.
:rtype: An attachment
:return: a :class:`boto.vpc.vpngateway.Attachment`
"""
params = {'VpnGatewayId': vpn_gateway_id,
'VpcId' : vpc_id}
return self.get_object('AttachVpnGateway', params, Attachment)
# Subnets
def get_all_subnets(self, subnet_ids=None, filters=None):
"""
Retrieve information about your Subnets. You can filter results to
return information only about those Subnets that match your search
parameters. Otherwise, all Subnets associated with your account
are returned.
:type subnet_ids: list
:param subnet_ids: A list of strings with the desired Subnet ID's
:type filters: list of tuples
:param filters: A list of tuples containing filters. Each tuple
consists of a filter key and a filter value.
Possible filter keys are:
- *state*, the state of the Subnet
(pending,available)
- *vpdId*, the ID of teh VPC the subnet is in.
- *cidrBlock*, CIDR block of the subnet
- *availabilityZone*, the Availability Zone
the subnet is in.
:rtype: list
:return: A list of :class:`boto.vpc.subnet.Subnet`
"""
params = {}
if subnet_ids:
self.build_list_params(params, subnet_ids, 'SubnetId')
if filters:
i = 1
for filter in filters:
params[('Filter.%d.Key' % i)] = filter[0]
params[('Filter.%d.Value.1')] = filter[1]
i += 1
return self.get_list('DescribeSubnets', params, [('item', Subnet)])
def create_subnet(self, vpc_id, cidr_block, availability_zone=None):
"""
Create a new Subnet
:type vpc_id: str
:param vpc_id: The ID of the VPC where you want to create the subnet.
:type cidr_block: str
:param cidr_block: The CIDR block you want the subnet to cover.
:type availability_zone: str
:param availability_zone: The AZ you want the subnet in
:rtype: The newly created Subnet
:return: A :class:`boto.vpc.customergateway.Subnet` object
"""
params = {'VpcId' : vpc_id,
'CidrBlock' : cidr_block}
if availability_zone:
params['AvailabilityZone'] = availability_zone
return self.get_object('CreateSubnet', params, Subnet)
def delete_subnet(self, subnet_id):
"""
Delete a subnet.
:type subnet_id: str
:param subnet_id: The ID of the subnet to be deleted.
:rtype: bool
:return: True if successful
"""
params = {'SubnetId': subnet_id}
return self.get_status('DeleteSubnet', params)
# DHCP Options
def get_all_dhcp_options(self, dhcp_options_ids=None):
"""
Retrieve information about your DhcpOptions.
:type dhcp_options_ids: list
:param dhcp_options_ids: A list of strings with the desired DhcpOption ID's
:rtype: list
:return: A list of :class:`boto.vpc.dhcpoptions.DhcpOptions`
"""
params = {}
if dhcp_options_ids:
self.build_list_params(params, dhcp_options_ids, 'DhcpOptionsId')
return self.get_list('DescribeDhcpOptions', params, [('item', DhcpOptions)])
def create_dhcp_options(self, vpc_id, cidr_block, availability_zone=None):
"""
Create a new DhcpOption
:type vpc_id: str
:param vpc_id: The ID of the VPC where you want to create the subnet.
:type cidr_block: str
:param cidr_block: The CIDR block you want the subnet to cover.
:type availability_zone: str
:param availability_zone: The AZ you want the subnet in
:rtype: The newly created DhcpOption
:return: A :class:`boto.vpc.customergateway.DhcpOption` object
"""
params = {'VpcId' : vpc_id,
'CidrBlock' : cidr_block}
if availability_zone:
params['AvailabilityZone'] = availability_zone
return self.get_object('CreateDhcpOption', params, DhcpOptions)
def delete_dhcp_options(self, dhcp_options_id):
"""
Delete a DHCP Options
:type dhcp_options_id: str
:param dhcp_options_id: The ID of the DHCP Options to be deleted.
:rtype: bool
:return: True if successful
"""
params = {'DhcpOptionsId': dhcp_options_id}
return self.get_status('DeleteDhcpOptions', params)
def associate_dhcp_options(self, dhcp_options_id, vpc_id):
"""
Associate a set of Dhcp Options with a VPC.
:type dhcp_options_id: str
:param dhcp_options_id: The ID of the Dhcp Options
:type vpc_id: str
:param vpc_id: The ID of the VPC.
:rtype: bool
:return: True if successful
"""
params = {'DhcpOptionsId': dhcp_options_id,
'VpcId' : vpc_id}
return self.get_status('AssociateDhcpOptions', params)
# VPN Connection
def get_all_vpn_connections(self, vpn_connection_ids=None, filters=None):
"""
Retrieve information about your VPN_CONNECTIONs. You can filter results to
return information only about those VPN_CONNECTIONs that match your search
parameters. Otherwise, all VPN_CONNECTIONs associated with your account
are returned.
:type vpn_connection_ids: list
:param vpn_connection_ids: A list of strings with the desired VPN_CONNECTION ID's
:type filters: list of tuples
:param filters: A list of tuples containing filters. Each tuple
consists of a filter key and a filter value.
Possible filter keys are:
- *state*, the state of the VPN_CONNECTION
pending,available,deleting,deleted
- *type*, the type of connection, currently 'ipsec.1'
- *customerGatewayId*, the ID of the customer gateway
associated with the VPN
- *vpnGatewayId*, the ID of the VPN gateway associated
with the VPN connection
:rtype: list
:return: A list of :class:`boto.vpn_connection.vpnconnection.VpnConnection`
"""
params = {}
if vpn_connection_ids:
self.build_list_params(params, vpn_connection_ids, 'Vpn_ConnectionId')
if filters:
i = 1
for filter in filters:
params[('Filter.%d.Key' % i)] = filter[0]
params[('Filter.%d.Value.1')] = filter[1]
i += 1
return self.get_list('DescribeVpnConnections', params, [('item', VpnConnection)])
def create_vpn_connection(self, type, customer_gateway_id, vpn_gateway_id):
"""
Create a new VPN Connection.
:type type: str
:param type: The type of VPN Connection. Currently only 'ipsec.1'
is supported
:type customer_gateway_id: str
:param customer_gateway_id: The ID of the customer gateway.
:type vpn_gateway_id: str
:param vpn_gateway_id: The ID of the VPN gateway.
:rtype: The newly created VpnConnection
:return: A :class:`boto.vpc.vpnconnection.VpnConnection` object
"""
params = {'Type' : type,
'CustomerGatewayId' : customer_gateway_id,
'VpnGatewayId' : vpn_gateway_id}
return self.get_object('CreateVpnConnection', params, VpnConnection)
def delete_vpn_connection(self, vpn_connection_id):
"""
Delete a VPN Connection.
:type vpn_connection_id: str
:param vpn_connection_id: The ID of the vpn_connection to be deleted.
:rtype: bool
:return: True if successful
"""
params = {'VpnConnectionId': vpn_connection_id}
return self.get_status('DeleteVpnConnection', params)
| Python |
# Copyright (c) 2009-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 a Vpn Gateway
"""
from boto.ec2.ec2object import TaggedEC2Object
class Attachment(object):
def __init__(self, connection=None):
self.vpc_id = None
self.state = None
def startElement(self, name, attrs, connection):
pass
def endElement(self, name, value, connection):
if name == 'vpcId':
self.vpc_id = value
elif name == 'state':
self.state = value
else:
setattr(self, name, value)
class VpnGateway(TaggedEC2Object):
def __init__(self, connection=None):
TaggedEC2Object.__init__(self, connection)
self.id = None
self.type = None
self.state = None
self.availability_zone = None
self.attachments = []
def __repr__(self):
return 'VpnGateway:%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 == 'item':
att = Attachment()
self.attachments.append(att)
return att
def endElement(self, name, value, connection):
if name == 'vpnGatewayId':
self.id = value
elif name == 'type':
self.type = value
elif name == 'state':
self.state = value
elif name == 'availabilityZone':
self.availability_zone = value
elif name == 'attachments':
pass
else:
setattr(self, name, value)
def attach(self, vpc_id):
return self.connection.attach_vpn_gateway(self.id, vpc_id)
| Python |
# Copyright (c) 2006,2007 Jon Colverson
#
# 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 was contributed by Jon Colverson. It provides a couple of helper
functions that allow you to use M2Crypto's implementation of HTTPSConnection
rather than the default version in httplib.py. The main benefit is that
M2Crypto's version verifies the certificate of the server.
To use this feature, do something like this:
from boto.ec2.connection import EC2Connection
ec2 = EC2Connection(ACCESS_KEY_ID, SECRET_ACCESS_KEY,
https_connection_factory=https_connection_factory(cafile=CA_FILE))
See http://code.google.com/p/boto/issues/detail?id=57 for more details.
"""
from M2Crypto import SSL
from M2Crypto.httpslib import HTTPSConnection
def secure_context(cafile=None, capath=None):
ctx = SSL.Context()
ctx.set_verify(SSL.verify_peer | SSL.verify_fail_if_no_peer_cert, depth=9)
if ctx.load_verify_locations(cafile=cafile, capath=capath) != 1:
raise Exception("Couldn't load certificates")
return ctx
def https_connection_factory(cafile=None, capath=None):
def factory(*args, **kwargs):
return HTTPSConnection(
ssl_context=secure_context(cafile=cafile, capath=capath),
*args, **kwargs)
return (factory, (SSL.SSLError,))
| Python |
# Copyright (c) 2006,2007 Chris Moyer
#
# 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 was contributed by Chris Moyer. It provides a subclass of the
SQS Message class that supports YAML as the body of the message.
This module requires the yaml module.
"""
from boto.sqs.message import Message
import yaml
class YAMLMessage(Message):
"""
The YAMLMessage class provides a YAML compatible message. Encoding and
decoding are handled automaticaly.
Access this message data like such:
m.data = [ 1, 2, 3]
m.data[0] # Returns 1
This depends on the PyYAML package
"""
def __init__(self, queue=None, body='', xml_attrs=None):
self.data = None
Message.__init__(self, queue, body)
def set_body(self, body):
self.data = yaml.load(body)
def get_body(self):
return yaml.dump(self.data)
| 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) 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.
from boto.connection import AWSQueryConnection
from boto.sdb.regioninfo import SDBRegionInfo
import boto
import uuid
try:
import json
except ImportError:
import simplejson as json
#boto.set_stream_logger('sns')
class SNSConnection(AWSQueryConnection):
DefaultRegionName = 'us-east-1'
DefaultRegionEndpoint = 'sns.us-east-1.amazonaws.com'
APIVersion = '2010-03-31'
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=0,
https_connection_factory=None, region=None, path='/', converter=None):
if not region:
region = SDBRegionInfo(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_all_topics(self, next_token=None):
"""
:type next_token: string
:param next_token: Token returned by the previous call to
this method.
"""
params = {'ContentType' : 'JSON'}
if next_token:
params['NextToken'] = next_token
response = self.make_request('ListTopics', params, '/', 'GET')
body = response.read()
if response.status == 200:
return json.loads(body)
else:
boto.log.error('%s %s' % (response.status, response.reason))
boto.log.error('%s' % body)
raise self.ResponseError(response.status, response.reason, body)
def get_topic_attributes(self, topic):
"""
Get attributes of a Topic
:type topic: string
:param topic: The ARN of the topic.
"""
params = {'ContentType' : 'JSON',
'TopicArn' : topic}
response = self.make_request('GetTopicAttributes', params, '/', 'GET')
body = response.read()
if response.status == 200:
return json.loads(body)
else:
boto.log.error('%s %s' % (response.status, response.reason))
boto.log.error('%s' % body)
raise self.ResponseError(response.status, response.reason, body)
def add_permission(self, topic, label, account_ids, actions):
"""
Adds a statement to a topic's access control policy, granting
access for the specified AWS accounts to the specified actions.
:type topic: string
:param topic: The ARN of the topic.
:type label: string
:param label: A unique identifier for the new policy statement.
:type account_ids: list of strings
:param account_ids: The AWS account ids of the users who will be
give access to the specified actions.
:type actions: list of strings
:param actions: The actions you want to allow for each of the
specified principal(s).
"""
params = {'ContentType' : 'JSON',
'TopicArn' : topic,
'Label' : label}
self.build_list_params(params, account_ids, 'AWSAccountId')
self.build_list_params(params, actions, 'ActionName')
response = self.make_request('AddPermission', params, '/', 'GET')
body = response.read()
if response.status == 200:
return json.loads(body)
else:
boto.log.error('%s %s' % (response.status, response.reason))
boto.log.error('%s' % body)
raise self.ResponseError(response.status, response.reason, body)
def remove_permission(self, topic, label):
"""
Removes a statement from a topic's access control policy.
:type topic: string
:param topic: The ARN of the topic.
:type label: string
:param label: A unique identifier for the policy statement
to be removed.
"""
params = {'ContentType' : 'JSON',
'TopicArn' : topic,
'Label' : label}
response = self.make_request('RemovePermission', params, '/', 'GET')
body = response.read()
if response.status == 200:
return json.loads(body)
else:
boto.log.error('%s %s' % (response.status, response.reason))
boto.log.error('%s' % body)
raise self.ResponseError(response.status, response.reason, body)
def create_topic(self, topic):
"""
Create a new Topic.
:type topic: string
:param topic: The name of the new topic.
"""
params = {'ContentType' : 'JSON',
'Name' : topic}
response = self.make_request('CreateTopic', params, '/', 'GET')
body = response.read()
if response.status == 200:
return json.loads(body)
else:
boto.log.error('%s %s' % (response.status, response.reason))
boto.log.error('%s' % body)
raise self.ResponseError(response.status, response.reason, body)
def delete_topic(self, topic):
"""
Delete an existing topic
:type topic: string
:param topic: The ARN of the topic
"""
params = {'ContentType' : 'JSON',
'TopicArn' : topic}
response = self.make_request('DeleteTopic', params, '/', 'GET')
body = response.read()
if response.status == 200:
return json.loads(body)
else:
boto.log.error('%s %s' % (response.status, response.reason))
boto.log.error('%s' % body)
raise self.ResponseError(response.status, response.reason, body)
def publish(self, topic, message, subject=None):
"""
Get properties of a Topic
:type topic: string
:param topic: The ARN of the new topic.
:type message: string
:param message: The message you want to send to the topic.
Messages must be UTF-8 encoded strings and
be at most 4KB in size.
:type subject: string
:param subject: Optional parameter to be used as the "Subject"
line of the email notifications.
"""
params = {'ContentType' : 'JSON',
'TopicArn' : topic,
'Message' : message}
if subject:
params['Subject'] = subject
response = self.make_request('Publish', params, '/', 'GET')
body = response.read()
if response.status == 200:
return json.loads(body)
else:
boto.log.error('%s %s' % (response.status, response.reason))
boto.log.error('%s' % body)
raise self.ResponseError(response.status, response.reason, body)
def subscribe(self, topic, protocol, endpoint):
"""
Subscribe to a Topic.
:type topic: string
:param topic: The name of the new topic.
:type protocol: string
:param protocol: The protocol used to communicate with
the subscriber. Current choices are:
email|email-json|http|https|sqs
:type endpoint: string
:param endpoint: The location of the endpoint for
the subscriber.
* For email, this would be a valid email address
* For email-json, this would be a valid email address
* For http, this would be a URL beginning with http
* For https, this would be a URL beginning with https
* For sqs, this would be the ARN of an SQS Queue
:rtype: :class:`boto.sdb.domain.Domain` object
:return: The newly created domain
"""
params = {'ContentType' : 'JSON',
'TopicArn' : topic,
'Protocol' : protocol,
'Endpoint' : endpoint}
response = self.make_request('Subscribe', params, '/', 'GET')
body = response.read()
if response.status == 200:
return json.loads(body)
else:
boto.log.error('%s %s' % (response.status, response.reason))
boto.log.error('%s' % body)
raise self.ResponseError(response.status, response.reason, body)
def subscribe_sqs_queue(self, topic, queue):
"""
Subscribe an SQS queue to a topic.
This is convenience method that handles most of the complexity involved
in using ans SQS queue as an endpoint for an SNS topic. To achieve this
the following operations are performed:
* The correct ARN is constructed for the SQS queue and that ARN is
then subscribed to the topic.
* A JSON policy document is contructed that grants permission to
the SNS topic to send messages to the SQS queue.
* This JSON policy is then associated with the SQS queue using
the queue's set_attribute method. If the queue already has
a policy associated with it, this process will add a Statement to
that policy. If no policy exists, a new policy will be created.
:type topic: string
:param topic: The name of the new topic.
:type queue: A boto Queue object
:param queue: The queue you wish to subscribe to the SNS Topic.
"""
t = queue.id.split('/')
q_arn = 'arn:aws:sqs:%s:%s:%s' % (queue.connection.region.name,
t[1], t[2])
resp = self.subscribe(topic, 'sqs', q_arn)
policy = queue.get_attributes('Policy')
if 'Version' not in policy:
policy['Version'] = '2008-10-17'
if 'Statement' not in policy:
policy['Statement'] = []
statement = {'Action' : 'SQS:SendMessage',
'Effect' : 'Allow',
'Principal' : {'AWS' : '*'},
'Resource' : q_arn,
'Sid' : str(uuid.uuid4()),
'Condition' : {'StringLike' : {'aws:SourceArn' : topic}}}
policy['Statement'].append(statement)
queue.set_attribute('Policy', json.dumps(policy))
return resp
def confirm_subscription(self, topic, token,
authenticate_on_unsubscribe=False):
"""
Get properties of a Topic
:type topic: string
:param topic: The ARN of the new topic.
:type token: string
:param token: Short-lived token sent to and endpoint during
the Subscribe operation.
:type authenticate_on_unsubscribe: bool
:param authenticate_on_unsubscribe: Optional parameter indicating
that you wish to disable
unauthenticated unsubscription
of the subscription.
"""
params = {'ContentType' : 'JSON',
'TopicArn' : topic,
'Token' : token}
if authenticate_on_unsubscribe:
params['AuthenticateOnUnsubscribe'] = 'true'
response = self.make_request('ConfirmSubscription', params, '/', 'GET')
body = response.read()
if response.status == 200:
return json.loads(body)
else:
boto.log.error('%s %s' % (response.status, response.reason))
boto.log.error('%s' % body)
raise self.ResponseError(response.status, response.reason, body)
def unsubscribe(self, subscription):
"""
Allows endpoint owner to delete subscription.
Confirmation message will be delivered.
:type subscription: string
:param subscription: The ARN of the subscription to be deleted.
"""
params = {'ContentType' : 'JSON',
'SubscriptionArn' : subscription}
response = self.make_request('Unsubscribe', params, '/', 'GET')
body = response.read()
if response.status == 200:
return json.loads(body)
else:
boto.log.error('%s %s' % (response.status, response.reason))
boto.log.error('%s' % body)
raise self.ResponseError(response.status, response.reason, body)
def get_all_subscriptions(self, next_token=None):
"""
Get list of all subscriptions.
:type next_token: string
:param next_token: Token returned by the previous call to
this method.
"""
params = {'ContentType' : 'JSON'}
if next_token:
params['NextToken'] = next_token
response = self.make_request('ListSubscriptions', params, '/', 'GET')
body = response.read()
if response.status == 200:
return json.loads(body)
else:
boto.log.error('%s %s' % (response.status, response.reason))
boto.log.error('%s' % body)
raise self.ResponseError(response.status, response.reason, body)
def get_all_subscriptions_by_topic(self, topic, next_token=None):
"""
Get list of all subscriptions to a specific topic.
:type topic: string
:param topic: The ARN of the topic for which you wish to
find subscriptions.
:type next_token: string
:param next_token: Token returned by the previous call to
this method.
"""
params = {'ContentType' : 'JSON',
'TopicArn' : topic}
if next_token:
params['NextToken'] = next_token
response = self.make_request('ListSubscriptions', params, '/', 'GET')
body = response.read()
if response.status == 200:
return json.loads(body)
else:
boto.log.error('%s %s' % (response.status, response.reason))
boto.log.error('%s' % body)
raise self.ResponseError(response.status, response.reason, body)
| Python |
# Copyright (c) 2006-2010 Mitch Garnaat http://garnaat.org/
# Copyright (c) 2010 Google
# Copyright (c) 2008 rPath, Inc.
# Copyright (c) 2009 The Echo Nest Corporation
# 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.
#
# Parts of this code were copied or derived from sample code supplied by AWS.
# The following notice applies to that code.
#
# This software code is made available "AS IS" without warranties of any
# kind. You may copy, display, modify and redistribute the software
# code either by itself or as incorporated into your code; provided that
# you do not remove any proprietary notices. Your use of this software
# code is at your own risk and you waive any claim against Amazon
# Digital Services, Inc. or its affiliates with respect to your use of
# this software code. (c) 2006 Amazon Digital Services, Inc. or its
# affiliates.
"""
Handles basic connections to AWS
"""
import base64
import hmac
import httplib
import socket, errno
import re
import sys
import time
import urllib, urlparse
import os
import xml.sax
import Queue
import boto
from boto.exception import AWSConnectionError, BotoClientError, BotoServerError
from boto.resultset import ResultSet
from boto.provider import Provider
import boto.utils
from boto import config, UserAgent, handler
#
# the following is necessary because of the incompatibilities
# between Python 2.4, 2.5, and 2.6 as well as the fact that some
# people running 2.4 have installed hashlib as a separate module
# this fix was provided by boto user mccormix.
# see: http://code.google.com/p/boto/issues/detail?id=172
# for more details.
#
try:
from hashlib import sha1 as sha
from hashlib import sha256 as sha256
if sys.version[:3] == "2.4":
# we are using an hmac that expects a .new() method.
class Faker:
def __init__(self, which):
self.which = which
self.digest_size = self.which().digest_size
def new(self, *args, **kwargs):
return self.which(*args, **kwargs)
sha = Faker(sha)
sha256 = Faker(sha256)
except ImportError:
import sha
sha256 = None
PORTS_BY_SECURITY = { True: 443, False: 80 }
class ConnectionPool:
def __init__(self, hosts, connections_per_host):
self._hosts = boto.utils.LRUCache(hosts)
self.connections_per_host = connections_per_host
def __getitem__(self, key):
if key not in self._hosts:
self._hosts[key] = Queue.Queue(self.connections_per_host)
return self._hosts[key]
def __repr__(self):
return 'ConnectionPool:%s' % ','.join(self._hosts._dict.keys())
class AWSAuthConnection(object):
def __init__(self, host, 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, path='/', provider='aws'):
"""
:type host: string
:param host: The host to make the connection to
:type aws_access_key_id: string
:param aws_access_key_id: AWS Access Key ID (provided by Amazon)
:type aws_secret_access_key: string
:param aws_secret_access_key: Secret Access Key (provided by Amazon)
:type is_secure: boolean
:param is_secure: Whether the connection is over SSL
:type https_connection_factory: list or tuple
:param https_connection_factory: A pair of an HTTP connection
factory and the exceptions to catch.
The factory should have a similar
interface to L{httplib.HTTPSConnection}.
:type proxy:
:param proxy:
:type proxy_port: int
:param proxy_port: The port to use when connecting over a proxy
:type proxy_user: string
:param proxy_user: The username to connect with on the proxy
:type proxy_pass: string
:param proxy_pass: The password to use when connection over a proxy.
:type port: integer
:param port: The port to use to connect
"""
self.num_retries = 5
# Override passed-in is_secure setting if value was defined in config.
if config.has_option('Boto', 'is_secure'):
is_secure = config.getboolean('Boto', 'is_secure')
self.is_secure = is_secure
self.handle_proxy(proxy, proxy_port, proxy_user, proxy_pass)
# define exceptions from httplib that we want to catch and retry
self.http_exceptions = (httplib.HTTPException, socket.error,
socket.gaierror)
# define values in socket exceptions we don't want to catch
self.socket_exception_values = (errno.EINTR,)
if https_connection_factory is not None:
self.https_connection_factory = https_connection_factory[0]
self.http_exceptions += https_connection_factory[1]
else:
self.https_connection_factory = None
if (is_secure):
self.protocol = 'https'
else:
self.protocol = 'http'
self.host = host
self.path = path
if debug:
self.debug = debug
else:
self.debug = config.getint('Boto', 'debug', debug)
if port:
self.port = port
else:
self.port = PORTS_BY_SECURITY[is_secure]
self.provider = Provider(provider,
aws_access_key_id,
aws_secret_access_key)
# allow config file to override default host
if self.provider.host:
self.host = self.provider.host
if self.secret_key is None:
raise BotoClientError('No credentials have been supplied')
# initialize an HMAC for signatures, make copies with each request
self.hmac = hmac.new(self.secret_key, digestmod=sha)
if sha256:
self.hmac_256 = hmac.new(self.secret_key, digestmod=sha256)
else:
self.hmac_256 = None
# cache up to 20 connections per host, up to 20 hosts
self._pool = ConnectionPool(20, 20)
self._connection = (self.server_name(), self.is_secure)
self._last_rs = None
def __repr__(self):
return '%s:%s' % (self.__class__.__name__, self.host)
def _cached_name(self, host, is_secure):
if host is None:
host = self.server_name()
cached_name = is_secure and 'https://' or 'http://'
cached_name += host
return cached_name
def connection(self):
return self.get_http_connection(*self._connection)
connection = property(connection)
def aws_access_key_id(self):
return self.provider.access_key
aws_access_key_id = property(aws_access_key_id)
gs_access_key_id = aws_access_key_id
access_key = aws_access_key_id
def aws_secret_access_key(self):
return self.provider.secret_key
aws_secret_access_key = property(aws_secret_access_key)
gs_secret_access_key = aws_secret_access_key
secret_key = aws_secret_access_key
def get_path(self, path='/'):
pos = path.find('?')
if pos >= 0:
params = path[pos:]
path = path[:pos]
else:
params = None
if path[-1] == '/':
need_trailing = True
else:
need_trailing = False
path_elements = self.path.split('/')
path_elements.extend(path.split('/'))
path_elements = [p for p in path_elements if p]
path = '/' + '/'.join(path_elements)
if path[-1] != '/' and need_trailing:
path += '/'
if params:
path = path + params
return path
def server_name(self, port=None):
if not port:
port = self.port
if port == 80:
signature_host = self.host
else:
# This unfortunate little hack can be attributed to
# a difference in the 2.6 version of httplib. In old
# versions, it would append ":443" to the hostname sent
# in the Host header and so we needed to make sure we
# did the same when calculating the V2 signature. In 2.6
# (and higher!)
# it no longer does that. Hence, this kludge.
if sys.version[:3] in ('2.6', '2.7') and port == 443:
signature_host = self.host
else:
signature_host = '%s:%d' % (self.host, port)
return signature_host
def handle_proxy(self, proxy, proxy_port, proxy_user, proxy_pass):
self.proxy = proxy
self.proxy_port = proxy_port
self.proxy_user = proxy_user
self.proxy_pass = proxy_pass
if os.environ.has_key('http_proxy') and not self.proxy:
pattern = re.compile(
'(?:http://)?' \
'(?:(?P<user>\w+):(?P<pass>.*)@)?' \
'(?P<host>[\w\-\.]+)' \
'(?::(?P<port>\d+))?'
)
match = pattern.match(os.environ['http_proxy'])
if match:
self.proxy = match.group('host')
self.proxy_port = match.group('port')
self.proxy_user = match.group('user')
self.proxy_pass = match.group('pass')
else:
if not self.proxy:
self.proxy = config.get_value('Boto', 'proxy', None)
if not self.proxy_port:
self.proxy_port = config.get_value('Boto', 'proxy_port', None)
if not self.proxy_user:
self.proxy_user = config.get_value('Boto', 'proxy_user', None)
if not self.proxy_pass:
self.proxy_pass = config.get_value('Boto', 'proxy_pass', None)
if not self.proxy_port and self.proxy:
print "http_proxy environment variable does not specify " \
"a port, using default"
self.proxy_port = self.port
self.use_proxy = (self.proxy != None)
def get_http_connection(self, host, is_secure):
queue = self._pool[self._cached_name(host, is_secure)]
try:
return queue.get_nowait()
except Queue.Empty:
return self.new_http_connection(host, is_secure)
def new_http_connection(self, host, is_secure):
if self.use_proxy:
host = '%s:%d' % (self.proxy, int(self.proxy_port))
if host is None:
host = self.server_name()
boto.log.debug('establishing HTTP connection')
if is_secure:
if self.use_proxy:
connection = self.proxy_ssl()
elif self.https_connection_factory:
connection = self.https_connection_factory(host)
else:
connection = httplib.HTTPSConnection(host)
else:
connection = httplib.HTTPConnection(host)
if self.debug > 1:
connection.set_debuglevel(self.debug)
# self.connection must be maintained for backwards-compatibility
# however, it must be dynamically pulled from the connection pool
# set a private variable which will enable that
if host.split(':')[0] == self.host and is_secure == self.is_secure:
self._connection = (host, is_secure)
return connection
def put_http_connection(self, host, is_secure, connection):
try:
self._pool[self._cached_name(host, is_secure)].put_nowait(connection)
except Queue.Full:
# gracefully fail in case of pool overflow
connection.close()
def proxy_ssl(self):
host = '%s:%d' % (self.host, self.port)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.connect((self.proxy, int(self.proxy_port)))
except:
raise
sock.sendall("CONNECT %s HTTP/1.0\r\n" % host)
sock.sendall("User-Agent: %s\r\n" % UserAgent)
if self.proxy_user and self.proxy_pass:
for k, v in self.get_proxy_auth_header().items():
sock.sendall("%s: %s\r\n" % (k, v))
sock.sendall("\r\n")
resp = httplib.HTTPResponse(sock, strict=True)
resp.begin()
if resp.status != 200:
# Fake a socket error, use a code that make it obvious it hasn't
# been generated by the socket library
raise socket.error(-71,
"Error talking to HTTP proxy %s:%s: %s (%s)" %
(self.proxy, self.proxy_port, resp.status, resp.reason))
# We can safely close the response, it duped the original socket
resp.close()
h = httplib.HTTPConnection(host)
# Wrap the socket in an SSL socket
if hasattr(httplib, 'ssl'):
sslSock = httplib.ssl.SSLSocket(sock)
else: # Old Python, no ssl module
sslSock = socket.ssl(sock, None, None)
sslSock = httplib.FakeSocket(sock, sslSock)
# This is a bit unclean
h.sock = sslSock
return h
def prefix_proxy_to_path(self, path, host=None):
path = self.protocol + '://' + (host or self.server_name()) + path
return path
def get_proxy_auth_header(self):
auth = base64.encodestring(self.proxy_user+':'+self.proxy_pass)
return {'Proxy-Authorization': 'Basic %s' % auth}
def _mexe(self, method, path, data, headers, host=None, sender=None,
override_num_retries=None):
"""
mexe - Multi-execute inside a loop, retrying multiple times to handle
transient Internet errors by simply trying again.
Also handles redirects.
This code was inspired by the S3Utils classes posted to the boto-users
Google group by Larry Bates. Thanks!
"""
boto.log.debug('Method: %s' % method)
boto.log.debug('Path: %s' % path)
boto.log.debug('Data: %s' % data)
boto.log.debug('Headers: %s' % headers)
boto.log.debug('Host: %s' % host)
response = None
body = None
e = None
if override_num_retries is None:
num_retries = config.getint('Boto', 'num_retries', self.num_retries)
else:
num_retries = override_num_retries
i = 0
connection = self.get_http_connection(host, self.is_secure)
while i <= num_retries:
try:
if callable(sender):
response = sender(connection, method, path, data, headers)
else:
connection.request(method, path, data, headers)
response = connection.getresponse()
location = response.getheader('location')
# -- gross hack --
# httplib gets confused with chunked responses to HEAD requests
# so I have to fake it out
if method == 'HEAD' and getattr(response, 'chunked', False):
response.chunked = 0
if response.status == 500 or response.status == 503:
boto.log.debug('received %d response, retrying in %d seconds' % (response.status, 2**i))
body = response.read()
elif response.status == 408:
body = response.read()
print '-------------------------'
print ' 4 0 8 '
print 'path=%s' % path
print body
print '-------------------------'
elif response.status < 300 or response.status >= 400 or \
not location:
self.put_http_connection(host, self.is_secure, connection)
return response
else:
scheme, host, path, params, query, fragment = \
urlparse.urlparse(location)
if query:
path += '?' + query
boto.log.debug('Redirecting: %s' % scheme + '://' + host + path)
connection = self.get_http_connection(host,
scheme == 'https')
continue
except KeyboardInterrupt:
sys.exit('Keyboard Interrupt')
except self.http_exceptions, e:
boto.log.debug('encountered %s exception, reconnecting' % \
e.__class__.__name__)
connection = self.new_http_connection(host, self.is_secure)
time.sleep(2**i)
i += 1
# If we made it here, it's because we have exhausted our retries and stil haven't
# succeeded. So, if we have a response object, use it to raise an exception.
# Otherwise, raise the exception that must have already happened.
if response:
raise BotoServerError(response.status, response.reason, body)
elif e:
raise e
else:
raise BotoClientError('Please report this exception as a Boto Issue!')
def build_request(self, method, path, headers=None, data='', host=None,
auth_path=None):
"""Builds a request that can be sent for multiple retries."""
path = self.get_path(path)
if headers == None:
headers = {}
else:
headers = headers.copy()
headers['User-Agent'] = UserAgent
if not headers.has_key('Content-Length'):
headers['Content-Length'] = str(len(data))
if self.use_proxy:
path = self.prefix_proxy_to_path(path, host)
if self.proxy_user and self.proxy_pass and not self.is_secure:
# If is_secure, we don't have to set the proxy authentication
# header here, we did that in the CONNECT to the proxy.
headers.update(self.get_proxy_auth_header())
request_string = auth_path or path
for key in headers:
val = headers[key]
if isinstance(val, unicode):
headers[key] = urllib.quote_plus(val.encode('utf-8'))
self.add_aws_auth_header(headers, method, request_string)
return (path, headers)
def make_request(self, method, path, headers=None, data='', host=None,
auth_path=None, sender=None, override_num_retries=None):
"""Makes a request to the server, with stock multiple-retry logic."""
(path, headers) = self.build_request(method, path, headers, data, host,
auth_path)
return self._mexe(method, path, data, headers, host, sender,
override_num_retries)
def add_aws_auth_header(self, headers, method, path):
path = self.get_path(path)
if not headers.has_key('Date'):
headers['Date'] = time.strftime("%a, %d %b %Y %H:%M:%S GMT",
time.gmtime())
c_string = boto.utils.canonical_string(method, path, headers,
None, self.provider)
boto.log.debug('Canonical: %s' % c_string)
hmac = self.hmac.copy()
hmac.update(c_string)
b64_hmac = base64.encodestring(hmac.digest()).strip()
auth_hdr = self.provider.auth_header
headers['Authorization'] = ("%s %s:%s" %
(auth_hdr,
self.aws_access_key_id, b64_hmac))
def close(self):
"""(Optional) Close any open HTTP connections. This is non-destructive,
and making a new request will open a connection again."""
boto.log.debug('closing all HTTP connections')
self.connection = None # compat field
class AWSQueryConnection(AWSAuthConnection):
APIVersion = ''
SignatureVersion = '1'
ResponseError = BotoServerError
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=None, debug=0,
https_connection_factory=None, path='/'):
AWSAuthConnection.__init__(self, host, aws_access_key_id, aws_secret_access_key,
is_secure, port, proxy, proxy_port, proxy_user, proxy_pass,
debug, https_connection_factory, path)
def get_utf8_value(self, value):
if not isinstance(value, str) and not isinstance(value, unicode):
value = str(value)
if isinstance(value, unicode):
return value.encode('utf-8')
else:
return value
def calc_signature_0(self, params):
boto.log.debug('using calc_signature_0')
hmac = self.hmac.copy()
s = params['Action'] + params['Timestamp']
hmac.update(s)
keys = params.keys()
keys.sort(cmp = lambda x, y: cmp(x.lower(), y.lower()))
pairs = []
for key in keys:
val = self.get_utf8_value(params[key])
pairs.append(key + '=' + urllib.quote(val))
qs = '&'.join(pairs)
return (qs, base64.b64encode(hmac.digest()))
def calc_signature_1(self, params):
boto.log.debug('using calc_signature_1')
hmac = self.hmac.copy()
keys = params.keys()
keys.sort(cmp = lambda x, y: cmp(x.lower(), y.lower()))
pairs = []
for key in keys:
hmac.update(key)
val = self.get_utf8_value(params[key])
hmac.update(val)
pairs.append(key + '=' + urllib.quote(val))
qs = '&'.join(pairs)
return (qs, base64.b64encode(hmac.digest()))
def calc_signature_2(self, params, verb, path):
boto.log.debug('using calc_signature_2')
string_to_sign = '%s\n%s\n%s\n' % (verb, self.server_name().lower(), path)
if self.hmac_256:
hmac = self.hmac_256.copy()
params['SignatureMethod'] = 'HmacSHA256'
else:
hmac = self.hmac.copy()
params['SignatureMethod'] = 'HmacSHA1'
keys = params.keys()
keys.sort()
pairs = []
for key in keys:
val = self.get_utf8_value(params[key])
pairs.append(urllib.quote(key, safe='') + '=' + urllib.quote(val, safe='-_~'))
qs = '&'.join(pairs)
boto.log.debug('query string: %s' % qs)
string_to_sign += qs
boto.log.debug('string_to_sign: %s' % string_to_sign)
hmac.update(string_to_sign)
b64 = base64.b64encode(hmac.digest())
boto.log.debug('len(b64)=%d' % len(b64))
boto.log.debug('base64 encoded digest: %s' % b64)
return (qs, b64)
def get_signature(self, params, verb, path):
if self.SignatureVersion == '0':
t = self.calc_signature_0(params)
elif self.SignatureVersion == '1':
t = self.calc_signature_1(params)
elif self.SignatureVersion == '2':
t = self.calc_signature_2(params, verb, path)
else:
raise BotoClientError('Unknown Signature Version: %s' % self.SignatureVersion)
return t
def make_request(self, action, params=None, path='/', verb='GET'):
headers = {}
if params == None:
params = {}
params['Action'] = action
params['Version'] = self.APIVersion
params['AWSAccessKeyId'] = self.aws_access_key_id
params['SignatureVersion'] = self.SignatureVersion
params['Timestamp'] = time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime())
qs, signature = self.get_signature(params, verb, self.get_path(path))
if verb == 'POST':
headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
request_body = qs + '&Signature=' + urllib.quote(signature)
qs = path
else:
request_body = ''
qs = path + '?' + qs + '&Signature=' + urllib.quote(signature)
return AWSAuthConnection.make_request(self, verb, qs,
data=request_body,
headers=headers)
def build_list_params(self, params, items, label):
if isinstance(items, str):
items = [items]
for i in range(1, len(items)+1):
params['%s.%d' % (label, i)] = items[i-1]
# generics
def get_list(self, action, params, markers, path='/', parent=None, verb='GET'):
if not parent:
parent = self
response = self.make_request(action, params, path, verb)
body = response.read()
boto.log.debug(body)
if response.status == 200:
rs = ResultSet(markers)
h = handler.XmlHandler(rs, parent)
xml.sax.parseString(body, h)
return rs
else:
boto.log.error('%s %s' % (response.status, response.reason))
boto.log.error('%s' % body)
raise self.ResponseError(response.status, response.reason, body)
def get_object(self, action, params, cls, path='/', parent=None, verb='GET'):
if not parent:
parent = self
response = self.make_request(action, params, path, verb)
body = response.read()
boto.log.debug(body)
if response.status == 200:
obj = cls(parent)
h = handler.XmlHandler(obj, parent)
xml.sax.parseString(body, h)
return obj
else:
boto.log.error('%s %s' % (response.status, response.reason))
boto.log.error('%s' % body)
raise self.ResponseError(response.status, response.reason, body)
def get_status(self, action, params, path='/', parent=None, verb='GET'):
if not parent:
parent = self
response = self.make_request(action, params, path, verb)
body = response.read()
boto.log.debug(body)
if response.status == 200:
rs = ResultSet()
h = handler.XmlHandler(rs, parent)
xml.sax.parseString(body, h)
return rs.status
else:
boto.log.error('%s %s' % (response.status, response.reason))
boto.log.error('%s' % body)
raise self.ResponseError(response.status, response.reason, body)
| 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 SimpleResultSet(list):
"""
ResultSet facade built from a simple list, rather than via XML parsing.
"""
def __init__(self, input_list):
for x in input_list:
self.append(x)
self.is_truncated = False
| 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.
# File representation of key, for use with "file://" URIs.
import os, shutil, StringIO
class Key(object):
def __init__(self, bucket, name, fp=None):
self.bucket = bucket
self.full_path = name
self.name = name
self.fp = fp
def __str__(self):
return 'file://' + self.full_path
def get_file(self, fp, headers=None, cb=None, num_cb=10, torrent=False):
"""
Retrieves a file from a Key
:type fp: file
:param fp: File pointer to put the data into
:type headers: string
:param: ignored in this subclass.
:type cb: function
:param cb: ignored in this subclass.
:type cb: int
:param num_cb ignored in this subclass.
:type torrent: bool
:param torrent: ignored in this subclass.
"""
key_file = open(self.full_path, 'rb')
shutil.copyfileobj(key_file, fp)
def set_contents_from_file(self, fp, headers=None, replace=True, cb=None,
num_cb=10, policy=None, md5=None):
"""
Store an object in a file using the name of the Key object as the
key in file URI and the contents of the file pointed to by 'fp' as the
contents.
:type fp: file
:param fp: the file whose contents to upload
:type headers: dict
:param headers: ignored in this subclass.
: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: ignored in this subclass.
:type cb: int
:param num_cb: ignored in this subclass.
:type policy: :class:`boto.s3.acl.CannedACLStrings`
:param policy: ignored in this subclass.
: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: ignored in this subclass.
"""
if not replace and os.path.exists(self.full_path):
return
key_file = open(self.full_path, 'wb')
shutil.copyfileobj(fp, key_file)
key_file.close()
def get_contents_as_string(self, headers=None, cb=None, num_cb=10,
torrent=False):
"""
Retrieve file data from thie Key, and return contents as a string.
:type headers: dict
:param headers: ignored in this subclass.
:type cb: function
:param cb: ignored in this subclass.
:type cb: int
:param num_cb: ignored in this subclass.
:type cb: int
:param num_cb: ignored in this subclass.
:type torrent: bool
:param torrent: ignored in this subclass.
:rtype: string
:returns: The contents of the file as a string
"""
fp = StringIO.StringIO()
self.get_contents_to_file(fp)
return fp.getvalue()
| 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.
# File representation of connection, for use with "file://" URIs.
from bucket import Bucket
class FileConnection(object):
def __init__(self, file_storage_uri):
# FileConnections are per-file storage URI.
self.file_storage_uri = file_storage_uri
def get_bucket(self, bucket_name, validate=True, headers=None):
return Bucket(bucket_name, self.file_storage_uri.object_name)
| 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 connection import FileConnection as Connection
from key import Key
from bucket import Bucket
__all__ = ['Connection', 'Key', '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.
# File representation of bucket, for use with "file://" URIs.
import os
from key import Key
from boto.file.simpleresultset import SimpleResultSet
from boto.s3.bucketlistresultset import BucketListResultSet
class Bucket(object):
def __init__(self, name, contained_key):
"""Instantiate an anonymous file-based Bucket around a single key.
"""
self.name = name
self.contained_key = contained_key
def __iter__(self):
return iter(BucketListResultSet(self))
def __str__(self):
return 'anonymous bucket for file://' + self.contained_key
def delete_key(self, key_name, headers=None,
version_id=None, mfa_token=None):
"""
Deletes a key from the bucket.
:type key_name: string
:param key_name: The key name to delete
:type version_id: string
:param version_id: Unused in this subclass.
:type mfa_token: tuple or list of strings
:param mfa_token: Unused in this subclass.
"""
os.remove(key_name)
def get_all_keys(self, headers=None, **params):
"""
This method returns the single key around which this anonymous Bucket
was instantiated.
:rtype: SimpleResultSet
:return: The result from file system listing the keys requested
"""
key = Key(self.name, self.contained_key)
return SimpleResultSet([key])
def get_key(self, key_name, headers=None, version_id=None):
"""
Check to see if a particular key exists within the bucket.
Returns: An instance of a Key object or None
:type key_name: string
:param key_name: The name of the key to retrieve
:type version_id: string
:param version_id: Unused in this subclass.
:rtype: :class:`boto.file.key.Key`
:returns: A Key object from this bucket.
"""
fp = open(key_name, 'rb')
return Key(self.name, key_name, fp)
def new_key(self, key_name=None):
"""
Creates a new key
:type key_name: string
:param key_name: The name of the key to create
:rtype: :class:`boto.file.key.Key`
:returns: An instance of the newly created key object
"""
dir_name = os.path.dirname(key_name)
if dir_name and not os.path.exists(dir_name):
os.makedirs(dir_name)
fp = open(key_name, 'wb')
return Key(self.name, key_name, fp)
| 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.
"""
Exception classes - Subclassing allows you to check for specific errors
"""
import base64
import xml.sax
from boto import handler
from boto.resultset import ResultSet
class BotoClientError(StandardError):
"""
General Boto Client error (error accessing AWS)
"""
def __init__(self, reason):
StandardError.__init__(self)
self.reason = reason
def __repr__(self):
return 'BotoClientError: %s' % self.reason
def __str__(self):
return 'BotoClientError: %s' % self.reason
class SDBPersistenceError(StandardError):
pass
class StoragePermissionsError(BotoClientError):
"""
Permissions error when accessing a bucket or key on a storage service.
"""
pass
class S3PermissionsError(StoragePermissionsError):
"""
Permissions error when accessing a bucket or key on S3.
"""
pass
class GSPermissionsError(StoragePermissionsError):
"""
Permissions error when accessing a bucket or key on GS.
"""
pass
class BotoServerError(StandardError):
def __init__(self, status, reason, body=None):
StandardError.__init__(self)
self.status = status
self.reason = reason
self.body = body or ''
self.request_id = None
self.error_code = None
self.error_message = None
self.box_usage = None
# Attempt to parse the error response. If body isn't present,
# then just ignore the error response.
if self.body:
try:
h = handler.XmlHandler(self, self)
xml.sax.parseString(self.body, h)
except xml.sax.SAXParseException, pe:
# Go ahead and clean up anything that may have
# managed to get into the error data so we
# don't get partial garbage.
print "Warning: failed to parse error message from AWS: %s" % pe
self._cleanupParsedProperties()
def __getattr__(self, name):
if name == 'message':
return self.error_message
if name == 'code':
return self.error_code
raise AttributeError
def __repr__(self):
return '%s: %s %s\n%s' % (self.__class__.__name__,
self.status, self.reason, self.body)
def __str__(self):
return '%s: %s %s\n%s' % (self.__class__.__name__,
self.status, self.reason, self.body)
def startElement(self, name, attrs, connection):
pass
def endElement(self, name, value, connection):
if name in ('RequestId', 'RequestID'):
self.request_id = value
elif name == 'Code':
self.error_code = value
elif name == 'Message':
self.error_message = value
elif name == 'BoxUsage':
self.box_usage = value
return None
def _cleanupParsedProperties(self):
self.request_id = None
self.error_code = None
self.error_message = None
self.box_usage = None
class ConsoleOutput:
def __init__(self, parent=None):
self.parent = parent
self.instance_id = None
self.timestamp = None
self.comment = None
self.output = 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 StorageCreateError(BotoServerError):
"""
Error creating a bucket or key on a storage service.
"""
def __init__(self, status, reason, body=None):
self.bucket = None
BotoServerError.__init__(self, status, reason, body)
def endElement(self, name, value, connection):
if name == 'BucketName':
self.bucket = value
else:
return BotoServerError.endElement(self, name, value, connection)
class S3CreateError(StorageCreateError):
"""
Error creating a bucket or key on S3.
"""
pass
class GSCreateError(StorageCreateError):
"""
Error creating a bucket or key on GS.
"""
pass
class StorageCopyError(BotoServerError):
"""
Error copying a key on a storage service.
"""
pass
class S3CopyError(StorageCopyError):
"""
Error copying a key on S3.
"""
pass
class GSCopyError(StorageCopyError):
"""
Error copying a key on GS.
"""
pass
class SQSError(BotoServerError):
"""
General Error on Simple Queue Service.
"""
def __init__(self, status, reason, body=None):
self.detail = None
self.type = None
BotoServerError.__init__(self, status, reason, body)
def startElement(self, name, attrs, connection):
return BotoServerError.startElement(self, name, attrs, connection)
def endElement(self, name, value, connection):
if name == 'Detail':
self.detail = value
elif name == 'Type':
self.type = value
else:
return BotoServerError.endElement(self, name, value, connection)
def _cleanupParsedProperties(self):
BotoServerError._cleanupParsedProperties(self)
for p in ('detail', 'type'):
setattr(self, p, None)
class SQSDecodeError(BotoClientError):
"""
Error when decoding an SQS message.
"""
def __init__(self, reason, message):
BotoClientError.__init__(self, reason)
self.message = message
def __repr__(self):
return 'SQSDecodeError: %s' % self.reason
def __str__(self):
return 'SQSDecodeError: %s' % self.reason
class StorageResponseError(BotoServerError):
"""
Error in response from a storage service.
"""
def __init__(self, status, reason, body=None):
self.resource = None
BotoServerError.__init__(self, status, reason, body)
def startElement(self, name, attrs, connection):
return BotoServerError.startElement(self, name, attrs, connection)
def endElement(self, name, value, connection):
if name == 'Resource':
self.resource = value
else:
return BotoServerError.endElement(self, name, value, connection)
def _cleanupParsedProperties(self):
BotoServerError._cleanupParsedProperties(self)
for p in ('resource'):
setattr(self, p, None)
class S3ResponseError(StorageResponseError):
"""
Error in response from S3.
"""
pass
class GSResponseError(StorageResponseError):
"""
Error in response from GS.
"""
pass
class EC2ResponseError(BotoServerError):
"""
Error in response from EC2.
"""
def __init__(self, status, reason, body=None):
self.errors = None
self._errorResultSet = []
BotoServerError.__init__(self, status, reason, body)
self.errors = [ (e.error_code, e.error_message) \
for e in self._errorResultSet ]
if len(self.errors):
self.error_code, self.error_message = self.errors[0]
def startElement(self, name, attrs, connection):
if name == 'Errors':
self._errorResultSet = ResultSet([('Error', _EC2Error)])
return self._errorResultSet
else:
return None
def endElement(self, name, value, connection):
if name == 'RequestID':
self.request_id = value
else:
return None # don't call subclass here
def _cleanupParsedProperties(self):
BotoServerError._cleanupParsedProperties(self)
self._errorResultSet = []
for p in ('errors'):
setattr(self, p, None)
class EmrResponseError(BotoServerError):
"""
Error in response from EMR
"""
pass
class _EC2Error:
def __init__(self, connection=None):
self.connection = connection
self.error_code = None
self.error_message = None
def startElement(self, name, attrs, connection):
return None
def endElement(self, name, value, connection):
if name == 'Code':
self.error_code = value
elif name == 'Message':
self.error_message = value
else:
return None
class SDBResponseError(BotoServerError):
"""
Error in respones from SDB.
"""
pass
class AWSConnectionError(BotoClientError):
"""
General error connecting to Amazon Web Services.
"""
pass
class StorageDataError(BotoClientError):
"""
Error receiving data from a storage service.
"""
pass
class S3DataError(StorageDataError):
"""
Error receiving data from S3.
"""
pass
class GSDataError(StorageDataError):
"""
Error receiving data from GS.
"""
pass
class FPSResponseError(BotoServerError):
pass
class InvalidUriError(Exception):
"""Exception raised when URI is invalid."""
def __init__(self, message):
Exception.__init__(self)
self.message = message
class InvalidAclError(Exception):
"""Exception raised when ACL XML is invalid."""
def __init__(self, message):
Exception.__init__(self)
self.message = message
# Enum class for resumable upload failure disposition.
class ResumableTransferDisposition(object):
# START_OVER means an attempt to resume an existing transfer failed,
# and a new resumable upload should be attempted (without delay).
START_OVER = 'START_OVER'
# WAIT_BEFORE_RETRY means the resumable transfer failed but that it can
# be retried after a time delay.
WAIT_BEFORE_RETRY = 'WAIT_BEFORE_RETRY'
# ABORT means the resumable transfer failed and that delaying/retrying
# within the current process will not help.
ABORT = 'ABORT'
class ResumableUploadException(Exception):
"""
Exception raised for various resumable upload problems.
self.disposition is of type ResumableTransferDisposition.
"""
def __init__(self, message, disposition):
Exception.__init__(self)
self.message = message
self.disposition = disposition
def __repr__(self):
return 'ResumableUploadException("%s", %s)' % (
self.message, self.disposition)
class ResumableDownloadException(Exception):
"""
Exception raised for various resumable download problems.
self.disposition is of type ResumableTransferDisposition.
"""
def __init__(self, message, disposition):
Exception.__init__(self)
self.message = message
self.disposition = disposition
def __repr__(self):
return 'ResumableDownloadException("%s", %s)' % (
self.message, self.disposition)
| 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 ResultSet(list):
"""
The ResultSet is used to pass results back from the Amazon services
to the client. It has an ugly but workable mechanism for parsing
the XML results from AWS. Because I don't really want any dependencies
on external libraries, I'm using the standard SAX parser that comes
with Python. The good news is that it's quite fast and efficient but
it makes some things rather difficult.
You can pass in, as the marker_elem parameter, a list of tuples.
Each tuple contains a string as the first element which represents
the XML element that the resultset needs to be on the lookout for
and a Python class as the second element of the tuple. Each time the
specified element is found in the XML, a new instance of the class
will be created and popped onto the stack.
"""
def __init__(self, marker_elem=None):
list.__init__(self)
if isinstance(marker_elem, list):
self.markers = marker_elem
else:
self.markers = []
self.marker = None
self.key_marker = None
self.next_key_marker = None
self.next_version_id_marker = None
self.version_id_marker = None
self.is_truncated = False
self.next_token = None
self.status = True
def startElement(self, name, attrs, connection):
for t in self.markers:
if name == t[0]:
obj = t[1](connection)
self.append(obj)
return obj
return None
def to_boolean(self, value, true_value='true'):
if value == true_value:
return True
else:
return False
def endElement(self, name, value, connection):
if name == 'IsTruncated':
self.is_truncated = self.to_boolean(value)
elif name == 'Marker':
self.marker = value
elif name == 'KeyMarker':
self.key_marker = value
elif name == 'VersionIdMarker':
self.version_id_marker = value
elif name == 'NextKeyMarker':
self.next_key_marker = value
elif name == 'NextVersionIdMarker':
self.next_version_id_marker = value
elif name == 'Prefix':
self.prefix = value
elif name == 'return':
self.status = self.to_boolean(value)
elif name == 'StatusCode':
self.status = self.to_boolean(value, 'Success')
elif name == 'ItemName':
self.append(value)
elif name == 'NextToken':
self.next_token = value
elif name == 'BoxUsage':
try:
connection.box_usage += float(value)
except:
pass
elif name == 'IsValid':
self.status = self.to_boolean(value, 'True')
else:
setattr(self, name, value)
class BooleanResult(object):
def __init__(self, marker_elem=None):
self.status = True
self.request_id = None
self.box_usage = None
def __repr__(self):
if self.status:
return 'True'
else:
return 'False'
def __nonzero__(self):
return self.status
def startElement(self, name, attrs, connection):
return None
def to_boolean(self, value, true_value='true'):
if value == true_value:
return True
else:
return False
def endElement(self, name, value, connection):
if name == 'return':
self.status = self.to_boolean(value)
elif name == 'StatusCode':
self.status = self.to_boolean(value, 'Success')
elif name == 'IsValid':
self.status = self.to_boolean(value, 'True')
elif name == 'RequestId':
self.request_id = value
elif name == 'requestId':
self.request_id = value
elif name == 'BoxUsage':
self.request_id = value
else:
setattr(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.
"""
High-level abstraction of an EC2 order for servers
"""
import boto
import boto.ec2
from boto.mashups.server import Server, ServerSet
from boto.mashups.iobject import IObject
from boto.pyami.config import Config
from boto.sdb.persist import get_domain, set_domain
import time, StringIO
InstanceTypes = ['m1.small', 'm1.large', 'm1.xlarge', 'c1.medium', 'c1.xlarge']
class Item(IObject):
def __init__(self):
self.region = None
self.name = None
self.instance_type = None
self.quantity = 0
self.zone = None
self.ami = None
self.groups = []
self.key = None
self.ec2 = None
self.config = None
def set_userdata(self, key, value):
self.userdata[key] = value
def get_userdata(self, key):
return self.userdata[key]
def set_region(self, region=None):
if region:
self.region = region
else:
l = [(r, r.name, r.endpoint) for r in boto.ec2.regions()]
self.region = self.choose_from_list(l, prompt='Choose Region')
def set_name(self, name=None):
if name:
self.name = name
else:
self.name = self.get_string('Name')
def set_instance_type(self, instance_type=None):
if instance_type:
self.instance_type = instance_type
else:
self.instance_type = self.choose_from_list(InstanceTypes, 'Instance Type')
def set_quantity(self, n=0):
if n > 0:
self.quantity = n
else:
self.quantity = self.get_int('Quantity')
def set_zone(self, zone=None):
if zone:
self.zone = zone
else:
l = [(z, z.name, z.state) for z in self.ec2.get_all_zones()]
self.zone = self.choose_from_list(l, prompt='Choose Availability Zone')
def set_ami(self, ami=None):
if ami:
self.ami = ami
else:
l = [(a, a.id, a.location) for a in self.ec2.get_all_images()]
self.ami = self.choose_from_list(l, prompt='Choose AMI')
def add_group(self, group=None):
if group:
self.groups.append(group)
else:
l = [(s, s.name, s.description) for s in self.ec2.get_all_security_groups()]
self.groups.append(self.choose_from_list(l, prompt='Choose Security Group'))
def set_key(self, key=None):
if key:
self.key = key
else:
l = [(k, k.name, '') for k in self.ec2.get_all_key_pairs()]
self.key = self.choose_from_list(l, prompt='Choose Keypair')
def update_config(self):
if not self.config.has_section('Credentials'):
self.config.add_section('Credentials')
self.config.set('Credentials', 'aws_access_key_id', self.ec2.aws_access_key_id)
self.config.set('Credentials', 'aws_secret_access_key', self.ec2.aws_secret_access_key)
if not self.config.has_section('Pyami'):
self.config.add_section('Pyami')
sdb_domain = get_domain()
if sdb_domain:
self.config.set('Pyami', 'server_sdb_domain', sdb_domain)
self.config.set('Pyami', 'server_sdb_name', self.name)
def set_config(self, config_path=None):
if not config_path:
config_path = self.get_filename('Specify Config file')
self.config = Config(path=config_path)
def get_userdata_string(self):
s = StringIO.StringIO()
self.config.write(s)
return s.getvalue()
def enter(self, **params):
self.region = params.get('region', self.region)
if not self.region:
self.set_region()
self.ec2 = self.region.connect()
self.name = params.get('name', self.name)
if not self.name:
self.set_name()
self.instance_type = params.get('instance_type', self.instance_type)
if not self.instance_type:
self.set_instance_type()
self.zone = params.get('zone', self.zone)
if not self.zone:
self.set_zone()
self.quantity = params.get('quantity', self.quantity)
if not self.quantity:
self.set_quantity()
self.ami = params.get('ami', self.ami)
if not self.ami:
self.set_ami()
self.groups = params.get('groups', self.groups)
if not self.groups:
self.add_group()
self.key = params.get('key', self.key)
if not self.key:
self.set_key()
self.config = params.get('config', self.config)
if not self.config:
self.set_config()
self.update_config()
class Order(IObject):
def __init__(self):
self.items = []
self.reservation = None
def add_item(self, **params):
item = Item()
item.enter(**params)
self.items.append(item)
def display(self):
print 'This Order consists of the following items'
print
print 'QTY\tNAME\tTYPE\nAMI\t\tGroups\t\t\tKeyPair'
for item in self.items:
print '%s\t%s\t%s\t%s\t%s\t%s' % (item.quantity, item.name, item.instance_type,
item.ami.id, item.groups, item.key.name)
def place(self, block=True):
if get_domain() == None:
print 'SDB Persistence Domain not set'
domain_name = self.get_string('Specify SDB Domain')
set_domain(domain_name)
s = ServerSet()
for item in self.items:
r = item.ami.run(min_count=1, max_count=item.quantity,
key_name=item.key.name, user_data=item.get_userdata_string(),
security_groups=item.groups, instance_type=item.instance_type,
placement=item.zone.name)
if block:
states = [i.state for i in r.instances]
if states.count('running') != len(states):
print states
time.sleep(15)
states = [i.update() for i in r.instances]
for i in r.instances:
server = Server()
server.name = item.name
server.instance_id = i.id
server.reservation = r
server.save()
s.append(server)
if len(s) == 1:
return s[0]
else:
return s
| 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.
"""
High-level abstraction of an EC2 server
"""
import boto
import boto.utils
from boto.mashups.iobject import IObject
from boto.pyami.config import Config, BotoConfigPath
from boto.mashups.interactive import interactive_shell
from boto.sdb.db.model import Model
from boto.sdb.db.property import StringProperty
import os
import StringIO
class ServerSet(list):
def __getattr__(self, name):
results = []
is_callable = False
for server in self:
try:
val = getattr(server, name)
if callable(val):
is_callable = True
results.append(val)
except:
results.append(None)
if is_callable:
self.map_list = results
return self.map
return results
def map(self, *args):
results = []
for fn in self.map_list:
results.append(fn(*args))
return results
class Server(Model):
@property
def ec2(self):
if self._ec2 is None:
self._ec2 = boto.connect_ec2()
return self._ec2
@classmethod
def Inventory(cls):
"""
Returns a list of Server instances, one for each Server object
persisted in the db
"""
l = ServerSet()
rs = cls.find()
for server in rs:
l.append(server)
return l
@classmethod
def Register(cls, name, instance_id, description=''):
s = cls()
s.name = name
s.instance_id = instance_id
s.description = description
s.save()
return s
def __init__(self, id=None, **kw):
Model.__init__(self, id, **kw)
self._reservation = None
self._instance = None
self._ssh_client = None
self._pkey = None
self._config = None
self._ec2 = None
name = StringProperty(unique=True, verbose_name="Name")
instance_id = StringProperty(verbose_name="Instance ID")
config_uri = StringProperty()
ami_id = StringProperty(verbose_name="AMI ID")
zone = StringProperty(verbose_name="Availability Zone")
security_group = StringProperty(verbose_name="Security Group", default="default")
key_name = StringProperty(verbose_name="Key Name")
elastic_ip = StringProperty(verbose_name="Elastic IP")
instance_type = StringProperty(verbose_name="Instance Type")
description = StringProperty(verbose_name="Description")
log = StringProperty()
def setReadOnly(self, value):
raise AttributeError
def getInstance(self):
if not self._instance:
if self.instance_id:
try:
rs = self.ec2.get_all_instances([self.instance_id])
except:
return None
if len(rs) > 0:
self._reservation = rs[0]
self._instance = self._reservation.instances[0]
return self._instance
instance = property(getInstance, setReadOnly, None, 'The Instance for the server')
def getAMI(self):
if self.instance:
return self.instance.image_id
ami = property(getAMI, setReadOnly, None, 'The AMI for the server')
def getStatus(self):
if self.instance:
self.instance.update()
return self.instance.state
status = property(getStatus, setReadOnly, None,
'The status of the server')
def getHostname(self):
if self.instance:
return self.instance.public_dns_name
hostname = property(getHostname, setReadOnly, None,
'The public DNS name of the server')
def getPrivateHostname(self):
if self.instance:
return self.instance.private_dns_name
private_hostname = property(getPrivateHostname, setReadOnly, None,
'The private DNS name of the server')
def getLaunchTime(self):
if self.instance:
return self.instance.launch_time
launch_time = property(getLaunchTime, setReadOnly, None,
'The time the Server was started')
def getConsoleOutput(self):
if self.instance:
return self.instance.get_console_output()
console_output = property(getConsoleOutput, setReadOnly, None,
'Retrieve the console output for server')
def getGroups(self):
if self._reservation:
return self._reservation.groups
else:
return None
groups = property(getGroups, setReadOnly, None,
'The Security Groups controlling access to this server')
def getConfig(self):
if not self._config:
remote_file = BotoConfigPath
local_file = '%s.ini' % self.instance.id
self.get_file(remote_file, local_file)
self._config = Config(local_file)
return self._config
def setConfig(self, config):
local_file = '%s.ini' % self.instance.id
fp = open(local_file)
config.write(fp)
fp.close()
self.put_file(local_file, BotoConfigPath)
self._config = config
config = property(getConfig, setConfig, None,
'The instance data for this server')
def set_config(self, config):
"""
Set SDB based config
"""
self._config = config
self._config.dump_to_sdb("botoConfigs", self.id)
def load_config(self):
self._config = Config(do_load=False)
self._config.load_from_sdb("botoConfigs", self.id)
def stop(self):
if self.instance:
self.instance.stop()
def start(self):
self.stop()
ec2 = boto.connect_ec2()
ami = ec2.get_all_images(image_ids = [str(self.ami_id)])[0]
groups = ec2.get_all_security_groups(groupnames=[str(self.security_group)])
if not self._config:
self.load_config()
if not self._config.has_section("Credentials"):
self._config.add_section("Credentials")
self._config.set("Credentials", "aws_access_key_id", ec2.aws_access_key_id)
self._config.set("Credentials", "aws_secret_access_key", ec2.aws_secret_access_key)
if not self._config.has_section("Pyami"):
self._config.add_section("Pyami")
if self._manager.domain:
self._config.set('Pyami', 'server_sdb_domain', self._manager.domain.name)
self._config.set("Pyami", 'server_sdb_name', self.name)
cfg = StringIO.StringIO()
self._config.write(cfg)
cfg = cfg.getvalue()
r = ami.run(min_count=1,
max_count=1,
key_name=self.key_name,
security_groups = groups,
instance_type = self.instance_type,
placement = self.zone,
user_data = cfg)
i = r.instances[0]
self.instance_id = i.id
self.put()
if self.elastic_ip:
ec2.associate_address(self.instance_id, self.elastic_ip)
def reboot(self):
if self.instance:
self.instance.reboot()
def get_ssh_client(self, key_file=None, host_key_file='~/.ssh/known_hosts',
uname='root'):
import paramiko
if not self.instance:
print 'No instance yet!'
return
if not self._ssh_client:
if not key_file:
iobject = IObject()
key_file = iobject.get_filename('Path to OpenSSH Key file')
self._pkey = paramiko.RSAKey.from_private_key_file(key_file)
self._ssh_client = paramiko.SSHClient()
self._ssh_client.load_system_host_keys()
self._ssh_client.load_host_keys(os.path.expanduser(host_key_file))
self._ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self._ssh_client.connect(self.instance.public_dns_name,
username=uname, pkey=self._pkey)
return self._ssh_client
def get_file(self, remotepath, localpath):
ssh_client = self.get_ssh_client()
sftp_client = ssh_client.open_sftp()
sftp_client.get(remotepath, localpath)
def put_file(self, localpath, remotepath):
ssh_client = self.get_ssh_client()
sftp_client = ssh_client.open_sftp()
sftp_client.put(localpath, remotepath)
def listdir(self, remotepath):
ssh_client = self.get_ssh_client()
sftp_client = ssh_client.open_sftp()
return sftp_client.listdir(remotepath)
def shell(self, key_file=None):
ssh_client = self.get_ssh_client(key_file)
channel = ssh_client.invoke_shell()
interactive_shell(channel)
def bundle_image(self, prefix, key_file, cert_file, size):
print 'bundling image...'
print '\tcopying cert and pk over to /mnt directory on server'
ssh_client = self.get_ssh_client()
sftp_client = ssh_client.open_sftp()
path, name = os.path.split(key_file)
remote_key_file = '/mnt/%s' % name
self.put_file(key_file, remote_key_file)
path, name = os.path.split(cert_file)
remote_cert_file = '/mnt/%s' % name
self.put_file(cert_file, remote_cert_file)
print '\tdeleting %s' % BotoConfigPath
# delete the metadata.ini file if it exists
try:
sftp_client.remove(BotoConfigPath)
except:
pass
command = 'sudo ec2-bundle-vol '
command += '-c %s -k %s ' % (remote_cert_file, remote_key_file)
command += '-u %s ' % self._reservation.owner_id
command += '-p %s ' % prefix
command += '-s %d ' % size
command += '-d /mnt '
if self.instance.instance_type == 'm1.small' or self.instance_type == 'c1.medium':
command += '-r i386'
else:
command += '-r x86_64'
print '\t%s' % command
t = ssh_client.exec_command(command)
response = t[1].read()
print '\t%s' % response
print '\t%s' % t[2].read()
print '...complete!'
def upload_bundle(self, bucket, prefix):
print 'uploading bundle...'
command = 'ec2-upload-bundle '
command += '-m /mnt/%s.manifest.xml ' % prefix
command += '-b %s ' % bucket
command += '-a %s ' % self.ec2.aws_access_key_id
command += '-s %s ' % self.ec2.aws_secret_access_key
print '\t%s' % command
ssh_client = self.get_ssh_client()
t = ssh_client.exec_command(command)
response = t[1].read()
print '\t%s' % response
print '\t%s' % t[2].read()
print '...complete!'
def create_image(self, bucket=None, prefix=None, key_file=None, cert_file=None, size=None):
iobject = IObject()
if not bucket:
bucket = iobject.get_string('Name of S3 bucket')
if not prefix:
prefix = iobject.get_string('Prefix for AMI file')
if not key_file:
key_file = iobject.get_filename('Path to RSA private key file')
if not cert_file:
cert_file = iobject.get_filename('Path to RSA public cert file')
if not size:
size = iobject.get_int('Size (in MB) of bundled image')
self.bundle_image(prefix, key_file, cert_file, size)
self.upload_bundle(bucket, prefix)
print 'registering image...'
self.image_id = self.ec2.register_image('%s/%s.manifest.xml' % (bucket, prefix))
return self.image_id
def attach_volume(self, volume, device="/dev/sdp"):
"""
Attach an EBS volume to this server
:param volume: EBS Volume to attach
:type volume: boto.ec2.volume.Volume
:param device: Device to attach to (default to /dev/sdp)
:type device: string
"""
if hasattr(volume, "id"):
volume_id = volume.id
else:
volume_id = volume
return self.ec2.attach_volume(volume_id=volume_id, instance_id=self.instance_id, device=device)
def detach_volume(self, volume):
"""
Detach an EBS volume from this server
:param volume: EBS Volume to detach
:type volume: boto.ec2.volume.Volume
"""
if hasattr(volume, "id"):
volume_id = volume.id
else:
volume_id = volume
return self.ec2.detach_volume(volume_id=volume_id, instance_id=self.instance_id)
def install_package(self, package_name):
print 'installing %s...' % package_name
command = 'yum -y install %s' % package_name
print '\t%s' % command
ssh_client = self.get_ssh_client()
t = ssh_client.exec_command(command)
response = t[1].read()
print '\t%s' % response
print '\t%s' % t[2].read()
print '...complete!'
| 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) 2003-2007 Robey Pointer <robey@lag.net>
#
# This file is part of paramiko.
#
# Paramiko is free software; you can redistribute it and/or modify it under the
# terms of the GNU Lesser General Public License as published by the Free
# Software Foundation; either version 2.1 of the License, or (at your option)
# any later version.
#
# Paramiko is distrubuted 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 Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Paramiko; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
import socket
import sys
# windows does not have termios...
try:
import termios
import tty
has_termios = True
except ImportError:
has_termios = False
def interactive_shell(chan):
if has_termios:
posix_shell(chan)
else:
windows_shell(chan)
def posix_shell(chan):
import select
oldtty = termios.tcgetattr(sys.stdin)
try:
tty.setraw(sys.stdin.fileno())
tty.setcbreak(sys.stdin.fileno())
chan.settimeout(0.0)
while True:
r, w, e = select.select([chan, sys.stdin], [], [])
if chan in r:
try:
x = chan.recv(1024)
if len(x) == 0:
print '\r\n*** EOF\r\n',
break
sys.stdout.write(x)
sys.stdout.flush()
except socket.timeout:
pass
if sys.stdin in r:
x = sys.stdin.read(1)
if len(x) == 0:
break
chan.send(x)
finally:
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
# thanks to Mike Looijmans for this code
def windows_shell(chan):
import threading
sys.stdout.write("Line-buffered terminal emulation. Press F6 or ^Z to send EOF.\r\n\r\n")
def writeall(sock):
while True:
data = sock.recv(256)
if not data:
sys.stdout.write('\r\n*** EOF ***\r\n\r\n')
sys.stdout.flush()
break
sys.stdout.write(data)
sys.stdout.flush()
writer = threading.Thread(target=writeall, args=(chan,))
writer.start()
try:
while True:
d = sys.stdin.read(1)
if not d:
break
chan.send(d)
except EOFError:
# user hit ^Z or F6
pass
| 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 os
def int_val_fn(v):
try:
int(v)
return True
except:
return False
class IObject(object):
def choose_from_list(self, item_list, search_str='',
prompt='Enter Selection'):
if not item_list:
print 'No Choices Available'
return
choice = None
while not choice:
n = 1
choices = []
for item in item_list:
if isinstance(item, str):
print '[%d] %s' % (n, item)
choices.append(item)
n += 1
else:
obj, id, desc = item
if desc:
if desc.find(search_str) >= 0:
print '[%d] %s - %s' % (n, id, desc)
choices.append(obj)
n += 1
else:
if id.find(search_str) >= 0:
print '[%d] %s' % (n, id)
choices.append(obj)
n += 1
if choices:
val = raw_input('%s[1-%d]: ' % (prompt, len(choices)))
if val.startswith('/'):
search_str = val[1:]
else:
try:
int_val = int(val)
if int_val == 0:
return None
choice = choices[int_val-1]
except ValueError:
print '%s is not a valid choice' % val
except IndexError:
print '%s is not within the range[1-%d]' % (val,
len(choices))
else:
print "No objects matched your pattern"
search_str = ''
return choice
def get_string(self, prompt, validation_fn=None):
okay = False
while not okay:
val = raw_input('%s: ' % prompt)
if validation_fn:
okay = validation_fn(val)
if not okay:
print 'Invalid value: %s' % val
else:
okay = True
return val
def get_filename(self, prompt):
okay = False
val = ''
while not okay:
val = raw_input('%s: %s' % (prompt, val))
val = os.path.expanduser(val)
if os.path.isfile(val):
okay = True
elif os.path.isdir(val):
path = val
val = self.choose_from_list(os.listdir(path))
if val:
val = os.path.join(path, val)
okay = True
else:
val = ''
else:
print 'Invalid value: %s' % val
val = ''
return val
def get_int(self, prompt):
s = self.get_string(prompt, int_val_fn)
return int(s)
| 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
from boto.sdb.db.property import StringProperty, DateTimeProperty, IntegerProperty
from boto.sdb.db.model import Model
import datetime, subprocess, StringIO, time
def check_hour(val):
if val == '*':
return
if int(val) < 0 or int(val) > 23:
raise ValueError
class Task(Model):
"""
A scheduled, repeating task that can be executed by any participating servers.
The scheduling is similar to cron jobs. Each task has an hour attribute.
The allowable values for hour are [0-23|*].
To keep the operation reasonably efficient and not cause excessive polling,
the minimum granularity of a Task is hourly. Some examples:
hour='*' - the task would be executed each hour
hour='3' - the task would be executed at 3AM GMT each day.
"""
name = StringProperty()
hour = StringProperty(required=True, validator=check_hour, default='*')
command = StringProperty(required=True)
last_executed = DateTimeProperty()
last_status = IntegerProperty()
last_output = StringProperty()
message_id = StringProperty()
@classmethod
def start_all(cls, queue_name):
for task in cls.all():
task.start(queue_name)
def __init__(self, id=None, **kw):
Model.__init__(self, id, **kw)
self.hourly = self.hour == '*'
self.daily = self.hour != '*'
self.now = datetime.datetime.utcnow()
def check(self):
"""
Determine how long until the next scheduled time for a Task.
Returns the number of seconds until the next scheduled time or zero
if the task needs to be run immediately.
If it's an hourly task and it's never been run, run it now.
If it's a daily task and it's never been run and the hour is right, run it now.
"""
boto.log.info('checking Task[%s]-now=%s, last=%s' % (self.name, self.now, self.last_executed))
if self.hourly and not self.last_executed:
return 0
if self.daily and not self.last_executed:
if int(self.hour) == self.now.hour:
return 0
else:
return max( (int(self.hour)-self.now.hour), (self.now.hour-int(self.hour)) )*60*60
delta = self.now - self.last_executed
if self.hourly:
if delta.seconds >= 60*60:
return 0
else:
return 60*60 - delta.seconds
else:
if int(self.hour) == self.now.hour:
if delta.days >= 1:
return 0
else:
return 82800 # 23 hours, just to be safe
else:
return max( (int(self.hour)-self.now.hour), (self.now.hour-int(self.hour)) )*60*60
def _run(self, msg, vtimeout):
boto.log.info('Task[%s] - running:%s' % (self.name, self.command))
log_fp = StringIO.StringIO()
process = subprocess.Popen(self.command, shell=True, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
nsecs = 5
current_timeout = vtimeout
while process.poll() == None:
boto.log.info('nsecs=%s, timeout=%s' % (nsecs, current_timeout))
if nsecs >= current_timeout:
current_timeout += vtimeout
boto.log.info('Task[%s] - setting timeout to %d seconds' % (self.name, current_timeout))
if msg:
msg.change_visibility(current_timeout)
time.sleep(5)
nsecs += 5
t = process.communicate()
log_fp.write(t[0])
log_fp.write(t[1])
boto.log.info('Task[%s] - output: %s' % (self.name, log_fp.getvalue()))
self.last_executed = self.now
self.last_status = process.returncode
self.last_output = log_fp.getvalue()[0:1023]
def run(self, msg, vtimeout=60):
delay = self.check()
boto.log.info('Task[%s] - delay=%s seconds' % (self.name, delay))
if delay == 0:
self._run(msg, vtimeout)
queue = msg.queue
new_msg = queue.new_message(self.id)
new_msg = queue.write(new_msg)
self.message_id = new_msg.id
self.put()
boto.log.info('Task[%s] - new message id=%s' % (self.name, new_msg.id))
msg.delete()
boto.log.info('Task[%s] - deleted message %s' % (self.name, msg.id))
else:
boto.log.info('new_vtimeout: %d' % delay)
msg.change_visibility(delay)
def start(self, queue_name):
boto.log.info('Task[%s] - starting with queue: %s' % (self.name, queue_name))
queue = boto.lookup('sqs', queue_name)
msg = queue.new_message(self.id)
msg = queue.write(msg)
self.message_id = msg.id
self.put()
boto.log.info('Task[%s] - start successful' % self.name)
class TaskPoller(object):
def __init__(self, queue_name):
self.sqs = boto.connect_sqs()
self.queue = self.sqs.lookup(queue_name)
def poll(self, wait=60, vtimeout=60):
while 1:
m = self.queue.read(vtimeout)
if m:
task = Task.get_by_id(m.get_body())
if task:
if not task.message_id or m.id == task.message_id:
boto.log.info('Task[%s] - read message %s' % (task.name, m.id))
task.run(m, vtimeout)
else:
boto.log.info('Task[%s] - found extraneous message, ignoring' % task.name)
else:
time.sleep(wait)
| 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.
def get(prop, choices=None):
prompt = prop.verbose_name
if not prompt:
prompt = prop.name
if choices:
if callable(choices):
choices = choices()
else:
choices = prop.get_choices()
valid = False
while not valid:
if choices:
min = 1
max = len(choices)
for i in range(min, max+1):
value = choices[i-1]
if isinstance(value, tuple):
value = value[0]
print '[%d] %s' % (i, value)
value = raw_input('%s [%d-%d]: ' % (prompt, min, max))
try:
int_value = int(value)
value = choices[int_value-1]
if isinstance(value, tuple):
value = value[1]
valid = True
except ValueError:
print '%s is not a valid choice' % value
except IndexError:
print '%s is not within the range[%d-%d]' % (min, max)
else:
value = raw_input('%s: ' % prompt)
try:
value = prop.validate(value)
if prop.empty(value) and prop.required:
print 'A value is required'
else:
valid = True
except:
print 'Invalid value: %s' % value
return value
| Python |
# Copyright (c) 2006-2009 Mitch Garnaat http://garnaat.org/
# Copyright (c) 2010 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.
"""
High-level abstraction of an EC2 server
"""
from __future__ import with_statement
import boto.ec2
from boto.mashups.iobject import IObject
from boto.pyami.config import BotoConfigPath, Config
from boto.sdb.db.model import Model
from boto.sdb.db.property import StringProperty, IntegerProperty, BooleanProperty, CalculatedProperty
from boto.manage import propget
from boto.ec2.zone import Zone
from boto.ec2.keypair import KeyPair
import os, time, StringIO
from contextlib import closing
from boto.exception import EC2ResponseError
InstanceTypes = ['m1.small', 'm1.large', 'm1.xlarge',
'c1.medium', 'c1.xlarge',
'm2.2xlarge', 'm2.4xlarge']
class Bundler(object):
def __init__(self, server, uname='root'):
from boto.manage.cmdshell import SSHClient
self.server = server
self.uname = uname
self.ssh_client = SSHClient(server, uname=uname)
def copy_x509(self, key_file, cert_file):
print '\tcopying cert and pk over to /mnt directory on server'
self.ssh_client.open_sftp()
path, name = os.path.split(key_file)
self.remote_key_file = '/mnt/%s' % name
self.ssh_client.put_file(key_file, self.remote_key_file)
path, name = os.path.split(cert_file)
self.remote_cert_file = '/mnt/%s' % name
self.ssh_client.put_file(cert_file, self.remote_cert_file)
print '...complete!'
def bundle_image(self, prefix, size, ssh_key):
command = ""
if self.uname != 'root':
command = "sudo "
command += 'ec2-bundle-vol '
command += '-c %s -k %s ' % (self.remote_cert_file, self.remote_key_file)
command += '-u %s ' % self.server._reservation.owner_id
command += '-p %s ' % prefix
command += '-s %d ' % size
command += '-d /mnt '
if self.server.instance_type == 'm1.small' or self.server.instance_type == 'c1.medium':
command += '-r i386'
else:
command += '-r x86_64'
return command
def upload_bundle(self, bucket, prefix, ssh_key):
command = ""
if self.uname != 'root':
command = "sudo "
command += 'ec2-upload-bundle '
command += '-m /mnt/%s.manifest.xml ' % prefix
command += '-b %s ' % bucket
command += '-a %s ' % self.server.ec2.aws_access_key_id
command += '-s %s ' % self.server.ec2.aws_secret_access_key
return command
def bundle(self, bucket=None, prefix=None, key_file=None, cert_file=None,
size=None, ssh_key=None, fp=None, clear_history=True):
iobject = IObject()
if not bucket:
bucket = iobject.get_string('Name of S3 bucket')
if not prefix:
prefix = iobject.get_string('Prefix for AMI file')
if not key_file:
key_file = iobject.get_filename('Path to RSA private key file')
if not cert_file:
cert_file = iobject.get_filename('Path to RSA public cert file')
if not size:
size = iobject.get_int('Size (in MB) of bundled image')
if not ssh_key:
ssh_key = self.server.get_ssh_key_file()
self.copy_x509(key_file, cert_file)
if not fp:
fp = StringIO.StringIO()
fp.write('sudo mv %s /mnt/boto.cfg; ' % BotoConfigPath)
fp.write('mv ~/.ssh/authorized_keys /mnt/authorized_keys; ')
if clear_history:
fp.write('history -c; ')
fp.write(self.bundle_image(prefix, size, ssh_key))
fp.write('; ')
fp.write(self.upload_bundle(bucket, prefix, ssh_key))
fp.write('; ')
fp.write('sudo mv /mnt/boto.cfg %s; ' % BotoConfigPath)
fp.write('mv /mnt/authorized_keys ~/.ssh/authorized_keys')
command = fp.getvalue()
print 'running the following command on the remote server:'
print command
t = self.ssh_client.run(command)
print '\t%s' % t[0]
print '\t%s' % t[1]
print '...complete!'
print 'registering image...'
self.image_id = self.server.ec2.register_image(name=prefix, image_location='%s/%s.manifest.xml' % (bucket, prefix))
return self.image_id
class CommandLineGetter(object):
def get_ami_list(self):
my_amis = []
for ami in self.ec2.get_all_images():
# hack alert, need a better way to do this!
if ami.location.find('pyami') >= 0:
my_amis.append((ami.location, ami))
return my_amis
def get_region(self, params):
region = params.get('region', None)
if isinstance(region, str) or isinstance(region, unicode):
region = boto.ec2.get_region(region)
params['region'] = region
if not region:
prop = self.cls.find_property('region_name')
params['region'] = propget.get(prop, choices=boto.ec2.regions)
self.ec2 = params['region'].connect()
def get_name(self, params):
if not params.get('name', None):
prop = self.cls.find_property('name')
params['name'] = propget.get(prop)
def get_description(self, params):
if not params.get('description', None):
prop = self.cls.find_property('description')
params['description'] = propget.get(prop)
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_ami_id(self, params):
valid = False
while not valid:
ami = params.get('ami', None)
if not ami:
prop = StringProperty(name='ami', verbose_name='AMI')
ami = propget.get(prop)
try:
rs = self.ec2.get_all_images([ami])
if len(rs) == 1:
valid = True
params['ami'] = rs[0]
except EC2ResponseError:
pass
def get_group(self, params):
group = params.get('group', None)
if isinstance(group, str) or isinstance(group, unicode):
group_list = self.ec2.get_all_security_groups()
for g in group_list:
if g.name == group:
group = g
params['group'] = g
if not group:
prop = StringProperty(name='group', verbose_name='EC2 Security Group',
choices=self.ec2.get_all_security_groups)
params['group'] = propget.get(prop)
def get_key(self, params):
keypair = params.get('keypair', None)
if isinstance(keypair, str) or isinstance(keypair, unicode):
key_list = self.ec2.get_all_key_pairs()
for k in key_list:
if k.name == keypair:
keypair = k.name
params['keypair'] = k.name
if not keypair:
prop = StringProperty(name='keypair', verbose_name='EC2 KeyPair',
choices=self.ec2.get_all_key_pairs)
params['keypair'] = propget.get(prop).name
def get(self, cls, params):
self.cls = cls
self.get_region(params)
self.ec2 = params['region'].connect()
self.get_name(params)
self.get_description(params)
self.get_instance_type(params)
self.get_zone(params)
self.get_quantity(params)
self.get_ami_id(params)
self.get_group(params)
self.get_key(params)
class Server(Model):
#
# The properties of this object consists of real properties for data that
# is not already stored in EC2 somewhere (e.g. name, description) plus
# calculated properties for all of the properties that are already in
# EC2 (e.g. hostname, security groups, etc.)
#
name = StringProperty(unique=True, verbose_name="Name")
description = StringProperty(verbose_name="Description")
region_name = StringProperty(verbose_name="EC2 Region Name")
instance_id = StringProperty(verbose_name="EC2 Instance ID")
elastic_ip = StringProperty(verbose_name="EC2 Elastic IP Address")
production = BooleanProperty(verbose_name="Is This Server Production", default=False)
ami_id = CalculatedProperty(verbose_name="AMI ID", calculated_type=str, use_method=True)
zone = CalculatedProperty(verbose_name="Availability Zone Name", calculated_type=str, use_method=True)
hostname = CalculatedProperty(verbose_name="Public DNS Name", calculated_type=str, use_method=True)
private_hostname = CalculatedProperty(verbose_name="Private DNS Name", calculated_type=str, use_method=True)
groups = CalculatedProperty(verbose_name="Security Groups", calculated_type=list, use_method=True)
security_group = CalculatedProperty(verbose_name="Primary Security Group Name", calculated_type=str, use_method=True)
key_name = CalculatedProperty(verbose_name="Key Name", calculated_type=str, use_method=True)
instance_type = CalculatedProperty(verbose_name="Instance Type", calculated_type=str, use_method=True)
status = CalculatedProperty(verbose_name="Current Status", calculated_type=str, use_method=True)
launch_time = CalculatedProperty(verbose_name="Server Launch Time", calculated_type=str, use_method=True)
console_output = CalculatedProperty(verbose_name="Console Output", calculated_type=file, use_method=True)
packages = []
plugins = []
@classmethod
def add_credentials(cls, cfg, aws_access_key_id, aws_secret_access_key):
if not cfg.has_section('Credentials'):
cfg.add_section('Credentials')
cfg.set('Credentials', 'aws_access_key_id', aws_access_key_id)
cfg.set('Credentials', 'aws_secret_access_key', aws_secret_access_key)
if not cfg.has_section('DB_Server'):
cfg.add_section('DB_Server')
cfg.set('DB_Server', 'db_type', 'SimpleDB')
cfg.set('DB_Server', 'db_name', cls._manager.domain.name)
@classmethod
def create(cls, config_file=None, logical_volume = None, cfg = None, **params):
"""
Create a new instance based on the specified configuration file or the specified
configuration and the passed in parameters.
If the config_file argument is not None, the configuration is read from there.
Otherwise, the cfg argument is used.
The config file may include other config files with a #import reference. The included
config files must reside in the same directory as the specified file.
The logical_volume argument, if supplied, will be used to get the current physical
volume ID and use that as an override of the value specified in the config file. This
may be useful for debugging purposes when you want to debug with a production config
file but a test Volume.
The dictionary argument may be used to override any EC2 configuration values in the
config file.
"""
if config_file:
cfg = Config(path=config_file)
if cfg.has_section('EC2'):
# include any EC2 configuration values that aren't specified in params:
for option in cfg.options('EC2'):
if option not in params:
params[option] = cfg.get('EC2', option)
getter = CommandLineGetter()
getter.get(cls, params)
region = params.get('region')
ec2 = region.connect()
cls.add_credentials(cfg, ec2.aws_access_key_id, ec2.aws_secret_access_key)
ami = params.get('ami')
kp = params.get('keypair')
group = params.get('group')
zone = params.get('zone')
# deal with possibly passed in logical volume:
if logical_volume != None:
cfg.set('EBS', 'logical_volume_name', logical_volume.name)
cfg_fp = StringIO.StringIO()
cfg.write(cfg_fp)
# deal with the possibility that zone and/or keypair are strings read from the config file:
if isinstance(zone, Zone):
zone = zone.name
if isinstance(kp, KeyPair):
kp = kp.name
reservation = ami.run(min_count=1,
max_count=params.get('quantity', 1),
key_name=kp,
security_groups=[group],
instance_type=params.get('instance_type'),
placement = zone,
user_data = cfg_fp.getvalue())
l = []
i = 0
elastic_ip = params.get('elastic_ip')
instances = reservation.instances
if elastic_ip != None and instances.__len__() > 0:
instance = instances[0]
print 'Waiting for instance to start so we can set its elastic IP address...'
# Sometimes we get a message from ec2 that says that the instance does not exist.
# Hopefully the following delay will giv eec2 enough time to get to a stable state:
time.sleep(5)
while instance.update() != 'running':
time.sleep(1)
instance.use_ip(elastic_ip)
print 'set the elastic IP of the first instance to %s' % elastic_ip
for instance in instances:
s = cls()
s.ec2 = ec2
s.name = params.get('name') + '' if i==0 else str(i)
s.description = params.get('description')
s.region_name = region.name
s.instance_id = instance.id
if elastic_ip and i == 0:
s.elastic_ip = elastic_ip
s.put()
l.append(s)
i += 1
return l
@classmethod
def create_from_instance_id(cls, instance_id, name, description=''):
regions = boto.ec2.regions()
for region in regions:
ec2 = region.connect()
try:
rs = ec2.get_all_instances([instance_id])
except:
rs = []
if len(rs) == 1:
s = cls()
s.ec2 = ec2
s.name = name
s.description = description
s.region_name = region.name
s.instance_id = instance_id
s._reservation = rs[0]
for instance in s._reservation.instances:
if instance.id == instance_id:
s._instance = instance
s.put()
return s
return None
@classmethod
def create_from_current_instances(cls):
servers = []
regions = boto.ec2.regions()
for region in regions:
ec2 = region.connect()
rs = ec2.get_all_instances()
for reservation in rs:
for instance in reservation.instances:
try:
Server.find(instance_id=instance.id).next()
boto.log.info('Server for %s already exists' % instance.id)
except StopIteration:
s = cls()
s.ec2 = ec2
s.name = instance.id
s.region_name = region.name
s.instance_id = instance.id
s._reservation = reservation
s.put()
servers.append(s)
return servers
def __init__(self, id=None, **kw):
Model.__init__(self, id, **kw)
self.ssh_key_file = None
self.ec2 = None
self._cmdshell = None
self._reservation = None
self._instance = None
self._setup_ec2()
def _setup_ec2(self):
if self.ec2 and self._instance and self._reservation:
return
if self.id:
if self.region_name:
for region in boto.ec2.regions():
if region.name == self.region_name:
self.ec2 = region.connect()
if self.instance_id and not self._instance:
try:
rs = self.ec2.get_all_instances([self.instance_id])
if len(rs) >= 1:
for instance in rs[0].instances:
if instance.id == self.instance_id:
self._reservation = rs[0]
self._instance = instance
except EC2ResponseError:
pass
def _status(self):
status = ''
if self._instance:
self._instance.update()
status = self._instance.state
return status
def _hostname(self):
hostname = ''
if self._instance:
hostname = self._instance.public_dns_name
return hostname
def _private_hostname(self):
hostname = ''
if self._instance:
hostname = self._instance.private_dns_name
return hostname
def _instance_type(self):
it = ''
if self._instance:
it = self._instance.instance_type
return it
def _launch_time(self):
lt = ''
if self._instance:
lt = self._instance.launch_time
return lt
def _console_output(self):
co = ''
if self._instance:
co = self._instance.get_console_output()
return co
def _groups(self):
gn = []
if self._reservation:
gn = self._reservation.groups
return gn
def _security_group(self):
groups = self._groups()
if len(groups) >= 1:
return groups[0].id
return ""
def _zone(self):
zone = None
if self._instance:
zone = self._instance.placement
return zone
def _key_name(self):
kn = None
if self._instance:
kn = self._instance.key_name
return kn
def put(self):
Model.put(self)
self._setup_ec2()
def delete(self):
if self.production:
raise ValueError, "Can't delete a production server"
#self.stop()
Model.delete(self)
def stop(self):
if self.production:
raise ValueError, "Can't delete a production server"
if self._instance:
self._instance.stop()
def terminate(self):
if self.production:
raise ValueError, "Can't delete a production server"
if self._instance:
self._instance.terminate()
def reboot(self):
if self._instance:
self._instance.reboot()
def wait(self):
while self.status != 'running':
time.sleep(5)
def get_ssh_key_file(self):
if not self.ssh_key_file:
ssh_dir = os.path.expanduser('~/.ssh')
if os.path.isdir(ssh_dir):
ssh_file = os.path.join(ssh_dir, '%s.pem' % self.key_name)
if os.path.isfile(ssh_file):
self.ssh_key_file = ssh_file
if not self.ssh_key_file:
iobject = IObject()
self.ssh_key_file = iobject.get_filename('Path to OpenSSH Key file')
return self.ssh_key_file
def get_cmdshell(self):
if not self._cmdshell:
import cmdshell
self.get_ssh_key_file()
self._cmdshell = cmdshell.start(self)
return self._cmdshell
def reset_cmdshell(self):
self._cmdshell = None
def run(self, command):
with closing(self.get_cmdshell()) as cmd:
status = cmd.run(command)
return status
def get_bundler(self, uname='root'):
self.get_ssh_key_file()
return Bundler(self, uname)
def get_ssh_client(self, uname='root'):
from boto.manage.cmdshell import SSHClient
self.get_ssh_key_file()
return SSHClient(self, uname=uname)
def install(self, pkg):
return self.run('apt-get -y install %s' % pkg)
| 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.mashups.interactive import interactive_shell
import boto
import os
import time
import shutil
import StringIO
import paramiko
import socket
import subprocess
class SSHClient(object):
def __init__(self, server, host_key_file='~/.ssh/known_hosts', uname='root'):
self.server = server
self.host_key_file = host_key_file
self.uname = uname
self._pkey = paramiko.RSAKey.from_private_key_file(server.ssh_key_file)
self._ssh_client = paramiko.SSHClient()
self._ssh_client.load_system_host_keys()
self._ssh_client.load_host_keys(os.path.expanduser(host_key_file))
self._ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.connect()
def connect(self):
retry = 0
while retry < 5:
try:
self._ssh_client.connect(self.server.hostname, username=self.uname, pkey=self._pkey)
return
except socket.error, (value,message):
if value == 61:
print 'SSH Connection refused, will retry in 5 seconds'
time.sleep(5)
retry += 1
else:
raise
except paramiko.BadHostKeyException:
print "%s has an entry in ~/.ssh/known_hosts and it doesn't match" % self.server.hostname
print 'Edit that file to remove the entry and then hit return to try again'
raw_input('Hit Enter when ready')
retry += 1
except EOFError:
print 'Unexpected Error from SSH Connection, retry in 5 seconds'
time.sleep(5)
retry += 1
print 'Could not establish SSH connection'
def get_file(self, src, dst):
sftp_client = self._ssh_client.open_sftp()
sftp_client.get(src, dst)
def put_file(self, src, dst):
sftp_client = self._ssh_client.open_sftp()
sftp_client.put(src, dst)
def listdir(self, path):
sftp_client = self._ssh_client.open_sftp()
return sftp_client.listdir(path)
def open_sftp(self):
return self._ssh_client.open_sftp()
def isdir(self, path):
status = self.run('[ -d %s ] || echo "FALSE"' % path)
if status[1].startswith('FALSE'):
return 0
return 1
def exists(self, path):
status = self.run('[ -a %s ] || echo "FALSE"' % path)
if status[1].startswith('FALSE'):
return 0
return 1
def shell(self):
channel = self._ssh_client.invoke_shell()
interactive_shell(channel)
def run(self, command):
boto.log.info('running:%s on %s' % (command, self.server.instance_id))
log_fp = StringIO.StringIO()
status = 0
try:
t = self._ssh_client.exec_command(command)
except paramiko.SSHException:
status = 1
log_fp.write(t[1].read())
log_fp.write(t[2].read())
t[0].close()
t[1].close()
t[2].close()
boto.log.info('output: %s' % log_fp.getvalue())
return (status, log_fp.getvalue())
def close(self):
transport = self._ssh_client.get_transport()
transport.close()
self.server.reset_cmdshell()
class LocalClient(object):
def __init__(self, server, host_key_file=None, uname='root'):
self.server = server
self.host_key_file = host_key_file
self.uname = uname
def get_file(self, src, dst):
shutil.copyfile(src, dst)
def put_file(self, src, dst):
shutil.copyfile(src, dst)
def listdir(self, path):
return os.listdir(path)
def isdir(self, path):
return os.path.isdir(path)
def exists(self, path):
return os.path.exists(path)
def shell(self):
raise NotImplementedError, 'shell not supported with LocalClient'
def run(self):
boto.log.info('running:%s' % self.command)
log_fp = StringIO.StringIO()
process = subprocess.Popen(self.command, shell=True, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
while process.poll() == None:
time.sleep(1)
t = process.communicate()
log_fp.write(t[0])
log_fp.write(t[1])
boto.log.info(log_fp.getvalue())
boto.log.info('output: %s' % log_fp.getvalue())
return (process.returncode, log_fp.getvalue())
def close(self):
pass
def start(server):
instance_id = boto.config.get('Instance', 'instance-id', None)
if instance_id == server.instance_id:
return LocalClient(server)
else:
return SSHClient(server)
| 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 __future__ import with_statement
from boto.sdb.db.model import Model
from boto.sdb.db.property import StringProperty, IntegerProperty, ListProperty, ReferenceProperty, CalculatedProperty
from boto.manage.server import Server
from boto.manage import propget
import boto.ec2
import time
import traceback
from contextlib import closing
import dateutil.parser
import datetime
class CommandLineGetter(object):
def get_region(self, params):
if not params.get('region', None):
prop = self.cls.find_property('region_name')
params['region'] = propget.get(prop, choices=boto.ec2.regions)
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_name(self, params):
if not params.get('name', None):
prop = self.cls.find_property('name')
params['name'] = propget.get(prop)
def get_size(self, params):
if not params.get('size', None):
prop = IntegerProperty(name='size', verbose_name='Size (GB)')
params['size'] = propget.get(prop)
def get_mount_point(self, params):
if not params.get('mount_point', None):
prop = self.cls.find_property('mount_point')
params['mount_point'] = propget.get(prop)
def get_device(self, params):
if not params.get('device', None):
prop = self.cls.find_property('device')
params['device'] = propget.get(prop)
def get(self, cls, params):
self.cls = cls
self.get_region(params)
self.ec2 = params['region'].connect()
self.get_zone(params)
self.get_name(params)
self.get_size(params)
self.get_mount_point(params)
self.get_device(params)
class Volume(Model):
name = StringProperty(required=True, unique=True, verbose_name='Name')
region_name = StringProperty(required=True, verbose_name='EC2 Region')
zone_name = StringProperty(required=True, verbose_name='EC2 Zone')
mount_point = StringProperty(verbose_name='Mount Point')
device = StringProperty(verbose_name="Device Name", default='/dev/sdp')
volume_id = StringProperty(required=True)
past_volume_ids = ListProperty(item_type=str)
server = ReferenceProperty(Server, collection_name='volumes',
verbose_name='Server Attached To')
volume_state = CalculatedProperty(verbose_name="Volume State",
calculated_type=str, use_method=True)
attachment_state = CalculatedProperty(verbose_name="Attachment State",
calculated_type=str, use_method=True)
size = CalculatedProperty(verbose_name="Size (GB)",
calculated_type=int, use_method=True)
@classmethod
def create(cls, **params):
getter = CommandLineGetter()
getter.get(cls, params)
region = params.get('region')
ec2 = region.connect()
zone = params.get('zone')
size = params.get('size')
ebs_volume = ec2.create_volume(size, zone.name)
v = cls()
v.ec2 = ec2
v.volume_id = ebs_volume.id
v.name = params.get('name')
v.mount_point = params.get('mount_point')
v.device = params.get('device')
v.region_name = region.name
v.zone_name = zone.name
v.put()
return v
@classmethod
def create_from_volume_id(cls, region_name, volume_id, name):
vol = None
ec2 = boto.ec2.connect_to_region(region_name)
rs = ec2.get_all_volumes([volume_id])
if len(rs) == 1:
v = rs[0]
vol = cls()
vol.volume_id = v.id
vol.name = name
vol.region_name = v.region.name
vol.zone_name = v.zone
vol.put()
return vol
def create_from_latest_snapshot(self, name, size=None):
snapshot = self.get_snapshots()[-1]
return self.create_from_snapshot(name, snapshot, size)
def create_from_snapshot(self, name, snapshot, size=None):
if size < self.size:
size = self.size
ec2 = self.get_ec2_connection()
if self.zone_name == None or self.zone_name == '':
# deal with the migration case where the zone is not set in the logical volume:
current_volume = ec2.get_all_volumes([self.volume_id])[0]
self.zone_name = current_volume.zone
ebs_volume = ec2.create_volume(size, self.zone_name, snapshot)
v = Volume()
v.ec2 = self.ec2
v.volume_id = ebs_volume.id
v.name = name
v.mount_point = self.mount_point
v.device = self.device
v.region_name = self.region_name
v.zone_name = self.zone_name
v.put()
return v
def get_ec2_connection(self):
if self.server:
return self.server.ec2
if not hasattr(self, 'ec2') or self.ec2 == None:
self.ec2 = boto.ec2.connect_to_region(self.region_name)
return self.ec2
def _volume_state(self):
ec2 = self.get_ec2_connection()
rs = ec2.get_all_volumes([self.volume_id])
return rs[0].volume_state()
def _attachment_state(self):
ec2 = self.get_ec2_connection()
rs = ec2.get_all_volumes([self.volume_id])
return rs[0].attachment_state()
def _size(self):
if not hasattr(self, '__size'):
ec2 = self.get_ec2_connection()
rs = ec2.get_all_volumes([self.volume_id])
self.__size = rs[0].size
return self.__size
def install_xfs(self):
if self.server:
self.server.install('xfsprogs xfsdump')
def get_snapshots(self):
"""
Returns a list of all completed snapshots for this volume ID.
"""
ec2 = self.get_ec2_connection()
rs = ec2.get_all_snapshots()
all_vols = [self.volume_id] + self.past_volume_ids
snaps = []
for snapshot in rs:
if snapshot.volume_id in all_vols:
if snapshot.progress == '100%':
snapshot.date = dateutil.parser.parse(snapshot.start_time)
snapshot.keep = True
snaps.append(snapshot)
snaps.sort(cmp=lambda x,y: cmp(x.date, y.date))
return snaps
def attach(self, server=None):
if self.attachment_state == 'attached':
print 'already attached'
return None
if server:
self.server = server
self.put()
ec2 = self.get_ec2_connection()
ec2.attach_volume(self.volume_id, self.server.instance_id, self.device)
def detach(self, force=False):
state = self.attachment_state
if state == 'available' or state == None or state == 'detaching':
print 'already detached'
return None
ec2 = self.get_ec2_connection()
ec2.detach_volume(self.volume_id, self.server.instance_id, self.device, force)
self.server = None
self.put()
def checkfs(self, use_cmd=None):
if self.server == None:
raise ValueError, 'server attribute must be set to run this command'
# detemine state of file system on volume, only works if attached
if use_cmd:
cmd = use_cmd
else:
cmd = self.server.get_cmdshell()
status = cmd.run('xfs_check %s' % self.device)
if not use_cmd:
cmd.close()
if status[1].startswith('bad superblock magic number 0'):
return False
return True
def wait(self):
if self.server == None:
raise ValueError, 'server attribute must be set to run this command'
with closing(self.server.get_cmdshell()) as cmd:
# wait for the volume device to appear
cmd = self.server.get_cmdshell()
while not cmd.exists(self.device):
boto.log.info('%s still does not exist, waiting 10 seconds' % self.device)
time.sleep(10)
def format(self):
if self.server == None:
raise ValueError, 'server attribute must be set to run this command'
status = None
with closing(self.server.get_cmdshell()) as cmd:
if not self.checkfs(cmd):
boto.log.info('make_fs...')
status = cmd.run('mkfs -t xfs %s' % self.device)
return status
def mount(self):
if self.server == None:
raise ValueError, 'server attribute must be set to run this command'
boto.log.info('handle_mount_point')
with closing(self.server.get_cmdshell()) as cmd:
cmd = self.server.get_cmdshell()
if not cmd.isdir(self.mount_point):
boto.log.info('making directory')
# mount directory doesn't exist so create it
cmd.run("mkdir %s" % self.mount_point)
else:
boto.log.info('directory exists already')
status = cmd.run('mount -l')
lines = status[1].split('\n')
for line in lines:
t = line.split()
if t and t[2] == self.mount_point:
# something is already mounted at the mount point
# unmount that and mount it as /tmp
if t[0] != self.device:
cmd.run('umount %s' % self.mount_point)
cmd.run('mount %s /tmp' % t[0])
cmd.run('chmod 777 /tmp')
break
# Mount up our new EBS volume onto mount_point
cmd.run("mount %s %s" % (self.device, self.mount_point))
cmd.run('xfs_growfs %s' % self.mount_point)
def make_ready(self, server):
self.server = server
self.put()
self.install_xfs()
self.attach()
self.wait()
self.format()
self.mount()
def freeze(self):
if self.server:
return self.server.run("/usr/sbin/xfs_freeze -f %s" % self.mount_point)
def unfreeze(self):
if self.server:
return self.server.run("/usr/sbin/xfs_freeze -u %s" % self.mount_point)
def snapshot(self):
# if this volume is attached to a server
# we need to freeze the XFS file system
try:
self.freeze()
if self.server == None:
snapshot = self.get_ec2_connection().create_snapshot(self.volume_id)
else:
snapshot = self.server.ec2.create_snapshot(self.volume_id)
boto.log.info('Snapshot of Volume %s created: %s' % (self.name, snapshot))
except Exception:
boto.log.info('Snapshot error')
boto.log.info(traceback.format_exc())
finally:
status = self.unfreeze()
return status
def get_snapshot_range(self, snaps, start_date=None, end_date=None):
l = []
for snap in snaps:
if start_date and end_date:
if snap.date >= start_date and snap.date <= end_date:
l.append(snap)
elif start_date:
if snap.date >= start_date:
l.append(snap)
elif end_date:
if snap.date <= end_date:
l.append(snap)
else:
l.append(snap)
return l
def trim_snapshots(self, delete=False):
"""
Trim the number of snapshots for this volume. This method always
keeps the oldest snapshot. It then uses the parameters passed in
to determine how many others should be kept.
The algorithm is to keep all snapshots from the current day. Then
it will keep the first snapshot of the day for the previous seven days.
Then, it will keep the first snapshot of the week for the previous
four weeks. After than, it will keep the first snapshot of the month
for as many months as there are.
"""
snaps = self.get_snapshots()
# Always keep the oldest and the newest
if len(snaps) <= 2:
return snaps
snaps = snaps[1:-1]
now = datetime.datetime.now(snaps[0].date.tzinfo)
midnight = datetime.datetime(year=now.year, month=now.month,
day=now.day, tzinfo=now.tzinfo)
# Keep the first snapshot from each day of the previous week
one_week = datetime.timedelta(days=7, seconds=60*60)
print midnight-one_week, midnight
previous_week = self.get_snapshot_range(snaps, midnight-one_week, midnight)
print previous_week
if not previous_week:
return snaps
current_day = None
for snap in previous_week:
if current_day and current_day == snap.date.day:
snap.keep = False
else:
current_day = snap.date.day
# Get ourselves onto the next full week boundary
if previous_week:
week_boundary = previous_week[0].date
if week_boundary.weekday() != 0:
delta = datetime.timedelta(days=week_boundary.weekday())
week_boundary = week_boundary - delta
# Keep one within this partial week
partial_week = self.get_snapshot_range(snaps, week_boundary, previous_week[0].date)
if len(partial_week) > 1:
for snap in partial_week[1:]:
snap.keep = False
# Keep the first snapshot of each week for the previous 4 weeks
for i in range(0,4):
weeks_worth = self.get_snapshot_range(snaps, week_boundary-one_week, week_boundary)
if len(weeks_worth) > 1:
for snap in weeks_worth[1:]:
snap.keep = False
week_boundary = week_boundary - one_week
# Now look through all remaining snaps and keep one per month
remainder = self.get_snapshot_range(snaps, end_date=week_boundary)
current_month = None
for snap in remainder:
if current_month and current_month == snap.date.month:
snap.keep = False
else:
current_month = snap.date.month
if delete:
for snap in snaps:
if not snap.keep:
boto.log.info('Deleting %s(%s) for %s' % (snap, snap.date, self.name))
snap.delete()
return snaps
def grow(self, size):
pass
def copy(self, snapshot):
pass
def get_snapshot_from_date(self, date):
pass
def delete(self, delete_ebs_volume=False):
if delete_ebs_volume:
self.detach()
ec2 = self.get_ec2_connection()
ec2.delete_volume(self.volume_id)
Model.delete(self)
def archive(self):
# snapshot volume, trim snaps, delete volume-id
pass
| 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.
#
| 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 ParameterGroup(dict):
def __init__(self, connection=None):
dict.__init__(self)
self.connection = connection
self.name = None
self.description = None
self.engine = None
self._current_param = None
def __repr__(self):
return 'ParameterGroup:%s' % self.name
def startElement(self, name, attrs, connection):
if name == 'Parameter':
if self._current_param:
self[self._current_param.name] = self._current_param
self._current_param = Parameter(self)
return self._current_param
def endElement(self, name, value, connection):
if name == 'DBParameterGroupName':
self.name = value
elif name == 'Description':
self.description = value
elif name == 'Engine':
self.engine = value
else:
setattr(self, name, value)
def modifiable(self):
mod = []
for key in self:
p = self[key]
if p.is_modifiable:
mod.append(p)
return mod
def get_params(self):
pg = self.connection.get_all_dbparameters(self.name)
self.update(pg)
def add_param(self, name, value, apply_method):
param = Parameter()
param.name = name
param.value = value
param.apply_method = apply_method
self.params.append(param)
class Parameter(object):
"""
Represents a RDS Parameter
"""
ValidTypes = {'integer' : int,
'string' : str,
'boolean' : bool}
ValidSources = ['user', 'system', 'engine-default']
ValidApplyTypes = ['static', 'dynamic']
ValidApplyMethods = ['immediate', 'pending-reboot']
def __init__(self, group=None, name=None):
self.group = group
self.name = name
self._value = None
self.type = str
self.source = None
self.is_modifiable = True
self.description = None
self.apply_method = None
self.allowed_values = None
def __repr__(self):
return 'Parameter:%s' % self.name
def startElement(self, name, attrs, connection):
pass
def endElement(self, name, value, connection):
if name == 'ParameterName':
self.name = value
elif name == 'ParameterValue':
self._value = value
elif name == 'DataType':
if value in self.ValidTypes:
self.type = value
elif name == 'Source':
if value in self.ValidSources:
self.source = value
elif name == 'IsModifiable':
if value.lower() == 'true':
self.is_modifiable = True
else:
self.is_modifiable = False
elif name == 'Description':
self.description = value
elif name == 'ApplyType':
if value in self.ValidApplyTypes:
self.apply_type = value
elif name == 'AllowedValues':
self.allowed_values = value
else:
setattr(self, name, value)
def merge(self, d, i):
prefix = 'Parameters.member.%d.' % i
if self.name:
d[prefix+'ParameterName'] = self.name
if self._value:
d[prefix+'ParameterValue'] = self._value
if self.apply_type:
d[prefix+'ApplyMethod'] = self.apply_method
def _set_string_value(self, value):
if not isinstance(value, str) or isinstance(value, unicode):
raise ValueError, 'value must be of type str'
if self.allowed_values:
choices = self.allowed_values.split(',')
if value not in choices:
raise ValueError, 'value must be in %s' % self.allowed_values
self._value = value
def _set_integer_value(self, value):
if isinstance(value, str) or isinstance(value, unicode):
value = int(value)
if isinstance(value, int) or isinstance(value, long):
if self.allowed_values:
min, max = self.allowed_values.split('-')
if value < int(min) or value > int(max):
raise ValueError, 'range is %s' % self.allowed_values
self._value = value
else:
raise ValueError, 'value must be integer'
def _set_boolean_value(self, value):
if isinstance(value, bool):
self._value = value
elif isinstance(value, str) or isinstance(value, unicode):
if value.lower() == 'true':
self._value = True
else:
self._value = False
else:
raise ValueError, 'value must be boolean'
def set_value(self, value):
if self.type == 'string':
self._set_string_value(value)
elif self.type == 'integer':
self._set_integer_value(value)
elif self.type == 'boolean':
self._set_boolean_value(value)
else:
raise TypeError, 'unknown type (%s)' % self.type
def get_value(self):
if self._value == None:
return self._value
if self.type == 'string':
return self._value
elif self.type == 'integer':
if not isinstance(self._value, int) and not isinstance(self._value, long):
self._set_integer_value(self._value)
return self._value
elif self.type == 'boolean':
if not isinstance(self._value, bool):
self._set_boolean_value(self._value)
return self._value
else:
raise TypeError, 'unknown type (%s)' % self.type
value = property(get_value, set_value, 'The value of the parameter')
def apply(self, immediate=False):
if immediate:
self.apply_method = 'immediate'
else:
self.apply_method = 'pending-reboot'
self.group.connection.modify_parameter_group(self.group.name, [self])
| 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 RDSRegionInfo(RegionInfo):
def __init__(self, connection=None, name=None, endpoint=None):
from boto.rds import RDSConnection
RegionInfo.__init__(self, connection, name, endpoint,
RDSConnection)
| 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 Event(object):
def __init__(self, connection=None):
self.connection = connection
self.message = None
self.source_identifier = None
self.source_type = None
self.engine = None
self.date = None
def __repr__(self):
return '"%s"' % self.message
def startElement(self, name, attrs, connection):
pass
def endElement(self, name, value, connection):
if name == 'SourceIdentifier':
self.source_identifier = value
elif name == 'SourceType':
self.source_type = value
elif name == 'Message':
self.message = value
elif name == 'Date':
self.date = 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 DBSnapshot(object):
"""
Represents a RDS DB Snapshot
"""
def __init__(self, connection=None, id=None):
self.connection = connection
self.id = id
self.engine = None
self.snapshot_create_time = None
self.instance_create_time = None
self.port = None
self.status = None
self.availability_zone = None
self.master_username = None
self.allocated_storage = None
self.instance_id = None
self.availability_zone = None
def __repr__(self):
return 'DBSnapshot:%s' % self.id
def startElement(self, name, attrs, connection):
pass
def endElement(self, name, value, connection):
if name == 'Engine':
self.engine = value
elif name == 'InstanceCreateTime':
self.instance_create_time = value
elif name == 'SnapshotCreateTime':
self.snapshot_create_time = value
elif name == 'DBInstanceIdentifier':
self.instance_id = value
elif name == 'DBSnapshotIdentifier':
self.id = value
elif name == 'Port':
self.port = int(value)
elif name == 'Status':
self.status = value
elif name == 'AvailabilityZone':
self.availability_zone = value
elif name == 'MasterUsername':
self.master_username = value
elif name == 'AllocatedStorage':
self.allocated_storage = int(value)
elif name == 'SnapshotTime':
self.time = value
else:
setattr(self, name, value)
| 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.
"""
Represents an DBSecurityGroup
"""
from boto.ec2.securitygroup import SecurityGroup
class DBSecurityGroup(object):
def __init__(self, connection=None, owner_id=None,
name=None, description=None):
self.connection = connection
self.owner_id = owner_id
self.name = name
self.description = description
self.ec2_groups = []
self.ip_ranges = []
def __repr__(self):
return 'DBSecurityGroup:%s' % self.name
def startElement(self, name, attrs, connection):
if name == 'IPRange':
cidr = IPRange(self)
self.ip_ranges.append(cidr)
return cidr
elif name == 'EC2SecurityGroup':
ec2_grp = EC2SecurityGroup(self)
self.ec2_groups.append(ec2_grp)
return ec2_grp
else:
return None
def endElement(self, name, value, connection):
if name == 'OwnerId':
self.owner_id = value
elif name == 'DBSecurityGroupName':
self.name = value
elif name == 'DBSecurityGroupDescription':
self.description = value
elif name == 'IPRanges':
pass
else:
setattr(self, name, value)
def delete(self):
return self.connection.delete_dbsecurity_group(self.name)
def authorize(self, cidr_ip=None, ec2_group=None):
"""
Add a new rule to this DBSecurity group.
You need to pass in either a CIDR block to authorize or
and EC2 SecurityGroup.
@type cidr_ip: string
@param cidr_ip: A valid CIDR IP range to authorize
@type ec2_group: :class:`boto.ec2.securitygroup.SecurityGroup>`
@rtype: bool
@return: True if successful.
"""
if isinstance(ec2_group, SecurityGroup):
group_name = ec2_group.name
group_owner_id = ec2_group.owner_id
else:
group_name = None
group_owner_id = None
return self.connection.authorize_dbsecurity_group(self.name,
cidr_ip,
group_name,
group_owner_id)
def revoke(self, cidr_ip=None, ec2_group=None):
"""
Revoke access to a CIDR range or EC2 SecurityGroup
You need to pass in either a CIDR block to authorize or
and EC2 SecurityGroup.
@type cidr_ip: string
@param cidr_ip: A valid CIDR IP range to authorize
@type ec2_group: :class:`boto.ec2.securitygroup.SecurityGroup>`
@rtype: bool
@return: True if successful.
"""
if isinstance(ec2_group, SecurityGroup):
group_name = ec2_group.name
group_owner_id = ec2_group.owner_id
else:
group_name = None
group_owner_id = None
return self.connection.revoke_dbsecurity_group(self.name,
cidr_ip,
group_name,
group_owner_id)
class IPRange(object):
def __init__(self, parent=None):
self.parent = parent
self.cidr_ip = None
self.status = None
def __repr__(self):
return 'IPRange:%s' % self.cidr_ip
def startElement(self, name, attrs, connection):
pass
def endElement(self, name, value, connection):
if name == 'CIDRIP':
self.cidr_ip = value
elif name == 'Status':
self.status = value
else:
setattr(self, name, value)
class EC2SecurityGroup(object):
def __init__(self, parent=None):
self.parent = parent
self.name = None
self.owner_id = None
def __repr__(self):
return 'EC2SecurityGroup:%s' % self.name
def startElement(self, name, attrs, connection):
pass
def endElement(self, name, value, connection):
if name == 'EC2SecurityGroupName':
self.name = value
elif name == 'EC2SecurityGroupOwnerId':
self.owner_id = value
else:
setattr(self, name, value)
| 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.
#
import boto.utils
import urllib
from boto.connection import AWSQueryConnection
from boto.rds.dbinstance import DBInstance
from boto.rds.dbsecuritygroup import DBSecurityGroup
from boto.rds.parametergroup import ParameterGroup
from boto.rds.dbsnapshot import DBSnapshot
from boto.rds.event import Event
from boto.rds.regioninfo import RDSRegionInfo
def regions():
"""
Get all available regions for the RDS service.
:rtype: list
:return: A list of :class:`boto.rds.regioninfo.RDSRegionInfo`
"""
return [RDSRegionInfo(name='us-east-1',
endpoint='rds.amazonaws.com'),
RDSRegionInfo(name='eu-west-1',
endpoint='eu-west-1.rds.amazonaws.com'),
RDSRegionInfo(name='us-west-1',
endpoint='us-west-1.rds.amazonaws.com'),
RDSRegionInfo(name='ap-southeast-1',
endpoint='ap-southeast-1.rds.amazonaws.com')
]
def connect_to_region(region_name):
for region in regions():
if region.name == region_name:
return region.connect()
return None
#boto.set_stream_logger('rds')
class RDSConnection(AWSQueryConnection):
DefaultRegionName = 'us-east-1'
DefaultRegionEndpoint = 'rds.amazonaws.com'
APIVersion = '2009-10-16'
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=0,
https_connection_factory=None, region=None, path='/'):
if not region:
region = RDSRegionInfo(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)
# DB Instance methods
def get_all_dbinstances(self, instance_id=None, max_records=None,
marker=None):
"""
Retrieve all the DBInstances in your account.
:type instance_id: str
:param instance_id: DB Instance identifier. If supplied, only information
this instance will be returned. Otherwise, info
about all DB Instances will be returned.
:type max_records: int
:param max_records: The maximum number of records to be returned.
If more results are available, a MoreToken will
be returned in the response that can be used to
retrieve additional records. Default is 100.
:type marker: str
:param marker: The marker provided by a previous request.
:rtype: list
:return: A list of :class:`boto.rds.dbinstance.DBInstance`
"""
params = {}
if instance_id:
params['DBInstanceIdentifier'] = instance_id
if max_records:
params['MaxRecords'] = max_records
if marker:
params['Marker'] = marker
return self.get_list('DescribeDBInstances', params, [('DBInstance', DBInstance)])
def create_dbinstance(self, id, allocated_storage, instance_class,
master_username, master_password, port=3306,
engine='MySQL5.1', db_name=None, param_group=None,
security_groups=None, availability_zone=None,
preferred_maintenance_window=None,
backup_retention_period=None,
preferred_backup_window=None,
multi_az=False,
engine_version=None,
auto_minor_version_upgrade=True):
"""
Create a new DBInstance.
:type id: str
:param id: Unique identifier for the new instance.
Must contain 1-63 alphanumeric characters.
First character must be a letter.
May not end with a hyphen or contain two consecutive hyphens
:type allocated_storage: int
:param allocated_storage: Initially allocated storage size, in GBs.
Valid values are [5-1024]
:type instance_class: str
:param instance_class: The compute and memory capacity of the DBInstance.
Valid values are:
* db.m1.small
* db.m1.large
* db.m1.xlarge
* db.m2.xlarge
* db.m2.2xlarge
* db.m2.4xlarge
:type engine: str
:param engine: Name of database engine. Must be MySQL5.1 for now.
:type master_username: str
:param master_username: Name of master user for the DBInstance.
Must be 1-15 alphanumeric characters, first
must be a letter.
:type master_password: str
:param master_password: Password of master user for the DBInstance.
Must be 4-16 alphanumeric characters.
:type port: int
:param port: Port number on which database accepts connections.
Valid values [1115-65535]. Defaults to 3306.
:type db_name: str
:param db_name: Name of a database to create when the DBInstance
is created. Default is to create no databases.
:type param_group: str
:param param_group: Name of DBParameterGroup to associate with
this DBInstance. If no groups are specified
no parameter groups will be used.
:type security_groups: list of str or list of DBSecurityGroup objects
:param security_groups: List of names of DBSecurityGroup to authorize on
this DBInstance.
:type availability_zone: str
:param availability_zone: Name of the availability zone to place
DBInstance into.
:type preferred_maintenance_window: str
:param preferred_maintenance_window: The weekly time range (in UTC)
during which maintenance can occur.
Default is Sun:05:00-Sun:09:00
:type backup_retention_period: int
:param backup_retention_period: The number of days for which automated
backups are retained. Setting this to
zero disables automated backups.
:type preferred_backup_window: str
:param preferred_backup_window: The daily time range during which
automated backups are created (if
enabled). Must be in h24:mi-hh24:mi
format (UTC).
:type multi_az: bool
:param multi_az: If True, specifies the DB Instance will be
deployed in multiple availability zones.
:type engine_version: str
:param engine_version: Version number of the database engine to use.
:type auto_minor_version_upgrade: bool
:param auto_minor_version_upgrade: Indicates that minor engine
upgrades will be applied
automatically to the Read Replica
during the maintenance window.
Default is True.
:rtype: :class:`boto.rds.dbinstance.DBInstance`
:return: The new db instance.
"""
params = {'DBInstanceIdentifier' : id,
'AllocatedStorage' : allocated_storage,
'DBInstanceClass' : instance_class,
'Engine' : engine,
'MasterUsername' : master_username,
'MasterUserPassword' : master_password}
if port:
params['Port'] = port
if db_name:
params['DBName'] = db_name
if param_group:
params['DBParameterGroupName'] = param_group
if security_groups:
l = []
for group in security_groups:
if isinstance(group, DBSecurityGroup):
l.append(group.name)
else:
l.append(group)
self.build_list_params(params, l, 'DBSecurityGroups.member')
if availability_zone:
params['AvailabilityZone'] = availability_zone
if preferred_maintenance_window:
params['PreferredMaintenanceWindow'] = preferred_maintenance_window
if backup_retention_period:
params['BackupRetentionPeriod'] = backup_retention_period
if preferred_backup_window:
params['PreferredBackupWindow'] = preferred_backup_window
if multi_az:
params['MultiAZ'] = 'true'
if engine_version:
params['EngineVersion'] = engine_version
if auto_minor_version_upgrade is False:
params['AutoMinorVersionUpgrade'] = 'false'
return self.get_object('CreateDBInstance', params, DBInstance)
def create_dbinstance_read_replica(self, id, source_id,
instance_class=None,
port=3306,
availability_zone=None,
auto_minor_version_upgrade=None):
"""
Create a new DBInstance Read Replica.
:type id: str
:param id: Unique identifier for the new instance.
Must contain 1-63 alphanumeric characters.
First character must be a letter.
May not end with a hyphen or contain two consecutive hyphens
:type source_id: str
:param source_id: Unique identifier for the DB Instance for which this
DB Instance will act as a Read Replica.
:type instance_class: str
:param instance_class: The compute and memory capacity of the
DBInstance. Default is to inherit from
the source DB Instance.
Valid values are:
* db.m1.small
* db.m1.large
* db.m1.xlarge
* db.m2.xlarge
* db.m2.2xlarge
* db.m2.4xlarge
:type port: int
:param port: Port number on which database accepts connections.
Default is to inherit from source DB Instance.
Valid values [1115-65535]. Defaults to 3306.
:type availability_zone: str
:param availability_zone: Name of the availability zone to place
DBInstance into.
:type auto_minor_version_upgrade: bool
:param auto_minor_version_upgrade: Indicates that minor engine
upgrades will be applied
automatically to the Read Replica
during the maintenance window.
Default is to inherit this value
from the source DB Instance.
:rtype: :class:`boto.rds.dbinstance.DBInstance`
:return: The new db instance.
"""
params = {'DBInstanceIdentifier' : id,
'SourceDBInstanceIdentifier' : source_id}
if instance_class:
params['DBInstanceClass'] = instance_class
if port:
params['Port'] = port
if availability_zone:
params['AvailabilityZone'] = availability_zone
if auto_minor_version_upgrade is not None:
if auto_minor_version_upgrade is True:
params['AutoMinorVersionUpgrade'] = 'true'
else:
params['AutoMinorVersionUpgrade'] = 'false'
return self.get_object('CreateDBInstanceReadReplica',
params, DBInstance)
def modify_dbinstance(self, id, param_group=None, security_groups=None,
preferred_maintenance_window=None,
master_password=None, allocated_storage=None,
instance_class=None,
backup_retention_period=None,
preferred_backup_window=None,
multi_az=False,
apply_immediately=False):
"""
Modify an existing DBInstance.
:type id: str
:param id: Unique identifier for the new instance.
:type security_groups: list of str or list of DBSecurityGroup objects
:param security_groups: List of names of DBSecurityGroup to authorize on
this DBInstance.
:type preferred_maintenance_window: str
:param preferred_maintenance_window: The weekly time range (in UTC)
during which maintenance can
occur.
Default is Sun:05:00-Sun:09:00
:type master_password: str
:param master_password: Password of master user for the DBInstance.
Must be 4-15 alphanumeric characters.
:type allocated_storage: int
:param allocated_storage: The new allocated storage size, in GBs.
Valid values are [5-1024]
:type instance_class: str
:param instance_class: The compute and memory capacity of the
DBInstance. Changes will be applied at
next maintenance window unless
apply_immediately is True.
Valid values are:
* db.m1.small
* db.m1.large
* db.m1.xlarge
* db.m2.xlarge
* db.m2.2xlarge
* db.m2.4xlarge
:type apply_immediately: bool
:param apply_immediately: If true, the modifications will be applied
as soon as possible rather than waiting for
the next preferred maintenance window.
:type backup_retention_period: int
:param backup_retention_period: The number of days for which automated
backups are retained. Setting this to
zero disables automated backups.
:type preferred_backup_window: str
:param preferred_backup_window: The daily time range during which
automated backups are created (if
enabled). Must be in h24:mi-hh24:mi
format (UTC).
:type multi_az: bool
:param multi_az: If True, specifies the DB Instance will be
deployed in multiple availability zones.
:rtype: :class:`boto.rds.dbinstance.DBInstance`
:return: The modified db instance.
"""
params = {'DBInstanceIdentifier' : id}
if param_group:
params['DBParameterGroupName'] = param_group
if security_groups:
l = []
for group in security_groups:
if isinstance(group, DBSecurityGroup):
l.append(group.name)
else:
l.append(group)
self.build_list_params(params, l, 'DBSecurityGroups.member')
if preferred_maintenance_window:
params['PreferredMaintenanceWindow'] = preferred_maintenance_window
if master_password:
params['MasterUserPassword'] = master_password
if allocated_storage:
params['AllocatedStorage'] = allocated_storage
if instance_class:
params['DBInstanceClass'] = instance_class
if backup_retention_period:
params['BackupRetentionPeriod'] = backup_retention_period
if preferred_backup_window:
params['PreferredBackupWindow'] = preferred_backup_window
if multi_az:
params['MultiAZ'] = 'true'
if apply_immediately:
params['ApplyImmediately'] = 'true'
return self.get_object('ModifyDBInstance', params, DBInstance)
def delete_dbinstance(self, id, skip_final_snapshot=False,
final_snapshot_id=''):
"""
Delete an existing DBInstance.
:type id: str
:param id: Unique identifier for the new instance.
:type skip_final_snapshot: bool
:param skip_final_snapshot: This parameter determines whether a final
db snapshot is created before the instance
is deleted. If True, no snapshot is created.
If False, a snapshot is created before
deleting the instance.
:type final_snapshot_id: str
:param final_snapshot_id: If a final snapshot is requested, this
is the identifier used for that snapshot.
:rtype: :class:`boto.rds.dbinstance.DBInstance`
:return: The deleted db instance.
"""
params = {'DBInstanceIdentifier' : id}
if skip_final_snapshot:
params['SkipFinalSnapshot'] = 'true'
else:
params['SkipFinalSnapshot'] = 'false'
params['FinalDBSnapshotIdentifier'] = final_snapshot_id
return self.get_object('DeleteDBInstance', params, DBInstance)
def reboot_dbinstance(self, id):
"""
Reboot DBInstance.
:type id: str
:param id: Unique identifier of the instance.
:rtype: :class:`boto.rds.dbinstance.DBInstance`
:return: The rebooting db instance.
"""
params = {'DBInstanceIdentifier' : id}
return self.get_object('RebootDBInstance', params, DBInstance)
# DBParameterGroup methods
def get_all_dbparameter_groups(self, groupname=None, max_records=None,
marker=None):
"""
Get all parameter groups associated with your account in a region.
:type groupname: str
:param groupname: The name of the DBParameter group to retrieve.
If not provided, all DBParameter groups will be returned.
:type max_records: int
:param max_records: The maximum number of records to be returned.
If more results are available, a MoreToken will
be returned in the response that can be used to
retrieve additional records. Default is 100.
:type marker: str
:param marker: The marker provided by a previous request.
:rtype: list
:return: A list of :class:`boto.ec2.parametergroup.ParameterGroup`
"""
params = {}
if groupname:
params['DBParameterGroupName'] = groupname
if max_records:
params['MaxRecords'] = max_records
if marker:
params['Marker'] = marker
return self.get_list('DescribeDBParameterGroups', params,
[('DBParameterGroup', ParameterGroup)])
def get_all_dbparameters(self, groupname, source=None,
max_records=None, marker=None):
"""
Get all parameters associated with a ParameterGroup
:type groupname: str
:param groupname: The name of the DBParameter group to retrieve.
:type source: str
:param source: Specifies which parameters to return.
If not specified, all parameters will be returned.
Valid values are: user|system|engine-default
:type max_records: int
:param max_records: The maximum number of records to be returned.
If more results are available, a MoreToken will
be returned in the response that can be used to
retrieve additional records. Default is 100.
:type marker: str
:param marker: The marker provided by a previous request.
:rtype: :class:`boto.ec2.parametergroup.ParameterGroup`
:return: The ParameterGroup
"""
params = {'DBParameterGroupName' : groupname}
if source:
params['Source'] = source
if max_records:
params['MaxRecords'] = max_records
if marker:
params['Marker'] = marker
pg = self.get_object('DescribeDBParameters', params, ParameterGroup)
pg.name = groupname
return pg
def create_parameter_group(self, name, engine='MySQL5.1', description=''):
"""
Create a new dbparameter group for your account.
:type name: string
:param name: The name of the new dbparameter group
:type engine: str
:param engine: Name of database engine. Must be MySQL5.1 for now.
:type description: string
:param description: The description of the new security group
:rtype: :class:`boto.rds.dbsecuritygroup.DBSecurityGroup`
:return: The newly created DBSecurityGroup
"""
params = {'DBParameterGroupName': name,
'Engine': engine,
'Description' : description}
return self.get_object('CreateDBParameterGroup', params, ParameterGroup)
def modify_parameter_group(self, name, parameters=None):
"""
Modify a parameter group for your account.
:type name: string
:param name: The name of the new parameter group
:type parameters: list of :class:`boto.rds.parametergroup.Parameter`
:param parameters: The new parameters
:rtype: :class:`boto.rds.parametergroup.ParameterGroup`
:return: The newly created ParameterGroup
"""
params = {'DBParameterGroupName': name}
for i in range(0, len(parameters)):
parameter = parameters[i]
parameter.merge(params, i+1)
return self.get_list('ModifyDBParameterGroup', params, ParameterGroup)
def reset_parameter_group(self, name, reset_all_params=False, parameters=None):
"""
Resets some or all of the parameters of a ParameterGroup to the
default value
:type key_name: string
:param key_name: The name of the ParameterGroup to reset
:type parameters: list of :class:`boto.rds.parametergroup.Parameter`
:param parameters: The parameters to reset. If not supplied, all parameters
will be reset.
"""
params = {'DBParameterGroupName':name}
if reset_all_params:
params['ResetAllParameters'] = 'true'
else:
params['ResetAllParameters'] = 'false'
for i in range(0, len(parameters)):
parameter = parameters[i]
parameter.merge(params, i+1)
return self.get_status('ResetDBParameterGroup', params)
def delete_parameter_group(self, name):
"""
Delete a DBSecurityGroup from your account.
:type key_name: string
:param key_name: The name of the DBSecurityGroup to delete
"""
params = {'DBParameterGroupName':name}
return self.get_status('DeleteDBParameterGroup', params)
# DBSecurityGroup methods
def get_all_dbsecurity_groups(self, groupname=None, max_records=None,
marker=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 max_records: int
:param max_records: The maximum number of records to be returned.
If more results are available, a MoreToken will
be returned in the response that can be used to
retrieve additional records. Default is 100.
:type marker: str
:param marker: The marker provided by a previous request.
:rtype: list
:return: A list of :class:`boto.rds.dbsecuritygroup.DBSecurityGroup`
"""
params = {}
if groupname:
params['DBSecurityGroupName'] = groupname
if max_records:
params['MaxRecords'] = max_records
if marker:
params['Marker'] = marker
return self.get_list('DescribeDBSecurityGroups', params,
[('DBSecurityGroup', DBSecurityGroup)])
def create_dbsecurity_group(self, name, description=None):
"""
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.rds.dbsecuritygroup.DBSecurityGroup`
:return: The newly created DBSecurityGroup
"""
params = {'DBSecurityGroupName':name}
if description:
params['DBSecurityGroupDescription'] = description
group = self.get_object('CreateDBSecurityGroup', params, DBSecurityGroup)
group.name = name
group.description = description
return group
def delete_dbsecurity_group(self, name):
"""
Delete a DBSecurityGroup from your account.
:type key_name: string
:param key_name: The name of the DBSecurityGroup to delete
"""
params = {'DBSecurityGroupName':name}
return self.get_status('DeleteDBSecurityGroup', params)
def authorize_dbsecurity_group(self, group_name, cidr_ip=None,
ec2_security_group_name=None,
ec2_security_group_owner_id=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 a CIDR block but not both.
:type group_name: string
:param group_name: The name of the security group you are adding
the rule to.
:type ec2_security_group_name: string
:param ec2_security_group_name: The name of the EC2 security group you are
granting access to.
:type ec2_security_group_owner_id: string
:param ec2_security_group_owner_id: The ID of the owner of the EC2 security
group you are granting access to.
:type cidr_ip: string
:param cidr_ip: 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 = {'DBSecurityGroupName':group_name}
if ec2_security_group_name:
params['EC2SecurityGroupName'] = ec2_security_group_name
if ec2_security_group_owner_id:
params['EC2SecurityGroupOwnerId'] = ec2_security_group_owner_id
if cidr_ip:
params['CIDRIP'] = urllib.quote(cidr_ip)
return self.get_object('AuthorizeDBSecurityGroupIngress', params, DBSecurityGroup)
def revoke_security_group(self, group_name, ec2_security_group_name=None,
ec2_security_group_owner_id=None, cidr_ip=None):
"""
Remove an existing rule from an existing security group.
You need to pass in either ec2_security_group_name and
ec2_security_group_owner_id OR a CIDR block.
:type group_name: string
:param group_name: The name of the security group you are removing
the rule from.
:type ec2_security_group_name: string
:param ec2_security_group_name: The name of the EC2 security group you are
granting access to.
:type ec2_security_group_owner_id: string
:param ec2_security_group_owner_id: The ID of the owner of the EC2 security
group you are granting access to.
:type cidr_ip: string
:param cidr_ip: 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 = {'DBSecurityGroupName':group_name}
if ec2_security_group_name:
params['EC2SecurityGroupName'] = ec2_security_group_name
if ec2_security_group_owner_id:
params['EC2SecurityGroupOwnerId'] = ec2_security_group_owner_id
if cidr_ip:
params['CIDRIP'] = cidr_ip
return self.get_object('RevokeDBSecurityGroupIngress', params, DBSecurityGroup)
# DBSnapshot methods
def get_all_dbsnapshots(self, snapshot_id=None, instance_id=None,
max_records=None, marker=None):
"""
Get information about DB Snapshots.
:type snapshot_id: str
:param snapshot_id: The unique identifier of an RDS snapshot.
If not provided, all RDS snapshots will be returned.
:type instance_id: str
:param instance_id: The identifier of a DBInstance. If provided,
only the DBSnapshots related to that instance will
be returned.
If not provided, all RDS snapshots will be returned.
:type max_records: int
:param max_records: The maximum number of records to be returned.
If more results are available, a MoreToken will
be returned in the response that can be used to
retrieve additional records. Default is 100.
:type marker: str
:param marker: The marker provided by a previous request.
:rtype: list
:return: A list of :class:`boto.rds.dbsnapshot.DBSnapshot`
"""
params = {}
if snapshot_id:
params['DBSnapshotIdentifier'] = snapshot_id
if instance_id:
params['DBInstanceIdentifier'] = instance_id
if max_records:
params['MaxRecords'] = max_records
if marker:
params['Marker'] = marker
return self.get_list('DescribeDBSnapshots', params,
[('DBSnapshot', DBSnapshot)])
def create_dbsnapshot(self, snapshot_id, dbinstance_id):
"""
Create a new DB snapshot.
:type snapshot_id: string
:param snapshot_id: The identifier for the DBSnapshot
:type dbinstance_id: string
:param dbinstance_id: The source identifier for the RDS instance from
which the snapshot is created.
:rtype: :class:`boto.rds.dbsnapshot.DBSnapshot`
:return: The newly created DBSnapshot
"""
params = {'DBSnapshotIdentifier' : snapshot_id,
'DBInstanceIdentifier' : dbinstance_id}
return self.get_object('CreateDBSnapshot', params, DBSnapshot)
def delete_dbsnapshot(self, identifier):
"""
Delete a DBSnapshot
:type identifier: string
:param identifier: The identifier of the DBSnapshot to delete
"""
params = {'DBSnapshotIdentifier' : identifier}
return self.get_object('DeleteDBSnapshot', params, DBSnapshot)
def restore_dbinstance_from_dbsnapshot(self, identifier, instance_id,
instance_class, port=None,
availability_zone=None):
"""
Create a new DBInstance from a DB snapshot.
:type identifier: string
:param identifier: The identifier for the DBSnapshot
:type instance_id: string
:param instance_id: The source identifier for the RDS instance from
which the snapshot is created.
:type instance_class: str
:param instance_class: The compute and memory capacity of the DBInstance.
Valid values are:
db.m1.small | db.m1.large | db.m1.xlarge |
db.m2.2xlarge | db.m2.4xlarge
:type port: int
:param port: Port number on which database accepts connections.
Valid values [1115-65535]. Defaults to 3306.
:type availability_zone: str
:param availability_zone: Name of the availability zone to place
DBInstance into.
:rtype: :class:`boto.rds.dbinstance.DBInstance`
:return: The newly created DBInstance
"""
params = {'DBSnapshotIdentifier' : identifier,
'DBInstanceIdentifier' : instance_id,
'DBInstanceClass' : instance_class}
if port:
params['Port'] = port
if availability_zone:
params['AvailabilityZone'] = availability_zone
return self.get_object('RestoreDBInstanceFromDBSnapshot',
params, DBInstance)
def restore_dbinstance_from_point_in_time(self, source_instance_id,
target_instance_id,
use_latest=False,
restore_time=None,
dbinstance_class=None,
port=None,
availability_zone=None):
"""
Create a new DBInstance from a point in time.
:type source_instance_id: string
:param source_instance_id: The identifier for the source DBInstance.
:type target_instance_id: string
:param target_instance_id: The identifier of the new DBInstance.
:type use_latest: bool
:param use_latest: If True, the latest snapshot availabile will
be used.
:type restore_time: datetime
:param restore_time: The date and time to restore from. Only
used if use_latest is False.
:type instance_class: str
:param instance_class: The compute and memory capacity of the DBInstance.
Valid values are:
db.m1.small | db.m1.large | db.m1.xlarge |
db.m2.2xlarge | db.m2.4xlarge
:type port: int
:param port: Port number on which database accepts connections.
Valid values [1115-65535]. Defaults to 3306.
:type availability_zone: str
:param availability_zone: Name of the availability zone to place
DBInstance into.
:rtype: :class:`boto.rds.dbinstance.DBInstance`
:return: The newly created DBInstance
"""
params = {'SourceDBInstanceIdentifier' : source_instance_id,
'TargetDBInstanceIdentifier' : target_instance_id}
if use_latest:
params['UseLatestRestorableTime'] = 'true'
elif restore_time:
params['RestoreTime'] = restore_time.isoformat()
if dbinstance_class:
params['DBInstanceClass'] = dbinstance_class
if port:
params['Port'] = port
if availability_zone:
params['AvailabilityZone'] = availability_zone
return self.get_object('RestoreDBInstanceToPointInTime',
params, DBInstance)
# Events
def get_all_events(self, source_identifier=None, source_type=None,
start_time=None, end_time=None,
max_records=None, marker=None):
"""
Get information about events related to your DBInstances,
DBSecurityGroups and DBParameterGroups.
:type source_identifier: str
:param source_identifier: If supplied, the events returned will be
limited to those that apply to the identified
source. The value of this parameter depends
on the value of source_type. If neither
parameter is specified, all events in the time
span will be returned.
:type source_type: str
:param source_type: Specifies how the source_identifier should
be interpreted. Valid values are:
b-instance | db-security-group |
db-parameter-group | db-snapshot
:type start_time: datetime
:param start_time: The beginning of the time interval for events.
If not supplied, all available events will
be returned.
:type end_time: datetime
:param end_time: The ending of the time interval for events.
If not supplied, all available events will
be returned.
:type max_records: int
:param max_records: The maximum number of records to be returned.
If more results are available, a MoreToken will
be returned in the response that can be used to
retrieve additional records. Default is 100.
:type marker: str
:param marker: The marker provided by a previous request.
:rtype: list
:return: A list of class:`boto.rds.event.Event`
"""
params = {}
if source_identifier and source_type:
params['SourceIdentifier'] = source_identifier
params['SourceType'] = source_type
if start_time:
params['StartTime'] = start_time.isoformat()
if end_time:
params['EndTime'] = end_time.isoformat()
if max_records:
params['MaxRecords'] = max_records
if marker:
params['Marker'] = marker
return self.get_list('DescribeEvents', params, [('Event', Event)])
| 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.rds.dbsecuritygroup import DBSecurityGroup
from boto.rds.parametergroup import ParameterGroup
class DBInstance(object):
"""
Represents a RDS DBInstance
"""
def __init__(self, connection=None, id=None):
self.connection = connection
self.id = id
self.create_time = None
self.engine = None
self.status = None
self.allocated_storage = None
self.endpoint = None
self.instance_class = None
self.master_username = None
self.parameter_group = None
self.security_group = None
self.availability_zone = None
self.backup_retention_period = None
self.preferred_backup_window = None
self.preferred_maintenance_window = None
self.latest_restorable_time = None
self.multi_az = False
self._in_endpoint = False
self._port = None
self._address = None
def __repr__(self):
return 'DBInstance:%s' % self.id
def startElement(self, name, attrs, connection):
if name == 'Endpoint':
self._in_endpoint = True
elif name == 'DBParameterGroup':
self.parameter_group = ParameterGroup(self.connection)
return self.parameter_group
elif name == 'DBSecurityGroup':
self.security_group = DBSecurityGroup(self.connection)
return self.security_group
return None
def endElement(self, name, value, connection):
if name == 'DBInstanceIdentifier':
self.id = value
elif name == 'DBInstanceStatus':
self.status = value
elif name == 'InstanceCreateTime':
self.create_time = value
elif name == 'Engine':
self.engine = value
elif name == 'DBInstanceStatus':
self.status = value
elif name == 'AllocatedStorage':
self.allocated_storage = int(value)
elif name == 'DBInstanceClass':
self.instance_class = value
elif name == 'MasterUsername':
self.master_username = value
elif name == 'Port':
if self._in_endpoint:
self._port = int(value)
elif name == 'Address':
if self._in_endpoint:
self._address = value
elif name == 'Endpoint':
self.endpoint = (self._address, self._port)
self._in_endpoint = False
elif name == 'AvailabilityZone':
self.availability_zone = value
elif name == 'BackupRetentionPeriod':
self.backup_retention_period = value
elif name == 'LatestRestorableTime':
self.latest_restorable_time = value
elif name == 'PreferredMaintenanceWindow':
self.preferred_maintenance_window = value
elif name == 'PreferredBackupWindow':
self.preferred_backup_window = value
elif name == 'MultiAZ':
if value.lower() == 'true':
self.multi_az = True
else:
setattr(self, name, value)
def snapshot(self, snapshot_id):
"""
Create a new DB snapshot of this DBInstance.
:type identifier: string
:param identifier: The identifier for the DBSnapshot
:rtype: :class:`boto.rds.dbsnapshot.DBSnapshot`
:return: The newly created DBSnapshot
"""
return self.connection.create_dbsnapshot(snapshot_id, self.id)
def reboot(self):
"""
Reboot this DBInstance
:rtype: :class:`boto.rds.dbsnapshot.DBSnapshot`
:return: The newly created DBSnapshot
"""
return self.connection.reboot_dbinstance(self.id)
def stop(self, skip_final_snapshot, final_snapshot_id):
"""
Delete this DBInstance.
:type skip_final_snapshot: bool
:param skip_final_snapshot: This parameter determines whether a final
db snapshot is created before the instance
is deleted. If True, no snapshot is created.
If False, a snapshot is created before
deleting the instance.
:type final_snapshot_id: str
:param final_snapshot_id: If a final snapshot is requested, this
is the identifier used for that snapshot.
:rtype: :class:`boto.rds.dbinstance.DBInstance`
:return: The deleted db instance.
"""
return self.connection.delete_dbinstance(self.id,
skip_final_snapshot,
final_snapshot_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.
class LoggingInfo(object):
def __init__(self, bucket='', prefix=''):
self.bucket = bucket
self.prefix = prefix
def startElement(self, name, attrs, connection):
return None
def endElement(self, name, value, connection):
if name == 'Bucket':
self.bucket = value
elif name == 'Prefix':
self.prefix = 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.
import uuid
class OriginAccessIdentity:
def __init__(self, connection=None, config=None, id='',
s3_user_id='', comment=''):
self.connection = connection
self.config = config
self.id = id
self.s3_user_id = s3_user_id
self.comment = comment
self.etag = None
def startElement(self, name, attrs, connection):
if name == 'CloudFrontOriginAccessIdentityConfig':
self.config = OriginAccessIdentityConfig()
return self.config
else:
return None
def endElement(self, name, value, connection):
if name == 'Id':
self.id = value
elif name == 'S3CanonicalUserId':
self.s3_user_id = value
elif name == 'Comment':
self.comment = value
else:
setattr(self, name, value)
def update(self, comment=None):
new_config = OriginAccessIdentityConfig(self.connection,
self.config.caller_reference,
self.config.comment)
if comment != None:
new_config.comment = comment
self.etag = self.connection.set_origin_identity_config(self.id, self.etag, new_config)
self.config = new_config
def delete(self):
return self.connection.delete_origin_access_identity(self.id, self.etag)
def uri(self):
return 'origin-access-identity/cloudfront/%s' % self.id
class OriginAccessIdentityConfig:
def __init__(self, connection=None, caller_reference='', comment=''):
self.connection = connection
if caller_reference:
self.caller_reference = caller_reference
else:
self.caller_reference = str(uuid.uuid4())
self.comment = comment
def to_xml(self):
s = '<?xml version="1.0" encoding="UTF-8"?>\n'
s += '<CloudFrontOriginAccessIdentityConfig xmlns="http://cloudfront.amazonaws.com/doc/2009-09-09/">\n'
s += ' <CallerReference>%s</CallerReference>\n' % self.caller_reference
if self.comment:
s += ' <Comment>%s</Comment>\n' % self.comment
s += '</CloudFrontOriginAccessIdentityConfig>\n'
return s
def startElement(self, name, attrs, connection):
return None
def endElement(self, name, value, connection):
if name == 'Comment':
self.comment = value
elif name == 'CallerReference':
self.caller_reference = value
else:
setattr(self, name, value)
class OriginAccessIdentitySummary:
def __init__(self, connection=None, id='',
s3_user_id='', comment=''):
self.connection = connection
self.id = id
self.s3_user_id = s3_user_id
self.comment = comment
self.etag = None
def startElement(self, name, attrs, connection):
return None
def endElement(self, name, value, connection):
if name == 'Id':
self.id = value
elif name == 'S3CanonicalUserId':
self.s3_user_id = value
elif name == 'Comment':
self.comment = value
else:
setattr(self, name, value)
def get_origin_access_identity(self):
return self.connection.get_origin_access_identity_info(self.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.
from boto.exception import BotoServerError
class CloudFrontServerError(BotoServerError):
pass
| 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.s3.key import Key
class Object(Key):
def __init__(self, bucket, name=None):
Key.__init__(self, bucket, name=name)
self.distribution = bucket.distribution
def __repr__(self):
return '<Object: %s/%s>' % (self.distribution.config.origin, self.name)
def url(self, scheme='http'):
url = '%s://' % scheme
url += self.distribution.domain_name
if scheme.lower().startswith('rtmp'):
url += '/cfx/st/'
else:
url += '/'
url += self.name
return url
class StreamingObject(Object):
def url(self, scheme='rtmp'):
return Object.url(self, scheme)
| Python |
# Copyright (c) 2006-2010 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 uuid
import urllib
class InvalidationBatch(object):
"""A simple invalidation request.
:see: http://docs.amazonwebservices.com/AmazonCloudFront/2010-08-01/APIReference/index.html?InvalidationBatchDatatype.html
"""
def __init__(self, paths=[], connection=None, distribution=None, caller_reference=''):
"""Create a new invalidation request:
:paths: An array of paths to invalidate
"""
self.paths = paths
self.distribution = distribution
self.caller_reference = caller_reference
if not self.caller_reference:
self.caller_reference = str(uuid.uuid4())
# If we passed in a distribution,
# then we use that as the connection object
if distribution:
self.connection = connection
else:
self.connection = connection
def add(self, path):
"""Add another path to this invalidation request"""
return self.paths.append(path)
def remove(self, path):
"""Remove a path from this invalidation request"""
return self.paths.remove(path)
def __iter__(self):
return iter(self.paths)
def __getitem__(self, i):
return self.paths[i]
def __setitem__(self, k, v):
self.paths[k] = v
def escape(self, p):
"""Escape a path, make sure it begins with a slash and contains no invalid characters"""
if not p[0] == "/":
p = "/%s" % p
return urllib.quote(p)
def to_xml(self):
"""Get this batch as XML"""
assert self.connection != None
s = '<?xml version="1.0" encoding="UTF-8"?>\n'
s += '<InvalidationBatch xmlns="http://cloudfront.amazonaws.com/doc/%s/">\n' % self.connection.Version
for p in self.paths:
s += ' <Path>%s</Path>\n' % self.escape(p)
s += ' <CallerReference>%s</CallerReference>\n' % self.caller_reference
s += '</InvalidationBatch>\n'
return s
def startElement(self, name, attrs, connection):
if name == "InvalidationBatch":
self.paths = []
return None
def endElement(self, name, value, connection):
if name == 'Path':
self.paths.append(value)
elif name == "Status":
self.status = value
elif name == "Id":
self.id = id
elif name == "CreateTime":
self.create_time = value
elif name == "CallerReference":
self.caller_reference = value
return None
| 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 Signer:
def __init__(self):
self.id = None
self.key_pair_ids = []
def startElement(self, name, attrs, connection):
return None
def endElement(self, name, value, connection):
if name == 'Self':
self.id = 'Self'
elif name == 'AwsAccountNumber':
self.id = value
elif name == 'KeyPairId':
self.key_pair_ids.append(value)
class ActiveTrustedSigners(list):
def startElement(self, name, attrs, connection):
if name == 'Signer':
s = Signer()
self.append(s)
return s
def endElement(self, name, value, connection):
pass
class TrustedSigners(list):
def startElement(self, name, attrs, connection):
return None
def endElement(self, name, value, connection):
if name == 'Self':
self.append(name)
elif name == 'AwsAccountNumber':
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.
#
import xml.sax
import base64
import time
from boto.connection import AWSAuthConnection
from boto import handler
from boto.cloudfront.distribution import Distribution, DistributionSummary, DistributionConfig
from boto.cloudfront.distribution import StreamingDistribution, StreamingDistributionSummary, StreamingDistributionConfig
from boto.cloudfront.identity import OriginAccessIdentity
from boto.cloudfront.identity import OriginAccessIdentitySummary
from boto.cloudfront.identity import OriginAccessIdentityConfig
from boto.cloudfront.invalidation import InvalidationBatch
from boto.resultset import ResultSet
from boto.cloudfront.exception import CloudFrontServerError
class CloudFrontConnection(AWSAuthConnection):
DefaultHost = 'cloudfront.amazonaws.com'
Version = '2010-08-01'
def __init__(self, aws_access_key_id=None, aws_secret_access_key=None,
port=None, proxy=None, proxy_port=None,
host=DefaultHost, debug=0):
AWSAuthConnection.__init__(self, host,
aws_access_key_id, aws_secret_access_key,
True, port, proxy, proxy_port, debug=debug)
def get_etag(self, response):
response_headers = response.msg
for key in response_headers.keys():
if key.lower() == 'etag':
return response_headers[key]
return None
def add_aws_auth_header(self, headers, method, path):
if not headers.has_key('Date'):
headers['Date'] = time.strftime("%a, %d %b %Y %H:%M:%S GMT",
time.gmtime())
hmac = self.hmac.copy()
hmac.update(headers['Date'])
b64_hmac = base64.encodestring(hmac.digest()).strip()
headers['Authorization'] = "AWS %s:%s" % (self.aws_access_key_id, b64_hmac)
# Generics
def _get_all_objects(self, resource, tags):
if not tags:
tags=[('DistributionSummary', DistributionSummary)]
response = self.make_request('GET', '/%s/%s' % (self.Version, resource))
body = response.read()
if response.status >= 300:
raise CloudFrontServerError(response.status, response.reason, body)
rs = ResultSet(tags)
h = handler.XmlHandler(rs, self)
xml.sax.parseString(body, h)
return rs
def _get_info(self, id, resource, dist_class):
uri = '/%s/%s/%s' % (self.Version, resource, id)
response = self.make_request('GET', uri)
body = response.read()
if response.status >= 300:
raise CloudFrontServerError(response.status, response.reason, body)
d = dist_class(connection=self)
response_headers = response.msg
for key in response_headers.keys():
if key.lower() == 'etag':
d.etag = response_headers[key]
h = handler.XmlHandler(d, self)
xml.sax.parseString(body, h)
return d
def _get_config(self, id, resource, config_class):
uri = '/%s/%s/%s/config' % (self.Version, resource, id)
response = self.make_request('GET', uri)
body = response.read()
if response.status >= 300:
raise CloudFrontServerError(response.status, response.reason, body)
d = config_class(connection=self)
d.etag = self.get_etag(response)
h = handler.XmlHandler(d, self)
xml.sax.parseString(body, h)
return d
def _set_config(self, distribution_id, etag, config):
if isinstance(config, StreamingDistributionConfig):
resource = 'streaming-distribution'
else:
resource = 'distribution'
uri = '/%s/%s/%s/config' % (self.Version, resource, distribution_id)
headers = {'If-Match' : etag, 'Content-Type' : 'text/xml'}
response = self.make_request('PUT', uri, headers, config.to_xml())
body = response.read()
if response.status != 200:
raise CloudFrontServerError(response.status, response.reason, body)
return self.get_etag(response)
def _create_object(self, config, resource, dist_class):
response = self.make_request('POST', '/%s/%s' % (self.Version, resource),
{'Content-Type' : 'text/xml'}, data=config.to_xml())
body = response.read()
if response.status == 201:
d = dist_class(connection=self)
h = handler.XmlHandler(d, self)
xml.sax.parseString(body, h)
d.etag = self.get_etag(response)
return d
else:
raise CloudFrontServerError(response.status, response.reason, body)
def _delete_object(self, id, etag, resource):
uri = '/%s/%s/%s' % (self.Version, resource, id)
response = self.make_request('DELETE', uri, {'If-Match' : etag})
body = response.read()
if response.status != 204:
raise CloudFrontServerError(response.status, response.reason, body)
# Distributions
def get_all_distributions(self):
tags=[('DistributionSummary', DistributionSummary)]
return self._get_all_objects('distribution', tags)
def get_distribution_info(self, distribution_id):
return self._get_info(distribution_id, 'distribution', Distribution)
def get_distribution_config(self, distribution_id):
return self._get_config(distribution_id, 'distribution',
DistributionConfig)
def set_distribution_config(self, distribution_id, etag, config):
return self._set_config(distribution_id, etag, config)
def create_distribution(self, origin, enabled, caller_reference='',
cnames=None, comment=''):
config = DistributionConfig(origin=origin, enabled=enabled,
caller_reference=caller_reference,
cnames=cnames, comment=comment)
return self._create_object(config, 'distribution', Distribution)
def delete_distribution(self, distribution_id, etag):
return self._delete_object(distribution_id, etag, 'distribution')
# Streaming Distributions
def get_all_streaming_distributions(self):
tags=[('StreamingDistributionSummary', StreamingDistributionSummary)]
return self._get_all_objects('streaming-distribution', tags)
def get_streaming_distribution_info(self, distribution_id):
return self._get_info(distribution_id, 'streaming-distribution',
StreamingDistribution)
def get_streaming_distribution_config(self, distribution_id):
return self._get_config(distribution_id, 'streaming-distribution',
StreamingDistributionConfig)
def set_streaming_distribution_config(self, distribution_id, etag, config):
return self._set_config(distribution_id, etag, config)
def create_streaming_distribution(self, origin, enabled,
caller_reference='',
cnames=None, comment=''):
config = StreamingDistributionConfig(origin=origin, enabled=enabled,
caller_reference=caller_reference,
cnames=cnames, comment=comment)
return self._create_object(config, 'streaming-distribution',
StreamingDistribution)
def delete_streaming_distribution(self, distribution_id, etag):
return self._delete_object(distribution_id, etag, 'streaming-distribution')
# Origin Access Identity
def get_all_origin_access_identity(self):
tags=[('CloudFrontOriginAccessIdentitySummary',
OriginAccessIdentitySummary)]
return self._get_all_objects('origin-access-identity/cloudfront', tags)
def get_origin_access_identity_info(self, access_id):
return self._get_info(access_id, 'origin-access-identity/cloudfront',
OriginAccessIdentity)
def get_origin_access_identity_config(self, access_id):
return self._get_config(access_id,
'origin-access-identity/cloudfront',
OriginAccessIdentityConfig)
def set_origin_access_identity_config(self, access_id,
etag, config):
return self._set_config(access_id, etag, config)
def create_origin_access_identity(self, caller_reference='', comment=''):
config = OriginAccessIdentityConfig(caller_reference=caller_reference,
comment=comment)
return self._create_object(config, 'origin-access-identity/cloudfront',
OriginAccessIdentity)
def delete_origin_access_identity(self, access_id, etag):
return self._delete_object(access_id, etag,
'origin-access-identity/cloudfront')
# Object Invalidation
def create_invalidation_request(self, distribution_id, paths, caller_reference=None):
"""Creates a new invalidation request
:see: http://docs.amazonwebservices.com/AmazonCloudFront/2010-08-01/APIReference/index.html?CreateInvalidation.html
"""
# We allow you to pass in either an array or
# an InvalidationBatch object
if not isinstance(paths, InvalidationBatch):
paths = InvalidationBatch(paths)
paths.connection = self
response = self.make_request('POST', '/%s/distribution/%s/invalidation' % (self.Version, distribution_id),
{'Content-Type' : 'text/xml'}, data=paths.to_xml())
body = response.read()
if response.status == 201:
h = handler.XmlHandler(paths, self)
xml.sax.parseString(body, h)
return paths
else:
raise CloudFrontServerError(response.status, response.reason, body)
| 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 uuid
from boto.cloudfront.identity import OriginAccessIdentity
from boto.cloudfront.object import Object, StreamingObject
from boto.cloudfront.signers import ActiveTrustedSigners, TrustedSigners
from boto.cloudfront.logging import LoggingInfo
from boto.s3.acl import ACL
class DistributionConfig:
def __init__(self, connection=None, origin='', enabled=False,
caller_reference='', cnames=None, comment='',
origin_access_identity=None, trusted_signers=None,
default_root_object=None):
self.connection = connection
self.origin = origin
self.enabled = enabled
if caller_reference:
self.caller_reference = caller_reference
else:
self.caller_reference = str(uuid.uuid4())
self.cnames = []
if cnames:
self.cnames = cnames
self.comment = comment
self.origin_access_identity = origin_access_identity
self.trusted_signers = trusted_signers
self.logging = None
self.default_root_object = default_root_object
def get_oai_value(self):
if isinstance(self.origin_access_identity, OriginAccessIdentity):
return self.origin_access_identity.uri()
else:
return self.origin_access_identity
def to_xml(self):
s = '<?xml version="1.0" encoding="UTF-8"?>\n'
s += '<DistributionConfig xmlns="http://cloudfront.amazonaws.com/doc/2010-07-15/">\n'
s += ' <Origin>%s</Origin>\n' % self.origin
s += ' <CallerReference>%s</CallerReference>\n' % self.caller_reference
for cname in self.cnames:
s += ' <CNAME>%s</CNAME>\n' % cname
if self.comment:
s += ' <Comment>%s</Comment>\n' % self.comment
s += ' <Enabled>'
if self.enabled:
s += 'true'
else:
s += 'false'
s += '</Enabled>\n'
if self.origin_access_identity:
val = self.get_oai_value()
s += '<OriginAccessIdentity>%s</OriginAccessIdentity>\n' % val
if self.trusted_signers:
s += '<TrustedSigners>\n'
for signer in self.trusted_signers:
if signer == 'Self':
s += ' <Self></Self>\n'
else:
s += ' <AwsAccountNumber>%s</AwsAccountNumber>\n' % signer
s += '</TrustedSigners>\n'
if self.logging:
s += '<Logging>\n'
s += ' <Bucket>%s</Bucket>\n' % self.logging.bucket
s += ' <Prefix>%s</Prefix>\n' % self.logging.prefix
s += '</Logging>\n'
if self.default_root_object:
dro = self.default_root_object
s += '<DefaultRootObject>%s</DefaultRootObject>\n' % dro
s += '</DistributionConfig>\n'
return s
def startElement(self, name, attrs, connection):
if name == 'TrustedSigners':
self.trusted_signers = TrustedSigners()
return self.trusted_signers
elif name == 'Logging':
self.logging = LoggingInfo()
return self.logging
else:
return None
def endElement(self, name, value, connection):
if name == 'CNAME':
self.cnames.append(value)
elif name == 'Origin':
self.origin = value
elif name == 'Comment':
self.comment = value
elif name == 'Enabled':
if value.lower() == 'true':
self.enabled = True
else:
self.enabled = False
elif name == 'CallerReference':
self.caller_reference = value
elif name == 'OriginAccessIdentity':
self.origin_access_identity = value
elif name == 'DefaultRootObject':
self.default_root_object = value
else:
setattr(self, name, value)
class StreamingDistributionConfig(DistributionConfig):
def __init__(self, connection=None, origin='', enabled=False,
caller_reference='', cnames=None, comment=''):
DistributionConfig.__init__(self, connection, origin,
enabled, caller_reference,
cnames, comment)
def to_xml(self):
s = '<?xml version="1.0" encoding="UTF-8"?>\n'
s += '<StreamingDistributionConfig xmlns="http://cloudfront.amazonaws.com/doc/2009-12-01/">\n'
s += ' <Origin>%s</Origin>\n' % self.origin
s += ' <CallerReference>%s</CallerReference>\n' % self.caller_reference
for cname in self.cnames:
s += ' <CNAME>%s</CNAME>\n' % cname
if self.comment:
s += ' <Comment>%s</Comment>\n' % self.comment
s += ' <Enabled>'
if self.enabled:
s += 'true'
else:
s += 'false'
s += '</Enabled>\n'
s += '</StreamingDistributionConfig>\n'
return s
def startElement(self, name, attrs, connection):
pass
class DistributionSummary:
def __init__(self, connection=None, domain_name='', id='',
last_modified_time=None, status='', origin='',
cname='', comment='', enabled=False):
self.connection = connection
self.domain_name = domain_name
self.id = id
self.last_modified_time = last_modified_time
self.status = status
self.origin = origin
self.enabled = enabled
self.cnames = []
if cname:
self.cnames.append(cname)
self.comment = comment
self.trusted_signers = None
self.etag = None
self.streaming = False
def startElement(self, name, attrs, connection):
if name == 'TrustedSigners':
self.trusted_signers = TrustedSigners()
return self.trusted_signers
return None
def endElement(self, name, value, connection):
if name == 'Id':
self.id = value
elif name == 'Status':
self.status = value
elif name == 'LastModifiedTime':
self.last_modified_time = value
elif name == 'DomainName':
self.domain_name = value
elif name == 'Origin':
self.origin = value
elif name == 'CNAME':
self.cnames.append(value)
elif name == 'Comment':
self.comment = value
elif name == 'Enabled':
if value.lower() == 'true':
self.enabled = True
else:
self.enabled = False
elif name == 'StreamingDistributionSummary':
self.streaming = True
else:
setattr(self, name, value)
def get_distribution(self):
return self.connection.get_distribution_info(self.id)
class StreamingDistributionSummary(DistributionSummary):
def get_distribution(self):
return self.connection.get_streaming_distribution_info(self.id)
class Distribution:
def __init__(self, connection=None, config=None, domain_name='',
id='', last_modified_time=None, status=''):
self.connection = connection
self.config = config
self.domain_name = domain_name
self.id = id
self.last_modified_time = last_modified_time
self.status = status
self.active_signers = None
self.etag = None
self._bucket = None
self._object_class = Object
def startElement(self, name, attrs, connection):
if name == 'DistributionConfig':
self.config = DistributionConfig()
return self.config
elif name == 'ActiveTrustedSigners':
self.active_signers = ActiveTrustedSigners()
return self.active_signers
else:
return None
def endElement(self, name, value, connection):
if name == 'Id':
self.id = value
elif name == 'LastModifiedTime':
self.last_modified_time = value
elif name == 'Status':
self.status = value
elif name == 'DomainName':
self.domain_name = value
else:
setattr(self, name, value)
def update(self, enabled=None, cnames=None, comment=None,
origin_access_identity=None,
trusted_signers=None,
default_root_object=None):
"""
Update the configuration of the Distribution.
:type enabled: bool
:param enabled: Whether the Distribution is active or not.
:type cnames: list of str
:param cnames: The DNS CNAME's associated with this
Distribution. Maximum of 10 values.
:type comment: str or unicode
:param comment: The comment associated with the Distribution.
:type origin_access_identity: :class:`boto.cloudfront.identity.OriginAccessIdentity`
:param origin_access_identity: The CloudFront origin access identity
associated with the distribution. This
must be provided if you want the
distribution to serve private content.
:type trusted_signers: :class:`boto.cloudfront.signers.TrustedSigner`
:param trusted_signers: The AWS users who are authorized to sign
URL's for private content in this Distribution.
:type default_root_object: str
:param default_root_object: An option field that specifies a default
root object for the distribution (e.g. index.html)
"""
new_config = DistributionConfig(self.connection, self.config.origin,
self.config.enabled, self.config.caller_reference,
self.config.cnames, self.config.comment,
self.config.origin_access_identity,
self.config.trusted_signers,
self.config.default_root_object)
if enabled != None:
new_config.enabled = enabled
if cnames != None:
new_config.cnames = cnames
if comment != None:
new_config.comment = comment
if origin_access_identity != None:
new_config.origin_access_identity = origin_access_identity
if trusted_signers:
new_config.trusted_signers = trusted_signers
if default_root_object:
new_config.default_root_object = default_root_object
self.etag = self.connection.set_distribution_config(self.id, self.etag, new_config)
self.config = new_config
self._object_class = Object
def enable(self):
"""
Deactivate the Distribution. A convenience wrapper around
the update method.
"""
self.update(enabled=True)
def disable(self):
"""
Activate the Distribution. A convenience wrapper around
the update method.
"""
self.update(enabled=False)
def delete(self):
"""
Delete this CloudFront Distribution. The content
associated with the Distribution is not deleted from
the underlying Origin bucket in S3.
"""
self.connection.delete_distribution(self.id, self.etag)
def _get_bucket(self):
if not self._bucket:
bucket_name = self.config.origin.split('.')[0]
from boto.s3.connection import S3Connection
s3 = S3Connection(self.connection.aws_access_key_id,
self.connection.aws_secret_access_key,
proxy=self.connection.proxy,
proxy_port=self.connection.proxy_port,
proxy_user=self.connection.proxy_user,
proxy_pass=self.connection.proxy_pass)
self._bucket = s3.get_bucket(bucket_name)
self._bucket.distribution = self
self._bucket.set_key_class(self._object_class)
return self._bucket
def get_objects(self):
"""
Return a list of all content objects in this distribution.
:rtype: list of :class:`boto.cloudfront.object.Object`
:return: The content objects
"""
bucket = self._get_bucket()
objs = []
for key in bucket:
objs.append(key)
return objs
def set_permissions(self, object, replace=False):
"""
Sets the S3 ACL grants for the given object to the appropriate
value based on the type of Distribution. If the Distribution
is serving private content the ACL will be set to include the
Origin Access Identity associated with the Distribution. If
the Distribution is serving public content the content will
be set up with "public-read".
:type object: :class:`boto.cloudfront.object.Object`
:param enabled: The Object whose ACL is being set
:type replace: bool
:param replace: If False, the Origin Access Identity will be
appended to the existing ACL for the object.
If True, the ACL for the object will be
completely replaced with one that grants
READ permission to the Origin Access Identity.
"""
if self.config.origin_access_identity:
id = self.config.origin_access_identity.split('/')[-1]
oai = self.connection.get_origin_access_identity_info(id)
policy = object.get_acl()
if replace:
policy.acl = ACL()
policy.acl.add_user_grant('READ', oai.s3_user_id)
object.set_acl(policy)
else:
object.set_canned_acl('public-read')
def set_permissions_all(self, replace=False):
"""
Sets the S3 ACL grants for all objects in the Distribution
to the appropriate value based on the type of Distribution.
:type replace: bool
:param replace: If False, the Origin Access Identity will be
appended to the existing ACL for the object.
If True, the ACL for the object will be
completely replaced with one that grants
READ permission to the Origin Access Identity.
"""
bucket = self._get_bucket()
for key in bucket:
self.set_permissions(key)
def add_object(self, name, content, headers=None, replace=True):
"""
Adds a new content object to the Distribution. The content
for the object will be copied to a new Key in the S3 Bucket
and the permissions will be set appropriately for the type
of Distribution.
:type name: str or unicode
:param name: The name or key of the new object.
:type content: file-like object
:param content: A file-like object that contains the content
for the new object.
:type headers: dict
:param headers: A dictionary containing additional headers
you would like associated with the new
object in S3.
:rtype: :class:`boto.cloudfront.object.Object`
:return: The newly created object.
"""
if self.config.origin_access_identity:
policy = 'private'
else:
policy = 'public-read'
bucket = self._get_bucket()
object = bucket.new_key(name)
object.set_contents_from_file(content, headers=headers, policy=policy)
if self.config.origin_access_identity:
self.set_permissions(object, replace)
return object
class StreamingDistribution(Distribution):
def __init__(self, connection=None, config=None, domain_name='',
id='', last_modified_time=None, status=''):
Distribution.__init__(self, connection, config, domain_name,
id, last_modified_time, status)
self._object_class = StreamingObject
def startElement(self, name, attrs, connection):
if name == 'StreamingDistributionConfig':
self.config = StreamingDistributionConfig()
return self.config
else:
return None
def update(self, enabled=None, cnames=None, comment=None):
"""
Update the configuration of the Distribution.
:type enabled: bool
:param enabled: Whether the Distribution is active or not.
:type cnames: list of str
:param cnames: The DNS CNAME's associated with this
Distribution. Maximum of 10 values.
:type comment: str or unicode
:param comment: The comment associated with the Distribution.
"""
new_config = StreamingDistributionConfig(self.connection,
self.config.origin,
self.config.enabled,
self.config.caller_reference,
self.config.cnames,
self.config.comment)
if enabled != None:
new_config.enabled = enabled
if cnames != None:
new_config.cnames = cnames
if comment != None:
new_config.comment = comment
self.etag = self.connection.set_streaming_distribution_config(self.id,
self.etag,
new_config)
self.config = new_config
def delete(self):
self.connection.delete_streaming_distribution(self.id, self.etag)
| 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.
#
# Parts of this code were copied or derived from sample code supplied by AWS.
# The following notice applies to that code.
#
# This software code is made available "AS IS" without warranties of any
# kind. You may copy, display, modify and redistribute the software
# code either by itself or as incorporated into your code; provided that
# you do not remove any proprietary notices. Your use of this software
# code is at your own risk and you waive any claim against Amazon
# Digital Services, Inc. or its affiliates with respect to your use of
# this software code. (c) 2006 Amazon Digital Services, Inc. or its
# affiliates.
"""
Some handy utility functions used by several classes.
"""
import re
import urllib
import urllib2
import imp
import subprocess
import StringIO
import time
import logging.handlers
import boto
import tempfile
import smtplib
import datetime
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import formatdate
from email import Encoders
try:
import hashlib
_hashfn = hashlib.sha512
except ImportError:
import md5
_hashfn = md5.md5
# generates the aws canonical string for the given parameters
def canonical_string(method, path, headers, expires=None,
provider=None):
if not provider:
provider = boto.provider.get_default()
interesting_headers = {}
for key in headers:
lk = key.lower()
if headers[key] != None and (lk in ['content-md5', 'content-type', 'date'] or
lk.startswith(provider.header_prefix)):
interesting_headers[lk] = headers[key].strip()
# these keys get empty strings if they don't exist
if not interesting_headers.has_key('content-type'):
interesting_headers['content-type'] = ''
if not interesting_headers.has_key('content-md5'):
interesting_headers['content-md5'] = ''
# just in case someone used this. it's not necessary in this lib.
if interesting_headers.has_key(provider.date_header):
interesting_headers['date'] = ''
# if you're using expires for query string auth, then it trumps date
# (and provider.date_header)
if expires:
interesting_headers['date'] = str(expires)
sorted_header_keys = interesting_headers.keys()
sorted_header_keys.sort()
buf = "%s\n" % method
for key in sorted_header_keys:
val = interesting_headers[key]
if key.startswith(provider.header_prefix):
buf += "%s:%s\n" % (key, val)
else:
buf += "%s\n" % val
# don't include anything after the first ? in the resource...
buf += "%s" % path.split('?')[0]
# ...unless there is an acl or torrent parameter
if re.search("[&?]acl($|=|&)", path):
buf += "?acl"
elif re.search("[&?]logging($|=|&)", path):
buf += "?logging"
elif re.search("[&?]torrent($|=|&)", path):
buf += "?torrent"
elif re.search("[&?]location($|=|&)", path):
buf += "?location"
elif re.search("[&?]requestPayment($|=|&)", path):
buf += "?requestPayment"
elif re.search("[&?]versions($|=|&)", path):
buf += "?versions"
elif re.search("[&?]versioning($|=|&)", path):
buf += "?versioning"
else:
m = re.search("[&?]versionId=([^&]+)($|=|&)", path)
if m:
buf += '?versionId=' + m.group(1)
return buf
def merge_meta(headers, metadata, provider=None):
if not provider:
provider = boto.provider.get_default()
metadata_prefix = provider.metadata_prefix
final_headers = headers.copy()
for k in metadata.keys():
if k.lower() in ['cache-control', 'content-md5', 'content-type',
'content-encoding', 'content-disposition',
'date', 'expires']:
final_headers[k] = metadata[k]
else:
final_headers[metadata_prefix + k] = metadata[k]
return final_headers
def get_aws_metadata(headers, provider=None):
if not provider:
provider = boto.provider.get_default()
metadata_prefix = provider.metadata_prefix
metadata = {}
for hkey in headers.keys():
if hkey.lower().startswith(metadata_prefix):
val = urllib.unquote_plus(headers[hkey])
metadata[hkey[len(metadata_prefix):]] = unicode(val, 'utf-8')
del headers[hkey]
return metadata
def retry_url(url, retry_on_404=True):
for i in range(0, 10):
try:
req = urllib2.Request(url)
resp = urllib2.urlopen(req)
return resp.read()
except urllib2.HTTPError, e:
# in 2.6 you use getcode(), in 2.5 and earlier you use code
if hasattr(e, 'getcode'):
code = e.getcode()
else:
code = e.code
if code == 404 and not retry_on_404:
return ''
except:
pass
boto.log.exception('Caught exception reading instance data')
time.sleep(2**i)
boto.log.error('Unable to read instance data, giving up')
return ''
def _get_instance_metadata(url):
d = {}
data = retry_url(url)
if data:
fields = data.split('\n')
for field in fields:
if field.endswith('/'):
d[field[0:-1]] = _get_instance_metadata(url + field)
else:
p = field.find('=')
if p > 0:
key = field[p+1:]
resource = field[0:p] + '/openssh-key'
else:
key = resource = field
val = retry_url(url + resource)
p = val.find('\n')
if p > 0:
val = val.split('\n')
d[key] = val
return d
def get_instance_metadata(version='latest'):
"""
Returns the instance metadata as a nested Python dictionary.
Simple values (e.g. local_hostname, hostname, etc.) will be
stored as string values. Values such as ancestor-ami-ids will
be stored in the dict as a list of string values. More complex
fields such as public-keys and will be stored as nested dicts.
"""
url = 'http://169.254.169.254/%s/meta-data/' % version
return _get_instance_metadata(url)
def get_instance_userdata(version='latest', sep=None):
url = 'http://169.254.169.254/%s/user-data' % version
user_data = retry_url(url, retry_on_404=False)
if user_data:
if sep:
l = user_data.split(sep)
user_data = {}
for nvpair in l:
t = nvpair.split('=')
user_data[t[0].strip()] = t[1].strip()
return user_data
ISO8601 = '%Y-%m-%dT%H:%M:%SZ'
def get_ts(ts=None):
if not ts:
ts = time.gmtime()
return time.strftime(ISO8601, ts)
def parse_ts(ts):
return datetime.datetime.strptime(ts, ISO8601)
def find_class(module_name, class_name=None):
if class_name:
module_name = "%s.%s" % (module_name, class_name)
modules = module_name.split('.')
c = None
try:
for m in modules[1:]:
if c:
c = getattr(c, m)
else:
c = getattr(__import__(".".join(modules[0:-1])), m)
return c
except:
return None
def update_dme(username, password, dme_id, ip_address):
"""
Update your Dynamic DNS record with DNSMadeEasy.com
"""
dme_url = 'https://www.dnsmadeeasy.com/servlet/updateip'
dme_url += '?username=%s&password=%s&id=%s&ip=%s'
s = urllib2.urlopen(dme_url % (username, password, dme_id, ip_address))
return s.read()
def fetch_file(uri, file=None, username=None, password=None):
"""
Fetch a file based on the URI provided. If you do not pass in a file pointer
a tempfile.NamedTemporaryFile, or None if the file could not be
retrieved is returned.
The URI can be either an HTTP url, or "s3://bucket_name/key_name"
"""
boto.log.info('Fetching %s' % uri)
if file == None:
file = tempfile.NamedTemporaryFile()
try:
if uri.startswith('s3://'):
bucket_name, key_name = uri[len('s3://'):].split('/', 1)
c = boto.connect_s3()
bucket = c.get_bucket(bucket_name)
key = bucket.get_key(key_name)
key.get_contents_to_file(file)
else:
if username and password:
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, uri, username, password)
authhandler = urllib2.HTTPBasicAuthHandler(passman)
opener = urllib2.build_opener(authhandler)
urllib2.install_opener(opener)
s = urllib2.urlopen(uri)
file.write(s.read())
file.seek(0)
except:
raise
boto.log.exception('Problem Retrieving file: %s' % uri)
file = None
return file
class ShellCommand(object):
def __init__(self, command, wait=True):
self.exit_code = 0
self.command = command
self.log_fp = StringIO.StringIO()
self.wait = wait
self.run()
def run(self):
boto.log.info('running:%s' % self.command)
self.process = subprocess.Popen(self.command, shell=True, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if(self.wait):
while self.process.poll() == None:
time.sleep(1)
t = self.process.communicate()
self.log_fp.write(t[0])
self.log_fp.write(t[1])
boto.log.info(self.log_fp.getvalue())
self.exit_code = self.process.returncode
return self.exit_code
def setReadOnly(self, value):
raise AttributeError
def getStatus(self):
return self.exit_code
status = property(getStatus, setReadOnly, None, 'The exit code for the command')
def getOutput(self):
return self.log_fp.getvalue()
output = property(getOutput, setReadOnly, None, 'The STDIN and STDERR output of the command')
class AuthSMTPHandler(logging.handlers.SMTPHandler):
"""
This class extends the SMTPHandler in the standard Python logging module
to accept a username and password on the constructor and to then use those
credentials to authenticate with the SMTP server. To use this, you could
add something like this in your boto config file:
[handler_hand07]
class=boto.utils.AuthSMTPHandler
level=WARN
formatter=form07
args=('localhost', 'username', 'password', 'from@abc', ['user1@abc', 'user2@xyz'], 'Logger Subject')
"""
def __init__(self, mailhost, username, password, fromaddr, toaddrs, subject):
"""
Initialize the handler.
We have extended the constructor to accept a username/password
for SMTP authentication.
"""
logging.handlers.SMTPHandler.__init__(self, mailhost, fromaddr, toaddrs, subject)
self.username = username
self.password = password
def emit(self, record):
"""
Emit a record.
Format the record and send it to the specified addressees.
It would be really nice if I could add authorization to this class
without having to resort to cut and paste inheritance but, no.
"""
try:
port = self.mailport
if not port:
port = smtplib.SMTP_PORT
smtp = smtplib.SMTP(self.mailhost, port)
smtp.login(self.username, self.password)
msg = self.format(record)
msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\nDate: %s\r\n\r\n%s" % (
self.fromaddr,
','.join(self.toaddrs),
self.getSubject(record),
formatdate(), msg)
smtp.sendmail(self.fromaddr, self.toaddrs, msg)
smtp.quit()
except (KeyboardInterrupt, SystemExit):
raise
except:
self.handleError(record)
class LRUCache(dict):
"""A dictionary-like object that stores only a certain number of items, and
discards its least recently used item when full.
>>> cache = LRUCache(3)
>>> cache['A'] = 0
>>> cache['B'] = 1
>>> cache['C'] = 2
>>> len(cache)
3
>>> cache['A']
0
Adding new items to the cache does not increase its size. Instead, the least
recently used item is dropped:
>>> cache['D'] = 3
>>> len(cache)
3
>>> 'B' in cache
False
Iterating over the cache returns the keys, starting with the most recently
used:
>>> for key in cache:
... print key
D
A
C
This code is based on the LRUCache class from Genshi which is based on
Mighty's LRUCache from ``myghtyutils.util``, written
by Mike Bayer and released under the MIT license (Genshi uses the
BSD License). See:
http://svn.myghty.org/myghtyutils/trunk/lib/myghtyutils/util.py
"""
class _Item(object):
def __init__(self, key, value):
self.previous = self.next = None
self.key = key
self.value = value
def __repr__(self):
return repr(self.value)
def __init__(self, capacity):
self._dict = dict()
self.capacity = capacity
self.head = None
self.tail = None
def __contains__(self, key):
return key in self._dict
def __iter__(self):
cur = self.head
while cur:
yield cur.key
cur = cur.next
def __len__(self):
return len(self._dict)
def __getitem__(self, key):
item = self._dict[key]
self._update_item(item)
return item.value
def __setitem__(self, key, value):
item = self._dict.get(key)
if item is None:
item = self._Item(key, value)
self._dict[key] = item
self._insert_item(item)
else:
item.value = value
self._update_item(item)
self._manage_size()
def __repr__(self):
return repr(self._dict)
def _insert_item(self, item):
item.previous = None
item.next = self.head
if self.head is not None:
self.head.previous = item
else:
self.tail = item
self.head = item
self._manage_size()
def _manage_size(self):
while len(self._dict) > self.capacity:
del self._dict[self.tail.key]
if self.tail != self.head:
self.tail = self.tail.previous
self.tail.next = None
else:
self.head = self.tail = None
def _update_item(self, item):
if self.head == item:
return
previous = item.previous
previous.next = item.next
if item.next is not None:
item.next.previous = previous
else:
self.tail = previous
item.previous = None
item.next = self.head
self.head.previous = self.head = item
class Password(object):
"""
Password object that stores itself as SHA512 hashed.
"""
def __init__(self, str=None):
"""
Load the string from an initial value, this should be the raw SHA512 hashed password
"""
self.str = str
def set(self, value):
self.str = _hashfn(value).hexdigest()
def __str__(self):
return str(self.str)
def __eq__(self, other):
if other == None:
return False
return str(_hashfn(other).hexdigest()) == str(self.str)
def __len__(self):
if self.str:
return len(self.str)
else:
return 0
def notify(subject, body=None, html_body=None, to_string=None, attachments=[], append_instance_id=True):
if append_instance_id:
subject = "[%s] %s" % (boto.config.get_value("Instance", "instance-id"), subject)
if not to_string:
to_string = boto.config.get_value('Notification', 'smtp_to', None)
if to_string:
try:
from_string = boto.config.get_value('Notification', 'smtp_from', 'boto')
msg = MIMEMultipart()
msg['From'] = from_string
msg['Reply-To'] = from_string
msg['To'] = to_string
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject
if body:
msg.attach(MIMEText(body))
if html_body:
part = MIMEBase('text', 'html')
part.set_payload(html_body)
Encoders.encode_base64(part)
msg.attach(part)
for part in attachments:
msg.attach(part)
smtp_host = boto.config.get_value('Notification', 'smtp_host', 'localhost')
# Alternate port support
if boto.config.get_value("Notification", "smtp_port"):
server = smtplib.SMTP(smtp_host, int(boto.config.get_value("Notification", "smtp_port")))
else:
server = smtplib.SMTP(smtp_host)
# TLS support
if boto.config.getbool("Notification", "smtp_tls"):
server.ehlo()
server.starttls()
server.ehlo()
smtp_user = boto.config.get_value('Notification', 'smtp_user', '')
smtp_pass = boto.config.get_value('Notification', 'smtp_pass', '')
if smtp_user:
server.login(smtp_user, smtp_pass)
server.sendmail(from_string, to_string, msg.as_string())
server.quit()
except:
boto.log.exception('notify failed')
| 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.