예제 #1
0
    def setup_method(self):
        """Method to create project"""

        # Resetting context
        ContextObj = get_context()
        ContextObj.reset_configuration()

        # Resetting metadata object
        reset_metadata_obj()

        runner = CliRunner()
        self.dsl_project_name = "Test_DSL_Project_{}".format(str(uuid.uuid4()))
        result = runner.invoke(
            cli,
            [
                "create",
                "project",
                "--file={}".format(DSL_PROJECT_PATH),
                "--name={}".format(self.dsl_project_name),
                "--description='Test DSL Project to delete'",
            ],
        )
        if result.exit_code:
            cli_res_dict = {
                "Output": result.output,
                "Exception": str(result.exception)
            }
            LOG.debug("Cli Response: {}".format(
                json.dumps(cli_res_dict, indent=4, separators=(",", ": "))))
            LOG.debug("Traceback: \n{}".format("".join(
                traceback.format_tb(result.exc_info[2]))))
            pytest.fail("Project creation from python file failed")
예제 #2
0
    def get_cache_tables(cls, sync_version=False):
        """returns tables used for cache purpose"""

        db = get_db_handle()
        db_tables = db.registered_tables

        # Get calm version from api only if necessary
        calm_version = CALM_VERSION
        if sync_version or (not calm_version):
            context = get_context()
            server_config = context.get_server_config()
            client = get_client_handle_obj(
                server_config["pc_ip"],
                server_config["pc_port"],
                auth=(server_config["pc_username"], server_config["pc_password"]),
            )
            res, err = client.version.get_calm_version()
            if err:
                LOG.error("Failed to get version")
                sys.exit(err["error"])
            calm_version = res.content.decode("utf-8")

        cache_tables = {}
        for table in db_tables:
            if hasattr(table, "__cache_type__") and (
                LV(calm_version) >= LV(table.feature_min_version)
            ):
                cache_tables[table.__cache_type__] = table
        return cache_tables
예제 #3
0
def test_json():

    ContextObj = get_context()

    ContextObj.update_project_context(project_name=PROJECT_NAME)
    print(MyAhvVm.json_dumps(pprint=True))
    ContextObj.reset_configuration()
예제 #4
0
def compile_runbook_command(runbook_file, out):

    rb_payload = compile_runbook(runbook_file)
    if rb_payload is None:
        LOG.error("User runbook not found in {}".format(runbook_file))
        return

    ContextObj = get_context()
    project_config = ContextObj.get_project_config()
    project_name = project_config["name"]
    project_cache_data = Cache.get_entity_data(entity_type="project", name=project_name)

    if not project_cache_data:
        LOG.error(
            "Project {} not found. Please run: calm update cache".format(project_name)
        )

    project_uuid = project_cache_data.get("uuid", "")
    rb_payload["metadata"]["project_reference"] = {
        "type": "project",
        "uuid": project_uuid,
        "name": project_name,
    }

    if out == "json":
        click.echo(json.dumps(rb_payload, indent=4, separators=(",", ": ")))
    elif out == "yaml":
        click.echo(yaml.dump(rb_payload, default_flow_style=False))
    else:
        LOG.error("Unknown output format {} given".format(out))
예제 #5
0
def test_multivm_with_diff_bootconfig():
    """
    Tests in case of multi-vm blueprint, correct disk is set to bootable
    """

    # Ahv Helpers uses Metadata Context, It should the context(if any) defined in this file only
    get_metadata_payload(__file__)
    ContextObj = get_context()
    ContextObj.reset_configuration()

    spec = AhvBlueprint.get_dict()
    substrate_list = spec["substrate_definition_list"]

    # From AhvBlueprint class
    # substrate_list[0] = AhvVmSubstrate and substrate_list[1] = AhvVmSubstrate2

    # In AhvVmSubstrate -> MyAhvVm (vm_cls)
    # Check SCSI disk with device_index = 2 is bootable
    ahv_vm_substrate_spec = substrate_list[0]
    assert ahv_vm_substrate_spec["create_spec"]["resources"]["boot_config"] == {
        "boot_device": {"disk_address": {"device_index": 2, "adapter_type": "SCSI"}}
    }

    # In AhvVmSubstrate2 -> MyAhvVm2 (vm_cls)
    # Check PCI disk with device_index = 0 is bootable
    ahv_vm_substrate2_spec = substrate_list[1]
    assert ahv_vm_substrate2_spec["create_spec"]["resources"]["boot_config"] == {
        "boot_device": {"disk_address": {"device_index": 0, "adapter_type": "PCI"}}
    }
