Beispiel #1
0
def _process_identity_and_resource_options(parsed_args,
                                           identity_client_manager):
    kwargs = {}
    if parsed_args.user and parsed_args.domain:
        kwargs['user'] = common.find_user(
            identity_client_manager,
            parsed_args.user,
            parsed_args.user_domain,
        ).id
        kwargs['domain'] = common.find_domain(
            identity_client_manager,
            parsed_args.domain,
        ).id
    elif parsed_args.user and parsed_args.project:
        kwargs['user'] = common.find_user(
            identity_client_manager,
            parsed_args.user,
            parsed_args.user_domain,
        ).id
        kwargs['project'] = common.find_project(
            identity_client_manager,
            parsed_args.project,
            parsed_args.project_domain,
        ).id
    elif parsed_args.group and parsed_args.domain:
        kwargs['group'] = common.find_group(
            identity_client_manager,
            parsed_args.group,
            parsed_args.group_domain,
        ).id
        kwargs['domain'] = common.find_domain(
            identity_client_manager,
            parsed_args.domain,
        ).id
    elif parsed_args.group and parsed_args.project:
        kwargs['group'] = common.find_group(
            identity_client_manager,
            parsed_args.group,
            parsed_args.group_domain,
        ).id
        kwargs['project'] = common.find_project(
            identity_client_manager,
            parsed_args.project,
            parsed_args.project_domain,
        ).id
    kwargs['os_inherit_extension_inherited'] = parsed_args.inherited
    return kwargs
Beispiel #2
0
    def take_action(self, parsed_args):
        identity_client = self.app.client_manager.identity

        # NOTE(stevemar): Find the two users, project and roles that
        # are necessary for making a trust usable, the API dictates that
        # trustee, project and role are optional, but that makes the trust
        # pointless, and trusts are immutable, so let's enforce it at the
        # client level.
        trustor_id = common.find_user(identity_client, parsed_args.trustor,
                                      parsed_args.trustor_domain).id
        trustee_id = common.find_user(identity_client, parsed_args.trustee,
                                      parsed_args.trustee_domain).id
        project_id = common.find_project(identity_client, parsed_args.project,
                                         parsed_args.project_domain).id

        role_names = []
        for role in parsed_args.role:
            role_name = utils.find_resource(
                identity_client.roles,
                role,
            ).name
            role_names.append(role_name)

        expires_at = None
        if parsed_args.expiration:
            expires_at = datetime.datetime.strptime(parsed_args.expiration,
                                                    '%Y-%m-%dT%H:%M:%S')

        trust = identity_client.trusts.create(
            trustee_id,
            trustor_id,
            impersonation=parsed_args.impersonate,
            project=project_id,
            role_names=role_names,
            expires_at=expires_at,
        )

        trust._info.pop('roles_links', None)
        trust._info.pop('links', None)

        # Format roles into something sensible
        roles = trust._info.pop('roles')
        msg = ' '.join(r['name'] for r in roles)
        trust._info['roles'] = msg

        return zip(*sorted(six.iteritems(trust._info)))
Beispiel #3
0
    def take_action(self, parsed_args):
        identity_client = self.app.client_manager.identity

        project_id = None
        if parsed_args.project:
            project_id = common.find_project(identity_client,
                                             parsed_args.project,
                                             parsed_args.project_domain).id

        domain_id = None
        if parsed_args.domain:
            domain_id = common.find_domain(identity_client,
                                           parsed_args.domain).id

        enabled = True
        if parsed_args.disable:
            enabled = False
        if parsed_args.password_prompt:
            parsed_args.password = utils.get_password(self.app.stdin)

        try:
            user = identity_client.users.create(
                name=parsed_args.name,
                domain=domain_id,
                default_project=project_id,
                password=parsed_args.password,
                email=parsed_args.email,
                description=parsed_args.description,
                enabled=enabled)
        except ks_exc.Conflict as e:
            if parsed_args.or_show:
                user = utils.find_resource(identity_client.users,
                                           parsed_args.name,
                                           domain_id=domain_id)
                self.log.info('Returning existing user %s', user.name)
            else:
                raise e

        user._info.pop('links')
        return zip(*sorted(six.iteritems(user._info)))
