def server_token(context: Context, client_types: "string[]" = ["agent"]) -> "string": token = Config.get("compiler_rest_transport", "token", "") if token == "": return "" # Request a new token for this agent token = "" try: client = context.get_client() env = Config.get("config", "environment", None) if env is None: raise Exception( "The environment of this model should be configured in config>environment" ) def call(): return client.create_token(tid=env, client_types=list(client_types), idempotent=True) result = context.run_sync(call) if result.code == 200: token = result.result["token"] else: logging.getLogger(__name__).warning("Unable to get a new token") raise Exception("Unable to get a valid token") except ConnectionRefusedError: logging.getLogger(__name__).exception("Unable to get a new token") raise Exception("Unable to get a valid token") return token
def getfact(context: Context, resource: "any", fact_name: "string", default_value: "any"=None) -> "any": """ Retrieve a fact of the given resource """ resource_id = resources.to_id(resource) if resource_id is None: raise Exception("Facts can only be retreived from resources.") # Special case for unit testing and mocking if hasattr(context.compiler, "refs") and "facts" in context.compiler.refs: if resource_id in context.compiler.refs["facts"] and fact_name in context.compiler.refs["facts"][resource_id]: return context.compiler.refs["facts"][resource_id][fact_name] fact_value = Unknown(source=resource) unknown_parameters.append({"resource": resource_id, "parameter": fact_name, "source": "fact"}) if default_value is not None: return default_value return fact_value # End special case fact_value = None try: client = context.get_client() env = Config.get("config", "environment", None) if env is None: raise Exception("The environment of this model should be configured in config>environment") def call(): return client.get_param(tid=env, id=fact_name, resource_id=resource_id) result = context.run_sync(call) if result.code == 200: fact_value = result.result["parameter"]["value"] else: logging.getLogger(__name__).info("Param %s of resource %s is unknown", fact_name, resource_id) fact_value = Unknown(source=resource) unknown_parameters.append({"resource": resource_id, "parameter": fact_name, "source": "fact"}) except ConnectionRefusedError: logging.getLogger(__name__).warning("Param %s of resource %s is unknown because connection to server was refused", fact_name, resource_id) fact_value = Unknown(source=resource) unknown_parameters.append({"resource": resource_id, "parameter": fact_name, "source": "fact"}) if isinstance(fact_value, Unknown) and default_value is not None: return default_value return fact_value
def is_instance(ctx: Context, obj: "any", cls: "string") -> "bool": t = ctx.get_type(cls) try: t.validate(obj._get_instance()) except RuntimeException: return False return True
def generate_password(context: Context, pw_id: "string", length: "number" = 20) -> "string": """ Generate a new random password and store it in the data directory of the project. On next invocations the stored password will be used. :param pw_id: The id of the password to identify it. :param length: The length of the password, default length is 20 """ data_dir = context.get_data_dir() pw_file = os.path.join(data_dir, "passwordfile.txt") if "=" in pw_id: raise Exception("The password id cannot contain =") records = get_passwords(pw_file) if pw_id in records: return records[pw_id] rnd = random.SystemRandom() pw = "" while len(pw) < length: x = chr(rnd.randint(33, 126)) if re.match("[A-Za-z0-9]", x) is not None: pw += x # store the new value records[pw_id] = pw save_passwords(pw_file, records) return pw
def get_private_key(context: Context, name: "string") -> "string": """ Create or return if it already exists a key with the given name. The private key is returned. """ priv, pub = get_or_create_key(context.get_data_dir(), name) return priv
def environment_server(ctx: Context) -> "string": """ Return the address of the management server """ client = ctx.get_client() server_url = client._transport_instance._get_client_config() match = re.search("^http[s]?://([^:]+):", server_url) if match is not None: return match.group(1) return Unknown(source=server_url)
def get_putty_key(context: Context, name: "string") -> "string": priv_key = os.path.join(context.get_data_dir(), name) if not os.path.exists(priv_key): get_private_key(context, name) ppk_key = priv_key + ".ppk" subprocess.check_output(["puttygen", priv_key, "-o", ppk_key]) with open(ppk_key, "r") as fd: return fd.read()
def environment_name(ctx: Context) -> "string": """ Return the name of the environment (as defined on the server) """ env = environment() def call(): return ctx.get_client().get_environment(id=env) result = ctx.run_sync(call) if result.code != 200: return Unknown(source=env) return result.result["environment"]["name"]
def get_param(ctx: Context, name: "string") -> "string": """ Get a parameter from the SO """ env = config.Config.get("config", "environment", None) def get(): return ctx.get_client().get_param(tid=env, id=name) result = ctx.run_sync(get) if result.code == 200: return result.result["parameter"]["value"] return None
def get_vnf_instances(ctx: Context, vnf_name): env = config.Config.get("config", "environment", None) def get_instances(): return ctx.get_client().list_params(env, {"module": "state"}) result = ctx.run_sync(get_instances) vnfs = [] params = {} if result.code != 200: return None else: for p in result.result["parameters"]: if p["name"].startswith("fsm_" + vnf_name): vnfs.append(int(p["name"].split("_")[-1])) params[p["name"]] = p return vnfs, params
def password(context: Context, pw_id: "string") -> "string": """ Retrieve the given password from a password file. It raises an exception when a password is not found :param pw_id: The id of the password to identify it. """ data_dir = context.get_data_dir() pw_file = os.path.join(data_dir, "passwordfile.txt") if "=" in pw_id: raise Exception("The password id cannot contain =") records = get_passwords(pw_file) if pw_id in records: return records[pw_id] else: raise Exception("Password %s does not exist in file %s" % (pw_id, pw_file))
def template(ctx: Context, path: "string"): """ Execute the template in path in the current context. This function will generate a new statement that has dependencies on the used variables. """ jinja_env = _get_template_engine(ctx) template_path = _extend_path(ctx, path) if template_path in tcache: template = tcache[template_path] else: template = jinja_env.get_template(template_path) tcache[template_path] = template resolver = ctx.get_resolver() try: out = template.render({"{{resolver": resolver}) return out except UndefinedError as e: raise NotFoundException(ctx.owner, None, e.message)
def set_param(ctx: Context, name: "string", value: "string", recompile: "bool" = False) -> "string": """ Set a parameter on the SO """ env = config.Config.get("config", "environment", None) def setp(): return ctx.get_client().set_param(tid=env, id=name, value=value, source="plugin", metadata={"module": "clearwater"}, recompile=recompile) result = ctx.run_sync(setp) if result.code != 200: raise Exception(result.result)
def get_public_key(context: Context, name: "string") -> "string": """ See get_private_key """ priv, pub = get_or_create_key(context.get_data_dir(), name) return pub