예제 #6
0
def abort_runbook_execution(runlog_uuid):

    client = get_api_client()
    res, err = client.runbook.poll_action_run(runlog_uuid)
    if err:
        raise Exception("[{}] - {}".format(err["code"], err["error"]))
    response = res.json()
    state = response["status"]["state"]
    if state in RUNLOG.TERMINAL_STATES:
        LOG.warning("Runbook Execution is in terminal state: {}".format(state))
        sys.exit(0)
    res, err = client.runbook.abort(runlog_uuid)
    if err:
        raise Exception("[{}] - {}".format(err["code"], err["error"]))
    response = res.json()
    state = response["status"]["state"]
    LOG.info("Abort triggered for the given runbook execution.")

    ContextObj = get_context()
    server_config = ContextObj.get_server_config()
    pc_ip = server_config["pc_ip"]
    pc_port = server_config["pc_port"]
    link = "https://{}:{}/console/#page/explore/calm/runbooks/runlogs/{}".format(
        pc_ip, pc_port, runlog_uuid
    )
    stdout_dict = {"link": link, "state": state}
    click.echo(json.dumps(stdout_dict, indent=4, separators=(",", ": ")))
예제 #7
0
def poll_launch_status(client, blueprint_uuid, launch_req_id):
    # Poll every 10 seconds on the app status, for 5 mins
    maxWait = 5 * 60
    count = 0
    while count < maxWait:
        # call status api
        LOG.info("Polling status of Launch")
        res, err = client.blueprint.poll_launch(blueprint_uuid, launch_req_id)
        response = res.json()
        app_state = response["status"]["state"]
        pprint(response)
        if app_state == "success":
            app_uuid = response["status"]["application_uuid"]

            context = get_context()
            server_config = context.get_server_config()
            pc_ip = server_config["pc_ip"]
            pc_port = server_config["pc_port"]

            click.echo(
                "Successfully launched. App uuid is: {}".format(app_uuid))

            LOG.info(
                "App url: https://{}:{}/console/#page/explore/calm/applications/{}"
                .format(pc_ip, pc_port, app_uuid))
            break
        elif app_state == "failure":
            LOG.debug("API response: {}".format(response))
            LOG.error("Failed to launch blueprint. Check API response above.")
            break
        elif err:
            raise Exception("[{}] - {}".format(err["code"], err["error"]))
        LOG.info(app_state)
        count += 10
        time.sleep(10)
예제 #8
0
def test_json():
    """Test the generated json for a single VM
    against known output"""
    import json
    import os
    import sys

    # Setting the recursion limit to max for comparison
    sys.setrecursionlimit(100000)

    # Resetting context
    ContextObj = get_context()
    ContextObj.reset_configuration()

    dir_path = os.path.dirname(os.path.realpath(__file__))
    file_path = os.path.join(dir_path, "test_inheritance_bp_output.json")

    # Change dynamic values in known json and remove account_uuid from generated_json
    generated_json = json.loads(TestInheritance.json_dumps(pprint=True))
    known_json = json.loads(open(file_path).read())

    generated_json["app_profile_list"][0].pop("snapshot_config_list", None)
    generated_json["app_profile_list"][0].pop("restore_config_list", None)
    generated_json["app_profile_list"][0].pop("patch_list", None)
    for _sd in generated_json["substrate_definition_list"]:
        _sd["create_spec"]["resources"].pop("account_uuid", None)

    assert sorted(known_json.items()) == sorted(generated_json.items())