Beispiel #4
0
    def take_action(self, parsed_args):
        identity_client = self.app.client_manager.identity

        if parsed_args.password_prompt:
            parsed_args.password = utils.get_password(self.app.stdin)

        if (not parsed_args.name and not parsed_args.name
                and not parsed_args.password and not parsed_args.email
                and not parsed_args.project and not parsed_args.description
                and not parsed_args.enable and not parsed_args.disable):
            sys.stderr.write("Incorrect set of arguments "
                             "provided. See ecl --help for more "
                             "details\n")
            return

        user = utils.find_resource(
            identity_client.users,
            parsed_args.user,
        )
        kwargs = {}
        if parsed_args.name:
            kwargs['name'] = parsed_args.name
        if parsed_args.email:
            kwargs['email'] = parsed_args.email
        if parsed_args.password:
            kwargs['password'] = parsed_args.password
        if parsed_args.description:
            kwargs['description'] = parsed_args.description
        if parsed_args.project:
            project_id = common.find_project(identity_client,
                                             parsed_args.project,
                                             parsed_args.project_domain).id
            kwargs['default_project'] = project_id
        kwargs['enabled'] = user.enabled
        if parsed_args.enable:
            kwargs['enabled'] = True
        if parsed_args.disable:
            kwargs['enabled'] = False

        identity_client.users.update(user.id, **kwargs)
Beispiel #5
0
    def take_action(self, parsed_args):
        identity_client = self.app.client_manager.identity

        if (not parsed_args.name and not parsed_args.domain
                and not parsed_args.description and not parsed_args.enable
                and not parsed_args.property and not parsed_args.disable):
            return
        project = common.find_project(identity_client, parsed_args.project,
                                      parsed_args.domain)

        kwargs = {}
        if parsed_args.name:
            kwargs['name'] = parsed_args.name
        if parsed_args.description:
            kwargs['description'] = parsed_args.description
        if parsed_args.enable:
            kwargs['enabled'] = True
        if parsed_args.disable:
            kwargs['enabled'] = False
        if parsed_args.property:
            kwargs.update(parsed_args.property)

        identity_client.projects.update(project.id, **kwargs)
Beispiel #6
0
    def take_action(self, parsed_args):
        identity_client = self.app.client_manager.identity
        image_client = self.app.client_manager.image

        for deadopt in self.deadopts:
            if getattr(parsed_args, deadopt.replace('-', '_'), None):
                raise exceptions.CommandError(
                    "ERROR: --%s was given, which is an Image v1 option"
                    " that is no longer supported in Image v2" % deadopt)

        kwargs = {}
        copy_attrs = ('architecture', 'container_format', 'disk_format',
                      'file', 'instance_id', 'kernel_id', 'locations',
                      'min_disk', 'min_ram', 'name', 'os_distro', 'os_version',
                      'prefix', 'progress', 'ramdisk_id', 'tags')
        for attr in copy_attrs:
            if attr in parsed_args:
                val = getattr(parsed_args, attr, None)
                if val:
                    # Only include a value in kwargs for attributes that are
                    # actually present on the command line
                    kwargs[attr] = val

        # Properties should get flattened into the general kwargs
        if getattr(parsed_args, 'properties', None):
            for k, v in six.iteritems(parsed_args.properties):
                kwargs[k] = str(v)

        # Handle exclusive booleans with care
        # Avoid including attributes in kwargs if an option is not
        # present on the command line.  These exclusive booleans are not
        # a single value for the pair of options because the default must be
        # to do nothing when no options are present as opposed to always
        # setting a default.
        if parsed_args.protected:
            kwargs['protected'] = True
        if parsed_args.unprotected:
            kwargs['protected'] = False
        if parsed_args.public:
            kwargs['visibility'] = 'public'
        if parsed_args.private:
            kwargs['visibility'] = 'private'

        # Handle deprecated --owner option
        project_arg = parsed_args.project
        if parsed_args.owner:
            project_arg = parsed_args.owner
            self.log.warning(
                _('The --owner option is deprecated, '
                  'please use --project instead.'))
        if project_arg:
            kwargs['owner'] = common.find_project(
                identity_client,
                project_arg,
                parsed_args.project_domain,
            ).id

        # Checks if anything that requires getting the image
        if not (kwargs or parsed_args.deactivate or parsed_args.activate):
            self.log.warning("No arguments specified")
            return {}, {}

        image = utils.find_resource(image_client.images, parsed_args.image)

        activation_status = None
        if parsed_args.deactivate:
            image_client.images.deactivate(image.id)
            activation_status = "deactivated"
        if parsed_args.activate:
            image_client.images.reactivate(image.id)
            activation_status = "activated"

        # Check if need to do the actual update
        if not kwargs:
            return {}, {}

        if parsed_args.tags:
            # Tags should be extended, but duplicates removed
            kwargs['tags'] = list(set(image.tags).union(set(parsed_args.tags)))

        try:
            image = image_client.images.update(image.id, **kwargs)
        except Exception as e:
            if activation_status is not None:
                print("Image %s was %s." % (image.id, activation_status))
            raise e
