def test_name(self):
        self.list_resources.return_value = {RESOURCES: [self.matrix]}

        result = common.find(self.mock_client, RESOURCE, RESOURCES, NAME)

        self.assertEqual(ID, result)
        self.list_resources.assert_called_with(fields='id', name=NAME)
示例#2
0
 def take_action(self, parsed_args):
     self.log.debug("take_action(%s)" % parsed_args)
     client = self.app.client_manager.network
     _id = common.find(client, "network", "networks", parsed_args.identifier)
     delete_method = getattr(client, "delete_network")
     delete_method(_id)
     return
示例#3
0
 def take_action(self, parsed_args):
     self.log.debug('take_action(%s)' % parsed_args)
     client = self.app.client_manager.network
     delete_method = getattr(client, "delete_network")
     for network in parsed_args.networks:
         _id = common.find(client, 'network', 'networks', network)
         delete_method(_id)
     return
示例#4
0
 def take_action(self, parsed_args):
     self.log.debug('take_action(%s)' % parsed_args)
     client = self.app.client_manager.network
     delete_method = getattr(client, "delete_network")
     for network in parsed_args.networks:
         _id = common.find(client, 'network', 'networks', network)
         delete_method(_id)
     return
    def test_id(self):
        self.list_resources.side_effect = [{RESOURCES: []},
                                           {RESOURCES: [self.matrix]}]

        result = common.find(self.mock_client, RESOURCE, RESOURCES, NAME)

        self.assertEqual(ID, result)
        self.list_resources.assert_called_with(fields='id', id=NAME)
示例#6
0
 def take_action(self, parsed_args):
     self.log.debug("take_action(%s)" % parsed_args)
     client = self.app.client_manager.network
     _id = common.find(client, "network", "networks", parsed_args.identifier)
     show_method = getattr(client, "show_network")
     data = show_method(_id)["network"]
     data = filters(data)
     return zip(*sorted(six.iteritems(data)))
 def take_action(self, parsed_args):
     self.log.debug('take_action(%s)' % parsed_args)
     client = self.app.client_manager.network
     _id = common.find(client, 'network', 'networks',
                       parsed_args.identifier)
     show_method = getattr(client, "show_network")
     data = show_method(_id)['network']
     data = filters(data)
     return zip(*sorted(six.iteritems(data)))
 def take_action(self, parsed_args):
     self.log.debug('take_action(%s)' % parsed_args)
     client = self.app.client_manager.network
     _id = common.find(client, 'network', 'networks',
                       parsed_args.identifier)
     body = {}
     if parsed_args.name is not None:
         body['name'] = str(parsed_args.name)
     if parsed_args.admin_state is not None:
         body['admin_state_up'] = parsed_args.admin_state
     if parsed_args.shared is not None:
         body['shared'] = parsed_args.shared
     if body == {}:
         raise exceptions.CommandError("Nothing specified to be set")
     update_method = getattr(client, "update_network")
     update_method(_id, {'network': body})
     return
 def take_action(self, parsed_args):
     self.log.debug('take_action(%s)' % parsed_args)
     client = self.app.client_manager.network
     _id = common.find(client, 'network', 'networks',
                       parsed_args.identifier)
     body = {}
     if parsed_args.name is not None:
         body['name'] = str(parsed_args.name)
     if parsed_args.admin_state is not None:
         body['admin_state_up'] = parsed_args.admin_state
     if parsed_args.shared is not None:
         body['shared'] = parsed_args.shared
     if body == {}:
         raise exceptions.CommandError("Nothing specified to be set")
     update_method = getattr(client, "update_network")
     update_method(_id, {'network': body})
     return