예제 #9
0
def compile_environment_command(env_file, project_name, out):
    """
    Compiles a DSL (Python) environment into JSON or YAML
    Args:
        env_file (str): Location for environment python file
        project_name (str): Project name
        out (str): Output format
    Returns:
        stdout (object): environment payload
    """

    # Update project on context
    ContextObj = get_context()
    ContextObj.update_project_context(project_name=project_name)

    user_env_module = get_environment_module_from_file(env_file)
    UserEnvironment = get_env_class_from_module(user_env_module)
    if UserEnvironment is None:
        LOG.error("User environment not found in {}".format(env_file))
        return

    env_payload = compile_environment_dsl_class(UserEnvironment)

    # Reset context
    ContextObj.reset_configuration()

    if out == "json":
        click.echo(json.dumps(env_payload, indent=4, separators=(",", ": ")))
    elif out == "yaml":
        click.echo(yaml.dump(env_payload, default_flow_style=False))
    else:
        LOG.error("Unknown output format {} given".format(out))
예제 #10
0
    def test_endpoint_list_with_project_reference(self):

        client = get_api_client()

        ContextObj = get_context()
        project_config = ContextObj.get_project_config()
        project_name = project_config["name"]
        # Fetch project details
        project_params = {"filter": "name=={}".format(project_name)}
        res, err = client.project.list(params=project_params)
        if err:
            pytest.fail("[{}] - {}".format(err["code"], err["error"]))

        response = res.json()
        entities = response.get("entities", None)
        if not entities:
            raise Exception("No project with name {} exists".format(project_name))

        project_id = entities[0]["metadata"]["uuid"]
        params = {
            "length": 20,
            "offset": 0,
            "filter": "project_reference=={}".format(project_id),
        }
        res, err = client.endpoint.list(params=params)

        if not err:
            print("\n>> Endpoint list call successful>>")
            assert res.ok is True
        else:
            pytest.fail("[{}] - {}".format(err["code"], err["error"]))
예제 #11
0
파일: main.py 프로젝트: bmp-ntnx/calm-dsl
def main(ctx, config_file, sync):
    """Calm CLI

    \b
    Commonly used commands:
      calm get apps   -> Get list of apps
      calm get bps   -> Get list of blueprints
      calm launch bp --app_name Fancy-App-1 MyFancyBlueprint   -> Launch a new app from an existing blueprint
      calm create bp -f sample_bp.py --name Sample-App-3   -> Upload a new blueprint from a python DSL file
      calm describe app Fancy-App-1   -> Describe an existing app
      calm app Fancy-App-1 -w my_action   -> Run an action on an app
      calm get runbooks  -> Get list of runbooks
      calm describe runbook MyFancyRunbook   -> Describe an existing runbook
      calm create runbook -f sample_rb.py --name Sample-RB  -> Upload a new runbook from a python DSL file
      calm run runbook MyFancyRunbook -> Runs the existing runbook MyFancyRunbook
      calm run runbook -f sample_rb.py -> Runs the runbook from a python DSL file
      calm get execution_history  -> Get list of runbook executions
      calm get endpoints -> Get list of endpoints
      calm create endpoint -f sample_ep.py --name Sample-Endpoint -> Upload a new endpoint from a python DSL file"""
    ctx.ensure_object(dict)
    ctx.obj["verbose"] = True
    try:
        validate_version()
    except Exception:
        LOG.debug("Could not validate version")
        pass
    if config_file:
        ContextObj = get_context()
        ContextObj.update_config_file_context(config_file=config_file)
    if sync:
        Cache.sync()
    def teardown_method(self):
        """Method to delete creates bps and apps during tests"""

        # Resetting context
        ContextObj = get_context()
        ContextObj.reset_configuration()

        # Resetting metadata object
        reset_metadata_obj()

        for bp_name in self.created_bp_list:
            LOG.info("Deleting Blueprint {}".format(bp_name))
            runner = CliRunner()
            result = runner.invoke(cli, ["delete", "bp", bp_name])
            assert result.exit_code == 0

        for app_name in self.created_app_list:
            LOG.info("Deleting App {}".format(app_name))
            self._wait_for_non_busy_state(app_name=app_name)
            runner = CliRunner()
            result = runner.invoke(cli, ["delete", "app", app_name])
            assert result.exit_code == 0

        self.created_bp_list = []
        self.created_app_list = []