Beispiel #7
0
    def take_action(self, parsed_args):
        identity_client = self.app.client_manager.identity
        image_client = self.app.client_manager.image

        for deadopt in self.deadopts:
            if getattr(parsed_args, deadopt.replace('-', '_'), None):
                raise exceptions.CommandError(
                    "ERROR: --%s was given, which is an Image v1 option"
                    " that is no longer supported in Image v2" % deadopt)

        # Build an attribute dict from the parsed args, only include
        # attributes that were actually set on the command line
        kwargs = {}
        copy_attrs = ('name', 'id', 'container_format', 'disk_format',
                      'min_disk', 'min_ram', 'tags')
        for attr in copy_attrs:
            if attr in parsed_args:
                val = getattr(parsed_args, attr, None)
                if val:
                    # Only include a value in kwargs for attributes that
                    # are actually present on the command line
                    kwargs[attr] = val

        # properties should get flattened into the general kwargs
        if getattr(parsed_args, 'properties', None):
            for k, v in six.iteritems(parsed_args.properties):
                kwargs[k] = str(v)

        # Handle exclusive booleans with care
        # Avoid including attributes in kwargs if an option is not
        # present on the command line.  These exclusive booleans are not
        # a single value for the pair of options because the default must be
        # to do nothing when no options are present as opposed to always
        # setting a default.
        if parsed_args.protected:
            kwargs['protected'] = True
        if parsed_args.unprotected:
            kwargs['protected'] = False
        if parsed_args.public:
            kwargs['visibility'] = 'public'
        if parsed_args.private:
            kwargs['visibility'] = 'private'

        # Handle deprecated --owner option
        project_arg = parsed_args.project
        if parsed_args.owner:
            project_arg = parsed_args.owner
            self.log.warning(
                _('The --owner option is deprecated, '
                  'please use --project instead.'))
        if project_arg:
            kwargs['owner'] = common.find_project(
                identity_client,
                project_arg,
                parsed_args.project_domain,
            ).id

        # open the file first to ensure any failures are handled before the
        # image is created
        fp = gc_utils.get_data_file(parsed_args)
        info = {}
        if fp is not None and parsed_args.volume:
            raise exceptions.CommandError("Uploading data and using container "
                                          "are not allowed at the same time")

        if fp is None and parsed_args.file:
            self.log.warning("Failed to get an image file.")
            return {}, {}

        if parsed_args.owner:
            kwargs['owner'] = common.find_project(
                identity_client,
                parsed_args.owner,
                parsed_args.project_domain,
            ).id

        # If a volume is specified.
        if parsed_args.volume:
            volume_client = self.app.client_manager.volume
            source_volume = utils.find_resource(
                volume_client.volumes,
                parsed_args.volume,
            )
            response, body = volume_client.volumes.upload_to_image(
                source_volume.id,
                parsed_args.force,
                parsed_args.name,
                parsed_args.container_format,
                parsed_args.disk_format,
            )
            info = body['os-volume_upload_image']
            info['volume_type'] = info['volume_type']['name']
        else:
            image = image_client.images.create(**kwargs)

        if fp is not None:
            with fp:
                try:
                    image_client.images.upload(image.id, fp)
                except Exception as e:
                    # If the upload fails for some reason attempt to remove the
                    # dangling queued image made by the create() call above but
                    # only if the user did not specify an id which indicates
                    # the Image already exists and should be left alone.
                    try:
                        if 'id' not in kwargs:
                            image_client.images.delete(image.id)
                    except Exception:
                        pass  # we don't care about this one
                    raise e  # now, throw the upload exception again

                # update the image after the data has been uploaded
                image = image_client.images.get(image.id)

        if not info:
            info = _format_image(image._info)

        return zip(*sorted(six.iteritems(info)))
