Here are the examples of the python api requestbuilder.exceptions.ArgumentError taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
49 Examples
3
Example 1
def configure(self):
AutoScalingRequest.configure(self)
if self.args.get('user_data'):
if os.path.isfile(self.args['user_data']):
raise ArgumentError(
'argument -d/--user-data: to pass the contents of a file '
'as user data, use -f/--user-data-file. To pass the '
"literal value '{0}' as user data even though it matches "
'the name of a file, use --user-data-force.')
else:
self.params['UserData'] = base64.b64encode(
self.args['user_data'])
elif self.args.get('user_data_force'):
self.params['UserData'] = base64.b64encode(
self.args['user_data_force'])
elif self.args.get('user_data_file'):
with open(self.args['user_data_file']) as user_data_file:
self.params['UserData'] = base64.b64encode(
user_data_file.read())
3
Example 2
def configure(self):
S3Request.configure(self)
if self.args['dest'] == '-':
self.args['dest'] = sys.stdout
self.args['show_progress'] = False
elif isinstance(self.args['dest'], basestring):
if not os.path.exists(self.args['dest']):
raise ArgumentError(
"argument -d/--directory: '{0}' does not exist"
.format(self.args['dest']))
if not os.path.isdir(self.args['dest']):
raise ArgumentError(
"argument -d/--directory: '{0}' is not a directory"
.format(self.args['dest']))
3
Example 3
Project: euca2ools Source File: mixins.py
def configure_bundle_upload_auth(self):
if self.args.get('upload_policy'):
if not self.args.get('key_id'):
raise ArgumentError('-I/--access-key-id is required when '
'using an upload policy')
if not self.args.get('upload_policy_signature'):
raise ArgumentError('--upload-policy-signature is required '
'when using an upload policy')
self.auth = None
3
Example 4
def _assert_is_file(filename, filetype):
if not os.path.exists(filename):
raise ArgumentError("{0} file '{1}' does not exist"
.format(filetype, filename))
if not os.path.isfile(filename):
raise ArgumentError("{0} file '{1}' is not a file"
.format(filetype, filename))
3
Example 5
def configure(self):
EC2Request.configure(self)
if self.args.get('positional_interface'):
if self.params.get('NetworkInterfaceId'):
# Shouldn't be supplied both positionally and optionally
raise ArgumentError('unrecognized arguments: {0}'.format(
self.args['positional_interface']))
self.params['NetworkInterfaceId'] = \
self.args['positional_interface']
if not self.params.get('NetworkInterfaceId'):
raise ArgumentError('argument -n/--network-interface is required')
3
Example 6
def configure(self):
EC2Request.configure(self)
if (self.args.get('PublicIp') is not None and
self.args.get('AllocationId') is not None):
# Can't be both EC2 and VPC
raise ArgumentError(
'argument -a/--allocation-id: not allowed with an IP address')
if (self.args.get('PublicIp') is None and
self.args.get('AllocationId') is None):
# ...but we still have to be one of them
raise ArgumentError(
'argument -a/--allocation-id or an IP address is required')
if (self.args.get('PublicIp') or '').startswith('eipalloc-'):
# Make allocation IDs work positionally for convenience
self.params['AllocationId'] = self.params.pop('PublicIp')
3
Example 7
def configure(self):
EC2Request.configure(self)
if self.args.get('positional_cidr'):
if self.params.get('CidrBlock'):
# Shouldn't be supplied both positionally and optionally
raise ArgumentError('unrecognized arguments: {0}'.format(
self.args['positional_cidr']))
self.params['CidrBlock'] = self.args['positional_cidr']
if not self.params.get('CidrBlock'):
raise ArgumentError('argument -i/--cidr is required')
3
Example 8
def configure(self):
EC2Request.configure(self)
if not self.args.get('Size') and not self.args.get('SnapshotId'):
raise ArgumentError('-s/--size or --snapshot must be specified')
if self.args.get('Iops') and not self.args.get('VolumeType'):
raise ArgumentError('argument -i/--iops: -t/--type is required')
if self.args.get('Iops') and self.args.get('VolumeType') == 'standard':
raise ArgumentError(
'argument -i/--iops: not allowed with volume type "standard"')
3
Example 9
def configure(self):
EC2Request.configure(self)
self.configure_s3_access()
if self.args.get('ignore_active_task') and not self.args.get('task'):
raise ArgumentError('argument --ignore-active-task my only be '
'used with -t/--task')
3
Example 10
Project: euca2ools Source File: deletediskimage.py
def __download_manifest(self, s3path):
with tempfile.SpooledTemporaryFile(max_size=1024000) as \
manifest_destfile:
get_req = GetObject.from_other(
self, service=self.args['s3_service'],
auth=self.args['s3_auth'], source=s3path,
dest=manifest_destfile, show_progress=False)
try:
get_req.main()
except AWSError as err:
if err.status_code == 404:
raise ArgumentError('import manifest "{0}" does not exist'
.format(s3path))
raise
manifest_destfile.seek(0)
return ImportManifest.read_from_fileobj(manifest_destfile)
3
Example 11
def configure(self):
EC2Request.configure(self)
if self.args.get('all', False):
if self.args.get('ImageId'):
raise ArgumentError('argument -a/--all: not allowed with '
'a list of images')
if self.args.get('ExecutableBy'):
raise ArgumentError('argument -a/--all: not allowed with '
'argument -x/--executable-by')
if self.args.get('Owner'):
raise ArgumentError('argument -a/--all: not allowed with '
'argument -o/--owner')
3
Example 12
def configure(self):
EC2Request.configure(self)
if self.args.get('all'):
if self.args.get('Owner'):
raise ArgumentError('argument -a/--all: not allowed with '
'argument -o/--owner')
if self.args.get('RestorableBy'):
raise ArgumentError('argument -a/--all: not allowed with '
'argument -r/--restorable-by')
3
Example 13
def configure(self):
EC2Request.configure(self)
if self.args.get('PublicIp'):
if self.args.get('AssociationId'):
raise ArgumentError('argument -a/--association-id: not '
'allowed with an IP address')
elif self.args['PublicIp'].startswith('eipassoc'):
raise ArgumentError('VPC elastic IP association IDs must be '
'be specified with -a/--association-id')
elif not self.args.get('AssociationId'):
raise ArgumentError(
'argument -a/--association-id or an IP address is required')
3
Example 14
Project: euca2ools Source File: mixins.py
def configure_s3_access(self):
if self.args.get('owner_akid') and not self.args.get('owner_sak'):
raise ArgumentError('argument -o/--owner-akid also requires '
'-w/--owner-sak')
if self.args.get('owner_sak') and not self.args.get('owner_akid'):
raise ArgumentError('argument -w/--owner-sak also requires '
'-o/--owner-akid')
if not self.args.get('s3_auth'):
if self.args.get('owner_sak') and self.args.get('owner_akid'):
self.args['s3_auth'] = S3Request.AUTH_CLASS.from_other(
self.auth, key_id=self.args['owner_akid'],
secret_key=self.args['owner_sak'])
else:
self.args['s3_auth'] = S3Request.AUTH_CLASS.from_other(
self.auth)
if not self.args.get('s3_service'):
self.args['s3_service'] = S3.from_other(
self.service, url=self.args.get('s3_url'))
3
Example 15
def configure(self):
EC2Request.configure(self)
if (self.args.get('Reset') and
any(self.args.get(attr) is not None for attr in
('Cpu', 'Disk', 'Memory'))):
# Basically, reset is mutually exclusive with everything else.
raise ArgumentError('argument --reset may not be used with '
'instance type attributes')
3
Example 16
def configure(self):
EC2Request.configure(self)
if (self.args.get('Attachment.DeleteOnTermination') is not None and
not self.args.get('Attachment.AttachmentId')):
raise ArgumentError('argument --delete-on-termination may only be '
'used with -a/--attachment')
if (self.args.get('Attachment.AttachmentId') and
self.args.get('Attachment.DeleteOnTermination') is None):
raise ArgumentError('argument -a/--attachment also requires '
'--delete-on-termination')
3
Example 17
def configure(self):
EC2Request.configure(self)
if self.args.get('positional_vpc'):
if self.params.get('VpcId'):
# Shouldn't be supplied both positionally and optionally
raise ArgumentError('unrecognized arguments: {0}'.format(
self.args['positional_vpc']))
self.params['VpcId'] = self.args['positional_vpc']
if not self.params.get('VpcId'):
raise ArgumentError('argument -c/--vpc is required')
3
Example 18
def configure(self):
EC2Request.configure(self)
if (self.args.get('PublicIp') is not None and
self.args.get('AllocationId') is not None):
# Can't be both EC2 and VPC
raise ArgumentError(
'argument -a/--allocation-id: not allowed with an IP address')
if (self.args.get('PublicIp') is None and
self.args.get('AllocationId') is None):
# ...but we still have to be one of them
raise ArgumentError(
'argument -a/--allocation-id or an IP address is required')
3
Example 19
Project: euca2ools Source File: resumeimport.py
def configure(self):
EC2Request.configure(self)
self.configure_s3_access()
if not self.args.get('expires'):
self.args['expires'] = 30
if self.args['expires'] < 1:
raise ArgumentError(
'argument -x/--expires: value must be positive')
3
Example 20
def configure(self):
ELBRequest.configure(self)
target = self.args['HealthCheck.Target']
protocol, _, rest = target.partition(':')
if not rest:
raise ArgumentError('argument -t/--target: must have form '
'PROTOCOL:PORT[/PATH]')
if protocol.lower() in ('http', 'https') and '/' not in rest:
raise ArgumentError('argument -t/--target: path is required for '
"protocol '{0}'".format(protocol))
3
Example 21
Project: euca2ools Source File: createloadbalancerpolicy.py
def key_value_attribute(attr_as_str):
if '=' not in attr_as_str:
raise ArgumentError(
"attribute '{0}' must have format NAME=VALUE".format(attr_as_str))
key, val = attr_as_str.split('=', 1)
if not key:
raise ArgumentError(
"attribute '{0}' must have a name".format(attr_as_str))
return {'AttributeName': key.strip(), 'AttributeValue': val.strip()}
3
Example 22
def configure(self):
CloudWatchRequest.configure(self)
if self.args.get('period'):
if self.args['period'] <= 0:
raise ArgumentError(
'argument --period: value must be positive')
elif self.args['period'] % 60 != 0:
raise ArgumentError(
'argument --period: value must be a multiple of 60')
3
Example 23
def configure(self):
S3Request.configure(self)
bucket, _, key = self.args['path'].partition('/')
if not bucket:
raise ArgumentError('path must contain a bucket name')
if not key:
raise ArgumentError('path must contain a key name')
3
Example 24
Project: euca2ools Source File: listbucket.py
def configure(self):
S3Request.configure(self)
for path in self.args['paths']:
if path.startswith('/'):
raise ArgumentError((
'argument \'{0}\' must not start with '
'"/"; format is BUCKET[/KEY]').format(path))
bucket = path.split('/', 1)[0]
try:
validate_generic_bucket_name(bucket)
except ValueError as err:
raise ArgumentError(
'bucket "{0}": {1}'.format(bucket, err.message))
3
Example 25
def configure(self):
S3Request.configure(self)
if self.args['source'] == '-':
self.files['file'] = sys.stdin
elif isinstance(self.args['source'], basestring):
self.files['file'] = open(self.args['source'])
else:
self.files['file'] = self.args['source']
bucket, _, key = self.args['dest'].partition('/')
if not bucket:
raise ArgumentError('destination bucket name must be non-empty')
if not key:
raise ArgumentError('destination key name must be non-empty')
3
Example 26
def __get_account_id(self):
account_id = self.config.get_user_option('account-id')
if not account_id:
account_id = os.getenv('EC2_USER_ID')
if not account_id:
raise ArgumentError(
'failed to determine account ID; set account-id for '
'the user in configuration or EC2_USER_ID in the '
'environment')
return account_id
2
Example 27
def configure(self):
S3Request.configure(self)
if self.args['source'] == '-':
if self.args.get('size') is None:
raise requestbuilder.exceptions.ArgumentError(
"argument --size is required when uploading stdin")
source = _FileObjectExtent(sys.stdin, self.args['size'])
elif isinstance(self.args['source'], basestring):
source = _FileObjectExtent.from_filename(
self.args['source'], size=self.args.get('size'))
else:
if self.args.get('size') is None:
raise requestbuilder.exceptions.ArgumentError(
"argument --size is required when uploading a file object")
source = _FileObjectExtent(self.args['source'], self.args['size'])
self.args['source'] = source
bucket, _, key = self.args['dest'].partition('/')
if not bucket:
raise requestbuilder.exceptions.ArgumentError(
'destination bucket name must be non-empty')
if not key:
raise requestbuilder.exceptions.ArgumentError(
'destination key name must be non-empty')
0
Example 28
def configure(self):
if os.geteuid() != 0:
raise RuntimeError('must be superuser')
if not self.args.get('arch'):
raise ArgumentError('argument -r/--arch is required')
# Farm all the bundle arg validation out to BundleImage
self.__build_bundle_command('/dev/null', image_size=1)
root_device = _get_root_device()
if self.args.get('inherit'):
self.__populate_args_from_metadata()
if not self.args.get('partition'):
self.args['partition'] = _get_partition_table_type(root_device)
if not self.args['partition']:
self.log.warn('could not determine the partition table type '
'for root device %s', root_device)
raise ArgumentError(
'could not determine the type of partition table to use; '
'specify one with -P/--partition')
self.log.info('discovered partition table type %s',
self.args['partition'])
if not self.args.get('fstab') and not self.args.get('generate_fstab'):
self.args['fstab'] = '/etc/fstab'
0
Example 29
def configure(self):
S3Request.configure(self)
# The private key could be the user's or the cloud's. In the config
# this is a user-level option.
if not self.args.get('privatekey'):
config_privatekey = self.config.get_user_option('private-key')
if self.args.get('userregion'):
self.args['privatekey'] = config_privatekey
elif 'EC2_PRIVATE_KEY' in os.environ:
self.args['privatekey'] = os.getenv('EC2_PRIVATE_KEY')
elif config_privatekey:
self.args['privatekey'] = config_privatekey
else:
raise ArgumentError(
'missing private key; please supply one with -k')
self.args['privatekey'] = os.path.expanduser(os.path.expandvars(
self.args['privatekey']))
if not os.path.exists(self.args['privatekey']):
raise ArgumentError("private key file '{0}' does not exist"
.format(self.args['privatekey']))
if not os.path.isfile(self.args['privatekey']):
raise ArgumentError("private key file '{0}' is not a file"
.format(self.args['privatekey']))
self.log.debug('private key: %s', self.args['privatekey'])
0
Example 30
Project: euca2ools Source File: mixins.py
def configure_bundle_creds(self):
# User's account ID (user-level)
if not self.args.get('user'):
config_val = self.config.get_user_option('account-id')
if 'EC2_USER_ID' in os.environ:
self.log.debug('using account ID from environment')
self.args['user'] = os.getenv('EC2_USER_ID')
elif config_val:
self.log.debug('using account ID from configuration')
self.args['user'] = config_val
if self.args.get('user'):
self.args['user'] = self.args['user'].replace('-', '')
if not self.args.get('user'):
raise ArgumentError(
'missing account ID; please supply one with --user')
self.log.debug('account ID: %s', self.args['user'])
# User's X.509 certificate (user-level in config)
if not self.args.get('cert'):
config_val = self.config.get_user_option('certificate')
if 'EC2_CERT' in os.environ:
self.log.debug('using certificate from environment')
self.args['cert'] = os.getenv('EC2_CERT')
elif 'EUCA_CERT' in os.environ: # used by the NC
self.log.debug('using certificate from environment')
self.args['cert'] = os.getenv('EUCA_CERT')
elif config_val:
self.log.debug('using certificate from configuration')
self.args['cert'] = config_val
if self.args.get('cert'):
self.args['cert'] = os.path.expanduser(os.path.expandvars(
self.args['cert']))
_assert_is_file(self.args['cert'], 'user certificate')
self.log.debug('certificate: %s', self.args.get('cert'))
# User's private key (user-level in config)
if not self.args.get('privatekey'):
config_val = self.config.get_user_option('private-key')
if 'EC2_PRIVATE_KEY' in os.environ:
self.log.debug('using private key from environment')
self.args['privatekey'] = os.getenv('EC2_PRIVATE_KEY')
if 'EUCA_PRIVATE_KEY' in os.environ: # used by the NC
self.log.debug('using private key from environment')
self.args['privatekey'] = os.getenv('EUCA_PRIVATE_KEY')
elif config_val:
self.log.debug('using private key from configuration')
self.args['privatekey'] = config_val
if self.args.get('privatekey'):
self.args['privatekey'] = os.path.expanduser(os.path.expandvars(
self.args['privatekey']))
_assert_is_file(self.args['privatekey'], 'private key')
self.log.debug('private key: %s', self.args.get('privatekey'))
# Cloud's X.509 cert (region-level in config)
if not self.args.get('ec2cert'):
config_val = self.config.get_region_option('certificate')
if 'EUCALYPTUS_CERT' in os.environ:
# This has no EC2 equivalent since they just bundle their cert.
self.log.debug('using cloud certificate from environment')
self.args['ec2cert'] = os.getenv('EUCALYPTUS_CERT')
elif config_val:
self.log.debug('using cloud certificate from configuration')
self.args['ec2cert'] = config_val
elif (self.args.get('bootstrap_service') and
self.args.get('bootstrap_auth')):
# Sending requests during configure() can be precarious.
# Pay close attention to ordering to ensure all
# of this request's dependencies have been fulfilled.
fetched_cert = self.__get_bundle_certificate(
self.args['bootstrap_service'],
self.args['bootstrap_auth'])
if fetched_cert:
self.log.debug('using cloud certificate from '
'bootstrap service')
self.args['ec2cert'] = fetched_cert
if self.args.get('ec2cert'):
self.args['ec2cert'] = os.path.expanduser(os.path.expandvars(
self.args['ec2cert']))
_assert_is_file(self.args['ec2cert'], 'cloud certificate')
if not self.args.get('ec2cert'):
raise ArgumentError(
'missing cloud certificate; please supply one with '
'--ec2cert or use --bootstrap-url to fetch one automatically')
self.log.debug('cloud certificate: %s', self.args['ec2cert'])
0
Example 31
Project: euca2ools Source File: mixins.py
def configure_bundle_output(self):
if (self.args.get('destination') and
os.path.exists(self.args['destination']) and not
os.path.isdir(self.args['destination'])):
raise ArgumentError("argument -d/--destination: '{0}' is not a "
"directory".format(self.args['destination']))
if self.args['image'] == '-':
self.args['image'] = os.fdopen(os.dup(sys.stdin.fileno()))
if not self.args.get('prefix'):
raise ArgumentError(
'argument --prefix is required when bundling stdin')
if not self.args.get('image_size'):
raise ArgumentError(
'argument --image-size is required when bundling stdin')
elif isinstance(self.args['image'], basestring):
if not self.args.get('prefix'):
self.args['prefix'] = os.path.basename(self.args['image'])
if not self.args.get('image_size'):
self.args['image_size'] = euca2ools.util.get_filesize(
self.args['image'])
self.args['image'] = open(self.args['image'])
else:
# Assume it is already a file object
if not self.args.get('prefix'):
raise ArgumentError('argument --prefix is required when '
'bundling a file object')
if not self.args.get('image_size'):
raise ArgumentError('argument --image-size is required when '
'bundling a file object')
if self.args['image_size'] > EC2_BUNDLE_SIZE_LIMIT:
self.log.warn(
'image is incompatible with EC2 due to its size (%i > %i)',
self.args['image_size'], EC2_BUNDLE_SIZE_LIMIT)
0
Example 32
Project: euca2ools Source File: mixins.py
def configure_bundle_properties(self):
if self.args.get('kernel') == 'true':
self.args['image_type'] = 'kernel'
if self.args.get('ramdisk') == 'true':
self.args['image_type'] = 'ramdisk'
if self.args['image_type'] == 'kernel':
if self.args.get('kernel') and self.args['kernel'] != 'true':
raise ArgumentError("argument --kernel: not compatible with "
"image type 'kernel'")
if self.args.get('ramdisk'):
raise ArgumentError("argument --ramdisk: not compatible with "
"image type 'kernel'")
if self.args.get('block_device_mappings'):
raise ArgumentError("argument -B/--block-device-mappings: not "
"compatible with image type 'kernel'")
if self.args['image_type'] == 'ramdisk':
if self.args.get('kernel'):
raise ArgumentError("argument --kernel: not compatible with "
"image type 'ramdisk'")
if self.args.get('ramdisk') and self.args['ramdisk'] != 'true':
raise ArgumentError("argument --ramdisk: not compatible with "
"image type 'ramdisk'")
if self.args.get('block_device_mappings'):
raise ArgumentError("argument -B/--block-device-mappings: not "
"compatible with image type 'ramdisk'")
0
Example 33
Project: euca2ools Source File: unbundle.py
def configure(self):
BaseCommand.configure(self)
self.update_config_view()
# The private key could be the user's or the cloud's. In the config
# this is a user-level option.
if not self.args.get('privatekey'):
config_privatekey = self.config.get_user_option('private-key')
if self.args.get('userregion'):
self.args['privatekey'] = config_privatekey
elif 'EC2_PRIVATE_KEY' in os.environ:
self.args['privatekey'] = os.getenv('EC2_PRIVATE_KEY')
elif config_privatekey:
self.args['privatekey'] = config_privatekey
else:
raise ArgumentError(
'missing private key; please supply one with -k')
self.args['privatekey'] = os.path.expanduser(os.path.expandvars(
self.args['privatekey']))
if not os.path.exists(self.args['privatekey']):
raise ArgumentError("private key file '{0}' does not exist"
.format(self.args['privatekey']))
if not os.path.isfile(self.args['privatekey']):
raise ArgumentError("private key file '{0}' is not a file"
.format(self.args['privatekey']))
self.log.debug('private key: %s', self.args['privatekey'])
if not os.path.exists(self.args.get('source', '.')):
raise ArgumentError("argument -s/--source: directory '{0}' does "
"not exist".format(self.args['source']))
if not os.path.isdir(self.args.get('source', '.')):
raise ArgumentError("argument -s/--source: '{0}' is not a "
"directory".format(self.args['source']))
if not os.path.exists(self.args.get('destination', '.')):
raise ArgumentError("argument -d/--destination: directory '{0}' "
"does not exist"
.format(self.args['destination']))
if not os.path.isdir(self.args.get('destination', '.')):
raise ArgumentError("argument -d/--destination: '{0}' is not a "
"directory".format(self.args['destination']))
0
Example 34
def configure(self):
EC2Request.configure(self)
if not self.params.get('Storage.S3.AWSAccessKeyId'):
config_key_id = self.config.get_user_option('key-id')
if config_key_id:
self.log.info('Using access key ID %s from configuration',
config_key_id)
self.params['Storage.S3.AWSAccessKeyId'] = config_key_id
else:
raise ArgumentError('argument -o/--owner-akid is required')
if not self.params.get('Storage.S3.UploadPolicy'):
if not self.args.get('owner_sak'):
config_secret_key = self.config.get_user_option('secret-key')
if config_secret_key:
self.log.info('Using secret key from configuration')
self.args['owner_sak'] = config_secret_key
else:
raise ArgumentError('argument -w/--owner-sak is required '
'when -c/--policy is not used')
elif not self.args.get('Storage.S3.UploadPolicySignature'):
if not self.args.get('owner_sak'):
config_secret_key = self.config.get_user_option('secret-key')
if config_secret_key:
self.log.info('Using secret key from configuration')
self.args['owner_sak'] = config_secret_key
else:
raise ArgumentError('argument -w/--owner-sak is required '
'when -s/--policy-signature is not '
'used')
0
Example 35
Project: euca2ools Source File: importinstance.py
def configure(self):
EC2Request.configure(self)
self.configure_s3_access()
if (self.params['DiskImage.1.Image.Format'].upper() in
('VMDK', 'VHD', 'RAW')):
self.params['DiskImage.1.Image.Format'] = \
self.params['DiskImage.1.Image.Format'].upper()
if not self.params.get('DiskImage.1.Image.Bytes'):
if self.params['DiskImage.1.Image.Format'] == 'RAW':
image_size = euca2ools.util.get_filesize(self.args['source'])
self.params['DiskImage.1.Image.Bytes'] = image_size
elif self.params['DiskImage.1.Image.Format'] == 'VMDK':
image_size = euca2ools.util.get_vmdk_image_size(
self.args['source'])
self.params['DiskImage.1.Image.Bytes'] = image_size
else:
raise ArgumentError(
'argument --image-size is required for {0} files'
.format(self.params['DiskImage.1.Image.Format']))
if not self.params.get('DiskImage.1.Volume.Size'):
vol_size = math.ceil(self.params['DiskImage.1.Image.Bytes'] /
2 ** 30)
self.params['DiskImage.1.Volume.Size'] = int(vol_size)
if not self.args.get('expires'):
self.args['expires'] = 30
if self.args['expires'] < 1:
raise ArgumentError(
'argument -x/--expires: value must be positive')
0
Example 36
Project: euca2ools Source File: importvolume.py
def configure(self):
EC2Request.configure(self)
self.configure_s3_access()
if self.params['Image.Format'].upper() in ('VMDK', 'VHD', 'RAW'):
self.params['Image.Format'] = self.params['Image.Format'].upper()
if not self.params.get('Image.Bytes'):
if self.params['Image.Format'] == 'RAW':
image_size = euca2ools.util.get_filesize(self.args['source'])
self.params['Image.Bytes'] = image_size
elif self.params['Image.Format'] == 'VMDK':
image_size = euca2ools.util.get_vmdk_image_size(
self.args['source'])
self.params['Image.Bytes'] = image_size
else:
raise ArgumentError(
'argument --image-size is required for {0} files'
.format(self.params['Image.Format']))
if not self.params.get('Volume.Size'):
vol_size = math.ceil(self.params['Image.Bytes'] / 2 ** 30)
self.params['Volume.Size'] = int(vol_size)
if not self.args.get('expires'):
self.args['expires'] = 30
if self.args['expires'] < 1:
raise ArgumentError(
'argument -x/--expires: value must be positive')
0
Example 37
def preprocess(self):
if self.args.get('launch_permission'):
lperm = {}
for entity in self.args.get('add', []):
lperm.setdefault('Add', [])
if entity == 'all':
lperm['Add'].append({'Group': entity})
else:
lperm['Add'].append({'UserId': entity})
for entity in self.args.get('remove', []):
lperm.setdefault('Remove', [])
if entity == 'all':
lperm['Remove'].append({'Group': entity})
else:
lperm['Remove'].append({'UserId': entity})
if not lperm:
raise ArgumentError('at least one entity must be specified '
'with -a/--add or -r/--remove')
self.params['LaunchPermission'] = lperm
else:
if self.args.get('add'):
raise ArgumentError('argument -a/--add may only be used '
'with -l/--launch-permission')
if self.args.get('remove'):
raise ArgumentError('argument -r/--remove may only be used '
'with -l/--launch-permission')
0
Example 38
Project: euca2ools Source File: modifynetworkaclentry.py
def configure(self):
EC2Request.configure(self)
if not self.params.get('Egress'):
self.params['Egress'] = False
proto = self.args.get('Protocol') or -1
try:
self.params['Protocol'] = int(proto)
except ValueError:
if proto.lower() == 'all':
self.params['Protocol'] = -1
else:
try:
self.params['Protocol'] = socket.getprotobyname(proto)
except socket.error:
raise ArgumentError('argument -n/--rule-number: unknown '
'protocol "{0}"'.format(proto))
from_port, to_port = parse_ports(proto, self.args.get('port_range'),
self.args.get('icmp_type_code'))
if self.params['Protocol'] == 1: # ICMP
self.params['Icmp.Type'] = from_port
self.params['Icmp.Code'] = to_port
else:
self.params['PortRange.From'] = from_port
self.params['PortRange.To'] = to_port
0
Example 39
Project: euca2ools Source File: modifysecuritygrouprule.py
def configure(self):
EC2Request.configure(self)
if self.args['group'].startswith('sg-'):
# The check could probably be a little better, but meh. Fix if
# needed.
self.params['GroupId'] = self.args['group']
else:
if self.args['egress']:
raise ArgumentError('egress rules must use group IDs, not '
'names')
self.params['GroupName'] = self.args['group']
target_group = self.args.get('target_group')
if target_group is not None:
if target_group.startswith('sg-'):
# Same note as above
self.params['IpPermissions.1.Groups.1.GroupId'] = target_group
else:
if self.args['egress']:
raise ArgumentError('argument -o: egress rules must use '
'group IDs, not names')
self.params['IpPermissions.1.Groups.1.GroupName'] = target_group
protocol = self.args.get('IpPermissions.1.IpProtocol')
if str(protocol).lower() in ('icmp', 'tcp', 'udp', '1', '6', '17'):
from_port, to_port = parse_ports(
protocol, self.args.get('port_range'),
self.args.get('icmp_type_code'))
self.params['IpPermissions.1.FromPort'] = from_port
self.params['IpPermissions.1.ToPort'] = to_port
elif str(protocol).lower() in ('all', '-1'):
self.params['IpPermissions.1.IpProtocol'] = -1
elif not str(protocol).isdigit():
try:
self.params['IpPermissions.1.IpProtocol'] = \
socket.getprotobyname(protocol)
except socket.error:
raise ArgumentError('argument -P: no such protocol: {0}'
.format(protocol))
if (not self.args.get('IpPermissions.1.IpRanges.1.GroupName') and
not self.args.get('IpPermissions.1.IpRanges.1.CidrIp')):
# Default rule target is the entire Internet
self.params['IpPermissions.1.IpRanges.1.CidrIp'] = '0.0.0.0/0'
if (self.params.get('IpPermissions.1.Groups.1.GroupName') and
not self.args.get('IpPermissions.1.Groups.1.UserId')):
raise ArgumentError('argument -u is required when -o names a '
'security group by name')
0
Example 40
def preprocess(self):
if self.args.get('create_volume_permission'):
cvperm = {}
for entity in self.args.get('add', []):
cvperm.setdefault('Add', [])
if entity == 'all':
cvperm['Add'].append({'Group': entity})
else:
cvperm['Add'].append({'UserId': entity})
for entity in self.args.get('remove', []):
cvperm.setdefault('Remove', [])
if entity == 'all':
cvperm['Remove'].append({'Group': entity})
else:
cvperm['Remove'].append({'UserId': entity})
if not cvperm:
raise ArgumentError('at least one entity must be specified '
'with -a/--add or -r/--remove')
self.params['CreateVolumePermission'] = cvperm
else:
if self.args.get('add'):
raise ArgumentError('argument -a/--add may only be used '
'with -c/--create-volume-permission')
if self.args.get('remove'):
raise ArgumentError('argument -r/--remove may only be used '
'with -c/--create-volume-permission')
0
Example 41
def preprocess(self):
if self.args.get('ImageLocation'):
# instance-store image
if self.args.get('RootDeviceName'):
raise ArgumentError('argument --root-device-name: not allowed '
'with argument MANIFEST')
if self.args.get('snapshot'):
raise ArgumentError('argument --snapshot: not allowed with '
'argument MANIFEST')
else:
# Try for an EBS image
if not self.params.get('RootDeviceName'):
self.params['RootDeviceName'] = '/dev/sda1'
snapshot = self.args.get('snapshot')
# Look for a mapping for the root device
for mapping in self.args['BlockDeviceMapping']:
if mapping.get('DeviceName') == self.params['RootDeviceName']:
if (snapshot != mapping.get('Ebs', {}).get('SnapshotId')
and snapshot):
# The mapping's snapshot differs or doesn't exist
raise ArgumentError(
'snapshot ID supplied with --snapshot conflicts '
'with block device mapping for root device {0}'
.format(mapping['DeviceName']))
else:
# No need to apply --snapshot since the mapping is
# already there
break
else:
if snapshot:
self.params['BlockDeviceMapping'].append(
{'DeviceName': self.params['RootDeviceName'],
'Ebs': {'SnapshotId': snapshot}})
else:
raise ArgumentError(
'either a manifest location or a root device snapshot '
'mapping must be specified')
0
Example 42
Project: euca2ools Source File: resumeimport.py
def main(self):
if self.args.get('dry_run'):
return
if self.args.get('show_progress', False):
print 'Uploading image for task', self.args['task']
# Manifest
desc_conv = DescribeConversionTasks.from_other(
self, ConversionTaskId=[self.args['task']])
task = desc_conv.main()['conversionTasks'][0]
assert task['conversionTaskId'] == self.args['task']
if task.get('importVolume'):
vol_container = task['importVolume']
else:
vol_container = task['importInstance']['volumes'][0]
file_size = euca2ools.util.get_filesize(self.args['source'])
manifest = self.__get_or_create_manifest(vol_container, file_size)
file_size_from_manifest = manifest.image_parts[-1].end + 1
if file_size_from_manifest != file_size:
raise ArgumentError(
'file "{0}" is not the same size as the file the import '
'started with (expected: {1}, actual: {2})'
.format(self.args['source'], file_size_from_manifest,
file_size))
# Now we have a manifest; check to see what parts are already uploaded
_, bucket, _ = self.args['s3_service'].resolve_url_to_location(
vol_container['image']['importManifestUrl'])
pbar_label_template = euca2ools.util.build_progressbar_label_template(
[os.path.basename(part.key) for part in manifest.image_parts])
for part in manifest.image_parts:
part_s3path = '/'.join((bucket, part.key))
head_req = HeadObject.from_other(
self, service=self.args['s3_service'],
auth=self.args['s3_auth'], path=part_s3path)
try:
head_req.main()
except AWSError as err:
if err.status_code == 404:
self.__upload_part(part, part_s3path, pbar_label_template)
else:
raise
0
Example 43
def configure(self):
EC2Request.configure(self)
if self.args.get('user_data'):
if os.path.isfile(self.args['user_data']):
raise ArgumentError(
'argument -d/--user-data: to pass the contents of a file '
'as user data, use -f/--user-data-file. To pass the '
"literal value '{0}' as user data even though it matches "
'the name of a file, use --user-data-force.')
else:
self.params['UserData'] = base64.b64encode(
self.args['user_data'])
elif self.args.get('user_data_force'):
self.params['UserData'] = base64.b64encode(
self.args['user_data_force'])
elif self.args.get('user_data_file'):
with open(self.args['user_data_file']) as user_data_file:
self.params['UserData'] = base64.b64encode(
user_data_file.read())
if self.args.get('KeyName') is None:
default_key_name = self.config.get_region_option(
'ec2-default-keypair')
if default_key_name:
self.log.info("using default key pair '%s'", default_key_name)
self.params['KeyName'] = default_key_name
0
Example 44
def preprocess(self):
counts = self.args['count'].split('-')
if len(counts) == 1:
try:
self.params['MinCount'] = int(counts[0])
self.params['MaxCount'] = int(counts[0])
except ValueError:
raise ArgumentError('argument -n/--instance-count: instance '
'count must be an integer')
elif len(counts) == 2:
try:
self.params['MinCount'] = int(counts[0])
self.params['MaxCount'] = int(counts[1])
except ValueError:
raise ArgumentError('argument -n/--instance-count: instance '
'count range must be must be comprised of '
'integers')
else:
raise ArgumentError('argument -n/--instance-count: value must '
'have format "1" or "1-2"')
if self.params['MinCount'] < 1 or self.params['MaxCount'] < 1:
raise ArgumentError('argument -n/--instance-count: instance count '
'must be positive')
if self.params['MinCount'] > self.params['MaxCount']:
self.log.debug('MinCount > MaxCount; swapping')
self.params.update({'MinCount': self.params['MaxCount'],
'MaxCount': self.params['MinCount']})
iprofile = self.args.get('iam_profile')
if iprofile:
if iprofile.startswith('arn:'):
self.params['IamInstanceProfile.Arn'] = iprofile
else:
self.params['IamInstanceProfile.Name'] = iprofile
if self.args.get('subnet') or self.args.get('NetworkInterface'):
# This is going into a VPC.
# We can't mix top-level and interface-level parameters, so
# build an interface out of all the network-related options
# to make the split-up, "friendlier" options work.
cli_iface = {}
for group in self.args['group']:
if not group.startswith('sg-'):
raise ArgumentError('argument -g/--group: groups must be '
'specified by ID when using VPC')
cli_iface.setdefault('SecurityGroupId', [])
cli_iface['SecurityGroupId'].append(group)
if self.args.get('associate_public_ip_address') is not None:
cli_iface['AssociatePublicIpAddress'] = \
self.args['associate_public_ip_address']
if self.args.get('private_ip_address'):
cli_iface['PrivateIpAddresses'] = [
{'PrivateIpAddress': self.args['private_ip_address'],
'Primary': 'true'}]
if self.args.get('secondary_address'):
sec_ips = [{'PrivateIpAddress': addr} for addr in
self.args['secondary_address']]
if not cli_iface.get('PrivateIpAddresses'):
cli_iface['PrivateIpAddresses'] = []
cli_iface['PrivateIpAddresses'].extend(sec_ips)
if self.args.get('secondary_count'):
sec_ip_count = self.args['secondary_count']
cli_iface['SecondaryPrivateIpAddressCount'] = sec_ip_count
if self.args.get('subnet'):
cli_iface['SubnetId'] = self.args['subnet']
if cli_iface:
cli_iface['DeviceIndex'] = 0
if not self.params.get('NetworkInterface'):
self.params['NetworkInterface'] = []
self.params['NetworkInterface'].append(cli_iface)
self.log.debug('built network interface from CLI options: {0}'
.format(cli_iface))
else:
# Non-VPC
for group in self.args['group']:
if group.startswith('sg-'):
if not self.params.get('SecurityGroupId'):
self.params['SecurityGroupId'] = []
self.params['SecurityGroupId'].append(group)
else:
if not self.params.get('SecurityGroup'):
self.params['SecurityGroup'] = []
self.params['SecurityGroup'].append(group)
0
Example 45
def parse_ports(protocol, port_range=None, icmp_type_code=None):
# This function's error messages make assumptions about arguments'
# names, but currently all of its callers agree on them. If that
# changes then please fix this.
from_port = None
to_port = None
if str(protocol).lower() in ('icmp', '1'):
if port_range:
raise ArgumentError('argument -p/--port-range: not compatible '
'with protocol "{0}"'.format(protocol))
if not icmp_type_code:
icmp_type_code = '-1:-1'
types = icmp_type_code.split(':')
if len(types) == 2:
try:
from_port = int(types[0])
to_port = int(types[1])
except ValueError:
raise ArgumentError('argument -t/--icmp-type-code: value '
'must have format "1:2"')
else:
raise ArgumentError('argument -t/--icmp-type-code: value '
'must have format "1:2"')
if from_port < -1 or to_port < -1:
raise ArgumentError('argument -t/--icmp-type-code: ICMP type, '
'code must be at least -1')
elif str(protocol).lower() in ('tcp', '6', 'udp', '17'):
if icmp_type_code:
raise ArgumentError('argument -t/--icmp-type-code: not compatible '
'with protocol "{0}"'.format(protocol))
if not port_range:
raise ArgumentError('argument -p/--port-range is required '
'for protocol "{0}"'.format(protocol))
if ':' in port_range:
# Be extra helpful in the event of this common typo
raise ArgumentError('argument -p/--port-range: multi-port '
'range must be separated by "-", not ":"')
from_port, to_port = _parse_port_range(port_range, protocol)
if from_port < -1 or to_port < -1:
raise ArgumentError('argument -p/--port-range: port number(s) '
'must be at least -1')
if from_port == -1:
from_port = 1
if to_port == -1:
to_port = 65535
# We allow other protocols through without parsing port numbers at all.
return from_port, to_port
0
Example 46
def _parse_port_range(port_range, protocol):
# Try for an integer
try:
return (int(port_range), int(port_range))
except ValueError:
pass
# Try for an integer range
if port_range.count('-') == 1:
ports = port_range.split('-')
try:
return (int(ports[0]), int(ports[1]))
except ValueError:
pass
# Try for a service name
if isinstance(protocol, six.string_types):
try:
# This is going to fail if protocol is a number.
port = socket.getservbyname(port_range, protocol)
return (port, port)
except socket.error:
pass
# That's all, folks!
raise ArgumentError("argument -p/--port-range: '{0}' is neither a port "
"number, range of port numbers, nor a recognized "
"service name".format(port_range))
0
Example 47
def attribute(attr_as_str):
attr = {}
for pair in attr_as_str.split(','):
key, val = pair.split('=', 1)
if key.strip() == 'name':
attr['AttributeName'] = val.strip()
elif key.strip() == 'value':
attr['AttributeValue'] = val.strip()
else:
raise ArgumentError(
"attribute '{0}': '{1}' is not a valid part of an attribute "
"(choose from 'name', 'value')".format(attr_as_str,
key.strip()))
if 'AttributeName' not in attr:
raise ArgumentError(
"attribute '{0}': name is required".format(attr_as_str))
if 'AttributeValue' not in attr:
raise ArgumentError(
"attribute '{0}': value is required".format(attr_as_str))
return attr
0
Example 48
def configure(self):
S3Request.configure(self)
if '/' not in self.args['path']:
raise ArgumentError("path '{0}' must include a key name"
.format(self.args['path']))
0
Example 49
def configure(self):
S3Request.configure(self)
bucket, _, key = self.args['source'].partition('/')
if not bucket:
raise ArgumentError('source must contain a bucket name')
if not key:
raise ArgumentError('source must contain a key name')
if isinstance(self.args.get('dest'), basestring):
# If it is not a string we assume it is a file-like object
if self.args['dest'] == '-':
self.args['dest'] = sys.stdout
elif os.path.isdir(self.args['dest']):
basename = os.path.basename(key)
if not basename:
raise ArgumentError("specify a complete file path with -o "
"to download objects that end in '/'")
dest_path = os.path.join(self.args['dest'], basename)
self.args['dest'] = open(dest_path, 'w')
else:
self.args['dest'] = open(self.args['dest'], 'w')