Exemplo n.º 1
0
def run_module():
    """Module main function
    """
    # define available arguments/parameters a user can pass to the module
    module_args = dict(
        blueprint_name=dict(type='str', required=True),
        compose_type=dict(type='str', required=True),
        ref=dict(type='str', required=False, default='rhel/8/x86_64/edge'),
        parent=dict(type='str', required=False, default=''),
        wait=dict(type='bool', required=False, default=False),
    )

    # seed the result dict in the object
    # we primarily care about changed and state
    # change is if this module effectively modified the target
    # state will include any data that you want your module to pass back
    # for consumption, for example, in a subsequent task
    result = dict(changed=True, ansible_module_results='')

    # the AnsibleModule object will be our abstraction working with Ansible
    # this includes instantiation, a couple of common attr would be the
    # args/params passed to the execution, as well as if the module
    # supports check mode
    module = AnsibleModule(argument_spec=module_args, supports_check_mode=True)

    # if the user is working with this module in only check mode we do not
    # want to make any changes to the environment, just return the current
    # state with no modifications
    if module.check_mode:
        module.exit_json(**result)

    compose_params = {
        'blueprint_name': module.params['blueprint_name'],
        'compose_type': module.params['compose_type'],
        'ref': module.params['ref'],
        'parent': module.params['parent']
    }
    ret = client.post_url_json(SOCKET, '/api/v1/compose',
                               json.dumps(compose_params))
    build_id = ret['build_id']
    if module.params['wait']:
        while True:
            ret = client.get_url_json(SOCKET,
                                      '/api/v1/compose/info/' + build_id)
            if ret['queue_status'] not in ('RUNNING', 'QUEUED'):
                break
            time.sleep(1)

    result['ansible_module_results'] = client.get_url_json(
        SOCKET, '/api/v1/compose/info/' + build_id)

    if result['ansible_module_results']['queue_status'] == 'FAILED':
        result['failed'] = True
    # in the event of a successful module execution, you will want to
    # simple AnsibleModule.exit_json(), passing the key/value results
    module.exit_json(**result)
def run_module():
    """Module main function
    """
    # define available arguments/parameters a user can pass to the module
    module_args = dict(
        status=dict(type='str', required=False, default='all'),
        id=dict(type='str', required=False)
    )

    # seed the result dict in the object
    # we primarily care about changed and state
    # change is if this module effectively modified the target
    # state will include any data that you want your module to pass back
    # for consumption, for example, in a subsequent task
    result = dict(
        changed=False,
        ansible_module_results=''
    )

    # the AnsibleModule object will be our abstraction working with Ansible
    # this includes instantiation, a couple of common attr would be the
    # args/params passed to the execution, as well as if the module
    # supports check mode
    module = AnsibleModule(
        argument_spec=module_args,
        supports_check_mode=True
    )

    # if the user is working with this module in only check mode we do not
    # want to make any changes to the environment, just return the current
    # state with no modifications
    if module.check_mode:
        module.exit_json(**result)

    if module.params['id']:
        ret = client.get_url_json(SOCKET, '/api/v1/compose/info/' + module.params['id'])
        if 'errors' in ret.keys():
            result['failed'] = True
    else:
        ret = []
        if module.params['status'] == 'all' or module.params['status'] == 'running':
            ret += client.get_url_json(SOCKET, '/api/v1/compose/queue')['run']
        if module.params['status'] == 'all' or module.params['status'] == 'waiting':
            ret += client.get_url_json(SOCKET, '/api/v1/compose/queue')['new']
        if module.params['status'] == 'all' or module.params['status'] == 'finished':
            ret += client.get_url_json(SOCKET, '/api/v1/compose/finished')['finished']
        if module.params['status'] == 'all' or module.params['status'] == 'failed':
            ret += client.get_url_json(SOCKET, '/api/v1/compose/failed')['failed']

    result['ansible_module_results'] = ret

    # in the event of a successful module execution, you will want to
    # simple AnsibleModule.exit_json(), passing the key/value results
    module.exit_json(**result)
