def _find_host(cc, host): if host.isdigit() or utils.is_uuid_like(host): try: h = cc.host.get(host) except exc.HTTPNotFound: raise exc.CommandError('host not found: %s' % host) else: return h else: hostlist = cc.host.list() for h in hostlist: if h.hostname == host: return h else: raise exc.CommandError('host not found: %s' % host)
def do_host_delete(cc, args): """Delete a host.""" for n in args.hostnameorid: try: cc.host.delete(n) print('Deleted host %s' % n) except exc.HTTPNotFound: raise exc.CommandError('host not found: %s' % n)
def _find_node(cc, host, nodeuuid): nodes = cc.node.list(host.uuid) for i in nodes: if i.uuid == nodeuuid: break else: raise exc.CommandError('Inode not found: host %s if %s' % (host.hostname, nodeuuid)) return i
def _find_port(cc, host, portnameoruuid): ports = cc.port.list(host.uuid) for p in ports: if p.name == portnameoruuid or p.uuid == portnameoruuid: break else: raise exc.CommandError('Port not found: host %s port %s' % (host.id, portnameoruuid)) return p
def do_host_update(cc, args): """Update host attributes.""" patch = utils.args_array_to_patch("replace", args.attributes[0]) host = host_utils._find_host(cc, args.hostnameorid) try: host = cc.host.update(host.id, patch) except exc.HTTPNotFound: raise exc.CommandError('host not found: %s' % args.hostnameorid) _print_host_show(host)
def do_help(self, args): """Display help about this program or one of its subcommands.""" if getattr(args, 'command', None): if args.command in self.subcommands: self.subcommands[args.command].print_help() else: raise exc.CommandError("'%s' is not a valid subcommand" % args.command) else: self.parser.print_help()
def args_array_to_dict(kwargs, key_to_convert): values_to_convert = kwargs.get(key_to_convert) if values_to_convert: try: kwargs[key_to_convert] = dict( v.split("=", 1) for v in values_to_convert) except ValueError: raise exc.CommandError('%s must be a list of KEY=VALUE not "%s"' % (key_to_convert, values_to_convert)) return kwargs
def do_host_power_off(cc, args): """Power off a host.""" attributes = [] attributes.append('action=power-off') patch = utils.args_array_to_patch("replace", attributes) host = host_utils._find_host(cc, args.hostnameorid) try: host = cc.host.update(host.id, patch) except exc.HTTPNotFound: raise exc.CommandError('host not found: %s' % args.hostnameorid) _print_host_show(host)
def args_array_to_patch(op, attributes): patch = [] for attr in attributes: # Sanitize if not attr.startswith('/'): attr = '/' + attr if op in ['add', 'replace']: try: path, value = attr.split("=", 1) patch.append({'op': op, 'path': path, 'value': value}) except ValueError: raise exc.CommandError('Attributes must be a list of ' 'PATH=VALUE not "%s"' % attr) elif op == "remove": # For remove only the key is needed patch.append({'op': op, 'path': attr}) else: raise exc.CommandError('Unknown PATCH operation: %s' % op) return patch
def _find_cpu(cc, host, cpunameoruuid): cpus = cc.cpu.list(host.uuid) if cpunameoruuid.isdigit(): cpunameoruuid = int(cpunameoruuid) for c in cpus: if c.uuid == cpunameoruuid or c.cpu == cpunameoruuid: break else: raise exc.CommandError('CPU logical core not found: host %s cpu %s' % (host.hostname, cpunameoruuid)) return c
def do_host_bulk_add(cc, args): """Add multiple new hosts.""" field_list = ['hostsfile'] fields = dict((k, v) for (k, v) in vars(args).items() if k in field_list and not (v is None)) hostsfile = fields['hostsfile'] if os.path.isdir(hostsfile): raise exc.CommandError("Error: %s is a directory." % hostsfile) try: req = open(hostsfile, 'rb') except Exception: raise exc.CommandError("Error: Could not open file %s." % hostsfile) response = cc.host.create_many(req) if not response: raise exc.CommandError("The request timed out or there was an " "unknown error") success = response.get('success') error = response.get('error') if success: print("Success: " + success + "\n") if error: print("Error:\n" + error)
def do_host_swact(cc, args): """Switch activity away from this active host.""" attributes = [] if args.force is True: # Forced swact operation attributes.append('action=force-swact') else: # Normal swact operation attributes.append('action=swact') patch = utils.args_array_to_patch("replace", attributes) host = host_utils._find_host(cc, args.hostnameorid) try: host = cc.host.update(host.id, patch) except exc.HTTPNotFound: raise exc.CommandError('host not found: %s' % args.hostnameorid) _print_host_show(host)
def do_host_unlock(cc, args): """Unlock a host.""" attributes = [] if args.force is True: # Forced unlock operation attributes.append('action=force-unlock') else: # Normal unlock operation attributes.append('action=unlock') patch = utils.args_array_to_patch("replace", attributes) host = host_utils._find_host(cc, args.hostnameorid) try: host = cc.host.update(host.id, patch) except exc.HTTPNotFound: raise exc.CommandError('host not found: %s' % args.hostnameorid) _print_host_show(host)
def do_host_add(cc, args): """Add a new host.""" field_list = [ 'hostname', 'personality', 'subfunctions', 'mgmt_mac', 'mgmt_ip', 'bm_ip', 'bm_type', 'bm_username', 'bm_password', 'boot_device', 'rootfs_device', 'install_output', 'console', 'location', 'ttys_dcd' ] fields = dict((k, v) for (k, v) in vars(args).items() if k in field_list and not (v is None)) # This is the expected format of the location field if 'location' in fields: fields['location'] = {"locn": fields['location']} host = cc.host.create(**fields) suuid = getattr(host, 'uuid', '') try: host = cc.host.get(suuid) except exc.HTTPNotFound: raise exc.CommandError('Host not found: %s' % suuid) else: _print_host_show(host)
def find_resource(manager, name_or_id): """Helper for the _find_* methods.""" # first try to get entity as integer id try: if isinstance(name_or_id, int) or name_or_id.isdigit(): return manager.get(int(name_or_id)) except exc.NotFound: pass # now try to get entity as uuid try: uuid.UUID(str(name_or_id)) return manager.get(name_or_id) except (ValueError, exc.NotFound): pass # finally try to find entity by name try: return manager.find(name=name_or_id) except exc.NotFound: msg = "No %s with a name or ID of '%s' exists." % \ (manager.resource_class.__name__.lower(), name_or_id) raise exc.CommandError(msg)
def main(self, argv): # Parse args once to find version parser = self.get_base_parser() (options, args) = parser.parse_known_args(argv) self._setup_debugging(options.debug) # build available subcommands based on version api_version = options.inventory_api_version subcommand_parser = self.get_subcommand_parser(api_version) self.parser = subcommand_parser # Handle top-level --help/-h before attempting to parse # a command off the command line if options.help or not argv: self.do_help(options) return 0 # Parse args again and call whatever callback was selected args = subcommand_parser.parse_args(argv) # Short-circuit and deal with help command right away. if args.func == self.do_help: self.do_help(args) return 0 elif args.func == self.do_bash_completion: self.do_bash_completion(args) return 0 if not (args.os_auth_token and args.inventory_url): if not args.os_username: raise exc.CommandError("You must provide a username via " "either --os-username or via " "env[OS_USERNAME]") if not args.os_password: raise exc.CommandError("You must provide a password via " "either --os-password or via " "env[OS_PASSWORD]") if not (args.os_project_id or args.os_project_name): raise exc.CommandError("You must provide a project name via " "either --os-project-name or via " "env[OS_PROJECT_NAME]") if not args.os_auth_url: raise exc.CommandError("You must provide an auth url via " "either --os-auth-url or via " "env[OS_AUTH_URL]") if not args.os_region_name: raise exc.CommandError("You must provide an region name via " "either --os-region-name or via " "env[OS_REGION_NAME]") client_args = ('os_auth_token', 'inventory_url', 'os_username', 'os_password', 'os_auth_url', 'os_project_id', 'os_project_name', 'os_tenant_id', 'os_tenant_name', 'os_region_name', 'os_user_domain_id', 'os_user_domain_name', 'os_project_domain_id', 'os_project_domain_name', 'os_service_type', 'os_endpoint_type', 'timeout') kwargs = {} for key in client_args: client_key = key.replace("os_", "", 1) kwargs[client_key] = getattr(args, key) client = inventoryclient.client.get_client(api_version, **kwargs) try: args.func(client, args) except exc.Unauthorized: raise exc.CommandError("Invalid Identity credentials.")