Exemplo n.º 1
0
    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'.format(root_device))
            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'
Exemplo n.º 2
0
    def configure(self):
        BaseCommand.configure(self)
        set_userregion(self.config, self.args.get('userregion'))
        set_userregion(self.config, os.getenv('EUCA_REGION'))

        # Get creds
        add_bundle_creds(self.args, self.config)
        if not self.args.get('cert'):
            raise ArgumentError(
                'missing certificate; please supply one with -c')
        self.log.debug('certificate: %s', self.args['cert'])
        if not self.args.get('privatekey'):
            raise ArgumentError(
                'missing private key; please supply one with -k')
        self.log.debug('private key: %s', self.args['privatekey'])
        if not self.args.get('ec2cert'):
            raise ArgumentError(
                'missing cloud certificate; please supply one with --ec2cert')
        self.log.debug('cloud certificate: %s', self.args['ec2cert'])
        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'])

        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']))
Exemplo n.º 3
0
    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')
Exemplo n.º 4
0
 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)
 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')
Exemplo n.º 6
0
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))
 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')
Exemplo n.º 8
0
    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'])
Exemplo n.º 9
0
 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.args['RootDeviceName']:
                 if (snapshot and
                     snapshot != mapping.get('Ebs', {}).get('SnapshotId')):
                     # The mapping's snapshot differs or doesn't exist
                     raise ArgumentError('snapshot ID supplied with '
                         '--snapshot conflicts with block device mapping '
                         'for root device ' + mapping['DeviceName'])
                 else:
                     # No need to apply --snapshot since the mapping is
                     # already there
                     break
         else:
             if snapshot:
                 self.params['BlockDeviceMapping'].append(
                         {'DeviceName': self.args['RootDeviceName'],
                          'Ebs': {'SnapshotId': snapshot}})
             else:
                 raise ArgumentError('either a manifest location or a root '
                     'device snapshot mapping must be specified')
Exemplo n.º 10
0
 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')
 def configure(self):
     IAMRequest.configure(self)
     parsed = six.moves.urllib.parse.urlparse(self.args.get('Url') or '')
     if parsed.scheme != 'https':
         raise ArgumentError('URL must begin with "https://"')
     if not parsed.netloc:
         raise ArgumentError('URL must name a host to connect to')
Exemplo n.º 12
0
    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')
Exemplo n.º 13
0
 def configure(self):
     EucalyptusRequest.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"')
Exemplo n.º 14
0
 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')
Exemplo n.º 15
0
 def configure(self):
     EucalyptusRequest.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')
Exemplo n.º 16
0
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()}
Exemplo n.º 17
0
 def configure(self):
     WalrusRequest.configure(self)
     if (self.args.get('literal_dest', False)
             and len(self.args['sources']) != 1):
         # Can't explicitly specify dest file names when we're uploading
         # more than one thing
         raise ArgumentError('argument -T: only allowed with one file')
     if self.args['dest'].startswith('/'):
         raise ArgumentError('destination must begin with a bucket name')
Exemplo n.º 18
0
 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
Exemplo n.º 19
0
 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')
Exemplo n.º 20
0
 def configure(self):
     EucalyptusRequest.configure(self)
     if not self.args.get('Storage.S3.UploadPolicy'):
         if not self.args.get('owner_sak'):
             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'):
             raise ArgumentError('argument -w/--owner-sak is required when '
                                 '-s/--policy-signature is not used')
Exemplo n.º 21
0
 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')
Exemplo n.º 22
0
 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))
 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')
Exemplo n.º 24
0
 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')
Exemplo n.º 25
0
 def configure(self):
     EucalyptusRequest.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')
Exemplo n.º 26
0
 def configure(self):
     EucalyptusRequest.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')
Exemplo n.º 27
0
 def configure(self):
     EucalyptusRequest.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')
Exemplo n.º 28
0
 def configure(self):
     WalrusRequest.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))
Exemplo n.º 29
0
    def configure(self):
        EC2Request.configure(self)

        if (self.args['group'].startswith('sg-')
                and len(self.args['group']) == 11):
            # 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-') and len(target_group) == 11:
                # 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')
Exemplo n.º 30
0
    def configure(self):
        S3Request.configure(self)

        if self.args['source'] == '-':
            self.files['file'] = sys.stdin
        elif isinstance(self.args['source'], six.string_types):
            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')