Exemplo n.º 3
0
def compose_list(socket_path,
                 api_version,
                 args,
                 show_json=False,
                 testmode=0,
                 api=None):
    """Return a simple list of compose identifiers"""

    states = ("running", "waiting", "finished", "failed")

    which = set()

    if any(a not in states for a in args):
        # TODO: error about unknown state
        return 1
    elif not args:
        which.update(states)
    else:
        which.update(args)

    results = []

    if "running" in which or "waiting" in which:
        api_route = client.api_url(api_version, "/compose/queue")
        r = client.get_url_json(socket_path, api_route)
        if "running" in which:
            results += r["run"]
        if "waiting" in which:
            results += r["new"]

    if "finished" in which:
        api_route = client.api_url(api_version, "/compose/finished")
        r = client.get_url_json(socket_path, api_route)
        results += r["finished"]

    if "failed" in which:
        api_route = client.api_url(api_version, "/compose/failed")
        r = client.get_url_json(socket_path, api_route)
        results += r["failed"]

    if results:
        if show_json:
            print(json.dumps(results, indent=4))
        else:
            list_fmt = "{id} {queue_status} {blueprint} {version} {compose_type}"
            print("\n".join(list_fmt.format(**c) for c in results))

    return 0
Exemplo n.º 4
0
def sources_info(socket_path, api_version, args, show_json=False):
    """Output info on a list of projects

    :param socket_path: Path to the Unix socket to use for API communication
    :type socket_path: str
    :param api_version: Version of the API to talk to. eg. "0"
    :type api_version: str
    :param args: List of remaining arguments from the cmdline
    :type args: list of str
    :param show_json: Set to True to show the JSON output instead of the human readable output
    :type show_json: bool

    sources info <source-name>
    """
    if len(args) == 0:
        log.error("sources info is missing the name of the source")
        return 1

    if show_json:
        api_route = client.api_url(api_version, "/projects/source/info/%s" % ",".join(args))
        result = client.get_url_json(socket_path, api_route)
        print(json.dumps(result, indent=4))
        return 0
    else:
        api_route = client.api_url(api_version, "/projects/source/info/%s?format=toml" % ",".join(args))
        result = client.get_url_raw(socket_path, api_route)
        print(result)
    return 0
Exemplo n.º 5
0
Arquivo: upload.py Projeto: whot/lorax
def upload_log(socket_path, api_version, args, show_json=False, testmode=0):
    """Return the upload log

    :param socket_path: Path to the Unix socket to use for API communication
    :type socket_path: str
    :param api_version: Version of the API to talk to. eg. "0"
    :type api_version: str
    :param args: List of remaining arguments from the cmdline
    :type args: list of str
    :param show_json: Set to True to show the JSON output instead of the human readable output
    :type show_json: bool
    :param testmode: unused in this function
    :type testmode: int

    upload log <build-uuid>
    """
    if len(args) == 0:
        log.error("log is missing the upload uuid")
        return 1

    api_route = client.api_url(api_version, "/upload/log/%s" % args[0])
    result = client.get_url_json(socket_path, api_route)
    (rc, exit_now) = handle_api_result(result, show_json)
    if exit_now:
        return rc

    print("Upload log for %s:\n" % result["upload_id"])
    print(result["log"])

    return 0
Exemplo n.º 6
0
def compose_types(socket_path,
                  api_version,
                  args,
                  show_json=False,
                  testmode=0,
                  api=None):
    """Return information about the supported compose types

    :param socket_path: Path to the Unix socket to use for API communication
    :type socket_path: str
    :param api_version: Version of the API to talk to. eg. "0"
    :type api_version: str
    :param args: List of remaining arguments from the cmdline
    :type args: list of str
    :param show_json: Set to True to show the JSON output instead of the human readable output
    :type show_json: bool
    :param testmode: unused in this function
    :type testmode: int

    Add additional details to types that are known to composer-cli. Raw JSON output does not
    include this extra information.
    """
    api_route = client.api_url(api_version, "/compose/types")
    result = client.get_url_json(socket_path, api_route)
    if show_json:
        print(json.dumps(result, indent=4))
        return 0

    # output a plain list of identifiers, one per line
    print("\n".join(t["name"] for t in result["types"] if t["enabled"]))
