Exemplo n.º 1
0
    def authenticate(self):
        if not self.baseurl:
            msg = _("Authentication requires 'baseurl', which should be "
                    "specified in '%s'") % self.__class__.__name__
            raise exceptions.AuthorizationFailure(msg)

        if not self.username:
            msg = _("Authentication requires 'username', which should be "
                    "specified in '%s'") % self.__class__.__name__
            raise exceptions.AuthorizationFailure(msg)

        if not self.password:
            msg = _("Authentication requires 'password', which should be "
                    "specified in '%s'") % self.__class__.__name__
            raise exceptions.AuthorizationFailure(msg)

        resp = requests.post(self.baseurl + "/login",
                             data={
                                 'principal': self.username,
                                 'password': self.password
                             })
        if resp.status_code == 200:
            self.session_id = resp.cookies.get('beegosessionID')
            logging.debug("Successfully login, session id: %s" %
                          self.session_id)
Exemplo n.º 2
0
def discover_version(client, requested_version):
    """Discover most recent version supported by API and client.

    Checks ``requested_version`` and returns the most recent version
    supported by both the API and the client.

    :param client: client object
    :param requested_version: requested version represented by APIVersion obj
    :returns: APIVersion
    """
    server_start_version, server_end_version = _get_server_version_range(
        client)

    if (not requested_version.is_latest()
            and requested_version != APIVersion('2.0')):
        if server_start_version.is_null() and server_end_version.is_null():
            raise exceptions.UnsupportedVersion(
                _("Server doesn't support microversions"))
        if not requested_version.matches(server_start_version,
                                         server_end_version):
            raise exceptions.UnsupportedVersion(
                _("The specified version isn't supported by server. The valid "
                  "version range is '%(min)s' to '%(max)s'") % {
                      "min": server_start_version.get_string(),
                      "max": server_end_version.get_string()
                  })
        return requested_version

    if server_start_version.is_null() and server_end_version.is_null():
        return APIVersion('2.0')
    elif harborclient.API_MIN_VERSION > server_end_version:
        raise exceptions.UnsupportedVersion(
            _("Server version is too old. The client valid version range is "
              "'%(client_min)s' to '%(client_max)s'. The server valid version "
              "range is '%(server_min)s' to '%(server_max)s'.") % {
                  'client_min': harborclient.API_MIN_VERSION.get_string(),
                  'client_max': harborclient.API_MAX_VERSION.get_string(),
                  'server_min': server_start_version.get_string(),
                  'server_max': server_end_version.get_string()
              })
    elif harborclient.API_MAX_VERSION < server_start_version:
        raise exceptions.UnsupportedVersion(
            _("Server version is too new. The client valid version range is "
              "'%(client_min)s' to '%(client_max)s'. The server valid version "
              "range is '%(server_min)s' to '%(server_max)s'.") % {
                  'client_min': harborclient.API_MIN_VERSION.get_string(),
                  'client_max': harborclient.API_MAX_VERSION.get_string(),
                  'server_min': server_start_version.get_string(),
                  'server_max': server_end_version.get_string()
              })
    elif harborclient.API_MAX_VERSION <= server_end_version:
        return harborclient.API_MAX_VERSION
    elif server_end_version < harborclient.API_MAX_VERSION:
        return server_end_version
Exemplo n.º 3
0
def main():
    try:
        argv = [encodeutils.safe_decode(a) for a in sys.argv[1:]]
        HarborShell().main(argv)
    except Exception as exc:
        logger.debug(exc, exc_info=1)
        print(_("ERROR (%(type)s): %(msg)s") % {
            'type': exc.__class__.__name__,
            'msg': encodeutils.exception_to_unicode(exc)
        },
              file=sys.stderr)
        sys.exit(1)
    except KeyboardInterrupt:
        print(_("... terminating harbor client"), file=sys.stderr)
        sys.exit(130)
