Exemplo n.º 1
0
    def take_action(self, parsed_args):
        self.log.debug("take_action(%s)", parsed_args)
        client = self.app.client_manager.data_processing

        data = self._take_action(client, parsed_args)

        if parsed_args.count and parsed_args.count > 1:
            clusters = [
                utils.get_resource(client.clusters, id)
                for id in data['clusters']]

            if parsed_args.wait:
                for cluster in clusters:
                    if not osc_utils.wait_for_status(
                            client.clusters.get, cluster.id):
                        self.log.error(
                            'Error occurred during cluster creation: %s',
                            data['id'])

            data = {}
            for cluster in clusters:
                data[cluster.name] = cluster.id

        else:
            if parsed_args.wait:
                if not osc_utils.wait_for_status(
                        client.clusters.get, data['id']):
                    self.log.error(
                        'Error occurred during cluster creation: %s',
                        data['id'])
                data = client.clusters.get(data['id']).to_dict()
            _format_cluster_output(self.app, data)
            data = utils.prepare_data(data, CLUSTER_FIELDS)

        return self.dict2columns(data)
Exemplo n.º 2
0
    def take_action(self, parsed_args):
        share_client = self.app.client_manager.share

        share = utils.find_resource(share_client.shares, parsed_args.share)

        snapshot = share_client.share_snapshots.manage(
            share=share,
            provider_location=parsed_args.provider_location,
            driver_options=parsed_args.driver_option,
            name=parsed_args.name,
            description=parsed_args.description)

        if parsed_args.wait:
            if not utils.wait_for_status(
                    status_f=share_client.share_snapshots.get,
                    res_id=snapshot.id,
                    success_status=['available'],
                    error_status=['manage_error', 'error']):
                LOG.error(_("ERROR: Share snapshot is in error state."))

            snapshot = utils.find_resource(share_client.share_snapshots,
                                           snapshot.id)

        snapshot._info.pop('links', None)

        return self.dict2columns(snapshot._info)
Exemplo n.º 3
0
 def test_wait_for_status_error(self, mock_sleep):
     # Tests that we fail if the resource is status=error
     resource = mock.MagicMock(status='ERROR')
     status_f = mock.Mock(return_value=resource)
     res_id = str(uuid.uuid4())
     self.assertFalse(utils.wait_for_status(status_f, res_id))
     mock_sleep.assert_not_called()
Exemplo n.º 4
0
 def test_wait_for_status_ok(self, mock_sleep):
     # Tests the normal flow that the resource is status=active
     resource = mock.MagicMock(status='ACTIVE')
     status_f = mock.Mock(return_value=resource)
     res_id = str(uuid.uuid4())
     self.assertTrue(utils.wait_for_status(status_f, res_id,))
     mock_sleep.assert_not_called()
Exemplo n.º 5
0
 def test_wait_for_status_ok(self, mock_sleep):
     # Tests the normal flow that the resource is status=active
     resource = mock.MagicMock(status='ACTIVE')
     status_f = mock.Mock(return_value=resource)
     res_id = str(uuid.uuid4())
     self.assertTrue(utils.wait_for_status(status_f, res_id,))
     mock_sleep.assert_not_called()
Exemplo n.º 6
0
    def take_action(self, parsed_args):
        share_client = self.app.client_manager.share
        share = apiutils.find_resource(share_client.shares, parsed_args.share)
        share_size = share._info['size']
        new_size = parsed_args.new_size

        if share_size > new_size:
            try:
                share_client.shares.shrink(share, new_size)
            except Exception as e:
                raise exceptions.CommandError(_("Share resize failed: %s" % e))
        elif share_size < new_size:
            try:
                share_client.shares.extend(share, new_size)
            except Exception as e:
                raise exceptions.CommandError(_("Share resize failed: %s" % e))
        else:
            raise exceptions.CommandError(
                _("Share size is already at %s GiBs" % new_size))
        if parsed_args.wait:
            if not oscutils.wait_for_status(status_f=share_client.shares.get,
                                            res_id=share.id,
                                            success_status=['available']):
                raise exceptions.CommandError(
                    _("Share not available after resize attempt."))
 def test_wait_for_status_error(self, mock_sleep):
     # Tests that we fail if the resource is status=error
     resource = mock.MagicMock(status='ERROR')
     status_f = mock.Mock(return_value=resource)
     res_id = str(uuid.uuid4())
     self.assertFalse(utils.wait_for_status(status_f, res_id))
     mock_sleep.assert_not_called()