Exemplo n.º 7
0
Arquivo: upload.py Projeto: whot/lorax
def upload_list(socket_path, api_version, args, show_json=False, testmode=0):
    """Return the composes and their associated upload uuids and status

    :param socket_path: Path to the Unix socket to use for API communication
    :type socket_path: str
    :param api_version: Version of the API to talk to. eg. "0"
    :type api_version: str
    :param args: List of remaining arguments from the cmdline
    :type args: list of str
    :param show_json: Set to True to show the JSON output instead of the human readable output
    :type show_json: bool
    :param testmode: unused in this function
    :type testmode: int

    upload list
    """
    api_route = client.api_url(api_version, "/compose/finished")
    r = client.get_url_json(socket_path, api_route)
    results = r["finished"]
    if not results:
        return 0

    if show_json:
        print(json.dumps(results, indent=4))
    else:
        compose_fmt = "{id} {queue_status} {blueprint} {version} {compose_type}"
        upload_fmt = '    {uuid} "{image_name}" {provider_name} {status}'
        for c in results:
            print(compose_fmt.format(**c))
            print("\n".join(upload_fmt.format(**u) for u in c["uploads"]))
            print()

    return 0
Exemplo n.º 8
0
def projects_list(socket_path, api_version, args, show_json=False):
    """Output the list of available projects

    :param socket_path: Path to the Unix socket to use for API communication
    :type socket_path: str
    :param api_version: Version of the API to talk to. eg. "0"
    :type api_version: str
    :param args: List of remaining arguments from the cmdline
    :type args: list of str
    :param show_json: Set to True to show the JSON output instead of the human readable output
    :type show_json: bool

    projects list
    """
    api_route = client.api_url(api_version, "/projects/list")
    result = client.get_url_json(socket_path, api_route)
    (rc, exit_now) = handle_api_result(result, show_json)
    if exit_now:
        return rc

    for proj in result["projects"]:
        for k in [
                field
                for field in ("name", "summary", "homepage", "description")
                if proj[field]
        ]:
            print("%s: %s" %
                  (k.title(),
                   textwrap.fill(proj[k], subsequent_indent=" " *
                                 (len(k) + 2))))
        print("\n\n")

    return rc
Exemplo n.º 9
0
def modules_cmd(opts):
    """Process modules commands

    :param opts: Cmdline arguments
    :type opts: argparse.Namespace
    :returns: Value to return from sys.exit()
    :rtype: int
    """
    if opts.args[1] == "help" or opts.args[1] == "--help":
        print(modules_help)
        return 0
    elif opts.args[1] != "list":
        log.error("Unknown modules command: %s", opts.args[1])
        return 1

    api_route = client.api_url(opts.api_version, "/modules/list")
    result = client.get_url_json(opts.socket, api_route)
    (rc, exit_now) = handle_api_result(result, opts.json)
    if exit_now:
        return rc

    # "list" should output a plain list of identifiers, one per line.
    print("\n".join(r["name"] for r in result["modules"]))

    return rc
Exemplo n.º 10
0
def providers_list(socket_path, api_version, args, show_json=False, testmode=0):
    """Return the list of providers

    :param socket_path: Path to the Unix socket to use for API communication
    :type socket_path: str
    :param api_version: Version of the API to talk to. eg. "0"
    :type api_version: str
    :param args: List of remaining arguments from the cmdline
    :type args: list of str
    :param show_json: Set to True to show the JSON output instead of the human readable output
    :type show_json: bool
    :param testmode: unused in this function
    :type testmode: int

    providers list
    """
    api_route = client.api_url(api_version, "/upload/providers")
    r = client.get_url_json(socket_path, api_route)
    results = r["providers"]
    if not results:
        return 0

    if show_json:
        print(json.dumps(results, indent=4))
    else:
        if len(args) == 1:
            if args[0] not in results:
                log.error("%s is not a valid provider", args[0])
                return 1
            print("\n".join(sorted(results[args[0]]["profiles"].keys())))
        else:
            print("\n".join(sorted(results.keys())))

    return 0
Exemplo n.º 11
0
def blueprints_changes(socket_path, api_version, args, show_json=False):
    """Display the changes for each of the blueprints

    :param socket_path: Path to the Unix socket to use for API communication
    :type socket_path: str
    :param api_version: Version of the API to talk to. eg. "0"
    :type api_version: str
    :param args: List of remaining arguments from the cmdline
    :type args: list of str
    :param show_json: Set to True to show the JSON output instead of the human readable output
    :type show_json: bool

    blueprints changes <blueprint,...>     Display the changes for each blueprint.
    """
    api_route = client.api_url(
        api_version, "/blueprints/changes/%s" % (",".join(argify(args))))
    result = client.get_url_json(socket_path, api_route)
    if show_json:
        print(json.dumps(result, indent=4))
        return 0

    for blueprint in result["blueprints"]:
        print(blueprint["name"])
        for change in blueprint["changes"]:
            prettyCommitDetails(change)

    return 0