Exemplo n.º 4
0
    def __init__(self, version_str=None):
        """Create an API version object.

        :param version_str: String representation of APIVersionRequest.
                            Correct format is 'X.Y', where 'X' and 'Y'
                            are int values. None value should be used
                            to create Null APIVersionRequest, which is
                            equal to 0.0
        """
        self.ver_major = 0
        self.ver_minor = 0

        if version_str is not None:
            match = re.match(r"^([1-9]\d*)\.([1-9]\d*|0|latest)$", version_str)
            if match:
                self.ver_major = int(match.group(1))
                if match.group(2) == "latest":
                    # NOTE(andreykurilin): Infinity allows to easily determine
                    # latest version and doesn't require any additional checks
                    # in comparison methods.
                    self.ver_minor = float("inf")
                else:
                    self.ver_minor = int(match.group(2))
            else:
                msg = _("Invalid format of client version '%s'. "
                        "Expected format 'X.Y', where X is a major part and Y "
                        "is a minor part of version.") % version_str
                raise exceptions.UnsupportedVersion(msg)
Exemplo n.º 5
0
    def matches(self, min_version, max_version):
        """Matches the version object.

        Returns whether the version object represents a version
        greater than or equal to the minimum version and less than
        or equal to the maximum version.

        :param min_version: Minimum acceptable version.
        :param max_version: Maximum acceptable version.
        :returns: boolean

        If min_version is null then there is no minimum limit.
        If max_version is null then there is no maximum limit.
        If self is null then raise ValueError
        """

        if self.is_null():
            raise ValueError(_("Null APIVersion doesn't support 'matches'."))
        if max_version.is_null() and min_version.is_null():
            return True
        elif max_version.is_null():
            return min_version <= self
        elif min_version.is_null():
            return self <= max_version
        else:
            return min_version <= self <= max_version
Exemplo n.º 6
0
 def do_help(self, args):
     """Display help about this program or one of its subcommands."""
     if args.command:
         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()
Exemplo n.º 7
0
def _get_client_class_and_version(version):
    if not isinstance(version, api_versions.APIVersion):
        version = api_versions.get_api_version(version)
    else:
        api_versions.check_major_version(version)
    if version.is_latest():
        raise exceptions.UnsupportedVersion(
            _("The version should be explicit, not latest."))
    return version, importutils.import_class("harborclient.v%s.client.Client" %
                                             version.ver_major)
Exemplo n.º 8
0
    def get_string(self):
        """Version string representation.

        Converts object to string representation which if used to create
        an APIVersion object results in the same version.
        """
        if self.is_null():
            raise ValueError(
                _("Null APIVersion cannot be converted to string."))
        elif self.is_latest():
            return "%s.%s" % (self.ver_major, "latest")
        return "%s.%s" % (self.ver_major, self.ver_minor)
Exemplo n.º 9
0
def check_major_version(api_version):
    """Checks major part of ``APIVersion`` obj is supported.

    :raises harborclient.exceptions.UnsupportedVersion: if major part is not
                                                      supported
    """
    available_versions = get_available_major_versions()
    if (not api_version.is_null()
            and str(api_version.ver_major) not in available_versions):
        if len(available_versions) == 1:
            msg = _("Invalid client version '%(version)s'. "
                    "Major part should be '%(major)s'") % {
                        "version": api_version.get_string(),
                        "major": available_versions[0]
                    }
        else:
            msg = _("Invalid client version '%(version)s'. "
                    "Major part must be one of: '%(major)s'") % {
                        "version": api_version.get_string(),
                        "major": ", ".join(available_versions)
                    }
        raise exceptions.UnsupportedVersion(msg)
Exemplo n.º 10
0
    def error(self, message):
        """error(message: string)

        Prints a usage message incorporating the message to stderr and
        exits.
        """
        self.print_usage(sys.stderr)
        # FIXME(lzyeval): if changes occur in argparse.ArgParser._check_value
        choose_from = ' (choose from'
        progparts = self.prog.partition(' ')
        self.exit(
            2,
            _("error: %(errmsg)s\nTry '%(mainp)s help %(subp)s'"
              " for more information.\n") % {
                  'errmsg': message.split(choose_from)[0],
                  'mainp': progparts[0],
                  'subp': progparts[2]
              })