Exemplo n.º 8
0
    def take_action(self, parsed_args):
        compute_client = self.app.client_manager.compute

        server = utils.find_resource(
            compute_client.servers,
            parsed_args.server,
        )

        # Set sane defaults as this API wants all mouths to be fed
        if parsed_args.name is None:
            backup_name = server.name
        else:
            backup_name = parsed_args.name
        if parsed_args.type is None:
            backup_type = ""
        else:
            backup_type = parsed_args.type
        if parsed_args.rotate is None:
            backup_rotation = 1
        else:
            backup_rotation = parsed_args.rotate

        compute_client.servers.backup(
            server.id,
            backup_name,
            backup_type,
            backup_rotation,
        )

        image_client = self.app.client_manager.image
        image = utils.find_resource(
            image_client.images,
            backup_name,
        )

        if parsed_args.wait:
            if utils.wait_for_status(
                image_client.images.get,
                image.id,
                callback=_show_progress,
            ):
                sys.stdout.write('\n')
            else:
                msg = _('Error creating server backup: %s') % parsed_args.name
                raise exceptions.CommandError(msg)

        if self.app.client_manager._api_version['image'] == '1':
            info = {}
            info.update(image._info)
            info['properties'] = utils.format_dict(info.get('properties', {}))
        else:
            # Get the right image module to format the output
            image_module = importutils.import_module(
                self.IMAGE_API_VERSIONS[
                    self.app.client_manager._api_version['image']
                ]
            )
            info = image_module._format_image(image)
        return zip(*sorted(six.iteritems(info)))
Exemplo n.º 9
0
    def take_action(self, parsed_args):
        share_client = self.app.client_manager.share

        share_types = []
        for share_type in parsed_args.share_types:
            share_types.append(
                osc_utils.find_resource(
                    share_client.share_types,
                    share_type,
                ))
        share_group_type = None
        if parsed_args.share_group_type:
            share_group_type = osc_utils.find_resource(
                share_client.share_group_types,
                parsed_args.share_group_type).id

        share_network = None
        if parsed_args.share_network:
            share_network = osc_utils.find_resource(
                share_client.share_networks, parsed_args.share_network).id

        source_share_group_snapshot = None
        if parsed_args.source_share_group_snapshot:
            source_share_group_snapshot = osc_utils.find_resource(
                share_client.source_share_group_snapshots,
                parsed_args.source_share_group_snapshot).id

        body = {
            'name': parsed_args.name,
            'description': parsed_args.description,
            'share_types': share_types,
            'share_group_type': share_group_type,
            'share_network': share_network,
            'source_share_group_snapshot': source_share_group_snapshot,
            'availability_zone': parsed_args.availability_zone
        }

        share_group = share_client.share_groups.create(**body)

        if parsed_args.wait:
            if not osc_utils.wait_for_status(
                    status_f=share_client.share_groups.get,
                    res_id=share_group.id,
                    success_status=['available']):
                LOG.error(_("ERROR: Share group is in error state."))

            share_group = osc_utils.find_resource(share_client.share_groups,
                                                  share_group.id)

        printable_share_group = share_group._info
        printable_share_group.pop('links', None)

        if printable_share_group.get('share_types'):
            if parsed_args.formatter == 'table':
                printable_share_group['share_types'] = ("\n".join(
                    printable_share_group['share_types']))

        return self.dict2columns(printable_share_group)