Exemplo n.º 12
0
def status_cmd(opts):
    """Process status commands

    :param opts: Cmdline arguments
    :type opts: argparse.Namespace
    :returns: Value to return from sys.exit()
    :rtype: int
    """
    if opts.args[1] == "help" or opts.args[1] == "--help":
        print(status_help)
        return 0
    elif opts.args[1] != "show":
        log.error("Unknown status command: %s", opts.args[1])
        return 1

    result = client.get_url_json(opts.socket, "/api/status")
    (rc, exit_now) = handle_api_result(result, opts.json)
    if exit_now:
        return rc

    print("API server status:")
    print("    Database version:   " + result["db_version"])
    print("    Database supported: %s" % result["db_supported"])
    print("    Schema version:     " + result["schema_version"])
    print("    API version:        " + result["api"])
    print("    Backend:            " + result["backend"])
    print("    Build:              " + result["build"])

    if result["msgs"]:
        print("Error messages:")
        print("\n".join(["    " + r for r in result["msgs"]]))

    return rc
Exemplo n.º 13
0
def blueprints_depsolve(socket_path, api_version, args, show_json=False):
    """Display the packages needed to install the blueprint

    :param socket_path: Path to the Unix socket to use for API communication
    :type socket_path: str
    :param api_version: Version of the API to talk to. eg. "0"
    :type api_version: str
    :param args: List of remaining arguments from the cmdline
    :type args: list of str
    :param show_json: Set to True to show the JSON output instead of the human readable output
    :type show_json: bool

    blueprints depsolve <blueprint,...>    Display the packages needed to install the blueprint.
    """
    api_route = client.api_url(
        api_version, "/blueprints/depsolve/%s" % (",".join(argify(args))))
    result = client.get_url_json(socket_path, api_route)

    if show_json:
        print(json.dumps(result, indent=4))
        return 0

    for blueprint in result["blueprints"]:
        if blueprint["blueprint"].get("version", ""):
            print("blueprint: %s v%s" % (blueprint["blueprint"]["name"],
                                         blueprint["blueprint"]["version"]))
        else:
            print("blueprint: %s" % (blueprint["blueprint"]["name"]))
        for dep in blueprint["dependencies"]:
            print("    " + packageNEVRA(dep))

    return 0
Exemplo n.º 14
0
 def test_status(self):
     """Make sure the mock status response is working"""
     global LAST_REQUEST
     LAST_REQUEST = {}
     result = client.get_url_json(self.socket, "/api/status")
     self.assertTrue("path" in LAST_REQUEST)
     self.assertEqual(LAST_REQUEST["path"], "/api/status")
     self.assertEqual(result, OsBuildAPIv1HTTPHandler.STATUS)
Exemplo n.º 15
0
def compose_info(socket_path, api_version, args, show_json=False, testmode=0):
    """Return detailed information about the compose

    :param socket_path: Path to the Unix socket to use for API communication
    :type socket_path: str
    :param api_version: Version of the API to talk to. eg. "0"
    :type api_version: str
    :param args: List of remaining arguments from the cmdline
    :type args: list of str
    :param show_json: Set to True to show the JSON output instead of the human readable output
    :type show_json: bool
    :param testmode: unused in this function
    :type testmode: int

    compose info <uuid>

    This returns information about the compose, including the blueprint and the dependencies.
    """
    if len(args) == 0:
        log.error("info is missing the compose build id")
        return 1

    api_route = client.api_url(api_version, "/compose/info/%s" % args[0])
    result = client.get_url_json(socket_path, api_route)
    if show_json:
        print(json.dumps(result, indent=4))
        return 0

    for err in result.get("errors", []):
        log.error(err)

    if result.get("errors", []):
        return 1

    if result["image_size"] > 0:
        image_size = str(result["image_size"])
    else:
        image_size = ""


    print("%s %-8s %-15s %s %-16s %s" % (result["id"],
                                         result["queue_status"],
                                         result["blueprint"]["name"],
                                         result["blueprint"]["version"],
                                         result["compose_type"],
                                         image_size))
    print("Packages:")
    for p in result["blueprint"]["packages"]:
        print("    %s-%s" % (p["name"], p["version"]))

    print("Modules:")
    for m in result["blueprint"]["modules"]:
        print("    %s-%s" % (m["name"], m["version"]))

    print("Dependencies:")
    for d in result["deps"]["packages"]:
        print("    " + packageNEVRA(d))