示例#10
0
 def take_action(self, parsed_args):
     self.log.debug("take_action(%s)" % parsed_args)
     client = self.app.client_manager.network
     _id = common.find(client, "network", "networks", parsed_args.identifier)
     body = {}
     if parsed_args.name is not None:
         body["name"] = str(parsed_args.name)
     if parsed_args.admin_state is not None:
         body["admin_state_up"] = parsed_args.admin_state
     if parsed_args.shared is not None:
         body["shared"] = parsed_args.shared
     if body == {}:
         msg = "Nothing specified to be set"
         raise exceptions.CommandError(msg)
     update_method = getattr(client, "update_network")
     update_method(_id, {"network": body})
     return
示例#11
0
    def take_action(self, parsed_args):
        self.log.debug('take_action(%s)', parsed_args)
        compute_client = self.app.client_manager.compute
        volume_client = self.app.client_manager.volume

        # Lookup parsed_args.image
        image = None
        if parsed_args.image:
            image = utils.find_resource(
                compute_client.images,
                parsed_args.image,
            )

        # Lookup parsed_args.volume
        volume = None
        if parsed_args.volume:
            volume = utils.find_resource(
                volume_client.volumes,
                parsed_args.volume,
            ).id

        # Lookup parsed_args.flavor
        flavor = utils.find_resource(compute_client.flavors,
                                     parsed_args.flavor)

        boot_args = [parsed_args.server_name, image, flavor]

        files = {}
        for f in parsed_args.file:
            dst, src = f.split('=', 1)
            try:
                files[dst] = io.open(src, 'rb')
            except IOError as e:
                raise exceptions.CommandError("Can't open '%s': %s" % (src, e))

        if parsed_args.min > parsed_args.max:
            msg = _("min instances should be <= max instances")
            raise exceptions.CommandError(msg)
        if parsed_args.min < 1:
            msg = _("min instances should be > 0")
            raise exceptions.CommandError(msg)
        if parsed_args.max < 1:
            msg = _("max instances should be > 0")
            raise exceptions.CommandError(msg)

        userdata = None
        if parsed_args.user_data:
            try:
                userdata = io.open(parsed_args.user_data)
            except IOError as e:
                msg = "Can't open '%s': %s"
                raise exceptions.CommandError(msg % (parsed_args.user_data, e))

        block_device_mapping = {}
        if volume:
            # When booting from volume, for now assume no other mappings
            # This device value is likely KVM-specific
            block_device_mapping = {'vda': volume}
        else:
            for dev_map in parsed_args.block_device_mapping:
                dev_key, dev_vol = dev_map.split('=', 1)
                block_volume = None
                if dev_vol:
                    block_volume = utils.find_resource(
                        volume_client.volumes,
                        dev_vol,
                    ).id
                block_device_mapping.update({dev_key: block_volume})

        nics = []
        if parsed_args.nic:
            neutron_enabled = self._is_neutron_enabled()
        for nic_str in parsed_args.nic:
            nic_info = {
                "net-id": "",
                "v4-fixed-ip": "",
                "v6-fixed-ip": "",
                "port-id": ""
            }
            nic_info.update(
                dict(kv_str.split("=", 1) for kv_str in nic_str.split(",")))
            if bool(nic_info["net-id"]) == bool(nic_info["port-id"]):
                msg = _("either net-id or port-id should be specified "
                        "but not both")
                raise exceptions.CommandError(msg)
            if neutron_enabled:
                network_client = self.app.client_manager.network
                if nic_info["net-id"]:
                    nic_info["net-id"] = common.find(network_client, 'network',
                                                     'networks',
                                                     nic_info["net-id"])
                if nic_info["port-id"]:
                    nic_info["port-id"] = common.find(network_client, 'port',
                                                      'ports',
                                                      nic_info["port-id"])
            else:
                if nic_info["net-id"]:
                    nic_info["net-id"] = utils.find_resource(
                        compute_client.networks, nic_info["net-id"]).id
                if nic_info["port-id"]:
                    msg = _("can't create server with port specified "
                            "since neutron not enabled")
                    raise exceptions.CommandError(msg)
            nics.append(nic_info)

        hints = {}
        for hint in parsed_args.hint:
            key, _sep, value = hint.partition('=')
            # NOTE(vish): multiple copies of the same hint will
            #             result in a list of values
            if key in hints:
                if isinstance(hints[key], six.string_types):
                    hints[key] = [hints[key]]
                hints[key] += [value]
            else:
                hints[key] = value

        # What does a non-boolean value for config-drive do?
        # --config-drive argument is either a volume id or
        # 'True' (or '1') to use an ephemeral volume
        if str(parsed_args.config_drive).lower() in ("true", "1"):
            config_drive = True
        elif str(parsed_args.config_drive).lower() in ("false", "0", "",
                                                       "none"):
            config_drive = None
        else:
            config_drive = parsed_args.config_drive

        boot_kwargs = dict(meta=parsed_args.property,
                           files=files,
                           reservation_id=None,
                           min_count=parsed_args.min,
                           max_count=parsed_args.max,
                           security_groups=parsed_args.security_group,
                           userdata=userdata,
                           key_name=parsed_args.key_name,
                           availability_zone=parsed_args.availability_zone,
                           block_device_mapping=block_device_mapping,
                           nics=nics,
                           scheduler_hints=hints,
                           config_drive=config_drive)

        self.log.debug('boot_args: %s', boot_args)
        self.log.debug('boot_kwargs: %s', boot_kwargs)

        # Wrap the call to catch exceptions in order to close files
        try:
            server = compute_client.servers.create(*boot_args, **boot_kwargs)
        finally:
            # Clean up open files - make sure they are not strings
            for f in files:
                if hasattr(f, 'close'):
                    f.close()
            if hasattr(userdata, 'close'):
                userdata.close()

        if parsed_args.wait:
            if utils.wait_for_status(
                    compute_client.servers.get,
                    server.id,
                    callback=_show_progress,
            ):
                sys.stdout.write('\n')
            else:
                self.log.error(_('Error creating server: %s'),
                               parsed_args.server_name)
                sys.stdout.write(_('\nError creating server'))
                raise SystemExit

        details = _prep_server_detail(compute_client, server)
        return zip(*sorted(six.iteritems(details)))