Exemplo n.º 10
0
    def take_action(self, parsed_args):
        def _show_progress(progress):
            if progress:
                self.app.stderr.write('\rProgress: %s' % progress)
                self.app.stderr.flush()

        compute_client = self.app.client_manager.compute

        server = utils.find_resource(
            compute_client.servers,
            parsed_args.server,
        )

        # Set sane defaults as this API wants all mouths to be fed
        if parsed_args.name is None:
            backup_name = server.name
        else:
            backup_name = parsed_args.name
        if parsed_args.type is None:
            backup_type = ""
        else:
            backup_type = parsed_args.type
        if parsed_args.rotate is None:
            backup_rotation = 1
        else:
            backup_rotation = parsed_args.rotate

        compute_client.servers.backup(
            server.id,
            backup_name,
            backup_type,
            backup_rotation,
        )

        image_client = self.app.client_manager.image
        image = image_client.find_image(backup_name, ignore_missing=False)

        if parsed_args.wait:
            if utils.wait_for_status(
                    image_client.get_image,
                    image.id,
                    callback=_show_progress,
            ):
                self.app.stdout.write('\n')
            else:
                msg = _('Error creating server backup: %s') % parsed_args.name
                raise exceptions.CommandError(msg)

        if self.app.client_manager._api_version['image'] == '1':
            info = {}
            info.update(image._info)
            info['properties'] = utils.format_dict(info.get('properties', {}))
        else:
            # Get the right image module to format the output
            image_module = importlib.import_module(self.IMAGE_API_VERSIONS[
                self.app.client_manager._api_version['image']])
            info = image_module._format_image(image)
        return zip(*sorted(info.items()))
Exemplo n.º 11
0
    def take_action(self, parsed_args):
        # TODO(s0ru): the table shows 'Field', 'Value'
        share_client = self.app.client_manager.share

        share_type = None
        if parsed_args.share_type:
            share_type = apiutils.find_resource(share_client.share_types,
                                                parsed_args.share_type).id

        share_network = None
        if parsed_args.share_network:
            share_network = apiutils.find_resource(
                share_client.share_networks, parsed_args.share_network).id

        share_group = None
        if parsed_args.share_group:
            share_group = apiutils.find_resource(share_client.share_groups,
                                                 parsed_args.share_group).id

        size = parsed_args.size

        snapshot_id = None
        if parsed_args.snapshot_id:
            snapshot = apiutils.find_resource(share_client.share_snapshots,
                                              parsed_args.snapshot_id)
            snapshot_id = snapshot.id
            size = max(size or 0, snapshot.size)

        body = {
            'share_proto': parsed_args.share_proto,
            'size': size,
            'snapshot_id': snapshot_id,
            'name': parsed_args.name,
            'description': parsed_args.description,
            'metadata': parsed_args.property,
            'share_network': share_network,
            'share_type': share_type,
            'is_public': parsed_args.public,
            'availability_zone': parsed_args.availability_zone,
            'share_group_id': share_group
        }

        share = share_client.shares.create(**body)

        if parsed_args.wait:
            if not oscutils.wait_for_status(status_f=share_client.shares.get,
                                            res_id=share.id,
                                            success_status=['available']):
                LOG.error(_("ERROR: Share is in error state."))

            share = apiutils.find_resource(share_client.shares, share.id)

        printable_share = share._info
        printable_share.pop('links', None)
        printable_share.pop('shares_type', None)

        return self.dict2columns(printable_share)
Exemplo n.º 12
0
 def test_wait_for_status_error_with_overrides(self, mock_sleep):
     # Tests that we fail if the resource is my_status=failed
     resource = mock.MagicMock(my_status='FAILED')
     status_f = mock.Mock(return_value=resource)
     res_id = str(uuid.uuid4())
     self.assertFalse(utils.wait_for_status(status_f, res_id,
                                            status_field='my_status',
                                            error_status=['failed']))
     mock_sleep.assert_not_called()
Exemplo n.º 13
0
 def test_wait_for_status_error_with_overrides(self, mock_sleep):
     # Tests that we fail if the resource is my_status=failed
     resource = mock.MagicMock(my_status='FAILED')
     status_f = mock.Mock(return_value=resource)
     res_id = str(uuid.uuid4())
     self.assertFalse(utils.wait_for_status(status_f, res_id,
                                            status_field='my_status',
                                            error_status=['failed']))
     mock_sleep.assert_not_called()