Exemplo n.º 16
0
def blueprints_freeze(socket_path, api_version, args, show_json=False):
    """Handle the blueprints freeze commands

    :param socket_path: Path to the Unix socket to use for API communication
    :type socket_path: str
    :param api_version: Version of the API to talk to. eg. "0"
    :type api_version: str
    :param args: List of remaining arguments from the cmdline
    :type args: list of str
    :param show_json: Set to True to show the JSON output instead of the human readable output
    :type show_json: bool

    blueprints freeze <blueprint,...>      Display the frozen blueprint's modules and packages.
    blueprints freeze show <blueprint,...> Display the frozen blueprint in TOML format.
    blueprints freeze save <blueprint,...> Save the frozen blueprint to a file, <blueprint-name>.frozen.toml.
    """
    if args[0] == "show":
        return blueprints_freeze_show(socket_path, api_version, args[1:],
                                      show_json)
    elif args[0] == "save":
        return blueprints_freeze_save(socket_path, api_version, args[1:],
                                      show_json)

    if len(args) == 0:
        log.error("freeze is missing the blueprint name")
        return 1

    api_route = client.api_url(
        api_version, "/blueprints/freeze/%s" % (",".join(argify(args))))
    result = client.get_url_json(socket_path, api_route)

    if show_json:
        print(json.dumps(result, indent=4))
    else:
        for entry in result["blueprints"]:
            blueprint = entry["blueprint"]
            if blueprint.get("version", ""):
                print("blueprint: %s v%s" %
                      (blueprint["name"], blueprint["version"]))
            else:
                print("blueprint: %s" % (blueprint["name"]))

            for m in blueprint["modules"]:
                print("    %s-%s" % (m["name"], m["version"]))

            for p in blueprint["packages"]:
                print("    %s-%s" % (p["name"], p["version"]))

        # Print any errors
        for err in result.get("errors", []):
            log.error(err)

    # Return a 1 if there are any errors
    if result.get("errors", []):
        return 1
    else:
        return 0
Exemplo n.º 17
0
def providers_save(socket_path,
                   api_version,
                   args,
                   show_json=False,
                   testmode=0):
    """Save a provider's profile to a TOML file

    :param socket_path: Path to the Unix socket to use for API communication
    :type socket_path: str
    :param api_version: Version of the API to talk to. eg. "0"
    :type api_version: str
    :param args: List of remaining arguments from the cmdline
    :type args: list of str
    :param show_json: Set to True to show the JSON output instead of the human readable output
    :type show_json: bool
    :param testmode: unused in this function
    :type testmode: int

    providers save <provider> <profile>

    """
    if len(args) == 0:
        log.error("save is missing the provider name")
        return 1
    if len(args) == 1:
        log.error("save is missing the profile name")
        return 1

    api_route = client.api_url(api_version, "/upload/providers")
    r = client.get_url_json(socket_path, api_route)
    results = r["providers"]
    if not results:
        return 0

    if show_json:
        print(json.dumps(results, indent=4))
    else:
        if args[0] not in results:
            log.error("%s is not a valid provider", args[0])
            return 1
        if args[1] not in results[args[0]]["profiles"]:
            log.error("%s is not a valid %s profile", args[1], args[0])
            return 1

        profile = {
            "provider": args[0],
            "profile": args[1],
            "settings": results[args[0]]["profiles"][args[1]]
        }
        with open(toml_filename(args[1]), "w") as f:
            f.write(toml.dumps(profile))

    return 0
Exemplo n.º 18
0
def compose_cmd(opts):
    """Process compose commands

    :param opts: Cmdline arguments
    :type opts: argparse.Namespace
    :returns: Value to return from sys.exit()
    :rtype: int

    This dispatches the compose commands to a function

    compose_cmd expects api to be passed. eg.

        {"version": 1, "backend": "lorax-composer"}

    """
    result = client.get_url_json(opts.socket, "/api/status")
    # Get the api version and fall back to 0 if it fails.
    api_version = result.get("api", "0")
    backend = result.get("backend", "unknown")
    api = {"version": api_version, "backend": backend}

    cmd_map = {
        "list": compose_list,
        "status": compose_status,
        "types": compose_types,
        "start": compose_start,
        "log": compose_log,
        "cancel": compose_cancel,
        "delete": compose_delete,
        "info": compose_info,
        "metadata": compose_metadata,
        "results": compose_results,
        "logs": compose_logs,
        "image": compose_image,
        "start-ostree": compose_ostree,
    }
    if opts.args[1] == "help" or opts.args[1] == "--help":
        print(compose_help)
        return 0
    elif opts.args[1] not in cmd_map:
        log.error("Unknown compose command: %s", opts.args[1])
        return 1

    return cmd_map[opts.args[1]](opts.socket,
                                 opts.api_version,
                                 opts.args[2:],
                                 opts.json,
                                 opts.testmode,
                                 api=api)
