Example #1
0
    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.smc_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

        if not (args.os_auth_token and args.smc_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_auth_url:
                raise exc.CommandError("You must provide an auth url via "
                                       "either --os-auth-url or via "
                                       "env[OS_AUTH_URL]")

        client = cgclient.get_client(api_version, **(args.__dict__))

        # nargs = args.__dict__
        # nargs['neutron_endpoint'] = client.neutron_endpoint
        # client.neutronClient = get_neutron_client(**nargs)

        try:
            args.func(client, args)
        except exc.Unauthorized:
            raise exc.CommandError("Invalid Identity credentials.")
Example #2
0
def do_servicenode_show(cc, args):
    """Show a Service Node's attributes."""
    try:
        node = cc.smc_service_node.get(args.node)
    except exc.HTTPNotFound:
        raise exc.CommandError('Service Node not found: %s' % args.node)
    except exc.Forbidden:
        raise exc.CommandError("Not authorized. The requested action "
                               "requires 'admin' level")
    else:
        if node is None:
            print("Service node %s could not be found" % args.node)
            return
        _print_sm_service_node_show(node)
Example #3
0
def do_servicegroup_show(cc, args):
    """Show a Service Group."""
    try:
        servicegroup = cc.smc_servicegroup.get(args.servicegroup)
    except exc.HTTPNotFound:
        raise exc.CommandError('Service Group not found: %s' % args.servicegroup)
    except exc.Forbidden:
        raise exc.CommandError("Not authorized. The requested action "
                               "requires 'admin' level")
    else:
        if servicegroup is None:
            print("Service group %s could not be found" % args.servicegroup)
            return
        if servicegroup.status:
            servicegroup.state = (servicegroup.state + '-' +
                                  servicegroup.status)
        servicegroup.hostname = servicegroup.node_name
        _print_servicegroup_show(servicegroup)
Example #4
0
def do_service_show(cc, args):
    """Show a Service."""
    try:
        service = cc.smc_service.get(args.service)
    except exc.HTTPNotFound:
        raise exc.CommandError('service not found: %s' % args.service)
    except exc.Forbidden:
        raise exc.CommandError("Not authorized. The requested action "
                               "requires 'admin' level")
    else:
        if service is None:
            print("Service %s could not be found" % args.service)
            return
        if service.status:
            service.state = (service.state + '-' + service.status)
        service.service_name = service.name
        if getattr(service, 'node_name', None) is None:
            service.hostname = socket.gethostname()
        _print_service_show(service)
Example #5
0
 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()
Example #6
0
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
Example #7
0
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
Example #8
0
def do_servicenode_list(cc, args):
    """List Service Nodes."""
    try:
        node = cc.smc_service_node.list()
    except exc.Forbidden:
        raise exc.CommandError("Not authorized. The requested action "
                               "requires 'admin' level")
    else:
        fields = ['id', 'name', 'administrative_state', 'operational_state',
                  'availability_status', 'ready_state']
        field_labels = ['id', 'name', 'administrative', 'operational',
                        'availability', 'ready_state']
        utils.print_list(node, fields, field_labels, sortby=1)
Example #9
0
def do_servicegroup_list(cc, args):
    """List Service Groups."""
    try:
        servicegroup = cc.smc_servicegroup.list()
    except exc.Forbidden:
        raise exc.CommandError("Not authorized. The requested action "
                               "requires 'admin' level")
    else:
        fields = ['uuid', 'service_group_name', 'node_name', 'state']
        field_labels = ['uuid', 'service_group_name', 'hostname', 'state']
        for s in servicegroup:
            if s.status:
                s.state = (s.state + '-' + s.status)
        utils.print_list(servicegroup, fields, field_labels, sortby=1)
Example #10
0
def do_service_list(cc, args):
    """List Services."""
    try:
        service = cc.smc_service.list()
    except exc.Forbidden:
        raise exc.CommandError("Not authorized. The requested action "
                               "requires 'admin' level")
    else:
        fields = ['id', 'name', 'node_name', 'state']
        field_labels = ['id', 'service_name', 'hostname', 'state']
        # remove the entry in the initial state
        clean_list = [x for x in service if x.state != 'initial']
        for s in clean_list:
            if s.status:
                s.state = (s.state + '-' + s.status)
            if getattr(s, 'node_name', None) is None:
                s.node_name = socket.gethostname()

        utils.print_list(clean_list, fields, field_labels, sortby=1)
Example #11
0
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)