Exemplo n.º 14
0
 def test_wait_for_status_ok_with_overrides(self, mock_sleep):
     # Tests the normal flow that the resource is status=complete
     resource = mock.MagicMock(my_status='COMPLETE')
     status_f = mock.Mock(return_value=resource)
     res_id = str(uuid.uuid4())
     self.assertTrue(utils.wait_for_status(status_f, res_id,
                                           status_field='my_status',
                                           success_status=['complete']))
     mock_sleep.assert_not_called()
Exemplo n.º 15
0
 def test_wait_for_status_ok_with_overrides(self, mock_sleep):
     # Tests the normal flow that the resource is status=complete
     resource = mock.MagicMock(my_status='COMPLETE')
     status_f = mock.Mock(return_value=resource)
     res_id = str(uuid.uuid4())
     self.assertTrue(utils.wait_for_status(status_f, res_id,
                                           status_field='my_status',
                                           success_status=['complete']))
     mock_sleep.assert_not_called()
Exemplo n.º 16
0
    def _take_action(self, client, parsed_args):
        cluster = utils.get_resource(
            client.clusters, parsed_args.cluster)

        if parsed_args.json:
            blob = osc_utils.read_blob_file_contents(parsed_args.json)
            try:
                template = jsonutils.loads(blob)
            except ValueError as e:
                raise exceptions.CommandError(
                    'An error occurred when reading '
                    'template from file %s: %s' % (parsed_args.json, e))

            data = client.clusters.scale(cluster.id, template).cluster
        else:
            scale_object = {
                "add_node_groups": [],
                "resize_node_groups": []
            }
            scale_node_groups = dict(
                map(lambda x: x.split(':', 1), parsed_args.instances))
            cluster_ng_map = {
                ng['node_group_template_id']: ng['name'] for ng
                in cluster.node_groups}
            for name, count in scale_node_groups.items():
                ngt = utils.get_resource(client.node_group_templates, name)
                if ngt.id in cluster_ng_map:
                    scale_object["resize_node_groups"].append({
                        "name": cluster_ng_map[ngt.id],
                        "count": int(count)
                    })
                else:
                    scale_object["add_node_groups"].append({
                        "node_group_template_id": ngt.id,
                        "name": ngt.name,
                        "count": int(count)
                    })
            if not scale_object['add_node_groups']:
                del scale_object['add_node_groups']
            if not scale_object['resize_node_groups']:
                del scale_object['resize_node_groups']

            data = client.clusters.scale(cluster.id, scale_object).cluster

        sys.stdout.write(
            'Cluster "{cluster}" scaling has been started.\n'.format(
                cluster=parsed_args.cluster))
        if parsed_args.wait:
            if not osc_utils.wait_for_status(
                    client.clusters.get, data['id']):
                self.log.error(
                    'Error occurred during cluster scaling: %s' %
                    cluster.id)
            data = client.clusters.get(cluster.id).cluster

        return data
Exemplo n.º 17
0
    def _take_action(self, client, parsed_args):
        cluster = utils.get_resource(client.clusters, parsed_args.cluster)

        if parsed_args.json:
            blob = osc_utils.read_blob_file_contents(parsed_args.json)
            try:
                template = jsonutils.loads(blob)
            except ValueError as e:
                raise exceptions.CommandError('An error occurred when reading '
                                              'template from file %s: %s' %
                                              (parsed_args.json, e))

            data = client.clusters.scale(cluster.id, template).cluster
        else:
            scale_object = {"add_node_groups": [], "resize_node_groups": []}
            scale_node_groups = dict(
                map(lambda x: x.split(':', 1), parsed_args.instances))
            cluster_ng_map = {
                ng['node_group_template_id']: ng['name']
                for ng in cluster.node_groups
            }
            for name, count in scale_node_groups.items():
                ngt = utils.get_resource(client.node_group_templates, name)
                if ngt.id in cluster_ng_map:
                    scale_object["resize_node_groups"].append({
                        "name":
                        cluster_ng_map[ngt.id],
                        "count":
                        int(count)
                    })
                else:
                    scale_object["add_node_groups"].append({
                        "node_group_template_id":
                        ngt.id,
                        "name":
                        ngt.name,
                        "count":
                        int(count)
                    })
            if not scale_object['add_node_groups']:
                del scale_object['add_node_groups']
            if not scale_object['resize_node_groups']:
                del scale_object['resize_node_groups']

            data = client.clusters.scale(cluster.id, scale_object).cluster

        sys.stdout.write(
            'Cluster "{cluster}" scaling has been started.\n'.format(
                cluster=parsed_args.cluster))
        if parsed_args.wait:
            if not osc_utils.wait_for_status(client.clusters.get, data['id']):
                self.log.error('Error occurred during cluster scaling: %s' %
                               cluster.id)
            data = client.clusters.get(cluster.id).cluster

        return data