示例#12
0
    def take_action(self, parsed_args):
        self.log.debug('take_action(%s)', parsed_args)
        compute_client = self.app.client_manager.compute
        volume_client = self.app.client_manager.volume

        # Lookup parsed_args.image
        image = None
        if parsed_args.image:
            image = utils.find_resource(
                compute_client.images,
                parsed_args.image,
            )

        # Lookup parsed_args.volume
        volume = None
        if parsed_args.volume:
            volume = utils.find_resource(
                volume_client.volumes,
                parsed_args.volume,
            ).id

        # Lookup parsed_args.flavor
        flavor = utils.find_resource(compute_client.flavors,
                                     parsed_args.flavor)

        boot_args = [parsed_args.server_name, image, flavor]

        files = {}
        for f in parsed_args.file:
            dst, src = f.split('=', 1)
            try:
                files[dst] = io.open(src, 'rb')
            except IOError as e:
                raise exceptions.CommandError("Can't open '%s': %s" % (src, e))

        if parsed_args.min > parsed_args.max:
            msg = _("min instances should be <= max instances")
            raise exceptions.CommandError(msg)
        if parsed_args.min < 1:
            msg = _("min instances should be > 0")
            raise exceptions.CommandError(msg)
        if parsed_args.max < 1:
            msg = _("max instances should be > 0")
            raise exceptions.CommandError(msg)

        userdata = None
        if parsed_args.user_data:
            try:
                userdata = io.open(parsed_args.user_data)
            except IOError as e:
                msg = "Can't open '%s': %s"
                raise exceptions.CommandError(msg % (parsed_args.user_data, e))

        block_device_mapping = {}
        if volume:
            # When booting from volume, for now assume no other mappings
            # This device value is likely KVM-specific
            block_device_mapping = {'vda': volume}
        else:
            for dev_map in parsed_args.block_device_mapping:
                dev_key, dev_vol = dev_map.split('=', 1)
                block_volume = None
                if dev_vol:
                    block_volume = utils.find_resource(
                        volume_client.volumes,
                        dev_vol,
                    ).id
                block_device_mapping.update({dev_key: block_volume})

        nics = []
        if parsed_args.nic:
            neutron_enabled = self._is_neutron_enabled()
        for nic_str in parsed_args.nic:
            nic_info = {"net-id": "", "v4-fixed-ip": "",
                        "v6-fixed-ip": "", "port-id": ""}
            nic_info.update(dict(kv_str.split("=", 1)
                            for kv_str in nic_str.split(",")))
            if bool(nic_info["net-id"]) == bool(nic_info["port-id"]):
                msg = _("either net-id or port-id should be specified "
                        "but not both")
                raise exceptions.CommandError(msg)
            if neutron_enabled:
                network_client = self.app.client_manager.network
                if nic_info["net-id"]:
                    nic_info["net-id"] = common.find(network_client,
                                                     'network',
                                                     'networks',
                                                     nic_info["net-id"])
                if nic_info["port-id"]:
                    nic_info["port-id"] = common.find(network_client,
                                                      'port',
                                                      'ports',
                                                      nic_info["port-id"])
            else:
                if nic_info["net-id"]:
                    nic_info["net-id"] = utils.find_resource(
                        compute_client.networks,
                        nic_info["net-id"]
                    ).id
                if nic_info["port-id"]:
                    msg = _("can't create server with port specified "
                            "since neutron not enabled")
                    raise exceptions.CommandError(msg)
            nics.append(nic_info)

        hints = {}
        for hint in parsed_args.hint:
            key, _sep, value = hint.partition('=')
            # NOTE(vish): multiple copies of the same hint will
            #             result in a list of values
            if key in hints:
                if isinstance(hints[key], six.string_types):
                    hints[key] = [hints[key]]
                hints[key] += [value]
            else:
                hints[key] = value

        # What does a non-boolean value for config-drive do?
        # --config-drive argument is either a volume id or
        # 'True' (or '1') to use an ephemeral volume
        if str(parsed_args.config_drive).lower() in ("true", "1"):
            config_drive = True
        elif str(parsed_args.config_drive).lower() in ("false", "0",
                                                       "", "none"):
            config_drive = None
        else:
            config_drive = parsed_args.config_drive

        boot_kwargs = dict(
            meta=parsed_args.property,
            files=files,
            reservation_id=None,
            min_count=parsed_args.min,
            max_count=parsed_args.max,
            security_groups=parsed_args.security_group,
            userdata=userdata,
            key_name=parsed_args.key_name,
            availability_zone=parsed_args.availability_zone,
            block_device_mapping=block_device_mapping,
            nics=nics,
            scheduler_hints=hints,
            config_drive=config_drive)

        self.log.debug('boot_args: %s', boot_args)
        self.log.debug('boot_kwargs: %s', boot_kwargs)

        # Wrap the call to catch exceptions in order to close files
        try:
            server = compute_client.servers.create(*boot_args, **boot_kwargs)
        finally:
            # Clean up open files - make sure they are not strings
            for f in files:
                if hasattr(f, 'close'):
                    f.close()
            if hasattr(userdata, 'close'):
                userdata.close()

        if parsed_args.wait:
            if utils.wait_for_status(
                compute_client.servers.get,
                server.id,
                callback=_show_progress,
            ):
                sys.stdout.write('\n')
            else:
                self.log.error(_('Error creating server: %s'),
                               parsed_args.server_name)
                sys.stdout.write(_('\nError creating server'))
                raise SystemExit

        details = _prep_server_detail(compute_client, server)
        return zip(*sorted(six.iteritems(details)))