예제 #1
0
파일: clean.py 프로젝트: delphix/cloud-init
def remove_artifacts(remove_logs, remove_seed=False):
    """Helper which removes artifacts dir and optionally log files.

    @param: remove_logs: Boolean. Set True to delete the cloud_dir path. False
        preserves them.
    @param: remove_seed: Boolean. Set True to also delete seed subdir in
        paths.cloud_dir.
    @returns: 0 on success, 1 otherwise.
    """
    init = Init(ds_deps=[])
    init.read_cfg()
    if remove_logs:
        for log_file in get_config_logfiles(init.cfg):
            del_file(log_file)

    if not os.path.isdir(init.paths.cloud_dir):
        return 0  # Artifacts dir already cleaned
    seed_path = os.path.join(init.paths.cloud_dir, "seed")
    for path in glob.glob("%s/*" % init.paths.cloud_dir):
        if path == seed_path and not remove_seed:
            continue
        try:
            if os.path.isdir(path) and not is_link(path):
                del_dir(path)
            else:
                del_file(path)
        except OSError as e:
            error("Could not remove {0}: {1}".format(path, str(e)))
            return 1
    return 0
예제 #2
0
def handle_args(name, args):
    """Handle calls to 'cloud-id' cli.

    Print the canonical cloud-id on which the instance is running.

    @return: 0 on success, 1 otherwise.
    """
    try:
        instance_data = json.load(open(args.instance_data))
    except IOError:
        return error(
            "File not found '%s'. Provide a path to instance data json file"
            " using --instance-data" % args.instance_data)
    except ValueError as e:
        return error("File '%s' is not valid json. %s" %
                     (args.instance_data, e))
    v1 = instance_data.get("v1", {})
    cloud_id = canonical_cloud_id(
        v1.get("cloud_name", METADATA_UNKNOWN),
        v1.get("region", METADATA_UNKNOWN),
        v1.get("platform", METADATA_UNKNOWN),
    )
    if args.json:
        v1["cloud_id"] = cloud_id
        response = json.dumps(  # Pretty, sorted json
            v1,
            indent=1,
            sort_keys=True,
            separators=(",", ": "))
    elif args.long:
        response = "%s\t%s" % (cloud_id, v1.get("region", METADATA_UNKNOWN))
    else:
        response = cloud_id
    sys.stdout.write("%s\n" % response)
    return 0
예제 #3
0
파일: clean.py 프로젝트: delphix/cloud-init
def handle_clean_args(name, args):
    """Handle calls to 'cloud-init clean' as a subcommand."""
    exit_code = remove_artifacts(args.remove_logs, args.remove_seed)
    if exit_code == 0 and args.reboot:
        cmd = ["shutdown", "-r", "now"]
        try:
            subp(cmd, capture=False)
        except ProcessExecutionError as e:
            error('Could not reboot this system using "{0}": {1}'.format(
                cmd, str(e)))
            exit_code = 1
    return exit_code
예제 #4
0
def handle_schema_args(name, args):
    """Handle provided schema args and perform the appropriate actions."""
    exclusive_args = [args.config_file, args.docs, args.system]
    if len([arg for arg in exclusive_args if arg]) != 1:
        error("Expected one of --config-file, --system or --docs arguments")
    if args.annotate and args.docs:
        error("Invalid flag combination. Cannot use --annotate with --docs")
    full_schema = get_schema()
    if args.config_file or args.system:
        try:
            validate_cloudconfig_file(args.config_file, full_schema,
                                      args.annotate)
        except SchemaValidationError as e:
            if not args.annotate:
                error(str(e))
        except RuntimeError as e:
            error(str(e))
        else:
            if args.config_file is None:
                cfg_name = "system userdata"
            else:
                cfg_name = args.config_file
            print("Valid cloud-config:", cfg_name)
    elif args.docs:
        print(load_doc(args.docs))
예제 #5
0
def handle_args(name, args):
    """Handle calls to 'cloud-id' cli.

    Print the canonical cloud-id on which the instance is running.

    @return: 0 on success, 1 on error, 2 on disabled, 3 on cloud-init not run.
    """
    status, _status_details, _time = get_status_details()
    if status == UXAppStatus.DISABLED:
        sys.stdout.write("{0}\n".format(status.value))
        return 2
    elif status == UXAppStatus.NOT_RUN:
        sys.stdout.write("{0}\n".format(status.value))
        return 3

    try:
        instance_data = json.load(open(args.instance_data))
    except IOError:
        return error(
            "File not found '%s'. Provide a path to instance data json file"
            " using --instance-data" % args.instance_data)
    except ValueError as e:
        return error("File '%s' is not valid json. %s" %
                     (args.instance_data, e))
    v1 = instance_data.get("v1", {})
    cloud_id = canonical_cloud_id(
        v1.get("cloud_name", METADATA_UNKNOWN),
        v1.get("region", METADATA_UNKNOWN),
        v1.get("platform", METADATA_UNKNOWN),
    )
    if args.json:
        v1["cloud_id"] = cloud_id
        response = json.dumps(  # Pretty, sorted json
            v1,
            indent=1,
            sort_keys=True,
            separators=(",", ": "))
    elif args.long:
        response = "%s\t%s" % (cloud_id, v1.get("region", METADATA_UNKNOWN))
    else:
        response = cloud_id
    sys.stdout.write("%s\n" % response)
    return 0
예제 #6
0
def load_doc(requested_modules: list) -> str:
    """Load module docstrings

    Docstrings are generated on module load. Reduce, reuse, recycle.
    """
    docs = ""
    all_modules = list(get_modules().values()) + ["all"]
    invalid_docs = set(requested_modules).difference(set(all_modules))
    if invalid_docs:
        error("Invalid --docs value {}. Must be one of: {}".format(
            list(invalid_docs),
            ", ".join(all_modules),
        ))
    for mod_name in all_modules:
        if "all" in requested_modules or mod_name in requested_modules:
            (mod_locs, _) = importer.find_module(mod_name,
                                                 ["cloudinit.config"],
                                                 ["meta"])
            if mod_locs:
                mod = importer.import_module(mod_locs[0])
                docs += mod.__doc__ or ""
    return docs