Exemplo n.º 18
0
def wait_for_active(status_f, res_id):
    success = utils.wait_for_status(
        status_f=lambda x: munch.Munch(status_f(x)),
        res_id=res_id,
        status_field=constants.PROVISIONING_STATUS,
        sleep_time=3)
    if not success:
        raise exceptions.OctaviaClientException(
            code="n/a",
            message="The resource did not successfully reach ACTIVE status.")
Exemplo n.º 19
0
    def take_action(self, parsed_args):

        def _show_progress(progress):
            if progress:
                self.app.stdout.write('\rProgress: %s' % progress)
                self.app.stdout.flush()

        compute_client = self.app.client_manager.compute

        server = utils.find_resource(
            compute_client.servers,
            parsed_args.server,
        )
        if parsed_args.name:
            image_name = parsed_args.name
        else:
            image_name = server.name

        image_id = compute_client.servers.create_image(
            server.id,
            image_name,
        )

        image_client = self.app.client_manager.image
        image = utils.find_resource(
            image_client.images,
            image_id,
        )

        if parsed_args.wait:
            if utils.wait_for_status(
                image_client.images.get,
                image_id,
                callback=_show_progress,
            ):
                self.app.stdout.write('\n')
            else:
                LOG.error(_('Error creating server image: %s'),
                          parsed_args.server)
                raise exceptions.CommandError

        if self.app.client_manager._api_version['image'] == '1':
            info = {}
            info.update(image._info)
            info['properties'] = utils.format_dict(info.get('properties', {}))
        else:
            # Get the right image module to format the output
            image_module = importutils.import_module(
                self.IMAGE_API_VERSIONS[
                    self.app.client_manager._api_version['image']
                ]
            )
            info = image_module._format_image(image)
        return zip(*sorted(six.iteritems(info)))
Exemplo n.º 20
0
    def take_action(self, parsed_args):
        share_client = self.app.client_manager.share

        kwargs = {
            'service_host': parsed_args.service_host,
            'protocol': parsed_args.protocol,
            'export_path': parsed_args.export_path,
            'name': parsed_args.name,
            'description': parsed_args.description
        }

        share_type = None
        if parsed_args.share_type:
            share_type = apiutils.find_resource(share_client.share_types,
                                                parsed_args.share_type).id
            kwargs['share_type'] = share_type

        driver_options = None
        if parsed_args.driver_options:
            driver_options = utils.extract_properties(
                parsed_args.driver_options)
            kwargs['driver_options'] = driver_options

        if parsed_args.public:
            if share_client.api_version >= api_versions.APIVersion("2.8"):
                kwargs['public'] = True
            else:
                raise exceptions.CommandError(
                    'Setting share visibility while adopting a share is '
                    'available only for API microversion >= 2.8')

        if parsed_args.share_server_id:
            if share_client.api_version >= api_versions.APIVersion("2.49"):
                kwargs['share_server_id'] = parsed_args.share_server_id
            else:
                raise exceptions.CommandError(
                    'Selecting a share server ID is available only for '
                    'API microversion >= 2.49')

        share = share_client.shares.manage(**kwargs)

        if parsed_args.wait:
            if not oscutils.wait_for_status(
                    status_f=share_client.shares.get,
                    res_id=share.id,
                    success_status=['available'],
                    error_status=['manage_error', 'error']):
                LOG.error(_("ERROR: Share is in error state."))

            share = apiutils.find_resource(share_client.shares, share.id)
        share._info.pop('links', None)

        return self.dict2columns(share._info)
