class ServiceUnavailable(HttpServerError): """HTTP 503 - Service Unavailable. The server is currently unavailable. """ http_status = 503 message = _("Service Unavailable")
class HttpServerError(HttpError): """Server-side HTTP error. Exception for cases in which the server is aware that it has erred or is incapable of performing the request. """ message = _("HTTP Server Error")
def do_osimage_delete(cc, args): """Unregister osimage from xCAT3 service. :raises: ClientException, if error happens during the delete """ cc.osimage.delete(args.name) print(_("%s deleted" % args.name))
def _get_node_from_args(nodes=None): """Build the node(s) from node range""" name_list = [] if nodes: nodes = nodes.split(',') for node in nodes: names = [] try: if '[' in node and '-' in node and ']' in node: parts = node.split('[') prefix = parts[0] num_parts = parts[1].split('-') left = int(num_parts[0]) right = int(num_parts[1].split(']')[0]) while (left <= right): name = "%s%d" % (prefix, left) names.append(name) left += 1 else: node = node.replace('[', '').replace(']', '') names.append(node) name_list.extend(names) except Exception() as e: err = _("Invalied node name %(name)s. Error: %(err)s") raise exc.InvalidName(err % {'name': node, 'err': e}) return list(set(name_list))
def do_nic_delete(cc, args): """Unregister nic from xCAT3 service. :raises: ClientException, if error happens during the delete """ cc.nic.delete(args.uuid) print(_("%s deleted" % args.uuid))
class HttpVersionNotSupported(HttpServerError): """HTTP 505 - HttpVersion Not Supported. The server does not support the HTTP protocol version used in the request. """ http_status = 505 message = _("HTTP Version Not Supported")
def do_network_delete(cc, args): """Unregister network from xCAT3 service. :raises: ClientException, if error happens during the delete """ cc.network.delete(args.name) print(_("%s deleted" % args.name))
class InternalServerError(HttpServerError): """HTTP 500 - Internal Server Error. A generic error message, given when no more specific message is suitable. """ http_status = 500 message = _("Internal Server Error")
def do_passwd_delete(cc, args): """Unregister passwd from xCAT3 service. :raises: ClientException, if error happens during the delete """ cc.passwd.delete(args.key) print(_("%s deleted" % args.key))
class BadGateway(HttpServerError): """HTTP 502 - Bad Gateway. The server was acting as a gateway or proxy and received an invalid response from the upstream server. """ http_status = 502 message = _("Bad Gateway")
class GatewayTimeout(HttpServerError): """HTTP 504 - Gateway Timeout. The server was acting as a gateway or proxy and did not receive a timely response from the upstream server. """ http_status = 504 message = _("Gateway Timeout")
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) subcommand_parser = self.get_subcommand_parser('1') 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 these commands 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() return 0 if args.max_retries < 0: raise exc.CommandError(_("You must provide value >= 0 for " "--max-retries")) if args.retry_interval < 1: raise exc.CommandError(_("You must provide value >= 1 for " "--retry-interval")) client_args = ('xcat3_url',) kwargs = {} for key in client_args: kwargs[key] = getattr(args, key) if not kwargs.get('xcat3_url'): kwargs['xcat3_url'] = 'http://localhost:3010' client = xcatclient.get_client(**kwargs) try: args.func(client, args) except exc.CommandError as e: subcommand_parser = self.subcommands[args.subparser_name] subcommand_parser.error(e)
def to_attrs_dict(attrs, VALID_FIELDS): dct = {} for attr in attrs: k, v = attr.split('=') if k not in VALID_FIELDS: print(_('Unsupport attrbute %s ' % k)) exit(1) dct[k] = v return dct
def do_help(self, args): 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 do_export(cc, args): """Export node(s) information as a specific json data file""" nodes = _get_node_from_args(args.nodes) node_dict = {'nodes': []} map(lambda x: node_dict['nodes'].append({'name': x}), nodes) fields = [ 'name', 'mgt', 'netboot', 'type', 'arch', 'nics_info', 'control_info' ] result = cc.node.get(node_dict, fields) utils.write_to_file(args.output, json.dumps(result)) print(_("Export nodes data succefully."))
def print_list(objs, json_flag=False): """Print a list of objects or dict as a table, one row per object or dict. :param objs: iterable of :class:`Resource` :param json_flag: print the list as JSON instead of table """ if json_flag: json.dumps(objs) return if not objs: print(_("Could not find any resource.")) for item in objs: print(item)
def do_nic_show(cc, args): """Show detailed infomation about nic.""" fields = [] if args.fields: fields = args.fields.split(',') if fields and 'uuid' not in fields: fields.append('uuid') if args.uuid: result = cc.nic.show(args.uuid, fields) elif args.mac: result = cc.nic.get_by_mac(args.mac) else: print(_("Invalid argument given.")) return cliutils.print_dict(result)
class HttpError(ClientException): """The base exception class for all HTTP exceptions.""" http_status = 0 message = _("HTTP Error") def __init__(self, message=None, response=None, url=None, method=None, http_status=None): self.http_status = http_status or self.http_status self.message = message or self.message self.response = response self.url = url self.method = method formatted_string = "%s (HTTP %s)" % (self.message, self.http_status) super(HttpError, self).__init__(formatted_string)
def split_and_deserialize(string): """Split and try to JSON deserialize a string. Gets a string with the KEY=VALUE format, split it (using '=' as the separator) and try to JSON deserialize the VALUE. :returns: A tuple of (key, value). """ try: key, value = string.split("=", 1) except ValueError: raise exc.CommandError( _('Attributes must be a list of ' 'PATH=VALUE not "%s"') % string) try: value = json.loads(value) except ValueError: pass return (key, value)
def _validate(attr_dict): for attr in REQUIRE_FIELDS: if not attr_dict.has_key(attr): print(_('Could not find required field %(attr)s' % {'attr': attr})) exit(1)
def check_empty_arg(arg, arg_descriptor): if not arg.strip(): raise exc.CommandError( _('%(arg)s cannot be empty or only have blank' ' spaces') % {'arg': arg_descriptor})