Beispiel #8
0
    def take_action(self, parsed_args):
        identity_client = self.app.client_manager.identity

        role = None
        if parsed_args.role:
            role = utils.find_resource(
                identity_client.roles,
                parsed_args.role,
            )

        user = None
        if parsed_args.user:
            user = common.find_user(
                identity_client,
                parsed_args.user,
                parsed_args.user_domain,
            )

        domain = None
        if parsed_args.domain:
            domain = common.find_domain(
                identity_client,
                parsed_args.domain,
            )

        project = None
        if parsed_args.project:
            project = common.find_project(
                identity_client,
                parsed_args.project,
                parsed_args.project_domain,
            )

        group = None
        if parsed_args.group:
            group = common.find_group(
                identity_client,
                parsed_args.group,
                parsed_args.group_domain,
            )

        include_names = True if parsed_args.names else False
        effective = True if parsed_args.effective else False
        columns = ('Role', 'User', 'Group', 'Project', 'Domain', 'Inherited')

        inherited_to = 'projects' if parsed_args.inherited else None
        data = identity_client.role_assignments.list(
            domain=domain,
            user=user,
            group=group,
            project=project,
            role=role,
            effective=effective,
            os_inherit_extension_inherited_to=inherited_to,
            include_names=include_names)

        data_parsed = []
        for assignment in data:
            # Removing the extra "scope" layer in the assignment json
            scope = assignment.scope
            if 'project' in scope:
                if include_names:
                    prj = '@'.join([
                        scope['project']['name'],
                        scope['project']['domain']['name']
                    ])
                    setattr(assignment, 'project', prj)
                else:
                    setattr(assignment, 'project', scope['project']['id'])
                assignment.domain = ''
            elif 'domain' in scope:
                if include_names:
                    setattr(assignment, 'domain', scope['domain']['name'])
                else:
                    setattr(assignment, 'domain', scope['domain']['id'])
                assignment.project = ''

            else:
                assignment.domain = ''
                assignment.project = ''

            inherited = scope.get('OS-INHERIT:inherited_to') == 'projects'
            assignment.inherited = inherited

            del assignment.scope

            if hasattr(assignment, 'user'):
                if include_names:
                    usr = '******'.join([
                        assignment.user['name'],
                        assignment.user['domain']['name']
                    ])
                    setattr(assignment, 'user', usr)
                else:
                    setattr(assignment, 'user', assignment.user['id'])
                assignment.group = ''
            elif hasattr(assignment, 'group'):
                if include_names:
                    grp = '@'.join([
                        assignment.group['name'],
                        assignment.group['domain']['name']
                    ])
                    setattr(assignment, 'group', grp)
                else:
                    setattr(assignment, 'group', assignment.group['id'])
                assignment.user = ''
            else:
                assignment.user = ''
                assignment.group = ''

            if hasattr(assignment, 'role'):
                if include_names:
                    setattr(assignment, 'role', assignment.role['name'])
                else:
                    setattr(assignment, 'role', assignment.role['id'])
            else:
                assignment.role = ''

            # Creating a tuple from data object fields
            # (including the blank ones)
            data_parsed.append(self._as_tuple(assignment))

        return columns, tuple(data_parsed)