예제 #13
0
def get_users(name, filter_by, limit, offset, quiet, out):
    """ Get the users, optionally filtered by a string """

    client = get_api_client()

    params = {"length": limit, "offset": offset}
    filter_query = ""
    if name:
        filter_query = get_name_query([name])
    if filter_by:
        filter_query = filter_query + ";(" + filter_by + ")"
    if filter_query.startswith(";"):
        filter_query = filter_query[1:]

    if filter_query:
        params["filter"] = filter_query

    res, err = client.user.list(params=params)

    if err:
        ContextObj = get_context()
        server_config = ContextObj.get_server_config()
        pc_ip = server_config["pc_ip"]

        LOG.warning("Cannot fetch users from {}".format(pc_ip))
        return

    if out == "json":
        click.echo(json.dumps(res.json(), indent=4, separators=(",", ": ")))
        return

    json_rows = res.json()["entities"]
    if not json_rows:
        click.echo(highlight_text("No user found !!!\n"))
        return

    if quiet:
        for _row in json_rows:
            row = _row["status"]
            click.echo(highlight_text(row["name"]))
        return

    table = PrettyTable()
    table.field_names = ["NAME", "DISPLAY NAME", "TYPE", "STATE", "UUID"]

    for _row in json_rows:
        row = _row["status"]
        metadata = _row["metadata"]

        table.add_row(
            [
                highlight_text(row["name"]),
                highlight_text(row["resources"].get("display_name", "")),
                highlight_text(row["resources"]["user_type"]),
                highlight_text(row["state"]),
                highlight_text(metadata["uuid"]),
            ]
        )

    click.echo(table)
예제 #14
0
def test_json():

    # Ahv Helpers uses Metadata Context, It should the context(if any) defined in this file only
    get_metadata_payload(__file__)
    ContextObj = get_context()
    ContextObj.reset_configuration()

    print(MyAhvVm.json_dumps(pprint=True))
예제 #15
0
    def setup_method(self):
        """Method to instantiate to created_bp_list and reset context"""

        # Resetting context
        ContextObj = get_context()
        ContextObj.reset_configuration()

        self.created_bp_list = []
def create_environment_payload(UserEnvironment, metadata=dict()):
    """
    Creates environment payload
    Args:
        UserEnvironment(object): Environment object
        metadata (dict) : Metadata for environment
    Returns:
        response(tuple): tuple consisting of environment payload object and error
    """

    err = {"error": "", "code": -1}

    if UserEnvironment is None:
        err["error"] = "Given environment is empty."
        return None, err

    if not isinstance(UserEnvironment, EnvironmentType):
        err["error"] = "Given environment is not of type Environment"
        return None, err

    spec = {
        "name": UserEnvironment.__name__,
        "description": UserEnvironment.__doc__ or "",
        "resources": UserEnvironment,
    }

    env_project = metadata.get("project_reference", {}).get("name", "")
    if not env_project:
        ContextObj = get_context()
        project_config = ContextObj.get_project_config()
        env_project = project_config["name"]

    project_cache_data = Cache.get_entity_data(
        entity_type=CACHE.ENTITY.PROJECT, name=env_project)
    if not project_cache_data:
        LOG.error("Project {} not found.".format(env_project))
        sys.exit("Project {} not found.".format(env_project))

    metadata_payload = {
        "spec_version": 1,
        "kind": "environment",
        "name": UserEnvironment.__name__,
        "uuid": str(uuid.uuid4()),
    }

    calm_version = Version.get_version("Calm")
    if LV(calm_version) >= LV("3.2.0"):
        metadata_payload["project_reference"] = {
            "kind": "project",
            "name": project_cache_data["name"],
            "uuid": project_cache_data["uuid"],
        }

    UserEnvironmentPayload = _environment_payload()
    UserEnvironmentPayload.metadata = metadata_payload
    UserEnvironmentPayload.spec = spec

    return UserEnvironmentPayload, None