Exemplo n.º 19
0
def providers_show(socket_path,
                   api_version,
                   args,
                   show_json=False,
                   testmode=0):
    """Return details about a provider

    :param socket_path: Path to the Unix socket to use for API communication
    :type socket_path: str
    :param api_version: Version of the API to talk to. eg. "0"
    :type api_version: str
    :param args: List of remaining arguments from the cmdline
    :type args: list of str
    :param show_json: Set to True to show the JSON output instead of the human readable output
    :type show_json: bool
    :param testmode: unused in this function
    :type testmode: int

    providers show <provider> <profile>
    """
    if len(args) == 0:
        log.error("show is missing the provider name")
        return 1
    if len(args) == 1:
        log.error("show is missing the profile name")
        return 1

    api_route = client.api_url(api_version, "/upload/providers")
    r = client.get_url_json(socket_path, api_route)
    results = r["providers"]
    if not results:
        return 0

    if show_json:
        print(json.dumps(results, indent=4))
    else:
        if args[0] not in results:
            log.error("%s is not a valid provider", args[0])
            return 1
        if args[1] not in results[args[0]]["profiles"]:
            log.error("%s is not a valid %s profile", args[1], args[0])
            return 1

        # Print the details for this profile
        # fields are different for each provider, so we just print out the key:values
        for k in results[args[0]]["profiles"][args[1]]:
            print("%s: %s" % (k, results[args[0]]["profiles"][args[1]][k]))
    return 0
Exemplo n.º 20
0
def blueprints_diff(socket_path, api_version, args, show_json=False):
    """Display the differences between 2 versions of a blueprint

    :param socket_path: Path to the Unix socket to use for API communication
    :type socket_path: str
    :param api_version: Version of the API to talk to. eg. "0"
    :type api_version: str
    :param args: List of remaining arguments from the cmdline
    :type args: list of str
    :param show_json: Set to True to show the JSON output instead of the human readable output
    :type show_json: bool

    blueprints diff <blueprint-name>       Display the differences between 2 versions of a blueprint.
                 <from-commit>       Commit hash or NEWEST
                 <to-commit>         Commit hash, NEWEST, or WORKSPACE
    """
    if len(args) == 0:
        log.error(
            "blueprints diff is missing the blueprint name, from commit, and to commit"
        )
        return 1
    elif len(args) == 1:
        log.error(
            "blueprints diff is missing the from commit, and the to commit")
        return 1
    elif len(args) == 2:
        log.error("blueprints diff is missing the to commit")
        return 1

    api_route = client.api_url(
        api_version, "/blueprints/diff/%s/%s/%s" % (args[0], args[1], args[2]))
    result = client.get_url_json(socket_path, api_route)

    if show_json:
        print(json.dumps(result, indent=4))
        return 0

    for err in result.get("errors", []):
        log.error(err)

    if result.get("errors", False):
        return 1

    for diff in result["diff"]:
        print(prettyDiffEntry(diff))

    return 0
Exemplo n.º 21
0
def providers_template(socket_path,
                       api_version,
                       args,
                       show_json=False,
                       testmode=0):
    """Return a TOML template for setting the provider's fields

    :param socket_path: Path to the Unix socket to use for API communication
    :type socket_path: str
    :param api_version: Version of the API to talk to. eg. "0"
    :type api_version: str
    :param args: List of remaining arguments from the cmdline
    :type args: list of str
    :param show_json: Set to True to show the JSON output instead of the human readable output
    :type show_json: bool
    :param testmode: unused in this function
    :type testmode: int

    providers template <provider>
    """
    if len(args) == 0:
        log.error("template is missing the provider name")
        return 1

    api_route = client.api_url(api_version, "/upload/providers")
    r = client.get_url_json(socket_path, api_route)
    results = r["providers"]
    if not results:
        return 0

    if show_json:
        print(json.dumps(results, indent=4))
        return 0

    if args[0] not in results:
        log.error("%s is not a valid provider", args[0])
        return 1

    template = {"provider": args[0]}
    settings = results[args[0]]["settings-info"]
    template["settings"] = dict([(k, settings[k]["display"])
                                 for k in settings])
    print(toml.dumps(template))

    return 0