Exemplo n.º 21
0
    def take_action(self, parsed_args):
        def _show_progress(progress):
            if progress:
                self.app.stdout.write('\rProgress: %s' % progress)
                self.app.stdout.flush()

        compute_client = self.app.client_manager.sdk_connection.compute
        image_client = self.app.client_manager.image

        server = compute_client.find_server(
            parsed_args.server,
            ignore_missing=False,
        )

        if parsed_args.name:
            image_name = parsed_args.name
        else:
            image_name = server.name

        image_id = compute_client.create_server_image(
            server.id,
            image_name,
            parsed_args.properties,
        ).id

        if parsed_args.wait:
            if utils.wait_for_status(
                    image_client.get_image,
                    image_id,
                    callback=_show_progress,
            ):
                self.app.stdout.write('\n')
            else:
                LOG.error(_('Error creating server image: %s'),
                          parsed_args.server)
                raise exceptions.CommandError

        image = image_client.find_image(image_id, ignore_missing=False)

        if self.app.client_manager._api_version['image'] == '1':
            info = {}
            info.update(image._info)
            info['properties'] = utils.format_dict(info.get('properties', {}))
        else:
            # Get the right image module to format the output
            image_module = importlib.import_module(self.IMAGE_API_VERSIONS[
                self.app.client_manager._api_version['image']])
            info = image_module._format_image(image)

        return zip(*sorted(info.items()))
Exemplo n.º 22
0
    def take_action(self, parsed_args):
        self.log.debug("take_action(%s)", parsed_args)
        client = self.app.client_manager.data_processing

        data = self._take_action(client, parsed_args)

        if parsed_args.count and parsed_args.count > 1:
            clusters = []
            for cluster in data['clusters']:
                clusters.append(
                    utils.get_resource(client.clusters,
                                       cluster['cluster']['id']))

            if parsed_args.wait:
                for cluster in clusters:
                    if not osc_utils.wait_for_status(client.clusters.get,
                                                     cluster.id):
                        self.log.error(
                            'Error occurred during cluster creation: %s',
                            data['id'])

            data = {}
            for cluster in clusters:
                data[cluster.name] = cluster.id

        else:
            if parsed_args.wait:
                if not osc_utils.wait_for_status(client.clusters.get,
                                                 data['id']):
                    self.log.error(
                        'Error occurred during cluster creation: %s',
                        data['id'])
                data = client.clusters.get(data['id']).to_dict()
            _format_cluster_output(self.app, data)
            data = utils.prepare_data(data, c_v1.CLUSTER_FIELDS)

        return self.dict2columns(data)
Exemplo n.º 23
0
    def take_action(self, parsed_args):
        share_client = self.app.client_manager.share

        share = osc_utils.find_resource(share_client.shares, parsed_args.share)
        share_replica = share_client.share_replicas.create(
            share, availability_zone=parsed_args.availability_zone)
        if parsed_args.wait:
            if not osc_utils.wait_for_status(
                    status_f=share_client.share_replicas.get,
                    res_id=share_replica.id,
                    success_status=['available']):
                LOG.error(_("ERROR: Share replica is in error state."))

            share_replica = osc_utils.find_resource(
                share_client.share_replicas, share_replica.id)

        return self.dict2columns(share_replica._info)
Exemplo n.º 24
0
    def take_action(self, parsed_args):
        compute_client = self.app.client_manager.compute

        server = utils.find_resource(
            compute_client.servers,
            parsed_args.server,
        )
        if parsed_args.name:
            image_name = parsed_args.name
        else:
            image_name = server.name

        image_id = compute_client.servers.create_image(
            server.id,
            image_name,
        )

        image_client = self.app.client_manager.image
        image = utils.find_resource(
            image_client.images,
            image_id,
        )

        if parsed_args.wait:
            if utils.wait_for_status(
                    image_client.images.get,
                    image_id,
                    callback=_show_progress,
            ):
                sys.stdout.write('\n')
            else:
                LOG.error(_('Error creating server image: %s'),
                          parsed_args.server)
                raise exceptions.CommandError

        if self.app.client_manager._api_version['image'] == '1':
            info = {}
            info.update(image._info)
            info['properties'] = utils.format_dict(info.get('properties', {}))
        else:
            # Get the right image module to format the output
            image_module = importutils.import_module(self.IMAGE_API_VERSIONS[
                self.app.client_manager._api_version['image']])
            info = image_module._format_image(image)
        return zip(*sorted(six.iteritems(info)))