예제 #17
0
    def teardown_method(self):
        """ "Reset the context changes"""

        # Resetting context
        ContextObj = get_context()
        ContextObj.reset_configuration()

        # Resetting metadata object
        reset_metadata_obj()
예제 #18
0
def create_blueprint_command(bp_file, name, description, force):
    """Creates a blueprint"""

    client = get_api_client()

    if bp_file.endswith(".json"):
        res, err = create_blueprint_from_json(client,
                                              bp_file,
                                              name=name,
                                              description=description,
                                              force_create=force)
    elif bp_file.endswith(".py"):
        res, err = create_blueprint_from_dsl(client,
                                             bp_file,
                                             name=name,
                                             description=description,
                                             force_create=force)
    else:
        LOG.error("Unknown file format {}".format(bp_file))
        return

    if err:
        LOG.error(err["error"])
        return

    bp = res.json()
    bp_uuid = bp["metadata"]["uuid"]
    bp_name = bp["metadata"]["name"]
    bp_status = bp.get("status", {})
    bp_state = bp_status.get("state", "DRAFT")
    LOG.debug("Blueprint {} has state: {}".format(bp_name, bp_state))

    if bp_state != "ACTIVE":
        msg_list = bp_status.get("message_list", [])
        if not msg_list:
            LOG.error("Blueprint {} created with errors.".format(bp_name))
            LOG.debug(json.dumps(bp_status))
            sys.exit(-1)

        msgs = []
        for msg_dict in msg_list:
            msgs.append(msg_dict.get("message", ""))

        LOG.error("Blueprint {} created with {} error(s): {}".format(
            bp_name, len(msg_list), msgs))
        sys.exit(-1)

    LOG.info("Blueprint {} created successfully.".format(bp_name))

    context = get_context()
    server_config = context.get_server_config()
    pc_ip = server_config["pc_ip"]
    pc_port = server_config["pc_port"]
    link = "https://{}:{}/console/#page/explore/calm/blueprints/{}".format(
        pc_ip, pc_port, bp_uuid)
    stdout_dict = {"name": bp_name, "link": link, "state": bp_state}
    click.echo(json.dumps(stdout_dict, indent=4, separators=(",", ": ")))
예제 #19
0
    def teardown_method(self):
        """Method to delete project if not deleted during tests"""

        # Reset the context changes
        ContextObj = get_context()
        ContextObj.reset_configuration()

        if self.project_name and (not self.project_deleted):
            self._test_delete_project()
예제 #20
0
    def setup_method(self):
        """Method to instantiate variable for projects to be deleted"""

        self.project_deleted = False
        self.project_name = None

        # Reset the context changes
        ContextObj = get_context()
        ContextObj.reset_configuration()