Exemplo n.º 22
0
def providers_info(socket_path,
                   api_version,
                   args,
                   show_json=False,
                   testmode=0):
    """Show information about each provider

    :param socket_path: Path to the Unix socket to use for API communication
    :type socket_path: str
    :param api_version: Version of the API to talk to. eg. "0"
    :type api_version: str
    :param args: List of remaining arguments from the cmdline
    :type args: list of str
    :param show_json: Set to True to show the JSON output instead of the human readable output
    :type show_json: bool
    :param testmode: unused in this function
    :type testmode: int

    providers info <PROVIDER>
    """
    if len(args) == 0:
        log.error("info is missing the provider name")
        return 1

    api_route = client.api_url(api_version, "/upload/providers")
    r = client.get_url_json(socket_path, api_route)
    results = r["providers"]
    if not results:
        return 0

    if show_json:
        print(json.dumps(results, indent=4))
    else:
        if args[0] not in results:
            log.error("%s is not a valid provider", args[0])
            return 1
        p = results[args[0]]
        print("%s supports these image types: %s" %
              (p["display"], ", ".join(p["supported_types"])))
        print("Settings:")
        for k in p["settings-info"]:
            f = p["settings-info"][k]
            print("    %-20s: %s is a %s" % (k, f["display"], f["type"]))

    return 0
Exemplo n.º 23
0
def projects_info(socket_path, api_version, args, show_json=False):
    """Output info on a list of projects

    :param socket_path: Path to the Unix socket to use for API communication
    :type socket_path: str
    :param api_version: Version of the API to talk to. eg. "0"
    :type api_version: str
    :param args: List of remaining arguments from the cmdline
    :type args: list of str
    :param show_json: Set to True to show the JSON output instead of the human readable output
    :type show_json: bool

    projects info <project,...>
    """
    if len(args) == 0:
        log.error("projects info is missing the packages")
        return 1

    api_route = client.api_url(api_version,
                               "/projects/info/%s" % ",".join(args))
    result = client.get_url_json(socket_path, api_route)
    (rc, exit_now) = handle_api_result(result, show_json)
    if exit_now:
        return rc

    for proj in result["projects"]:
        for k in [
                field
                for field in ("name", "summary", "homepage", "description")
                if proj[field]
        ]:
            print("%s: %s" %
                  (k.title(),
                   textwrap.fill(proj[k], subsequent_indent=" " *
                                 (len(k) + 2))))
        print("Builds: ")
        for build in proj["builds"]:
            print("    %s%s-%s.%s at %s for %s" %
                  ("" if not build["epoch"] else str(build["epoch"]) + ":",
                   build["source"]["version"], build["release"], build["arch"],
                   build["build_time"], build["changelog"]))
        print("")
    return rc
Exemplo n.º 24
0
def sources_list(socket_path, api_version, args, show_json=False):
    """Output the list of available sources

    :param socket_path: Path to the Unix socket to use for API communication
    :type socket_path: str
    :param api_version: Version of the API to talk to. eg. "0"
    :type api_version: str
    :param args: List of remaining arguments from the cmdline
    :type args: list of str
    :param show_json: Set to True to show the JSON output instead of the human readable output
    :type show_json: bool

    sources list
    """
    api_route = client.api_url(api_version, "/projects/source/list")
    result = client.get_url_json(socket_path, api_route)
    if show_json:
        print(json.dumps(result, indent=4))
        return 0

    print("Sources: %s" % ", ".join(result["sources"]))
    return 0
Exemplo n.º 25
0
def modules_cmd(opts):
    """Process modules commands

    :param opts: Cmdline arguments
    :type opts: argparse.Namespace
    :returns: Value to return from sys.exit()
    :rtype: int
    """
    if opts.args[1] != "list":
        log.error("Unknown modules command: %s", opts.args[1])
        return 1

    api_route = client.api_url(opts.api_version, "/modules/list")
    result = client.get_url_json(opts.socket, api_route)
    if opts.json:
        print(json.dumps(result, indent=4))
        return 0

    print("Modules:\n" +
          "\n".join(["    " + r["name"] for r in result["modules"]]))

    return 0