Exemplo n.º 11
0
    def get_base_parser(self, argv):
        parser = HarborClientArgumentParser(
            prog='harbor',
            description=__doc__.strip(),
            epilog='See "harbor help COMMAND" '
            'for help on a specific command.',
            add_help=False,
            formatter_class=HarborHelpFormatter,
        )

        # Global arguments
        parser.add_argument(
            '-h',
            '--help',
            action='store_true',
            help=argparse.SUPPRESS,
        )

        parser.add_argument('--debug',
                            default=False,
                            action='store_true',
                            help=_("Print debugging output."))

        parser.add_argument('--timings',
                            default=False,
                            action='store_true',
                            help=_("Print call timing info."))

        parser.add_argument('--version',
                            action='version',
                            version=harborclient.__version__)

        parser.add_argument(
            '--os-username',
            dest='os_username',
            metavar='<username>',
            help=_('Username'),
        )

        parser.add_argument(
            '--os-password',
            dest='os_password',
            metavar='<password>',
            help=_("User's password"),
        )

        parser.add_argument(
            '--timeout',
            metavar='<timeout>',
            help=_("Set request timeout (in seconds)."),
        )

        parser.add_argument(
            '--os-baseurl',
            metavar='<baseurl>',
            help=_('API base url'),
        )

        parser.add_argument(
            '--os-api-version',
            metavar='<api-version>',
            default=utils.env('HARBOR_API_VERSION',
                              default=DEFAULT_API_VERSION),
            help=_('Accepts X, X.Y (where X is major and Y is minor part) or '
                   '"X.latest", defaults to env[HARBOR_API_VERSION].'))

        self._append_global_identity_args(parser, argv)

        return parser