Beispiel #9
0
    def take_action(self, parsed_args):
        identity_client = self.app.client_manager.identity

        if parsed_args.user:
            user = common.find_user(
                identity_client,
                parsed_args.user,
                parsed_args.user_domain,
            )
        elif parsed_args.group:
            group = common.find_group(
                identity_client,
                parsed_args.group,
                parsed_args.group_domain,
            )

        if parsed_args.domain:
            domain = common.find_domain(
                identity_client,
                parsed_args.domain,
            )
        elif parsed_args.project:
            project = common.find_project(
                identity_client,
                parsed_args.project,
                parsed_args.project_domain,
            )

        # no user or group specified, list all roles in the system
        if not parsed_args.user and not parsed_args.group:
            columns = ('ID', 'Name')
            data = identity_client.roles.list()
        elif parsed_args.user and parsed_args.domain:
            columns = ('ID', 'Name', 'Domain', 'User')
            data = identity_client.roles.list(
                user=user,
                domain=domain,
                os_inherit_extension_inherited=parsed_args.inherited)
            for user_role in data:
                user_role.user = user.name
                user_role.domain = domain.name
        elif parsed_args.user and parsed_args.project:
            columns = ('ID', 'Name', 'Project', 'User')
            data = identity_client.roles.list(
                user=user,
                project=project,
                os_inherit_extension_inherited=parsed_args.inherited)
            for user_role in data:
                user_role.user = user.name
                user_role.project = project.name
        elif parsed_args.user:
            columns = ('ID', 'Name')
            data = identity_client.roles.list(
                user=user,
                domain='default',
                os_inherit_extension_inherited=parsed_args.inherited)
        elif parsed_args.group and parsed_args.domain:
            columns = ('ID', 'Name', 'Domain', 'Group')
            data = identity_client.roles.list(
                group=group,
                domain=domain,
                os_inherit_extension_inherited=parsed_args.inherited)
            for group_role in data:
                group_role.group = group.name
                group_role.domain = domain.name
        elif parsed_args.group and parsed_args.project:
            columns = ('ID', 'Name', 'Project', 'Group')
            data = identity_client.roles.list(
                group=group,
                project=project,
                os_inherit_extension_inherited=parsed_args.inherited)
            for group_role in data:
                group_role.group = group.name
                group_role.project = project.name
        else:
            sys.stderr.write("Error: If a user or group is specified, either "
                             "--domain or --project must also be specified to "
                             "list role grants.\n")
            return ([], [])

        return (columns, (utils.get_item_properties(
            s,
            columns,
            formatters={},
        ) for s in data))
Beispiel #10
0
    def take_action(self, parsed_args):

        volume_client = self.app.client_manager.volume
        compute_client = self.app.client_manager.compute
        identity_client = self.app.client_manager.identity

        def _format_attach(attachments):
            """Return a formatted string of a volume's attached instances

            :param attachments: a volume.attachments field
            :rtype: a string of formatted instances
            """

            msg = ''
            for attachment in attachments:
                server = attachment['server_id']
                if server in server_cache:
                    server = server_cache[server].name
                device = attachment['device']
                msg += 'Attached to %s on %s ' % (server, device)
            return msg

        if parsed_args.long:
            columns = [
                'ID',
                'Name',
                'Status',
                'Size',
                'Volume Type',
                'Bootable',
                'Attachments',
                'Metadata',
            ]
            column_headers = copy.deepcopy(columns)
            column_headers[1] = 'Display Name'
            column_headers[4] = 'Type'
            column_headers[6] = 'Attached to'
            column_headers[7] = 'Properties'
        else:
            columns = [
                'ID',
                'Name',
                'Status',
                'Size',
                'Attachments',
            ]
            column_headers = copy.deepcopy(columns)
            column_headers[1] = 'Display Name'
            column_headers[4] = 'Attached to'

        # Cache the server list
        server_cache = {}
        try:
            for s in compute_client.servers.list():
                server_cache[s.id] = s
        except Exception:
            # Just forget it if there's any trouble
            pass

        project_id = None
        if parsed_args.project:
            project_id = identity_common.find_project(
                identity_client, parsed_args.project,
                parsed_args.project_domain)

        user_id = None
        if parsed_args.user:
            user_id = identity_common.find_user(identity_client,
                                                parsed_args.user,
                                                parsed_args.user_domain)

        search_opts = {
            'all_tenants': parsed_args.all_projects,
            'project_id': project_id,
            'user_id': user_id,
            'display_name': parsed_args.name,
            'status': parsed_args.status,
        }

        data = volume_client.volumes.list(search_opts=search_opts)

        return (column_headers, (utils.get_item_properties(
            s,
            columns,
            formatters={
                'Metadata': utils.format_dict,
                'Attachments': _format_attach
            },
        ) for s in data))