Exemplo n.º 26
0
def sources_list(socket_path, api_version, args, show_json=False):
    """Output the list of available sources

    :param socket_path: Path to the Unix socket to use for API communication
    :type socket_path: str
    :param api_version: Version of the API to talk to. eg. "0"
    :type api_version: str
    :param args: List of remaining arguments from the cmdline
    :type args: list of str
    :param show_json: Set to True to show the JSON output instead of the human readable output
    :type show_json: bool

    sources list
    """
    api_route = client.api_url(api_version, "/projects/source/list")
    result = client.get_url_json(socket_path, api_route)
    (rc, exit_now) = handle_api_result(result, show_json)
    if exit_now:
        return rc

    # "list" should output a plain list of identifiers, one per line.
    print("\n".join(result["sources"]))
    return rc
Exemplo n.º 27
0
Arquivo: upload.py Projeto: whot/lorax
def upload_info(socket_path, api_version, args, show_json=False, testmode=0):
    """Return detailed information about the upload

    :param socket_path: Path to the Unix socket to use for API communication
    :type socket_path: str
    :param api_version: Version of the API to talk to. eg. "0"
    :type api_version: str
    :param args: List of remaining arguments from the cmdline
    :type args: list of str
    :param show_json: Set to True to show the JSON output instead of the human readable output
    :type show_json: bool
    :param testmode: unused in this function
    :type testmode: int

    upload info <uuid>

    This returns information about the upload, including uuid, name, status, service, and image.
    """
    if len(args) == 0:
        log.error("info is missing the upload uuid")
        return 1

    api_route = client.api_url(api_version, "/upload/info/%s" % args[0])
    result = client.get_url_json(socket_path, api_route)
    (rc, exit_now) = handle_api_result(result, show_json)
    if exit_now:
        return rc

    image_path = result["upload"]["image_path"]
    print("%s %-8s %-15s %-8s %s" % (result["upload"]["uuid"],
                                     result["upload"]["status"],
                                     result["upload"]["image_name"],
                                     result["upload"]["provider_name"],
                                     os.path.basename(image_path) if image_path else "UNFINISHED"))

    return rc
Exemplo n.º 28
0
def compose_status(socket_path, api_version, args, show_json=False, testmode=0):
    """Return the status of all known composes

    :param socket_path: Path to the Unix socket to use for API communication
    :type socket_path: str
    :param api_version: Version of the API to talk to. eg. "0"
    :type api_version: str
    :param args: List of remaining arguments from the cmdline
    :type args: list of str
    :param show_json: Set to True to show the JSON output instead of the human readable output
    :type show_json: bool
    :param testmode: unused in this function
    :type testmode: int

    This doesn't map directly to an API command, it combines the results from queue, finished,
    and failed so raw JSON output is not available.
    """
    def get_status(compose):
        return {"id": compose["id"],
                "blueprint": compose["blueprint"],
                "version": compose["version"],
                "compose_type": compose["compose_type"],
                "image_size": compose["image_size"],
                "status": compose["queue_status"]}

    # Sort the status in a specific order
    def sort_status(a):
        order = ["RUNNING", "WAITING", "FINISHED", "FAILED"]
        return (order.index(a["status"]), a["blueprint"], a["version"], a["compose_type"])

    status = []

    # Get the composes currently in the queue
    api_route = client.api_url(api_version, "/compose/queue")
    result = client.get_url_json(socket_path, api_route)
    status.extend(list(map(get_status, result["run"] + result["new"])))

    # Get the list of finished composes
    api_route = client.api_url(api_version, "/compose/finished")
    result = client.get_url_json(socket_path, api_route)
    status.extend(list(map(get_status, result["finished"])))

    # Get the list of failed composes
    api_route = client.api_url(api_version, "/compose/failed")
    result = client.get_url_json(socket_path, api_route)
    status.extend(list(map(get_status, result["failed"])))

    # Sort them by status (running, waiting, finished, failed) and then by name and version.
    status.sort(key=sort_status)

    if show_json:
        print(json.dumps(status, indent=4))
        return 0

    # Print them as UUID blueprint STATUS
    for c in status:
        if c["image_size"] > 0:
            image_size = str(c["image_size"])
        else:
            image_size = ""

        print("%s %-8s %-15s %s %-16s %s" % (c["id"], c["status"], c["blueprint"], c["version"], c["compose_type"],
                                             image_size))