Exemplo n.º 12
0
class HarborShell(object):
    times = []

    def _append_global_identity_args(self, parser, argv):
        # Register the CLI arguments that have moved to the session object.
        parser.set_defaults(os_username=utils.env('HARBOR_USERNAME'))
        parser.set_defaults(os_password=utils.env('HARBOR_PASSWORD'))
        parser.set_defaults(os_baseurl=utils.env('HARBOR_URL'))

    def get_base_parser(self, argv):
        parser = HarborClientArgumentParser(
            prog='harbor',
            description=__doc__.strip(),
            epilog='See "harbor help COMMAND" '
            'for help on a specific command.',
            add_help=False,
            formatter_class=HarborHelpFormatter,
        )

        # Global arguments
        parser.add_argument(
            '-h',
            '--help',
            action='store_true',
            help=argparse.SUPPRESS,
        )

        parser.add_argument('--debug',
                            default=False,
                            action='store_true',
                            help=_("Print debugging output."))

        parser.add_argument('--timings',
                            default=False,
                            action='store_true',
                            help=_("Print call timing info."))

        parser.add_argument('--version',
                            action='version',
                            version=harborclient.__version__)

        parser.add_argument(
            '--os-username',
            dest='os_username',
            metavar='<username>',
            help=_('Username'),
        )

        parser.add_argument(
            '--os-password',
            dest='os_password',
            metavar='<password>',
            help=_("User's password"),
        )

        parser.add_argument(
            '--timeout',
            metavar='<timeout>',
            help=_("Set request timeout (in seconds)."),
        )

        parser.add_argument(
            '--os-baseurl',
            metavar='<baseurl>',
            help=_('API base url'),
        )

        parser.add_argument(
            '--os-api-version',
            metavar='<api-version>',
            default=utils.env('HARBOR_API_VERSION',
                              default=DEFAULT_API_VERSION),
            help=_('Accepts X, X.Y (where X is major and Y is minor part) or '
                   '"X.latest", defaults to env[HARBOR_API_VERSION].'))

        self._append_global_identity_args(parser, argv)

        return parser

    def get_subcommand_parser(self, version, do_help=False, argv=None):
        parser = self.get_base_parser(argv)

        self.subcommands = {}
        subparsers = parser.add_subparsers(metavar='<subcommand>')

        actions_module = importutils.import_module("harborclient.v%s.shell" %
                                                   version.ver_major)

        self._find_actions(subparsers, actions_module, version, do_help)
        self._find_actions(subparsers, self, version, do_help)
        self._add_bash_completion_subparser(subparsers)

        return parser

    def _add_bash_completion_subparser(self, subparsers):
        subparser = subparsers.add_parser('bash_completion',
                                          add_help=False,
                                          formatter_class=HarborHelpFormatter)
        self.subcommands['bash_completion'] = subparser
        subparser.set_defaults(func=self.do_bash_completion)

    def _find_actions(self, subparsers, actions_module, version, do_help):
        msg = _(" (Supported by API versions '%(start)s' - '%(end)s')")
        for attr in (a for a in dir(actions_module) if a.startswith('do_')):
            # I prefer to be hyphen-separated instead of underscores.
            command = attr[3:].replace('_', '-')
            callback = getattr(actions_module, attr)
            desc = callback.__doc__ or ''
            if hasattr(callback, "versioned"):
                additional_msg = ""
                subs = api_versions.get_substitutions(
                    utils.get_function_name(callback))
                if do_help:
                    additional_msg = msg % {
                        'start': subs[0].start_version.get_string(),
                        'end': subs[-1].end_version.get_string()
                    }
                subs = [
                    versioned_method for versioned_method in subs
                    if version.matches(versioned_method.start_version,
                                       versioned_method.end_version)
                ]
                if subs:
                    # use the "latest" substitution
                    callback = subs[-1].func
                else:
                    # there is no proper versioned method
                    continue
                desc = callback.__doc__ or desc
                desc += additional_msg

            action_help = desc.strip()
            arguments = getattr(callback, 'arguments', [])

            subparser = subparsers.add_parser(
                command,
                help=action_help,
                description=desc,
                add_help=False,
                formatter_class=HarborHelpFormatter)
            subparser.add_argument(
                '-h',
                '--help',
                action='help',
                help=argparse.SUPPRESS,
            )
            self.subcommands[command] = subparser
            for (args, kwargs) in arguments:
                start_version = kwargs.get("start_version", None)
                if start_version:
                    start_version = api_versions.APIVersion(start_version)
                    end_version = kwargs.get("end_version", None)
                    if end_version:
                        end_version = api_versions.APIVersion(end_version)
                    else:
                        end_version = api_versions.APIVersion(
                            "%s.latest" % start_version.ver_major)
                    if do_help:
                        kwargs["help"] = kwargs.get(
                            "help", "") + (msg % {
                                "start": start_version.get_string(),
                                "end": end_version.get_string()
                            })
                    if not version.matches(start_version, end_version):
                        continue
                kw = kwargs.copy()
                kw.pop("start_version", None)
                kw.pop("end_version", None)
                subparser.add_argument(*args, **kw)
            subparser.set_defaults(func=callback)

    def setup_debugging(self, debug):
        if not debug:
            return
        streamformat = "%(levelname)s (%(module)s:%(lineno)d) %(message)s"
        logging.basicConfig(level=logging.DEBUG, format=streamformat)
        logging.getLogger('iso8601').setLevel(logging.WARNING)

    def main(self, argv):
        # Parse args once to find version and debug settings
        parser = self.get_base_parser(argv)
        (args, args_list) = parser.parse_known_args(argv)
        self.setup_debugging(args.debug)
        do_help = ('help' in argv) or ('--help'
                                       in argv) or ('-h' in argv) or not argv

        # bash-completion should not require authentication
        if not args.os_api_version:
            api_version = api_versions.get_api_version(
                DEFAULT_MAJOR_OS_COMPUTE_API_VERSION)
        else:
            api_version = api_versions.get_api_version(args.os_api_version)

        os_username = args.os_username
        os_password = args.os_password
        os_baseurl = args.os_baseurl

        subcommand_parser = self.get_subcommand_parser(api_version,
                                                       do_help=do_help,
                                                       argv=argv)
        self.parser = subcommand_parser

        if args.help or not argv:
            subcommand_parser.print_help()
            return 0

        args = subcommand_parser.parse_args(argv)

        # Short-circuit and deal with help 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

        # Update username & password from subcommand if given
        if hasattr(args, "username") and args.username:
            os_username = args.username
            os_password = args.password
        # Recreate client object with discovered version.
        self.cs = client.Client(
            api_version,
            os_username,
            os_password,
            os_baseurl,
            timings=args.timings,
            http_log_debug=args.debug,
            timeout=args.timeout,
        )

        try:
            self.cs.authenticate()
        except exc.Unauthorized:
            raise exc.CommandError(_("Invalid Harbor credentials."))
        except exc.AuthorizationFailure as e:
            raise exc.CommandError("Unable to authorize user '%s':%s" %
                                   (os_username, e))
        args.func(self.cs, args)
        if args.timings:
            self._dump_timings(self.times + self.cs.get_timings())

    def _dump_timings(self, timings):
        results = [{
            "url": url,
            "seconds": end - start
        } for url, start, end in timings]
        total = 0.0
        for tyme in results:
            total += tyme['seconds']
        results.append({"url": "Total", "seconds": total})
        utils.print_list(results, ["url", "seconds"], align='l')
        print("Total: %s seconds" % total)

    def do_bash_completion(self, _args):
        """Print bash completion

        Prints all of the commands and options to stdout so that the
        harbor.bash_completion script doesn't have to hard code them.
        """
        commands = set()
        options = set()
        for sc_str, sc in self.subcommands.items():
            commands.add(sc_str)
            for option in sc._optionals._option_string_actions.keys():
                options.add(option)

        commands.remove('bash-completion')
        commands.remove('bash_completion')
        print(' '.join(commands | options))

    @utils.arg('command',
               metavar='<subcommand>',
               nargs='?',
               help=_('Display help for <subcommand>.'))
    def do_help(self, args):
        """Display help about this program or one of its subcommands."""
        if args.command:
            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()