예제 #21
0
def update_runbook_command(runbook_file, name, description):
    """Updates a runbook"""

    client = get_api_client()

    if runbook_file.endswith(".json"):
        res, err = update_runbook_from_json(
            client, runbook_file, name=name, description=description
        )
    elif runbook_file.endswith(".py"):
        res, err = update_runbook_from_dsl(
            client, runbook_file, name=name, description=description
        )
    else:
        LOG.error("Unknown file format {}".format(runbook_file))
        return

    if err:
        LOG.error(err["error"])
        return

    runbook = res.json()
    runbook_uuid = runbook["metadata"]["uuid"]
    runbook_name = runbook["metadata"]["name"]
    runbook_status = runbook.get("status", {})
    runbook_state = runbook_status.get("state", "DRAFT")
    LOG.debug("Runbook {} has state: {}".format(runbook_name, runbook_state))

    if runbook_state != "ACTIVE":
        msg_list = runbook_status.get("message_list", [])
        if not msg_list:
            LOG.error("Runbook {} updated with errors.".format(runbook_name))
            LOG.debug(json.dumps(runbook_status))
            sys.exit(-1)

        msgs = []
        for msg_dict in msg_list:
            msgs.append(msg_dict.get("message", ""))

        LOG.error(
            "Runbook {} updated with {} error(s): {}".format(
                runbook_name, len(msg_list), msgs
            )
        )
        sys.exit(-1)

    LOG.info("Runbook {} updated successfully.".format(runbook_name))
    ContextObj = get_context()
    server_config = ContextObj.get_server_config()
    pc_ip = server_config["pc_ip"]
    pc_port = server_config["pc_port"]
    link = "https://{}:{}/console/#page/explore/calm/runbooks/{}".format(
        pc_ip, pc_port, runbook_uuid
    )
    stdout_dict = {"name": runbook_name, "link": link, "state": runbook_state}
    click.echo(json.dumps(stdout_dict, indent=4, separators=(",", ": ")))
예제 #22
0
def render_ahv_template(template, bp_name):

    ContextObj = get_context()

    project_config = ContextObj.get_project_config()
    project_name = project_config.get("name") or "default"
    project_cache_data = Cache.get_entity_data(
        entity_type=CACHE.ENTITY.PROJECT, name=project_name)
    if not project_cache_data:
        LOG.error("Project {} not found. Please run: calm update cache".format(
            project_name))
        sys.exit(-1)

    # Fetch Nutanix_PC account registered
    project_accounts = project_cache_data["accounts_data"]
    account_uuid = project_accounts.get("nutanix_pc", "")
    if not account_uuid:
        LOG.error("No nutanix_pc account registered to project {}".format(
            project_name))

    # Fetch whitelisted subnets
    project_subnets = project_cache_data["whitelisted_subnets"]
    if not project_subnets:
        LOG.error("No subnets registered to project {}".format(project_name))
        sys.exit(-1)

    # Fetch data for first subnet
    subnet_cache_data = Cache.get_entity_data_using_uuid(
        entity_type=CACHE.ENTITY.AHV_SUBNET,
        uuid=project_subnets[0],
        account_uuid=account_uuid,
    )
    if not subnet_cache_data:
        # Case when project have a subnet that is not available in subnets from registered account
        context_data = {
            "Project Whitelisted Subnets": project_subnets,
            "Account UUID": account_uuid,
            "Project Name": project_name,
        }
        LOG.debug("Context data: {}".format(
            json.dumps(context_data, indent=4, separators=(",", ": "))))
        LOG.error(
            "Subnet configuration mismatch in registered account's subnets and whitelisted subnets in project"
        )
        sys.exit(-1)

    cluster_name = subnet_cache_data["cluster"]
    default_subnet = subnet_cache_data["name"]

    LOG.info("Rendering ahv template")
    text = template.render(bp_name=bp_name,
                           subnet_name=default_subnet,
                           cluster_name=cluster_name)

    return text.strip() + os.linesep
예제 #23
0
def test_macro_in_nic():
    """Tests macro in vm nics"""

    import json

    ContextObj = get_context()
    ContextObj.update_project_context(project_name=PROJECT_NAME)
    vm_data = json.loads(MyAhvVm.json_dumps())
    assert (vm_data["nic_list"][9]["subnet_reference"]["uuid"] ==
            "@@{substrate_variable}@@")
    ContextObj.reset_configuration()