Exemplo n.º 25
0
    def take_action(self, parsed_args):
        share_client = self.app.client_manager.share

        share = utils.find_resource(share_client.shares, parsed_args.share)

        share_snapshot = share_client.share_snapshots.create(
            share=share,
            force=parsed_args.force,
            name=parsed_args.name or None,
            description=parsed_args.description or None)
        if parsed_args.wait:
            if not utils.wait_for_status(
                    status_f=share_client.share_snapshots.get,
                    res_id=share_snapshot.id,
                    success_status=['available']):
                LOG.error(_("ERROR: Share snapshot is in error state."))

            share_snapshot = utils.find_resource(share_client.share_snapshots,
                                                 share_snapshot.id)
        share_snapshot._info.pop('links', None)

        return self.dict2columns(share_snapshot._info)
Exemplo n.º 26
0
    def take_action(self, parsed_args):
        share_client = self.app.client_manager.share

        share = apiutils.find_resource(share_client.shares, parsed_args.share)
        properties = {}
        if parsed_args.properties:
            if share_client.api_version >= api_versions.APIVersion("2.45"):
                properties = utils.extract_properties(parsed_args.properties)
            else:
                raise exceptions.CommandError(
                    "Adding properties to access rules is supported only "
                    "with API microversion 2.45 and beyond")
        try:
            share_access_rule = share.allow(
                access_type=parsed_args.access_type,
                access=parsed_args.access_to,
                access_level=parsed_args.access_level,
                metadata=properties)
            if parsed_args.wait:
                if not oscutils.wait_for_status(
                        status_f=share_client.share_access_rules.get,
                        res_id=share_access_rule['id'],
                        status_field='state'):
                    LOG.error(_("ERROR: Share access rule is in error state."))

                share_access_rule = oscutils.find_resource(
                    share_client.share_access_rules,
                    share_access_rule['id'])._info
            share_access_rule.update({
                'properties':
                utils.format_properties(share_access_rule.pop('metadata', {}))
            })
            return (ACCESS_RULE_ATTRIBUTES,
                    oscutils.get_dict_properties(share_access_rule,
                                                 ACCESS_RULE_ATTRIBUTES))
        except Exception as e:
            raise exceptions.CommandError("Failed to create access to share "
                                          "'%s': %s" % (share, e))
Exemplo n.º 27
0
    def take_action(self, parsed_args):
        self.log.debug("take_action(%s)" % parsed_args)
        client = self.app.client_manager.data_processing
        network_client = self.app.client_manager.network

        if parsed_args.json:
            blob = osc_utils.read_blob_file_contents(parsed_args.json)
            try:
                template = json.loads(blob)
            except ValueError as e:
                raise exceptions.CommandError('An error occurred when reading '
                                              'template from file %s: %s' %
                                              (parsed_args.json, e))

            if 'neutron_management_network' in template:
                template['net_id'] = template.pop('neutron_management_network')

            if 'count' in template:
                parsed_args.count = template['count']

            data = client.clusters.create(**template).to_dict()
        else:
            if not parsed_args.name or not parsed_args.cluster_template \
                    or not parsed_args.image:
                raise exceptions.CommandError(
                    'At least --name , --cluster-template, --image arguments '
                    'should be specified or json template should be provided '
                    'with --json argument')

            plugin, plugin_version, template_id = _get_plugin_version(
                parsed_args.cluster_template, client)

            image_id = utils.get_resource_id(client.images, parsed_args.image)

            net_id = (network_client.find_network(parsed_args.neutron_network,
                                                  ignore_missing=False).id
                      if parsed_args.neutron_network else None)

            data = client.clusters.create(
                name=parsed_args.name,
                plugin_name=plugin,
                hadoop_version=plugin_version,
                cluster_template_id=template_id,
                default_image_id=image_id,
                description=parsed_args.description,
                is_transient=parsed_args.transient,
                user_keypair_id=parsed_args.user_keypair,
                net_id=net_id,
                count=parsed_args.count,
                is_public=parsed_args.public,
                is_protected=parsed_args.protected).to_dict()
        if parsed_args.count and parsed_args.count > 1:
            clusters = [
                utils.get_resource(client.clusters, id)
                for id in data['clusters']
            ]

            if parsed_args.wait:
                for cluster in clusters:
                    if not osc_utils.wait_for_status(client.clusters.get,
                                                     cluster.id):
                        self.log.error(
                            'Error occurred during cluster creation: %s' %
                            data['id'])

            data = {}
            for cluster in clusters:
                data[cluster.name] = cluster.id

        else:
            if parsed_args.wait:
                if not osc_utils.wait_for_status(client.clusters.get,
                                                 data['id']):
                    self.log.error(
                        'Error occurred during cluster creation: %s' %
                        data['id'])
                data = client.clusters.get(data['id']).to_dict()
            _format_cluster_output(data)
            data = utils.prepare_data(data, CLUSTER_FIELDS)

        return self.dict2columns(data)