Exemplo n.º 13
0
    def main(self, argv):
        # Parse args once to find version and debug settings
        parser = self.get_base_parser(argv)
        (args, args_list) = parser.parse_known_args(argv)
        self.setup_debugging(args.debug)
        do_help = ('help' in argv) or ('--help'
                                       in argv) or ('-h' in argv) or not argv

        # bash-completion should not require authentication
        if not args.os_api_version:
            api_version = api_versions.get_api_version(
                DEFAULT_MAJOR_OS_COMPUTE_API_VERSION)
        else:
            api_version = api_versions.get_api_version(args.os_api_version)

        os_username = args.os_username
        os_password = args.os_password
        os_baseurl = args.os_baseurl

        subcommand_parser = self.get_subcommand_parser(api_version,
                                                       do_help=do_help,
                                                       argv=argv)
        self.parser = subcommand_parser

        if args.help or not argv:
            subcommand_parser.print_help()
            return 0

        args = subcommand_parser.parse_args(argv)

        # Short-circuit and deal with help 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

        # Update username & password from subcommand if given
        if hasattr(args, "username") and args.username:
            os_username = args.username
            os_password = args.password
        # Recreate client object with discovered version.
        self.cs = client.Client(
            api_version,
            os_username,
            os_password,
            os_baseurl,
            timings=args.timings,
            http_log_debug=args.debug,
            timeout=args.timeout,
        )

        try:
            self.cs.authenticate()
        except exc.Unauthorized:
            raise exc.CommandError(_("Invalid Harbor credentials."))
        except exc.AuthorizationFailure as e:
            raise exc.CommandError("Unable to authorize user '%s':%s" %
                                   (os_username, e))
        args.func(self.cs, args)
        if args.timings:
            self._dump_timings(self.times + self.cs.get_timings())