예제 #24
0
def simple_verbosity_option(logging_mod=None, *names, **kwargs):
    """A decorator that adds a `--verbose, -v` option to the decorated
    command.
    Name can be configured through ``*names``. Keyword arguments are passed to
    the underlying ``click.option`` decorator.
    """

    if not names:
        names = ["--verbose", "-v"]

    if not isinstance(logging_mod, CustomLogging):
        raise TypeError("Logging object should be instance of CustomLogging.")

    log_level = "INFO"
    try:
        ContextObj = get_context()
        log_config = ContextObj.get_log_config()

        if "level" in log_config:
            log_level = log_config.get("level") or log_level

    except (FileNotFoundError, ValueError):
        # At the time of initializing dsl, config file may not be present or incorrect
        pass

    logging_levels = logging_mod.get_logging_levels()
    if log_level not in logging_levels:
        raise ValueError("Invalid log level in config. Select from {}".format(
            logging_levels))

    log_level = logging_levels.index(log_level) + 1
    kwargs.setdefault("default", log_level)
    kwargs.setdefault("expose_value", False)
    kwargs.setdefault("help", "Verboses the output")
    kwargs.setdefault("is_eager", True)
    kwargs.setdefault("count", True)

    def decorator(f):
        def _set_level(ctx, param, value):
            logging_levels = logging_mod.get_logging_levels()
            if value < 1 or value > len(logging_levels):
                raise click.BadParameter(
                    "Should be atleast 1 and atmost {}".format(
                        len(logging_levels)))

            log_level = logging_levels[value - 1]
            x = getattr(logging_mod, log_level, None)
            CustomLogging.set_verbose_level(x)

        return click.option(*names, callback=_set_level, **kwargs)(f)

    return decorator
예제 #25
0
def _set_config(
    host,
    port,
    username,
    password,
    project_name,
    db_location,
    log_level,
    config_file,
    local_dir,
):
    """writes the configuration to config files i.e. config.ini and init.ini"""

    # Fetching context object
    ContextObj = get_context()

    server_config = ContextObj.get_server_config()
    host = host or server_config["pc_ip"]
    username = username or server_config["pc_username"]
    port = port or server_config["pc_port"]
    password = password or server_config["pc_password"]

    project_config = ContextObj.get_project_config()
    project_name = project_name or project_config.get("name") or "default"

    log_config = ContextObj.get_log_config()
    log_level = log_level or log_config.get("level") or "INFO"

    # Take init_configuration from user params or init file
    init_config = ContextObj.get_init_config()
    config_file = (
        config_file or ContextObj._CONFIG_FILE or init_config["CONFIG"]["location"]
    )
    db_location = db_location or init_config["DB"]["location"]
    local_dir = local_dir or init_config["LOCAL_DIR"]["location"]

    # Set the dsl configuration
    set_dsl_config(
        host=host,
        port=port,
        username=username,
        password=password,
        project_name=project_name,
        db_location=db_location,
        log_level=log_level,
        local_dir=local_dir,
        config_file=config_file,
    )
예제 #26
0
def test_json():
    """Test the generated json for a single VM
    against known output"""
    import os

    # Resetting context
    ContextObj = get_context()
    ContextObj.reset_configuration()

    dir_path = os.path.dirname(os.path.realpath(__file__))
    file_path = os.path.join(dir_path, "test_inheritance_bp_output.json")

    generated_json = TestInheritance.json_dumps(pprint=True)
    known_json = open(file_path).read()

    assert generated_json == known_json
예제 #27
0
파일: utils.py 프로젝트: tuxtof/calm-dsl
def read_local_file(filename):
    file_path = os.path.join(".local", filename)

    # Checking if file exists
    abs_file_path = os.path.join(
        os.path.dirname(inspect.getfile(sys._getframe(1))), file_path
    )

    # If not exists read from home directory
    if not file_exists(abs_file_path):
        ContextObj = get_context()
        init_data = ContextObj.get_init_config()
        file_path = os.path.join(init_data["LOCAL_DIR"]["location"], filename)
        return read_file(file_path, 0).rstrip()  # To remove \n, use rstrip

    return read_file(file_path, depth=2)