Exemplo n.º 28
0
    def take_action(self, parsed_args):
        # TODO(s0ru): the table shows 'Field', 'Value'
        share_client = self.app.client_manager.share

        share_type = None
        if parsed_args.share_type:
            share_type = apiutils.find_resource(share_client.share_types,
                                                parsed_args.share_type).id

        share_network = None
        if parsed_args.share_network:
            share_network = apiutils.find_resource(
                share_client.share_networks, parsed_args.share_network).id

        share_group = None
        if parsed_args.share_group:
            share_group = apiutils.find_resource(share_client.share_groups,
                                                 parsed_args.share_group).id

        size = parsed_args.size

        snapshot_id = None
        if parsed_args.snapshot_id:
            snapshot = apiutils.find_resource(share_client.share_snapshots,
                                              parsed_args.snapshot_id)
            snapshot_id = snapshot.id
            size = max(size or 0, snapshot.size)

        scheduler_hints = {}
        if parsed_args.scheduler_hint:
            if share_client.api_version < api_versions.APIVersion('2.65'):
                raise exceptions.CommandError(
                    'Setting share scheduler hints for a share is '
                    'available only for API microversion >= 2.65')
            else:
                scheduler_hints = utils.extract_key_value_options(
                    parsed_args.scheduler_hint)
                same_host_hint_shares = scheduler_hints.get('same_host')
                different_host_hint_shares = scheduler_hints.get(
                    'different_host')
                if same_host_hint_shares:
                    same_host_hint_shares = [
                        apiutils.find_resource(share_client.shares, sh).id
                        for sh in same_host_hint_shares.split(',')
                    ]
                    scheduler_hints['same_host'] = (
                        ','.join(same_host_hint_shares))
                if different_host_hint_shares:
                    different_host_hint_shares = [
                        apiutils.find_resource(share_client.shares, sh).id
                        for sh in different_host_hint_shares.split(',')
                    ]
                    scheduler_hints['different_host'] = (
                        ','.join(different_host_hint_shares))

        body = {
            'share_proto': parsed_args.share_proto,
            'size': size,
            'snapshot_id': snapshot_id,
            'name': parsed_args.name,
            'description': parsed_args.description,
            'metadata': parsed_args.property,
            'share_network': share_network,
            'share_type': share_type,
            'is_public': parsed_args.public,
            'availability_zone': parsed_args.availability_zone,
            'share_group_id': share_group,
            'scheduler_hints': scheduler_hints
        }

        share = share_client.shares.create(**body)

        if parsed_args.wait:
            if not oscutils.wait_for_status(status_f=share_client.shares.get,
                                            res_id=share.id,
                                            success_status=['available']):
                LOG.error(_("ERROR: Share is in error state."))

            share = apiutils.find_resource(share_client.shares, share.id)

        printable_share = share._info
        printable_share.pop('links', None)
        printable_share.pop('shares_type', None)

        return self.dict2columns(printable_share)