Exemplo n.º 14
0
    def _find_actions(self, subparsers, actions_module, version, do_help):
        msg = _(" (Supported by API versions '%(start)s' - '%(end)s')")
        for attr in (a for a in dir(actions_module) if a.startswith('do_')):
            # I prefer to be hyphen-separated instead of underscores.
            command = attr[3:].replace('_', '-')
            callback = getattr(actions_module, attr)
            desc = callback.__doc__ or ''
            if hasattr(callback, "versioned"):
                additional_msg = ""
                subs = api_versions.get_substitutions(
                    utils.get_function_name(callback))
                if do_help:
                    additional_msg = msg % {
                        'start': subs[0].start_version.get_string(),
                        'end': subs[-1].end_version.get_string()
                    }
                subs = [
                    versioned_method for versioned_method in subs
                    if version.matches(versioned_method.start_version,
                                       versioned_method.end_version)
                ]
                if subs:
                    # use the "latest" substitution
                    callback = subs[-1].func
                else:
                    # there is no proper versioned method
                    continue
                desc = callback.__doc__ or desc
                desc += additional_msg

            action_help = desc.strip()
            arguments = getattr(callback, 'arguments', [])

            subparser = subparsers.add_parser(
                command,
                help=action_help,
                description=desc,
                add_help=False,
                formatter_class=HarborHelpFormatter)
            subparser.add_argument(
                '-h',
                '--help',
                action='help',
                help=argparse.SUPPRESS,
            )
            self.subcommands[command] = subparser
            for (args, kwargs) in arguments:
                start_version = kwargs.get("start_version", None)
                if start_version:
                    start_version = api_versions.APIVersion(start_version)
                    end_version = kwargs.get("end_version", None)
                    if end_version:
                        end_version = api_versions.APIVersion(end_version)
                    else:
                        end_version = api_versions.APIVersion(
                            "%s.latest" % start_version.ver_major)
                    if do_help:
                        kwargs["help"] = kwargs.get(
                            "help", "") + (msg % {
                                "start": start_version.get_string(),
                                "end": end_version.get_string()
                            })
                    if not version.matches(start_version, end_version):
                        continue
                kw = kwargs.copy()
                kw.pop("start_version", None)
                kw.pop("end_version", None)
                subparser.add_argument(*args, **kw)
            subparser.set_defaults(func=callback)
Exemplo n.º 15
0
import logging
import os
import pkgutil
import re

import harborclient
from harborclient import exceptions
from harborclient.i18n import _

LOG = logging.getLogger(__name__)
_type_error_msg = _("'%(other)s' should be an instance of '%(cls)s'")

if not LOG.handlers:
    LOG.addHandler(logging.StreamHandler())


class APIVersion(object):
    """This class represents an API Version Request.

    This class provides convenience methods for manipulation
    and comparison of version numbers that we need to do to
    implement microversions.
    """
    def __init__(self, version_str=None):
        """Create an API version object.

        :param version_str: String representation of APIVersionRequest.
                            Correct format is 'X.Y', where 'X' and 'Y'
                            are int values. None value should be used
                            to create Null APIVersionRequest, which is
                            equal to 0.0
Exemplo n.º 16
0
import logging

from harborclient.i18n import _
from harborclient import utils

logger = logging.getLogger(__name__)


# /login
@utils.arg(
    '--username',
    metavar='<username>',
    dest='username',
    required=True,
    help=_('Username.'), )
@utils.arg(
    '--password',
    metavar='<password>',
    dest='password',
    required=True,
    help=_('Password.'), )
def do_login(cs, args):
    """Login and return the session id. """
    resp = cs.users.login(args.username, args.password, cs.baseurl)
    if resp.status_code == 200:
        print("Successfully login, session id: %s" %
              resp.cookies.get('beegosessionID'))
    else:
        print("Failed to login! Please re-check your username and password")