예제 #28
0
def create_blueprint_payload(UserBlueprint, metadata={}):

    err = {"error": "", "code": -1}

    if UserBlueprint is None:
        err["error"] = "Given blueprint is empty."
        return None, err

    if not isinstance(UserBlueprint, (BlueprintType, SimpleBlueprintType)):
        err["error"] = "Given blueprint is not of type Blueprint"
        return None, err

    spec = {
        "name": UserBlueprint.__name__,
        "description": UserBlueprint.__doc__ or "",
        "resources": UserBlueprint,
    }

    ContextObj = get_context()
    server_config = ContextObj.get_server_config()
    project_config = ContextObj.get_project_config()
    config_categories = ContextObj.get_categories_config()

    # Set the blueprint name and kind correctly
    metadata["name"] = UserBlueprint.__name__
    metadata["kind"] = "blueprint"

    #  Project will be taken from config if not provided
    if not metadata.get("project_reference", {}):
        project_name = project_config["name"]
        metadata["project_reference"] = Ref.Project(project_name)

    #  User will be taken from config if not provided
    if not metadata.get("owner_reference", {}):
        user_name = server_config["pc_username"]
        metadata["owner_reference"] = Ref.User(user_name)

    #  Categories will be taken from config if not provided
    if not metadata.get("categories", {}):
        metadata["categories"] = config_categories

    metadata["kind"] = "blueprint"
    UserBlueprintPayload = _blueprint_payload()
    UserBlueprintPayload.metadata = metadata
    UserBlueprintPayload.spec = spec

    return UserBlueprintPayload, None
예제 #29
0
파일: handle.py 프로젝트: bmp-ntnx/calm-dsl
def get_api_client():
    """returns global api client object (_API_CLIENT_HANDLE) """

    global _API_CLIENT_HANDLE

    if not _API_CLIENT_HANDLE:
        context = get_context()
        server_config = context.get_server_config()

        pc_ip = server_config.get("pc_ip")
        pc_port = server_config.get("pc_port")
        username = server_config.get("pc_username")
        password = server_config.get("pc_password")

        update_api_client(host=pc_ip, port=pc_port, auth=(username, password))

    return _API_CLIENT_HANDLE
예제 #30
0
파일: bps.py 프로젝트: tuxtof/calm-dsl
def create_blueprint_from_json(
    client, path_to_json, name=None, description=None, force_create=False
):
    """
    creates blueprint from the bp json supplied.
    NOTE: Project mentioned in the json file remains unchanged
    """

    with open(path_to_json, "r") as f:
        bp_payload = json.loads(f.read())

    ContextObj = get_context()
    project_config = ContextObj.get_project_config()
    configured_project = project_config["name"]

    # If no project is given in payload, it is created with default project
    bp_project_name = "default"

    if (
        bp_payload.get("metadata")
        and bp_payload["metadata"].get("project_reference")
        and bp_payload["metadata"]["project_reference"].get("uuid")
    ):
        bp_project_uuid = bp_payload["metadata"]["project_reference"]["uuid"]
        if bp_project_uuid:
            bp_project_data = Cache.get_entity_data_using_uuid(
                entity_type=CACHE.ENTITY.PROJECT, uuid=bp_project_uuid
            )
            if bp_project_data:
                bp_project_name = bp_project_data["name"]

    if bp_project_name != configured_project:
        LOG.warning(
            "Project in supplied json is different from configured project('{}')".format(
                configured_project
            )
        )

    return create_blueprint(
        client,
        bp_payload,
        name=name,
        description=description,
        force_create=force_create,
    )