docs: regenerate pdoc HTML documentation for v6.5.0b1
This commit is contained in:
1 parent
b3925fee07
commit
693531ed57
15 files changed
+5137
-674
No files matched your search
+124
-2
@@ -86,6 +86,78 @@ el.replaceWith(d);
|
||||
</details>
|
||||
<div class="desc"><p>Clear local variables on all frames in an exception's traceback chain.</p></div>
|
||||
</dd>
|
||||
<dt id="connpy.auth_utils.compile_active_context_patterns"><code class="name flex">
|
||||
<span>def <span class="ident">compile_active_context_patterns</span></span>(<span>cfg_dict: Any, *, strict: bool = False) ‑> list[re.Pattern[str]]</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<details class="source">
|
||||
<summary>
|
||||
<span>Expand source code</span>
|
||||
</summary>
|
||||
<pre><code class="python">def compile_active_context_patterns(
|
||||
cfg_dict: Any,
|
||||
*,
|
||||
strict: bool = False,
|
||||
) -> list[re.Pattern[str]]:
|
||||
"""Compile active context regexes purely respecting cfg_dict['case']."""
|
||||
patterns, _ = compile_active_context_patterns_with_status(cfg_dict, strict=strict)
|
||||
return patterns</code></pre>
|
||||
</details>
|
||||
<div class="desc"><p>Compile active context regexes purely respecting cfg_dict['case'].</p></div>
|
||||
</dd>
|
||||
<dt id="connpy.auth_utils.compile_active_context_patterns_with_status"><code class="name flex">
|
||||
<span>def <span class="ident">compile_active_context_patterns_with_status</span></span>(<span>cfg_dict: Any, *, strict: bool = False) ‑> tuple[list[re.Pattern[str]], bool]</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<details class="source">
|
||||
<summary>
|
||||
<span>Expand source code</span>
|
||||
</summary>
|
||||
<pre><code class="python">def compile_active_context_patterns_with_status(
|
||||
cfg_dict: Any,
|
||||
*,
|
||||
strict: bool = False,
|
||||
) -> tuple[list[re.Pattern[str]], bool]:
|
||||
"""Compile active context regexes purely, returning (patterns, had_error)."""
|
||||
if is_default_all_context_cfg(cfg_dict):
|
||||
return ([re.compile(".*")], False)
|
||||
|
||||
current_ctx = cfg_dict.get("current_context", "all")
|
||||
contexts = cfg_dict.get("contexts", {"all": [".*"]})
|
||||
raw_patterns = contexts.get(current_ctx, [".*"]) if isinstance(contexts, dict) else [".*"]
|
||||
flags = 0 if cfg_dict.get("case", False) else re.IGNORECASE
|
||||
|
||||
if not isinstance(raw_patterns, list):
|
||||
if strict:
|
||||
raise ValueError("Context regexes must be a list")
|
||||
return ([], True)
|
||||
|
||||
had_error = False
|
||||
if len(raw_patterns) > MAX_CONTEXT_REGEXES:
|
||||
if strict:
|
||||
raise ValueError(f"Context exceeds maximum of {MAX_CONTEXT_REGEXES} regexes")
|
||||
had_error = True
|
||||
raw_patterns = raw_patterns[:MAX_CONTEXT_REGEXES]
|
||||
|
||||
patterns: list[re.Pattern[str]] = []
|
||||
for pat in raw_patterns:
|
||||
if not isinstance(pat, str) or not pat or len(pat) > MAX_CONTEXT_PATTERN_LEN:
|
||||
if strict:
|
||||
raise ValueError(
|
||||
f"Context pattern must be a non-empty string up to {MAX_CONTEXT_PATTERN_LEN} chars"
|
||||
)
|
||||
had_error = True
|
||||
continue
|
||||
try:
|
||||
patterns.append(re.compile(pat, flags))
|
||||
except re.error as exc:
|
||||
if strict:
|
||||
raise ValueError(f"Invalid context regex {pat!r}: {exc}") from None
|
||||
had_error = True
|
||||
return (patterns, had_error)</code></pre>
|
||||
</details>
|
||||
<div class="desc"><p>Compile active context regexes purely, returning (patterns, had_error).</p></div>
|
||||
</dd>
|
||||
<dt id="connpy.auth_utils.extract_compose_profile_refs"><code class="name flex">
|
||||
<span>def <span class="ident">extract_compose_profile_refs</span></span>(<span>expr: str) ‑> set[str]</span>
|
||||
</code></dt>
|
||||
@@ -194,6 +266,28 @@ el.replaceWith(d);
|
||||
</details>
|
||||
<div class="desc"><p>Return True if value is a string with the explicit compose: prefix.</p></div>
|
||||
</dd>
|
||||
<dt id="connpy.auth_utils.is_default_all_context_cfg"><code class="name flex">
|
||||
<span>def <span class="ident">is_default_all_context_cfg</span></span>(<span>cfg_dict: Any) ‑> bool</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<details class="source">
|
||||
<summary>
|
||||
<span>Expand source code</span>
|
||||
</summary>
|
||||
<pre><code class="python">def is_default_all_context_cfg(cfg_dict: Any) -> bool:
|
||||
"""Return True when config uses the default unrestricted 'all' context."""
|
||||
if not isinstance(cfg_dict, dict):
|
||||
return True
|
||||
current_ctx = cfg_dict.get("current_context", "all")
|
||||
if current_ctx != "all":
|
||||
return False
|
||||
contexts = cfg_dict.get("contexts", {"all": [".*"]})
|
||||
if not isinstance(contexts, dict):
|
||||
return True
|
||||
return contexts.get("all", [".*"]) == [".*"]</code></pre>
|
||||
</details>
|
||||
<div class="desc"><p>Return True when config uses the default unrestricted 'all' context.</p></div>
|
||||
</dd>
|
||||
<dt id="connpy.auth_utils.is_rsa_blob"><code class="name flex">
|
||||
<span>def <span class="ident">is_rsa_blob</span></span>(<span>value: Any) ‑> bool</span>
|
||||
</code></dt>
|
||||
@@ -281,6 +375,22 @@ el.replaceWith(d);
|
||||
</details>
|
||||
<div class="desc"><p>Recursively mask sensitive node/profile credentials with '***' using a closed key list.</p></div>
|
||||
</dd>
|
||||
<dt id="connpy.auth_utils.match_active_context_patterns"><code class="name flex">
|
||||
<span>def <span class="ident">match_active_context_patterns</span></span>(<span>name: Any, patterns: Iterable[re.Pattern[str]]) ‑> bool</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<details class="source">
|
||||
<summary>
|
||||
<span>Expand source code</span>
|
||||
</summary>
|
||||
<pre><code class="python">def match_active_context_patterns(name: Any, patterns: Iterable[re.Pattern[str]]) -> bool:
|
||||
"""Return True if non-empty string name matches at least one compiled context regex."""
|
||||
if not isinstance(name, str) or not name:
|
||||
return False
|
||||
return any(p.match(name) for p in patterns)</code></pre>
|
||||
</details>
|
||||
<div class="desc"><p>Return True if non-empty string name matches at least one compiled context regex.</p></div>
|
||||
</dd>
|
||||
<dt id="connpy.auth_utils.normalize_prompt_line"><code class="name flex">
|
||||
<span>def <span class="ident">normalize_prompt_line</span></span>(<span>before_bytes: bytes, after_bytes: bytes) ‑> str</span>
|
||||
</code></dt>
|
||||
@@ -628,9 +738,17 @@ el.replaceWith(d);
|
||||
return []
|
||||
if stripped.startswith(("[", "{")):
|
||||
parsed = validate_json_depth_and_size(stripped)
|
||||
elif stripped.startswith("compose:"):
|
||||
validate_compose_syntax(stripped)
|
||||
return [stripped]
|
||||
elif stripped.startswith("@") and not stripped.startswith("@@") and "," in stripped:
|
||||
parts = [p.strip() for p in stripped.split(",")]
|
||||
if not parts or any(not _is_profile_ref(p) for p in parts):
|
||||
raise ValueError(
|
||||
"Comma-separated fallback entries must be valid @profile references"
|
||||
)
|
||||
parsed = parts
|
||||
else:
|
||||
if stripped.startswith("compose:"):
|
||||
validate_compose_syntax(stripped)
|
||||
return [stripped]
|
||||
|
||||
if isinstance(parsed, dict):
|
||||
@@ -1439,13 +1557,17 @@ class RuntimeAuthCandidate:
|
||||
<li><h3><a href="#header-functions">Functions</a></h3>
|
||||
<ul class="">
|
||||
<li><code><a title="connpy.auth_utils.clear_exception_frames" href="#connpy.auth_utils.clear_exception_frames">clear_exception_frames</a></code></li>
|
||||
<li><code><a title="connpy.auth_utils.compile_active_context_patterns" href="#connpy.auth_utils.compile_active_context_patterns">compile_active_context_patterns</a></code></li>
|
||||
<li><code><a title="connpy.auth_utils.compile_active_context_patterns_with_status" href="#connpy.auth_utils.compile_active_context_patterns_with_status">compile_active_context_patterns_with_status</a></code></li>
|
||||
<li><code><a title="connpy.auth_utils.extract_compose_profile_refs" href="#connpy.auth_utils.extract_compose_profile_refs">extract_compose_profile_refs</a></code></li>
|
||||
<li><code><a title="connpy.auth_utils.extract_profile_refs_from_value" href="#connpy.auth_utils.extract_profile_refs_from_value">extract_profile_refs_from_value</a></code></li>
|
||||
<li><code><a title="connpy.auth_utils.has_insecure_hostkey_checking" href="#connpy.auth_utils.has_insecure_hostkey_checking">has_insecure_hostkey_checking</a></code></li>
|
||||
<li><code><a title="connpy.auth_utils.host_exact_re" href="#connpy.auth_utils.host_exact_re">host_exact_re</a></code></li>
|
||||
<li><code><a title="connpy.auth_utils.is_compose_expression" href="#connpy.auth_utils.is_compose_expression">is_compose_expression</a></code></li>
|
||||
<li><code><a title="connpy.auth_utils.is_default_all_context_cfg" href="#connpy.auth_utils.is_default_all_context_cfg">is_default_all_context_cfg</a></code></li>
|
||||
<li><code><a title="connpy.auth_utils.is_rsa_blob" href="#connpy.auth_utils.is_rsa_blob">is_rsa_blob</a></code></li>
|
||||
<li><code><a title="connpy.auth_utils.mask_node_secrets" href="#connpy.auth_utils.mask_node_secrets">mask_node_secrets</a></code></li>
|
||||
<li><code><a title="connpy.auth_utils.match_active_context_patterns" href="#connpy.auth_utils.match_active_context_patterns">match_active_context_patterns</a></code></li>
|
||||
<li><code><a title="connpy.auth_utils.normalize_prompt_line" href="#connpy.auth_utils.normalize_prompt_line">normalize_prompt_line</a></code></li>
|
||||
<li><code><a title="connpy.auth_utils.parse_compose_expression" href="#connpy.auth_utils.parse_compose_expression">parse_compose_expression</a></code></li>
|
||||
<li><code><a title="connpy.auth_utils.raise_sanitized_auth_error" href="#connpy.auth_utils.raise_sanitized_auth_error">raise_sanitized_auth_error</a></code></li>
|
||||
|
||||
@@ -156,7 +156,7 @@ el.replaceWith(d);
|
||||
fbq = [
|
||||
inquirer.Text(
|
||||
"fallback",
|
||||
message="Add fallback credentials (JSON list/dict, @profile, or compose:)",
|
||||
message="Add fallback credentials (@profile, @p1,@p2, JSON list/dict, or compose:)",
|
||||
validate=self.validators.fallback_validation,
|
||||
default=def_fb_str.replace("{", "{{").replace("}", "}}"),
|
||||
)
|
||||
@@ -228,7 +228,7 @@ el.replaceWith(d);
|
||||
if edit.get("fallback"):
|
||||
raw_def_fb = defaults.get("fallback", "")
|
||||
def_fb_str = json.dumps(raw_def_fb) if isinstance(raw_def_fb, (list, dict)) else str(raw_def_fb or "")
|
||||
questions.append(inquirer.Text("fallback", message="Add fallback credentials (JSON list/dict, @profile, or compose:)", validate=self.validators.fallback_validation, default=def_fb_str.replace("{", "{{").replace("}", "}}")))
|
||||
questions.append(inquirer.Text("fallback", message="Add fallback credentials (@profile, @p1,@p2, JSON list/dict, or compose:)", validate=self.validators.fallback_validation, default=def_fb_str.replace("{", "{{").replace("}", "}}")))
|
||||
else:
|
||||
profile["fallback"] = defaults.get("fallback", "")
|
||||
|
||||
@@ -286,7 +286,7 @@ el.replaceWith(d);
|
||||
fbq = [
|
||||
inquirer.Text(
|
||||
"fallback",
|
||||
message="Add fallback credentials (JSON list/dict, @profile, or compose:)",
|
||||
message="Add fallback credentials (@profile, @p1,@p2, JSON list/dict, or compose:)",
|
||||
validate=self.validators.fallback_validation,
|
||||
)
|
||||
]
|
||||
@@ -524,7 +524,7 @@ el.replaceWith(d);
|
||||
fbq = [
|
||||
inquirer.Text(
|
||||
"fallback",
|
||||
message="Add fallback credentials (JSON list/dict, @profile, or compose:)",
|
||||
message="Add fallback credentials (@profile, @p1,@p2, JSON list/dict, or compose:)",
|
||||
validate=self.validators.fallback_validation,
|
||||
)
|
||||
]
|
||||
@@ -655,7 +655,7 @@ el.replaceWith(d);
|
||||
fbq = [
|
||||
inquirer.Text(
|
||||
"fallback",
|
||||
message="Add fallback credentials (JSON list/dict, @profile, or compose:)",
|
||||
message="Add fallback credentials (@profile, @p1,@p2, JSON list/dict, or compose:)",
|
||||
validate=self.validators.fallback_validation,
|
||||
default=def_fb_str.replace("{", "{{").replace("}", "}}"),
|
||||
)
|
||||
@@ -737,7 +737,7 @@ el.replaceWith(d);
|
||||
if edit.get("fallback"):
|
||||
raw_def_fb = defaults.get("fallback", "")
|
||||
def_fb_str = json.dumps(raw_def_fb) if isinstance(raw_def_fb, (list, dict)) else str(raw_def_fb or "")
|
||||
questions.append(inquirer.Text("fallback", message="Add fallback credentials (JSON list/dict, @profile, or compose:)", validate=self.validators.fallback_validation, default=def_fb_str.replace("{", "{{").replace("}", "}}")))
|
||||
questions.append(inquirer.Text("fallback", message="Add fallback credentials (@profile, @p1,@p2, JSON list/dict, or compose:)", validate=self.validators.fallback_validation, default=def_fb_str.replace("{", "{{").replace("}", "}}")))
|
||||
else:
|
||||
profile["fallback"] = defaults.get("fallback", "")
|
||||
|
||||
|
||||
@@ -193,6 +193,7 @@ el.replaceWith(d);
|
||||
uniques = self.app.services.nodes.explode_unique(args.data)
|
||||
if not uniques:
|
||||
raise InvalidConfigurationError(f"Invalid folder {args.data}")
|
||||
self.app.services.nodes.validate_parent_folder(args.data, is_folder=True)
|
||||
self.app.services.nodes.add_node(args.data, {}, is_folder=True)
|
||||
printer.success(f"{args.data} added successfully")
|
||||
else:
|
||||
@@ -364,6 +365,7 @@ def forms(self):
|
||||
uniques = self.app.services.nodes.explode_unique(args.data)
|
||||
if not uniques:
|
||||
raise InvalidConfigurationError(f"Invalid folder {args.data}")
|
||||
self.app.services.nodes.validate_parent_folder(args.data, is_folder=True)
|
||||
self.app.services.nodes.add_node(args.data, {}, is_folder=True)
|
||||
printer.success(f"{args.data} added successfully")
|
||||
else:
|
||||
|
||||
+132
-32
@@ -163,9 +163,19 @@ el.replaceWith(d);
|
||||
return True
|
||||
if len(stripped.encode("utf-8", errors="replace")) > MAX_JSON_INPUT_BYTES:
|
||||
_raise_val_err(f"Fallback exceeds maximum size of {MAX_JSON_INPUT_BYTES} bytes")
|
||||
if stripped.startswith("@") and "+" not in stripped:
|
||||
if stripped[1:] not in self.app.profiles:
|
||||
_raise_val_err(f"Profile {stripped} don't exist")
|
||||
if stripped.startswith("@") and not stripped.startswith("@@") and "+" not in stripped:
|
||||
parts = [p.strip() for p in stripped.split(",")]
|
||||
if any(not p for p in parts):
|
||||
_raise_val_err("Fallback profile entry cannot be empty")
|
||||
if len(parts) > MAX_FALLBACK_ENTRIES:
|
||||
_raise_val_err(f"Fallback exceeds maximum of {MAX_FALLBACK_ENTRIES} entries")
|
||||
for p in parts:
|
||||
if not p.startswith("@") or not re.fullmatch(r"[A-Za-z0-9_.$:/-]+", p[1:]):
|
||||
_raise_val_err(
|
||||
"Comma-separated fallback entries must be valid @profile references"
|
||||
)
|
||||
if p[1:] not in self.app.profiles:
|
||||
_raise_val_err(f"Profile {p} don't exist")
|
||||
return True
|
||||
try:
|
||||
if is_compose_expression(stripped):
|
||||
@@ -182,19 +192,33 @@ el.replaceWith(d);
|
||||
_raise_val_err(str(exc))
|
||||
return True
|
||||
|
||||
def _get_all_valid_nodes(self) -> list[str]:
|
||||
valid_nodes = list(getattr(self.app, "nodes_list", []) or [])
|
||||
if hasattr(self.app, "services") and hasattr(self.app.services, "nodes"):
|
||||
raw_fn = getattr(self.app.services.nodes, "_get_raw_nodes", None)
|
||||
if callable(raw_fn) and not hasattr(raw_fn, "assert_called"):
|
||||
raw_res = raw_fn()
|
||||
if isinstance(raw_res, (list, tuple, set)):
|
||||
valid_nodes = list(dict.fromkeys([*raw_res, *valid_nodes]))
|
||||
return valid_nodes
|
||||
|
||||
def _node_exists(self, target: str) -> bool:
|
||||
valid_nodes = self._get_all_valid_nodes()
|
||||
if getattr(self.app, "case", True):
|
||||
return target in valid_nodes
|
||||
return target.lower() in {n.lower() for n in valid_nodes}
|
||||
|
||||
def jumphost_validation(self, answers, current):
|
||||
if current.startswith("@"):
|
||||
if current[1:] not in self.app.profiles:
|
||||
_raise_val_err("Profile {} don't exist".format(current))
|
||||
elif current != "":
|
||||
if current not in self.app.nodes_list:
|
||||
_raise_val_err("Node {} don't exist.".format(current))
|
||||
_raise_val_err(f"Profile {current} don't exist")
|
||||
elif current != "" and not self._node_exists(current):
|
||||
_raise_val_err(f"Node {current} don't exist.")
|
||||
return True
|
||||
|
||||
def profile_jumphost_validation(self, answers, current):
|
||||
if current != "":
|
||||
if current not in self.app.nodes_list:
|
||||
_raise_val_err("Node {} don't exist.".format(current))
|
||||
if current != "" and not self._node_exists(current):
|
||||
_raise_val_err(f"Node {current} don't exist.")
|
||||
return True
|
||||
|
||||
def default_validation(self, answers, current):
|
||||
@@ -212,13 +236,47 @@ el.replaceWith(d);
|
||||
return True
|
||||
|
||||
def bulk_folder_validation(self, answers, current):
|
||||
if not self.app.case:
|
||||
case = getattr(self.app, "case", False)
|
||||
if not case:
|
||||
current = current.lower()
|
||||
|
||||
candidate = current
|
||||
if "/" in current:
|
||||
candidate = current.split("/")[0]
|
||||
|
||||
|
||||
candidate = current.split("/")[0] if "/" in current else current
|
||||
|
||||
if hasattr(self.app, "services") and hasattr(self.app.services, "context"):
|
||||
raw_folders = list(getattr(self.app, "folders", []) or [])
|
||||
if hasattr(self.app.services, "nodes"):
|
||||
raw_fn = getattr(self.app.services.nodes, "_get_raw_folders", None)
|
||||
if callable(raw_fn) and not hasattr(raw_fn, "assert_called"):
|
||||
raw_res = raw_fn()
|
||||
if isinstance(raw_res, (list, tuple, set)):
|
||||
raw_folders = list(raw_res)
|
||||
|
||||
def _folder_exists_norm(folder_name: str) -> bool:
|
||||
if case:
|
||||
return folder_name in raw_folders
|
||||
return folder_name.lower() in {f.lower() for f in raw_folders}
|
||||
|
||||
if current != "" and not _folder_exists_norm(candidate):
|
||||
_raise_val_err(f"Location {current} don't exist")
|
||||
|
||||
ctx_svc = self.app.services.context
|
||||
if ctx_svc is not None and not ctx_svc.is_default_all_context():
|
||||
raw_ids = answers.get("ids", "") if isinstance(answers, dict) else ""
|
||||
for nid in str(raw_ids).split(","):
|
||||
nid_stripped = nid.strip()
|
||||
if not nid_stripped:
|
||||
continue
|
||||
nid_norm = nid_stripped if case else nid_stripped.lower()
|
||||
full_id = f"{nid_norm}{candidate}" if candidate else nid_norm
|
||||
if not ctx_svc.matches_active_context(full_id):
|
||||
_raise_val_err(
|
||||
f"Node '{full_id}' does not match active context '{ctx_svc.current_context}'."
|
||||
)
|
||||
parent = full_id.partition("@")[2]
|
||||
if parent and not _folder_exists_norm(f"@{parent}"):
|
||||
_raise_val_err(f"Location @{parent} don't exist")
|
||||
return True
|
||||
|
||||
matches = list(filter(lambda k: k == candidate, self.app.folders))
|
||||
if current != "" and len(matches) == 0:
|
||||
_raise_val_err("Location {} don't exist".format(current))
|
||||
@@ -248,13 +306,47 @@ el.replaceWith(d);
|
||||
<span>Expand source code</span>
|
||||
</summary>
|
||||
<pre><code class="python">def bulk_folder_validation(self, answers, current):
|
||||
if not self.app.case:
|
||||
case = getattr(self.app, "case", False)
|
||||
if not case:
|
||||
current = current.lower()
|
||||
|
||||
candidate = current
|
||||
if "/" in current:
|
||||
candidate = current.split("/")[0]
|
||||
|
||||
|
||||
candidate = current.split("/")[0] if "/" in current else current
|
||||
|
||||
if hasattr(self.app, "services") and hasattr(self.app.services, "context"):
|
||||
raw_folders = list(getattr(self.app, "folders", []) or [])
|
||||
if hasattr(self.app.services, "nodes"):
|
||||
raw_fn = getattr(self.app.services.nodes, "_get_raw_folders", None)
|
||||
if callable(raw_fn) and not hasattr(raw_fn, "assert_called"):
|
||||
raw_res = raw_fn()
|
||||
if isinstance(raw_res, (list, tuple, set)):
|
||||
raw_folders = list(raw_res)
|
||||
|
||||
def _folder_exists_norm(folder_name: str) -> bool:
|
||||
if case:
|
||||
return folder_name in raw_folders
|
||||
return folder_name.lower() in {f.lower() for f in raw_folders}
|
||||
|
||||
if current != "" and not _folder_exists_norm(candidate):
|
||||
_raise_val_err(f"Location {current} don't exist")
|
||||
|
||||
ctx_svc = self.app.services.context
|
||||
if ctx_svc is not None and not ctx_svc.is_default_all_context():
|
||||
raw_ids = answers.get("ids", "") if isinstance(answers, dict) else ""
|
||||
for nid in str(raw_ids).split(","):
|
||||
nid_stripped = nid.strip()
|
||||
if not nid_stripped:
|
||||
continue
|
||||
nid_norm = nid_stripped if case else nid_stripped.lower()
|
||||
full_id = f"{nid_norm}{candidate}" if candidate else nid_norm
|
||||
if not ctx_svc.matches_active_context(full_id):
|
||||
_raise_val_err(
|
||||
f"Node '{full_id}' does not match active context '{ctx_svc.current_context}'."
|
||||
)
|
||||
parent = full_id.partition("@")[2]
|
||||
if parent and not _folder_exists_norm(f"@{parent}"):
|
||||
_raise_val_err(f"Location @{parent} don't exist")
|
||||
return True
|
||||
|
||||
matches = list(filter(lambda k: k == candidate, self.app.folders))
|
||||
if current != "" and len(matches) == 0:
|
||||
_raise_val_err("Location {} don't exist".format(current))
|
||||
@@ -334,9 +426,19 @@ el.replaceWith(d);
|
||||
return True
|
||||
if len(stripped.encode("utf-8", errors="replace")) > MAX_JSON_INPUT_BYTES:
|
||||
_raise_val_err(f"Fallback exceeds maximum size of {MAX_JSON_INPUT_BYTES} bytes")
|
||||
if stripped.startswith("@") and "+" not in stripped:
|
||||
if stripped[1:] not in self.app.profiles:
|
||||
_raise_val_err(f"Profile {stripped} don't exist")
|
||||
if stripped.startswith("@") and not stripped.startswith("@@") and "+" not in stripped:
|
||||
parts = [p.strip() for p in stripped.split(",")]
|
||||
if any(not p for p in parts):
|
||||
_raise_val_err("Fallback profile entry cannot be empty")
|
||||
if len(parts) > MAX_FALLBACK_ENTRIES:
|
||||
_raise_val_err(f"Fallback exceeds maximum of {MAX_FALLBACK_ENTRIES} entries")
|
||||
for p in parts:
|
||||
if not p.startswith("@") or not re.fullmatch(r"[A-Za-z0-9_.$:/-]+", p[1:]):
|
||||
_raise_val_err(
|
||||
"Comma-separated fallback entries must be valid @profile references"
|
||||
)
|
||||
if p[1:] not in self.app.profiles:
|
||||
_raise_val_err(f"Profile {p} don't exist")
|
||||
return True
|
||||
try:
|
||||
if is_compose_expression(stripped):
|
||||
@@ -384,10 +486,9 @@ el.replaceWith(d);
|
||||
<pre><code class="python">def jumphost_validation(self, answers, current):
|
||||
if current.startswith("@"):
|
||||
if current[1:] not in self.app.profiles:
|
||||
_raise_val_err("Profile {} don't exist".format(current))
|
||||
elif current != "":
|
||||
if current not in self.app.nodes_list:
|
||||
_raise_val_err("Node {} don't exist.".format(current))
|
||||
_raise_val_err(f"Profile {current} don't exist")
|
||||
elif current != "" and not self._node_exists(current):
|
||||
_raise_val_err(f"Node {current} don't exist.")
|
||||
return True</code></pre>
|
||||
</details>
|
||||
<div class="desc"></div>
|
||||
@@ -448,9 +549,8 @@ el.replaceWith(d);
|
||||
<span>Expand source code</span>
|
||||
</summary>
|
||||
<pre><code class="python">def profile_jumphost_validation(self, answers, current):
|
||||
if current != "":
|
||||
if current not in self.app.nodes_list:
|
||||
_raise_val_err("Node {} don't exist.".format(current))
|
||||
if current != "" and not self._node_exists(current):
|
||||
_raise_val_err(f"Node {current} don't exist.")
|
||||
return True</code></pre>
|
||||
</details>
|
||||
<div class="desc"></div>
|
||||
|
||||
@@ -110,7 +110,7 @@ el.replaceWith(d);
|
||||
from connpy.grpc_layer.user_registry import UserRegistry
|
||||
from connpy.services.provider import ServiceProvider
|
||||
|
||||
fallback_provider = ServiceProvider(config, mode="local")
|
||||
fallback_provider = ServiceProvider(config, mode="local", enforce_context=False)
|
||||
registry = UserRegistry(config.defaultdir)
|
||||
|
||||
# Check if trusted_gateway provider is configured if SSO Gateway Secret is present in env
|
||||
@@ -163,9 +163,7 @@ el.replaceWith(d);
|
||||
</summary>
|
||||
<pre><code class="python">class AIServicer(connpy_pb2_grpc.AIServiceServicer):
|
||||
def __init__(self, provider, registry=None, debug=False):
|
||||
if not hasattr(provider, "mode"):
|
||||
from connpy.services.provider import ServiceProvider
|
||||
provider = ServiceProvider(provider, mode="local")
|
||||
provider = _ensure_server_provider(provider)
|
||||
self._fallback_provider = provider
|
||||
self._registry = registry
|
||||
self.server_debug = debug
|
||||
@@ -927,9 +925,7 @@ interceptor chooses to service this RPC, or None otherwise.</p></div>
|
||||
</summary>
|
||||
<pre><code class="python">class ConfigServicer(connpy_pb2_grpc.ConfigServiceServicer):
|
||||
def __init__(self, provider, registry=None):
|
||||
if not hasattr(provider, "mode"):
|
||||
from connpy.services.provider import ServiceProvider
|
||||
provider = ServiceProvider(provider, mode="local")
|
||||
provider = _ensure_server_provider(provider)
|
||||
self._fallback_provider = provider
|
||||
self._registry = registry
|
||||
|
||||
@@ -1015,9 +1011,7 @@ def service(self):
|
||||
</summary>
|
||||
<pre><code class="python">class ExecutionServicer(connpy_pb2_grpc.ExecutionServiceServicer):
|
||||
def __init__(self, provider, registry=None):
|
||||
if not hasattr(provider, "mode"):
|
||||
from connpy.services.provider import ServiceProvider
|
||||
provider = ServiceProvider(provider, mode="local")
|
||||
provider = _ensure_server_provider(provider)
|
||||
self._fallback_provider = provider
|
||||
self._registry = registry
|
||||
|
||||
@@ -1186,9 +1180,7 @@ def service(self):
|
||||
</summary>
|
||||
<pre><code class="python">class ImportExportServicer(connpy_pb2_grpc.ImportExportServiceServicer):
|
||||
def __init__(self, provider, registry=None):
|
||||
if not hasattr(provider, "mode"):
|
||||
from connpy.services.provider import ServiceProvider
|
||||
provider = ServiceProvider(provider, mode="local")
|
||||
provider = _ensure_server_provider(provider)
|
||||
self._fallback_provider = provider
|
||||
self._registry = registry
|
||||
|
||||
@@ -1374,9 +1366,7 @@ interceptor chooses to service this RPC, or None otherwise.</p></div>
|
||||
</summary>
|
||||
<pre><code class="python">class NodeServicer(connpy_pb2_grpc.NodeServiceServicer):
|
||||
def __init__(self, provider, registry=None, debug=False):
|
||||
if not hasattr(provider, "mode"):
|
||||
from connpy.services.provider import ServiceProvider
|
||||
provider = ServiceProvider(provider, mode="local")
|
||||
provider = _ensure_server_provider(provider)
|
||||
self._fallback_provider = provider
|
||||
self._registry = registry
|
||||
self.server_debug = debug
|
||||
@@ -2041,9 +2031,7 @@ def service(self):
|
||||
</summary>
|
||||
<pre><code class="python">class PluginServicer(connpy_pb2_grpc.PluginServiceServicer, remote_plugin_pb2_grpc.RemotePluginServiceServicer):
|
||||
def __init__(self, provider, registry=None):
|
||||
if not hasattr(provider, "mode"):
|
||||
from connpy.services.provider import ServiceProvider
|
||||
provider = ServiceProvider(provider, mode="local")
|
||||
provider = _ensure_server_provider(provider)
|
||||
self._fallback_provider = provider
|
||||
self._registry = registry
|
||||
|
||||
@@ -2148,9 +2136,7 @@ def service(self):
|
||||
</summary>
|
||||
<pre><code class="python">class ProfileServicer(connpy_pb2_grpc.ProfileServiceServicer):
|
||||
def __init__(self, provider, registry=None):
|
||||
if not hasattr(provider, "mode"):
|
||||
from connpy.services.provider import ServiceProvider
|
||||
provider = ServiceProvider(provider, mode="local")
|
||||
provider = _ensure_server_provider(provider)
|
||||
self._fallback_provider = provider
|
||||
self._registry = registry
|
||||
|
||||
@@ -2451,9 +2437,7 @@ def service(self):
|
||||
</summary>
|
||||
<pre><code class="python">class SystemServicer(connpy_pb2_grpc.SystemServiceServicer):
|
||||
def __init__(self, provider, registry=None):
|
||||
if not hasattr(provider, "mode"):
|
||||
from connpy.services.provider import ServiceProvider
|
||||
provider = ServiceProvider(provider, mode="local")
|
||||
provider = _ensure_server_provider(provider)
|
||||
self._fallback_provider = provider
|
||||
self._registry = registry
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -113,7 +113,7 @@ el.replaceWith(d);
|
||||
try:
|
||||
# Attempt a fresh configuration load
|
||||
config = configfile(conf=conf_file, shared_config=self._shared_config)
|
||||
new_provider = ServiceProvider(config, mode="local")
|
||||
new_provider = ServiceProvider(config, mode="local", enforce_context=False)
|
||||
|
||||
# Successfully loaded, clean up the old provider
|
||||
if old_provider:
|
||||
@@ -221,7 +221,7 @@ el.replaceWith(d);
|
||||
try:
|
||||
# Attempt a fresh configuration load
|
||||
config = configfile(conf=conf_file, shared_config=self._shared_config)
|
||||
new_provider = ServiceProvider(config, mode="local")
|
||||
new_provider = ServiceProvider(config, mode="local", enforce_context=False)
|
||||
|
||||
# Successfully loaded, clean up the old provider
|
||||
if old_provider:
|
||||
|
||||
+22
-5
@@ -752,6 +752,7 @@ class configfile:
|
||||
def __init__(self, conf = None, key = None, shared_config = None):
|
||||
self._mutation_lock = threading.RLock()
|
||||
self._cache_dirty = False
|
||||
self._enforce_context = True
|
||||
self._shared_config = shared_config
|
||||
'''
|
||||
|
||||
@@ -1098,8 +1099,9 @@ class configfile:
|
||||
self._fsync_dir_nonfatal(conf)
|
||||
try:
|
||||
self._atomic_write_text_unlocked(self.cachefile, lambda f: json.dump(newconfig, f))
|
||||
self._generate_nodes_cache_unlocked(_raise_on_error=True)
|
||||
self._cache_dirty = False
|
||||
if self._is_context_filtering_enabled_unlocked():
|
||||
self._generate_nodes_cache_unlocked(_raise_on_error=True)
|
||||
except (OSError, TypeError, ValueError):
|
||||
self._cache_dirty = True
|
||||
return 0, None
|
||||
@@ -1183,18 +1185,33 @@ class configfile:
|
||||
self._cache_dirty = True
|
||||
return False
|
||||
|
||||
def _is_context_filtering_enabled_unlocked(self) -> bool:
|
||||
if not getattr(self, "_enforce_context", True):
|
||||
return False
|
||||
return not (len(sys.argv) > 1 and sys.argv[1] == "api")
|
||||
|
||||
def _filter_by_active_context_unlocked(self, items: list[str]) -> tuple[list[str], bool]:
|
||||
if not self._is_context_filtering_enabled_unlocked() or is_default_all_context_cfg(
|
||||
self.config
|
||||
):
|
||||
return (list(items), False)
|
||||
patterns, had_err = compile_active_context_patterns_with_status(self.config)
|
||||
return ([i for i in items if match_active_context_patterns(i, patterns)], had_err)
|
||||
|
||||
def _generate_nodes_cache_unlocked(self, nodes=None, folders=None, profiles=None, *, _raise_on_error=False):
|
||||
try:
|
||||
if nodes is None:
|
||||
nodes = self._getallnodes_unlocked()
|
||||
if folders is None:
|
||||
folders = self._getallfolders_unlocked()
|
||||
raw_nodes = self._getallnodes_unlocked() if nodes is None else list(nodes)
|
||||
raw_folders = self._getallfolders_unlocked() if folders is None else list(folders)
|
||||
nodes, err_n = self._filter_by_active_context_unlocked(raw_nodes)
|
||||
folders, err_f = self._filter_by_active_context_unlocked(raw_folders)
|
||||
if profiles is None:
|
||||
profiles = list(self.profiles.keys())
|
||||
|
||||
self._atomic_write_text_unlocked(self.fzf_cachefile, lambda f: f.write("\n".join(nodes)))
|
||||
self._atomic_write_text_unlocked(self.folders_cachefile, lambda f: f.write("\n".join(folders)))
|
||||
self._atomic_write_text_unlocked(self.profiles_cachefile, lambda f: f.write("\n".join(profiles)))
|
||||
if err_n or err_f:
|
||||
self._cache_dirty = True
|
||||
except (OSError, TypeError, ValueError):
|
||||
if _raise_on_error:
|
||||
raise
|
||||
|
||||
@@ -58,15 +58,31 @@ el.replaceWith(d);
|
||||
<pre><code class="python">class ContextService(BaseService):
|
||||
"""Business logic for managing and applying regex-based contexts locally."""
|
||||
|
||||
@staticmethod
|
||||
def _validate_regexes(regexes: Any) -> None:
|
||||
if not isinstance(regexes, list) or not (1 <= len(regexes) <= MAX_CONTEXT_REGEXES):
|
||||
raise ValueError(
|
||||
f"Context regexes must be a list of 1 to {MAX_CONTEXT_REGEXES} patterns"
|
||||
)
|
||||
for pat in regexes:
|
||||
if not isinstance(pat, str) or not (1 <= len(pat) <= MAX_CONTEXT_PATTERN_LEN):
|
||||
raise ValueError(
|
||||
f"Each context regex must be a non-empty string up to {MAX_CONTEXT_PATTERN_LEN} characters"
|
||||
)
|
||||
try:
|
||||
re.compile(pat)
|
||||
except re.error as exc:
|
||||
raise ValueError(f"Invalid context regex {pat!r}: {exc}") from None
|
||||
|
||||
@property
|
||||
def contexts(self) -> Dict[str, List[str]]:
|
||||
def contexts(self) -> dict[str, list[str]]:
|
||||
return self.config.config.get("contexts", {"all": [".*"]})
|
||||
|
||||
@property
|
||||
def current_context(self) -> str:
|
||||
return self.config.config.get("current_context", "all")
|
||||
|
||||
def list_contexts(self) -> List[Dict[str, Any]]:
|
||||
def list_contexts(self) -> list[dict[str, Any]]:
|
||||
result = []
|
||||
for name in self.contexts.keys():
|
||||
result.append({
|
||||
@@ -76,27 +92,29 @@ el.replaceWith(d);
|
||||
})
|
||||
return result
|
||||
|
||||
def add_context(self, name: str, regexes: List[str]):
|
||||
def add_context(self, name: str, regexes: list[str]):
|
||||
if not name.isalnum():
|
||||
raise ValueError("Context name must be alphanumeric")
|
||||
|
||||
self._validate_regexes(regexes)
|
||||
|
||||
ctxs = self.contexts
|
||||
if name in ctxs:
|
||||
raise ValueError(f"Context '{name}' already exists")
|
||||
|
||||
ctxs[name] = regexes
|
||||
|
||||
ctxs[name] = list(regexes)
|
||||
self.config.config["contexts"] = ctxs
|
||||
self.config._saveconfig(self.config.file)
|
||||
|
||||
def update_context(self, name: str, regexes: List[str]):
|
||||
def update_context(self, name: str, regexes: list[str]):
|
||||
if name == "all":
|
||||
raise ValueError("Cannot modify default context 'all'")
|
||||
|
||||
self._validate_regexes(regexes)
|
||||
|
||||
ctxs = self.contexts
|
||||
if name not in ctxs:
|
||||
raise ValueError(f"Context '{name}' does not exist")
|
||||
|
||||
ctxs[name] = regexes
|
||||
|
||||
ctxs[name] = list(regexes)
|
||||
self.config.config["contexts"] = ctxs
|
||||
self.config._saveconfig(self.config.file)
|
||||
|
||||
@@ -117,16 +135,48 @@ el.replaceWith(d);
|
||||
def set_active_context(self, name: str):
|
||||
if name not in self.contexts:
|
||||
raise ValueError(f"Context '{name}' does not exist")
|
||||
|
||||
|
||||
prev_context = self.current_context
|
||||
self.config.config["current_context"] = name
|
||||
self.config._saveconfig(self.config.file)
|
||||
can_refresh = (
|
||||
self.config._is_context_filtering_enabled_unlocked()
|
||||
if (
|
||||
not hasattr(self.config, "assert_called")
|
||||
and callable(getattr(self.config, "_is_context_filtering_enabled_unlocked", None))
|
||||
)
|
||||
else getattr(self.config, "_enforce_context", True)
|
||||
)
|
||||
if (
|
||||
name == "all"
|
||||
and prev_context != "all"
|
||||
and can_refresh
|
||||
and hasattr(self.config, "_generate_nodes_cache")
|
||||
):
|
||||
self.config._generate_nodes_cache()
|
||||
|
||||
def get_active_regexes(self) -> List[re.Pattern]:
|
||||
patterns = self.contexts.get(self.current_context, [".*"])
|
||||
return [re.compile(p) for p in patterns]
|
||||
def get_active_regexes(self) -> list[re.Pattern]:
|
||||
return compile_active_context_patterns(getattr(self.config, "config", None))
|
||||
|
||||
def _match_any(self, node_name: str, patterns: List[re.Pattern]) -> bool:
|
||||
return any(p.match(node_name) for p in patterns)
|
||||
def _match_any(self, node_name: str, patterns: list[re.Pattern]) -> bool:
|
||||
return match_active_context_patterns(node_name, patterns)
|
||||
|
||||
def is_default_all_context(self) -> bool:
|
||||
return is_default_all_context_cfg(getattr(self.config, "config", None))
|
||||
|
||||
def matches_active_context(self, name: str) -> bool:
|
||||
if self.is_default_all_context():
|
||||
return isinstance(name, str) and bool(name)
|
||||
if not isinstance(name, str) or not name:
|
||||
return False
|
||||
return match_active_context_patterns(name, self.get_active_regexes())
|
||||
|
||||
def validate_in_active_context(self, unique_id: str, is_folder: bool = False) -> None:
|
||||
if not self.is_default_all_context() and not self.matches_active_context(unique_id):
|
||||
label = "Folder" if is_folder else "Node"
|
||||
raise InvalidConfigurationError(
|
||||
f"{label} '{unique_id}' does not match active context '{self.current_context}'."
|
||||
)
|
||||
|
||||
# Hook handlers for filtering
|
||||
def filter_node_list(self, *args, **kwargs):
|
||||
@@ -151,14 +201,14 @@ el.replaceWith(d);
|
||||
</ul>
|
||||
<h3>Instance variables</h3>
|
||||
<dl>
|
||||
<dt id="connpy.services.context_service.ContextService.contexts"><code class="name">prop <span class="ident">contexts</span> : Dict[str, List[str]]</code></dt>
|
||||
<dt id="connpy.services.context_service.ContextService.contexts"><code class="name">prop <span class="ident">contexts</span> : dict[str, list[str]]</code></dt>
|
||||
<dd>
|
||||
<details class="source">
|
||||
<summary>
|
||||
<span>Expand source code</span>
|
||||
</summary>
|
||||
<pre><code class="python">@property
|
||||
def contexts(self) -> Dict[str, List[str]]:
|
||||
def contexts(self) -> dict[str, list[str]]:
|
||||
return self.config.config.get("contexts", {"all": [".*"]})</code></pre>
|
||||
</details>
|
||||
<div class="desc"></div>
|
||||
@@ -179,22 +229,23 @@ def current_context(self) -> str:
|
||||
<h3>Methods</h3>
|
||||
<dl>
|
||||
<dt id="connpy.services.context_service.ContextService.add_context"><code class="name flex">
|
||||
<span>def <span class="ident">add_context</span></span>(<span>self, name: str, regexes: List[str])</span>
|
||||
<span>def <span class="ident">add_context</span></span>(<span>self, name: str, regexes: list[str])</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<details class="source">
|
||||
<summary>
|
||||
<span>Expand source code</span>
|
||||
</summary>
|
||||
<pre><code class="python">def add_context(self, name: str, regexes: List[str]):
|
||||
<pre><code class="python">def add_context(self, name: str, regexes: list[str]):
|
||||
if not name.isalnum():
|
||||
raise ValueError("Context name must be alphanumeric")
|
||||
|
||||
self._validate_regexes(regexes)
|
||||
|
||||
ctxs = self.contexts
|
||||
if name in ctxs:
|
||||
raise ValueError(f"Context '{name}' already exists")
|
||||
|
||||
ctxs[name] = regexes
|
||||
|
||||
ctxs[name] = list(regexes)
|
||||
self.config.config["contexts"] = ctxs
|
||||
self.config._saveconfig(self.config.file)</code></pre>
|
||||
</details>
|
||||
@@ -253,28 +304,40 @@ def current_context(self) -> str:
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt id="connpy.services.context_service.ContextService.get_active_regexes"><code class="name flex">
|
||||
<span>def <span class="ident">get_active_regexes</span></span>(<span>self) ‑> List[re.Pattern]</span>
|
||||
<span>def <span class="ident">get_active_regexes</span></span>(<span>self) ‑> list[re.Pattern]</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<details class="source">
|
||||
<summary>
|
||||
<span>Expand source code</span>
|
||||
</summary>
|
||||
<pre><code class="python">def get_active_regexes(self) -> List[re.Pattern]:
|
||||
patterns = self.contexts.get(self.current_context, [".*"])
|
||||
return [re.compile(p) for p in patterns]</code></pre>
|
||||
<pre><code class="python">def get_active_regexes(self) -> list[re.Pattern]:
|
||||
return compile_active_context_patterns(getattr(self.config, "config", None))</code></pre>
|
||||
</details>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt id="connpy.services.context_service.ContextService.is_default_all_context"><code class="name flex">
|
||||
<span>def <span class="ident">is_default_all_context</span></span>(<span>self) ‑> bool</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<details class="source">
|
||||
<summary>
|
||||
<span>Expand source code</span>
|
||||
</summary>
|
||||
<pre><code class="python">def is_default_all_context(self) -> bool:
|
||||
return is_default_all_context_cfg(getattr(self.config, "config", None))</code></pre>
|
||||
</details>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt id="connpy.services.context_service.ContextService.list_contexts"><code class="name flex">
|
||||
<span>def <span class="ident">list_contexts</span></span>(<span>self) ‑> List[Dict[str, Any]]</span>
|
||||
<span>def <span class="ident">list_contexts</span></span>(<span>self) ‑> list[dict[str, typing.Any]]</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<details class="source">
|
||||
<summary>
|
||||
<span>Expand source code</span>
|
||||
</summary>
|
||||
<pre><code class="python">def list_contexts(self) -> List[Dict[str, Any]]:
|
||||
<pre><code class="python">def list_contexts(self) -> list[dict[str, Any]]:
|
||||
result = []
|
||||
for name in self.contexts.keys():
|
||||
result.append({
|
||||
@@ -286,6 +349,23 @@ def current_context(self) -> str:
|
||||
</details>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt id="connpy.services.context_service.ContextService.matches_active_context"><code class="name flex">
|
||||
<span>def <span class="ident">matches_active_context</span></span>(<span>self, name: str) ‑> bool</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<details class="source">
|
||||
<summary>
|
||||
<span>Expand source code</span>
|
||||
</summary>
|
||||
<pre><code class="python">def matches_active_context(self, name: str) -> bool:
|
||||
if self.is_default_all_context():
|
||||
return isinstance(name, str) and bool(name)
|
||||
if not isinstance(name, str) or not name:
|
||||
return False
|
||||
return match_active_context_patterns(name, self.get_active_regexes())</code></pre>
|
||||
</details>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt id="connpy.services.context_service.ContextService.set_active_context"><code class="name flex">
|
||||
<span>def <span class="ident">set_active_context</span></span>(<span>self, name: str)</span>
|
||||
</code></dt>
|
||||
@@ -297,34 +377,68 @@ def current_context(self) -> str:
|
||||
<pre><code class="python">def set_active_context(self, name: str):
|
||||
if name not in self.contexts:
|
||||
raise ValueError(f"Context '{name}' does not exist")
|
||||
|
||||
|
||||
prev_context = self.current_context
|
||||
self.config.config["current_context"] = name
|
||||
self.config._saveconfig(self.config.file)</code></pre>
|
||||
self.config._saveconfig(self.config.file)
|
||||
can_refresh = (
|
||||
self.config._is_context_filtering_enabled_unlocked()
|
||||
if (
|
||||
not hasattr(self.config, "assert_called")
|
||||
and callable(getattr(self.config, "_is_context_filtering_enabled_unlocked", None))
|
||||
)
|
||||
else getattr(self.config, "_enforce_context", True)
|
||||
)
|
||||
if (
|
||||
name == "all"
|
||||
and prev_context != "all"
|
||||
and can_refresh
|
||||
and hasattr(self.config, "_generate_nodes_cache")
|
||||
):
|
||||
self.config._generate_nodes_cache()</code></pre>
|
||||
</details>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt id="connpy.services.context_service.ContextService.update_context"><code class="name flex">
|
||||
<span>def <span class="ident">update_context</span></span>(<span>self, name: str, regexes: List[str])</span>
|
||||
<span>def <span class="ident">update_context</span></span>(<span>self, name: str, regexes: list[str])</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<details class="source">
|
||||
<summary>
|
||||
<span>Expand source code</span>
|
||||
</summary>
|
||||
<pre><code class="python">def update_context(self, name: str, regexes: List[str]):
|
||||
<pre><code class="python">def update_context(self, name: str, regexes: list[str]):
|
||||
if name == "all":
|
||||
raise ValueError("Cannot modify default context 'all'")
|
||||
|
||||
self._validate_regexes(regexes)
|
||||
|
||||
ctxs = self.contexts
|
||||
if name not in ctxs:
|
||||
raise ValueError(f"Context '{name}' does not exist")
|
||||
|
||||
ctxs[name] = regexes
|
||||
|
||||
ctxs[name] = list(regexes)
|
||||
self.config.config["contexts"] = ctxs
|
||||
self.config._saveconfig(self.config.file)</code></pre>
|
||||
</details>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
<dt id="connpy.services.context_service.ContextService.validate_in_active_context"><code class="name flex">
|
||||
<span>def <span class="ident">validate_in_active_context</span></span>(<span>self, unique_id: str, is_folder: bool = False) ‑> None</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<details class="source">
|
||||
<summary>
|
||||
<span>Expand source code</span>
|
||||
</summary>
|
||||
<pre><code class="python">def validate_in_active_context(self, unique_id: str, is_folder: bool = False) -> None:
|
||||
if not self.is_default_all_context() and not self.matches_active_context(unique_id):
|
||||
label = "Folder" if is_folder else "Node"
|
||||
raise InvalidConfigurationError(
|
||||
f"{label} '{unique_id}' does not match active context '{self.current_context}'."
|
||||
)</code></pre>
|
||||
</details>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
</dl>
|
||||
<h3>Inherited members</h3>
|
||||
<ul class="hlist">
|
||||
@@ -352,7 +466,7 @@ def current_context(self) -> str:
|
||||
<ul>
|
||||
<li>
|
||||
<h4><code><a title="connpy.services.context_service.ContextService" href="#connpy.services.context_service.ContextService">ContextService</a></code></h4>
|
||||
<ul class="two-column">
|
||||
<ul class="">
|
||||
<li><code><a title="connpy.services.context_service.ContextService.add_context" href="#connpy.services.context_service.ContextService.add_context">add_context</a></code></li>
|
||||
<li><code><a title="connpy.services.context_service.ContextService.contexts" href="#connpy.services.context_service.ContextService.contexts">contexts</a></code></li>
|
||||
<li><code><a title="connpy.services.context_service.ContextService.current_context" href="#connpy.services.context_service.ContextService.current_context">current_context</a></code></li>
|
||||
@@ -360,9 +474,12 @@ def current_context(self) -> str:
|
||||
<li><code><a title="connpy.services.context_service.ContextService.filter_node_dict" href="#connpy.services.context_service.ContextService.filter_node_dict">filter_node_dict</a></code></li>
|
||||
<li><code><a title="connpy.services.context_service.ContextService.filter_node_list" href="#connpy.services.context_service.ContextService.filter_node_list">filter_node_list</a></code></li>
|
||||
<li><code><a title="connpy.services.context_service.ContextService.get_active_regexes" href="#connpy.services.context_service.ContextService.get_active_regexes">get_active_regexes</a></code></li>
|
||||
<li><code><a title="connpy.services.context_service.ContextService.is_default_all_context" href="#connpy.services.context_service.ContextService.is_default_all_context">is_default_all_context</a></code></li>
|
||||
<li><code><a title="connpy.services.context_service.ContextService.list_contexts" href="#connpy.services.context_service.ContextService.list_contexts">list_contexts</a></code></li>
|
||||
<li><code><a title="connpy.services.context_service.ContextService.matches_active_context" href="#connpy.services.context_service.ContextService.matches_active_context">matches_active_context</a></code></li>
|
||||
<li><code><a title="connpy.services.context_service.ContextService.set_active_context" href="#connpy.services.context_service.ContextService.set_active_context">set_active_context</a></code></li>
|
||||
<li><code><a title="connpy.services.context_service.ContextService.update_context" href="#connpy.services.context_service.ContextService.update_context">update_context</a></code></li>
|
||||
<li><code><a title="connpy.services.context_service.ContextService.validate_in_active_context" href="#connpy.services.context_service.ContextService.validate_in_active_context">validate_in_active_context</a></code></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
@@ -48,7 +48,7 @@ el.replaceWith(d);
|
||||
<dl>
|
||||
<dt id="connpy.services.execution_service.ExecutionService"><code class="flex name class">
|
||||
<span>class <span class="ident">ExecutionService</span></span>
|
||||
<span>(</span><span>config=None, remote_stub=None, attempt_tracker=None)</span>
|
||||
<span>(</span><span>config=None, remote_stub=None, attempt_tracker=None, enforce_context: bool = True)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<details class="source">
|
||||
@@ -58,14 +58,33 @@ el.replaceWith(d);
|
||||
<pre><code class="python">class ExecutionService(BaseService):
|
||||
"""Business logic for executing commands on nodes and running automation scripts."""
|
||||
|
||||
def __init__(self, config=None, remote_stub=None, attempt_tracker=None):
|
||||
def __init__(
|
||||
self,
|
||||
config=None,
|
||||
remote_stub=None,
|
||||
attempt_tracker=None,
|
||||
enforce_context: bool = True,
|
||||
):
|
||||
super().__init__(config)
|
||||
self.remote_stub = remote_stub
|
||||
self.attempt_tracker = (
|
||||
attempt_tracker if attempt_tracker is not None else AuthAttemptTracker()
|
||||
)
|
||||
self.enforce_context = bool(enforce_context)
|
||||
self.last_fallback_used: dict[str, bool] = {}
|
||||
|
||||
def _get_context_service(self):
|
||||
if (
|
||||
not getattr(self, "enforce_context", True)
|
||||
or not getattr(self.config, "_enforce_context", True)
|
||||
or (len(sys.argv) > 1 and sys.argv[1] == "api")
|
||||
or not isinstance(getattr(self.config, "config", None), dict)
|
||||
):
|
||||
return None
|
||||
from .context_service import ContextService
|
||||
|
||||
return ContextService(self.config)
|
||||
|
||||
def _is_remote_backend(self) -> bool:
|
||||
"""Return True when execution is configured to run against a remote gRPC backend."""
|
||||
if getattr(self, "remote_stub", None) is not None:
|
||||
@@ -84,10 +103,7 @@ el.replaceWith(d);
|
||||
"connect_timeout and auth_timeout overrides are not supported in remote gRPC mode"
|
||||
)
|
||||
|
||||
def _get_remote_stub(self):
|
||||
"""Return the configured or lazily constructed ExecutionStub for remote gRPC mode."""
|
||||
if getattr(self, "remote_stub", None) is not None:
|
||||
return self.remote_stub
|
||||
def _get_remote_channel(self):
|
||||
cfg = getattr(self.config, "config", None)
|
||||
remote_host = cfg.get("remote_host") if isinstance(cfg, dict) else None
|
||||
if not remote_host:
|
||||
@@ -95,7 +111,7 @@ el.replaceWith(d);
|
||||
|
||||
import grpc
|
||||
|
||||
from connpy.grpc_layer.stubs import AuthClientInterceptor, ExecutionStub
|
||||
from connpy.grpc_layer.stubs import AuthClientInterceptor
|
||||
|
||||
def get_token():
|
||||
env_token = os.environ.get("CONNPY_TOKEN")
|
||||
@@ -111,8 +127,81 @@ el.replaceWith(d);
|
||||
|
||||
channel = grpc.insecure_channel(remote_host)
|
||||
channel = grpc.intercept_channel(channel, AuthClientInterceptor(get_token))
|
||||
return channel, remote_host
|
||||
|
||||
def _get_remote_stub(self):
|
||||
"""Return the configured or lazily constructed ExecutionStub for remote gRPC mode."""
|
||||
if getattr(self, "remote_stub", None) is not None:
|
||||
return self.remote_stub
|
||||
from connpy.grpc_layer.stubs import ExecutionStub
|
||||
|
||||
channel, remote_host = self._get_remote_channel()
|
||||
return ExecutionStub(channel, remote_host=remote_host)
|
||||
|
||||
def _filter_remote_nodes_filter(self, nodes_filter):
|
||||
ctx_svc = self._get_context_service()
|
||||
if ctx_svc is None or ctx_svc.is_default_all_context():
|
||||
return nodes_filter
|
||||
|
||||
if isinstance(nodes_filter, (list, tuple)):
|
||||
permitted = ctx_svc.filter_node_list(result=list(nodes_filter))
|
||||
else:
|
||||
if self.remote_stub is not None and callable(
|
||||
getattr(self.remote_stub, "list_nodes", None)
|
||||
):
|
||||
candidates = self.remote_stub.list_nodes(filter_str=nodes_filter)
|
||||
elif self.remote_stub is not None and callable(
|
||||
getattr(getattr(self.remote_stub, "node_stub", None), "list_nodes", None)
|
||||
):
|
||||
candidates = self.remote_stub.node_stub.list_nodes(filter_str=nodes_filter)
|
||||
elif self.remote_stub is None:
|
||||
from connpy.grpc_layer.stubs import NodeStub
|
||||
|
||||
channel, remote_host = self._get_remote_channel()
|
||||
node_stub = NodeStub(channel, remote_host=remote_host, config=self.config)
|
||||
candidates = node_stub.list_nodes(filter_str=nodes_filter)
|
||||
else:
|
||||
candidates = (
|
||||
self.config._getallnodes(nodes_filter)
|
||||
if hasattr(self.config, "_getallnodes")
|
||||
else []
|
||||
)
|
||||
if nodes_filter:
|
||||
cfg_dict = getattr(self.config, "config", None)
|
||||
case = cfg_dict.get("case", False) if isinstance(cfg_dict, dict) else False
|
||||
flags = 0 if case else re.IGNORECASE
|
||||
candidates = [c for c in candidates if re.search(nodes_filter, c, flags)]
|
||||
permitted = ctx_svc.filter_node_list(result=candidates)
|
||||
|
||||
if not permitted:
|
||||
raise ConnpyError(f"No nodes found matching filter: {nodes_filter}")
|
||||
return [f"^{re.escape(n)}$" for n in permitted]
|
||||
|
||||
def _build_remote_filter_batches(self, nodes_filter):
|
||||
filtered = self._filter_remote_nodes_filter(nodes_filter)
|
||||
if isinstance(filtered, list):
|
||||
return [
|
||||
filtered[i : i + MAX_REMOTE_FILTER_NODES]
|
||||
for i in range(0, len(filtered), MAX_REMOTE_FILTER_NODES)
|
||||
]
|
||||
return [filtered]
|
||||
|
||||
@staticmethod
|
||||
def _aggregate_remote_results(batch_results):
|
||||
if len(batch_results) == 1:
|
||||
return batch_results[0]
|
||||
if all(isinstance(r, dict) for r in batch_results):
|
||||
merged: dict[str, Any] = {}
|
||||
for r in batch_results:
|
||||
merged.update(r)
|
||||
return merged
|
||||
if all(isinstance(r, list) for r in batch_results):
|
||||
merged_list: list[Any] = []
|
||||
for r in batch_results:
|
||||
merged_list.extend(r)
|
||||
return merged_list
|
||||
return batch_results[-1]
|
||||
|
||||
def run_commands(
|
||||
self,
|
||||
nodes_filter: str,
|
||||
@@ -136,21 +225,29 @@ el.replaceWith(d);
|
||||
)
|
||||
|
||||
if self._is_remote_backend():
|
||||
batches = self._build_remote_filter_batches(nodes_filter)
|
||||
stub = self._get_remote_stub()
|
||||
return stub.run_commands(
|
||||
nodes_filter=nodes_filter,
|
||||
commands=commands,
|
||||
variables=variables,
|
||||
parallel=parallel,
|
||||
timeout=timeout if timeout is not None else 20,
|
||||
folder=folder,
|
||||
prompt=prompt,
|
||||
on_node_complete=on_node_complete,
|
||||
logger=logger,
|
||||
name=name or "",
|
||||
)
|
||||
batch_results = [
|
||||
stub.run_commands(
|
||||
nodes_filter=batch,
|
||||
commands=commands,
|
||||
variables=variables,
|
||||
parallel=parallel,
|
||||
timeout=timeout if timeout is not None else 20,
|
||||
folder=folder,
|
||||
prompt=prompt,
|
||||
on_node_complete=on_node_complete,
|
||||
logger=logger,
|
||||
name=name or "",
|
||||
)
|
||||
for batch in batches
|
||||
]
|
||||
return self._aggregate_remote_results(batch_results)
|
||||
|
||||
matched_names = self.config._getallnodes(nodes_filter)
|
||||
ctx_svc = self._get_context_service()
|
||||
if ctx_svc is not None and not ctx_svc.is_default_all_context():
|
||||
matched_names = ctx_svc.filter_node_list(result=matched_names)
|
||||
if not matched_names:
|
||||
raise ConnpyError(f"No nodes found matching filter: {nodes_filter}")
|
||||
|
||||
@@ -224,22 +321,30 @@ el.replaceWith(d);
|
||||
)
|
||||
|
||||
if self._is_remote_backend():
|
||||
batches = self._build_remote_filter_batches(nodes_filter)
|
||||
stub = self._get_remote_stub()
|
||||
return stub.test_commands(
|
||||
nodes_filter=nodes_filter,
|
||||
commands=commands,
|
||||
expected=expected,
|
||||
variables=variables,
|
||||
parallel=parallel,
|
||||
timeout=timeout if timeout is not None else 20,
|
||||
folder=folder or "",
|
||||
prompt=prompt,
|
||||
on_node_complete=on_node_complete,
|
||||
logger=logger,
|
||||
name=name or "",
|
||||
)
|
||||
batch_results = [
|
||||
stub.test_commands(
|
||||
nodes_filter=batch,
|
||||
commands=commands,
|
||||
expected=expected,
|
||||
variables=variables,
|
||||
parallel=parallel,
|
||||
timeout=timeout if timeout is not None else 20,
|
||||
folder=folder or "",
|
||||
prompt=prompt,
|
||||
on_node_complete=on_node_complete,
|
||||
logger=logger,
|
||||
name=name or "",
|
||||
)
|
||||
for batch in batches
|
||||
]
|
||||
return self._aggregate_remote_results(batch_results)
|
||||
|
||||
matched_names = self.config._getallnodes(nodes_filter)
|
||||
ctx_svc = self._get_context_service()
|
||||
if ctx_svc is not None and not ctx_svc.is_default_all_context():
|
||||
matched_names = ctx_svc.filter_node_list(result=matched_names)
|
||||
if not matched_names:
|
||||
raise ConnpyError(f"No nodes found matching filter: {nodes_filter}")
|
||||
|
||||
@@ -361,21 +466,29 @@ el.replaceWith(d);
|
||||
)
|
||||
|
||||
if self._is_remote_backend():
|
||||
batches = self._build_remote_filter_batches(nodes_filter)
|
||||
stub = self._get_remote_stub()
|
||||
return stub.run_commands(
|
||||
nodes_filter=nodes_filter,
|
||||
commands=commands,
|
||||
variables=variables,
|
||||
parallel=parallel,
|
||||
timeout=timeout if timeout is not None else 20,
|
||||
folder=folder,
|
||||
prompt=prompt,
|
||||
on_node_complete=on_node_complete,
|
||||
logger=logger,
|
||||
name=name or "",
|
||||
)
|
||||
batch_results = [
|
||||
stub.run_commands(
|
||||
nodes_filter=batch,
|
||||
commands=commands,
|
||||
variables=variables,
|
||||
parallel=parallel,
|
||||
timeout=timeout if timeout is not None else 20,
|
||||
folder=folder,
|
||||
prompt=prompt,
|
||||
on_node_complete=on_node_complete,
|
||||
logger=logger,
|
||||
name=name or "",
|
||||
)
|
||||
for batch in batches
|
||||
]
|
||||
return self._aggregate_remote_results(batch_results)
|
||||
|
||||
matched_names = self.config._getallnodes(nodes_filter)
|
||||
ctx_svc = self._get_context_service()
|
||||
if ctx_svc is not None and not ctx_svc.is_default_all_context():
|
||||
matched_names = ctx_svc.filter_node_list(result=matched_names)
|
||||
if not matched_names:
|
||||
raise ConnpyError(f"No nodes found matching filter: {nodes_filter}")
|
||||
|
||||
@@ -459,22 +572,30 @@ el.replaceWith(d);
|
||||
)
|
||||
|
||||
if self._is_remote_backend():
|
||||
batches = self._build_remote_filter_batches(nodes_filter)
|
||||
stub = self._get_remote_stub()
|
||||
return stub.test_commands(
|
||||
nodes_filter=nodes_filter,
|
||||
commands=commands,
|
||||
expected=expected,
|
||||
variables=variables,
|
||||
parallel=parallel,
|
||||
timeout=timeout if timeout is not None else 20,
|
||||
folder=folder or "",
|
||||
prompt=prompt,
|
||||
on_node_complete=on_node_complete,
|
||||
logger=logger,
|
||||
name=name or "",
|
||||
)
|
||||
batch_results = [
|
||||
stub.test_commands(
|
||||
nodes_filter=batch,
|
||||
commands=commands,
|
||||
expected=expected,
|
||||
variables=variables,
|
||||
parallel=parallel,
|
||||
timeout=timeout if timeout is not None else 20,
|
||||
folder=folder or "",
|
||||
prompt=prompt,
|
||||
on_node_complete=on_node_complete,
|
||||
logger=logger,
|
||||
name=name or "",
|
||||
)
|
||||
for batch in batches
|
||||
]
|
||||
return self._aggregate_remote_results(batch_results)
|
||||
|
||||
matched_names = self.config._getallnodes(nodes_filter)
|
||||
ctx_svc = self._get_context_service()
|
||||
if ctx_svc is not None and not ctx_svc.is_default_all_context():
|
||||
matched_names = ctx_svc.filter_node_list(result=matched_names)
|
||||
if not matched_names:
|
||||
raise ConnpyError(f"No nodes found matching filter: {nodes_filter}")
|
||||
|
||||
|
||||
@@ -48,7 +48,7 @@ el.replaceWith(d);
|
||||
<dl>
|
||||
<dt id="connpy.services.import_export_service.ImportExportService"><code class="flex name class">
|
||||
<span>class <span class="ident">ImportExportService</span></span>
|
||||
<span>(</span><span>config=None)</span>
|
||||
<span>(</span><span>config=None, enforce_context: bool = True)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<details class="source">
|
||||
@@ -58,6 +58,44 @@ el.replaceWith(d);
|
||||
<pre><code class="python">class ImportExportService(BaseService):
|
||||
"""Business logic for YAML/JSON inventory import and export."""
|
||||
|
||||
def __init__(self, config=None, enforce_context: bool = True):
|
||||
super().__init__(config)
|
||||
self.enforce_context = bool(enforce_context)
|
||||
|
||||
def _get_context_service(self, cfg=None):
|
||||
target_cfg = cfg or self.config
|
||||
if (
|
||||
not getattr(self, "enforce_context", True)
|
||||
or not getattr(target_cfg, "_enforce_context", True)
|
||||
or (len(sys.argv) > 1 and sys.argv[1] == "api")
|
||||
or not isinstance(getattr(target_cfg, "config", None), dict)
|
||||
):
|
||||
return None
|
||||
from .context_service import ContextService
|
||||
|
||||
return ContextService(target_cfg)
|
||||
|
||||
def _get_raw_folders(self, cfg=None) -> list[str]:
|
||||
target_cfg = cfg or self.config
|
||||
if target_cfg is None:
|
||||
return []
|
||||
if (
|
||||
not hasattr(target_cfg, "assert_called")
|
||||
and callable(getattr(target_cfg, "_getallfolders_unlocked", None))
|
||||
and hasattr(target_cfg, "_mutation_lock")
|
||||
):
|
||||
with target_cfg._mutation_lock:
|
||||
return target_cfg._getallfolders_unlocked()
|
||||
return target_cfg._getallfolders()
|
||||
|
||||
def _folder_exists(self, folder_id: str, raw_folders: list[str], cfg=None) -> bool:
|
||||
target_cfg = cfg or self.config
|
||||
cfg_dict = getattr(target_cfg, "config", None)
|
||||
case = cfg_dict.get("case", False) if isinstance(cfg_dict, dict) else False
|
||||
if case:
|
||||
return folder_id in raw_folders
|
||||
return folder_id.lower() in {f.lower() for f in raw_folders}
|
||||
|
||||
def export_to_file(self, file_path, folders=None):
|
||||
"""Export nodes/folders to a YAML file."""
|
||||
if os.path.exists(file_path):
|
||||
@@ -72,46 +110,72 @@ el.replaceWith(d);
|
||||
|
||||
def export_to_dict(self, folders=None):
|
||||
"""Export nodes/folders to a dictionary."""
|
||||
if not folders:
|
||||
ctx_svc = self._get_context_service()
|
||||
ctx_active = ctx_svc is not None and not ctx_svc.is_default_all_context()
|
||||
|
||||
if not folders and not ctx_active:
|
||||
return deepcopy(self.config.connections)
|
||||
else:
|
||||
# Validate folders exist
|
||||
|
||||
raw_folders = self._get_raw_folders()
|
||||
if folders:
|
||||
for f in folders:
|
||||
if f != "@" and f not in self.config._getallfolders():
|
||||
if f != "@" and (
|
||||
not self._folder_exists(f, raw_folders)
|
||||
or (ctx_active and not ctx_svc.matches_active_context(f))
|
||||
):
|
||||
raise NodeNotFoundError(f"Folder '{f}' not found.")
|
||||
|
||||
flat = self.config._getallnodesfull(folders, extract=False)
|
||||
nested = {}
|
||||
for k, v in flat.items():
|
||||
uniques = self.config._explode_unique(k)
|
||||
if not uniques:
|
||||
continue
|
||||
|
||||
if "folder" in uniques and "subfolder" in uniques:
|
||||
f_name = uniques["folder"]
|
||||
s_name = uniques["subfolder"]
|
||||
i_name = uniques["id"]
|
||||
|
||||
if f_name not in nested:
|
||||
nested[f_name] = {"type": "folder"}
|
||||
if s_name not in nested[f_name]:
|
||||
nested[f_name][s_name] = {"type": "subfolder"}
|
||||
|
||||
nested[f_name][s_name][i_name] = v
|
||||
|
||||
elif "folder" in uniques:
|
||||
f_name = uniques["folder"]
|
||||
i_name = uniques["id"]
|
||||
|
||||
if f_name not in nested:
|
||||
nested[f_name] = {"type": "folder"}
|
||||
|
||||
nested[f_name][i_name] = v
|
||||
else:
|
||||
i_name = uniques["id"]
|
||||
nested[i_name] = v
|
||||
|
||||
return nested
|
||||
allowed_folders = []
|
||||
else:
|
||||
allowed_folders = ctx_svc.filter_node_list(result=raw_folders)
|
||||
flat = self.config._getallnodesfull(extract=False)
|
||||
|
||||
if ctx_active:
|
||||
flat = ctx_svc.filter_node_dict(result=flat)
|
||||
|
||||
nested = {}
|
||||
for folder_id in allowed_folders:
|
||||
uniques = self.config._explode_unique(folder_id)
|
||||
if not uniques or "folder" not in uniques:
|
||||
continue
|
||||
f_name = uniques["folder"]
|
||||
if f_name not in nested:
|
||||
nested[f_name] = {"type": "folder"}
|
||||
if "subfolder" in uniques:
|
||||
s_name = uniques["subfolder"]
|
||||
if s_name not in nested[f_name]:
|
||||
nested[f_name][s_name] = {"type": "subfolder"}
|
||||
|
||||
for k, v in flat.items():
|
||||
uniques = self.config._explode_unique(k)
|
||||
if not uniques:
|
||||
continue
|
||||
|
||||
if "folder" in uniques and "subfolder" in uniques:
|
||||
f_name = uniques["folder"]
|
||||
s_name = uniques["subfolder"]
|
||||
i_name = uniques["id"]
|
||||
|
||||
if f_name not in nested:
|
||||
nested[f_name] = {"type": "folder"}
|
||||
if s_name not in nested[f_name]:
|
||||
nested[f_name][s_name] = {"type": "subfolder"}
|
||||
|
||||
nested[f_name][s_name][i_name] = v
|
||||
|
||||
elif "folder" in uniques:
|
||||
f_name = uniques["folder"]
|
||||
i_name = uniques["id"]
|
||||
|
||||
if f_name not in nested:
|
||||
nested[f_name] = {"type": "folder"}
|
||||
|
||||
nested[f_name][i_name] = v
|
||||
else:
|
||||
i_name = uniques["id"]
|
||||
nested[i_name] = v
|
||||
|
||||
return nested
|
||||
|
||||
def import_from_file(self, file_path):
|
||||
"""Import nodes/folders from a YAML file."""
|
||||
@@ -126,42 +190,94 @@ el.replaceWith(d);
|
||||
raise InvalidConfigurationError(f"Failed to read/parse import file: {e}")
|
||||
|
||||
def import_from_dict(self, data):
|
||||
"""Import nodes/folders from a dictionary."""
|
||||
"""Import nodes/folders from a dictionary atomically with context pre-validation."""
|
||||
if not isinstance(data, dict):
|
||||
raise InvalidConfigurationError("Invalid import data format: expected a dictionary of nodes.")
|
||||
raise InvalidConfigurationError(
|
||||
"Invalid import data format: expected a dictionary of nodes."
|
||||
)
|
||||
|
||||
def _traverse_import(node_data, current_folder='', current_subfolder=''):
|
||||
ctx_svc = self._get_context_service()
|
||||
ctx_active = ctx_svc is not None and not ctx_svc.is_default_all_context()
|
||||
raw_folders = self._get_raw_folders() if ctx_active else []
|
||||
planned_ops = []
|
||||
|
||||
def _plan_import(node_data, current_folder="", current_subfolder=""):
|
||||
for k, v in node_data.items():
|
||||
if k == "type":
|
||||
if k == "type" or not isinstance(v, dict):
|
||||
continue
|
||||
if isinstance(v, dict):
|
||||
node_type = v.get("type", "connection")
|
||||
if node_type == "folder":
|
||||
self.config._folder_add(folder=k)
|
||||
_traverse_import(v, current_folder=k, current_subfolder='')
|
||||
elif node_type == "subfolder":
|
||||
self.config._folder_add(folder=current_folder, subfolder=k)
|
||||
_traverse_import(v, current_folder=current_folder, current_subfolder=k)
|
||||
elif node_type == "connection":
|
||||
unique_id = k
|
||||
if current_subfolder:
|
||||
unique_id = f"{k}@{current_subfolder}@{current_folder}"
|
||||
elif current_folder:
|
||||
unique_id = f"{k}@{current_folder}"
|
||||
self._validate_node_name(unique_id)
|
||||
|
||||
kwargs = deepcopy(v)
|
||||
kwargs['id'] = k
|
||||
kwargs['folder'] = current_folder
|
||||
kwargs['subfolder'] = current_subfolder
|
||||
|
||||
self.config._connections_add(**kwargs)
|
||||
else:
|
||||
# Invalid format skip
|
||||
pass
|
||||
node_type = v.get("type", "connection")
|
||||
if node_type == "folder":
|
||||
folder_id = f"@{k}"
|
||||
has_children = any(
|
||||
isinstance(cv, dict) for ck, cv in v.items() if ck != "type"
|
||||
)
|
||||
if ctx_active and (
|
||||
not has_children
|
||||
or (
|
||||
not ctx_svc.matches_active_context(folder_id)
|
||||
and not self._folder_exists(folder_id, raw_folders)
|
||||
)
|
||||
):
|
||||
ctx_svc.validate_in_active_context(folder_id, is_folder=True)
|
||||
planned_ops.append(("folder", k, ""))
|
||||
_plan_import(v, current_folder=k, current_subfolder="")
|
||||
elif node_type == "subfolder":
|
||||
folder_id = f"@{k}@{current_folder}"
|
||||
has_children = any(
|
||||
isinstance(cv, dict) for ck, cv in v.items() if ck != "type"
|
||||
)
|
||||
if ctx_active and (
|
||||
not has_children
|
||||
or (
|
||||
not ctx_svc.matches_active_context(folder_id)
|
||||
and not self._folder_exists(folder_id, raw_folders)
|
||||
)
|
||||
):
|
||||
ctx_svc.validate_in_active_context(folder_id, is_folder=True)
|
||||
planned_ops.append(("folder", current_folder, k))
|
||||
_plan_import(v, current_folder=current_folder, current_subfolder=k)
|
||||
elif node_type == "connection":
|
||||
unique_id = k
|
||||
if current_subfolder:
|
||||
unique_id = f"{k}@{current_subfolder}@{current_folder}"
|
||||
elif current_folder:
|
||||
unique_id = f"{k}@{current_folder}"
|
||||
self._validate_node_name(unique_id)
|
||||
NodeService._validate_node_payload(v)
|
||||
if ctx_svc is not None:
|
||||
ctx_svc.validate_in_active_context(unique_id, is_folder=False)
|
||||
|
||||
_traverse_import(data)
|
||||
self.config._saveconfig(self.config.file)</code></pre>
|
||||
kwargs = deepcopy(v)
|
||||
kwargs["id"] = k
|
||||
kwargs["folder"] = current_folder
|
||||
kwargs["subfolder"] = current_subfolder
|
||||
planned_ops.append(("connection", kwargs))
|
||||
|
||||
_plan_import(data)
|
||||
|
||||
if _supports_transactional_update(self.config):
|
||||
def _mut(cfg):
|
||||
for op in planned_ops:
|
||||
if op[0] == "folder":
|
||||
cfg._folder_add_unlocked(folder=op[1], subfolder=op[2])
|
||||
else:
|
||||
cfg._connections_add_unlocked(**op[1])
|
||||
|
||||
self.config.transactional_update(_mut)
|
||||
return
|
||||
|
||||
snap_connections = deepcopy(self.config.connections)
|
||||
try:
|
||||
for op in planned_ops:
|
||||
if op[0] == "folder":
|
||||
self.config._folder_add(folder=op[1], subfolder=op[2])
|
||||
else:
|
||||
self.config._connections_add(**op[1])
|
||||
self.config._saveconfig(self.config.file)
|
||||
except BaseException:
|
||||
self.config.connections.clear()
|
||||
self.config.connections.update(snap_connections)
|
||||
raise</code></pre>
|
||||
</details>
|
||||
<div class="desc"><p>Business logic for YAML/JSON inventory import and export.</p>
|
||||
<p>Initialize the service.</p>
|
||||
@@ -187,46 +303,72 @@ el.replaceWith(d);
|
||||
</summary>
|
||||
<pre><code class="python">def export_to_dict(self, folders=None):
|
||||
"""Export nodes/folders to a dictionary."""
|
||||
if not folders:
|
||||
ctx_svc = self._get_context_service()
|
||||
ctx_active = ctx_svc is not None and not ctx_svc.is_default_all_context()
|
||||
|
||||
if not folders and not ctx_active:
|
||||
return deepcopy(self.config.connections)
|
||||
else:
|
||||
# Validate folders exist
|
||||
|
||||
raw_folders = self._get_raw_folders()
|
||||
if folders:
|
||||
for f in folders:
|
||||
if f != "@" and f not in self.config._getallfolders():
|
||||
if f != "@" and (
|
||||
not self._folder_exists(f, raw_folders)
|
||||
or (ctx_active and not ctx_svc.matches_active_context(f))
|
||||
):
|
||||
raise NodeNotFoundError(f"Folder '{f}' not found.")
|
||||
|
||||
flat = self.config._getallnodesfull(folders, extract=False)
|
||||
nested = {}
|
||||
for k, v in flat.items():
|
||||
uniques = self.config._explode_unique(k)
|
||||
if not uniques:
|
||||
continue
|
||||
|
||||
if "folder" in uniques and "subfolder" in uniques:
|
||||
f_name = uniques["folder"]
|
||||
s_name = uniques["subfolder"]
|
||||
i_name = uniques["id"]
|
||||
|
||||
if f_name not in nested:
|
||||
nested[f_name] = {"type": "folder"}
|
||||
if s_name not in nested[f_name]:
|
||||
nested[f_name][s_name] = {"type": "subfolder"}
|
||||
|
||||
nested[f_name][s_name][i_name] = v
|
||||
|
||||
elif "folder" in uniques:
|
||||
f_name = uniques["folder"]
|
||||
i_name = uniques["id"]
|
||||
|
||||
if f_name not in nested:
|
||||
nested[f_name] = {"type": "folder"}
|
||||
|
||||
nested[f_name][i_name] = v
|
||||
else:
|
||||
i_name = uniques["id"]
|
||||
nested[i_name] = v
|
||||
|
||||
return nested</code></pre>
|
||||
allowed_folders = []
|
||||
else:
|
||||
allowed_folders = ctx_svc.filter_node_list(result=raw_folders)
|
||||
flat = self.config._getallnodesfull(extract=False)
|
||||
|
||||
if ctx_active:
|
||||
flat = ctx_svc.filter_node_dict(result=flat)
|
||||
|
||||
nested = {}
|
||||
for folder_id in allowed_folders:
|
||||
uniques = self.config._explode_unique(folder_id)
|
||||
if not uniques or "folder" not in uniques:
|
||||
continue
|
||||
f_name = uniques["folder"]
|
||||
if f_name not in nested:
|
||||
nested[f_name] = {"type": "folder"}
|
||||
if "subfolder" in uniques:
|
||||
s_name = uniques["subfolder"]
|
||||
if s_name not in nested[f_name]:
|
||||
nested[f_name][s_name] = {"type": "subfolder"}
|
||||
|
||||
for k, v in flat.items():
|
||||
uniques = self.config._explode_unique(k)
|
||||
if not uniques:
|
||||
continue
|
||||
|
||||
if "folder" in uniques and "subfolder" in uniques:
|
||||
f_name = uniques["folder"]
|
||||
s_name = uniques["subfolder"]
|
||||
i_name = uniques["id"]
|
||||
|
||||
if f_name not in nested:
|
||||
nested[f_name] = {"type": "folder"}
|
||||
if s_name not in nested[f_name]:
|
||||
nested[f_name][s_name] = {"type": "subfolder"}
|
||||
|
||||
nested[f_name][s_name][i_name] = v
|
||||
|
||||
elif "folder" in uniques:
|
||||
f_name = uniques["folder"]
|
||||
i_name = uniques["id"]
|
||||
|
||||
if f_name not in nested:
|
||||
nested[f_name] = {"type": "folder"}
|
||||
|
||||
nested[f_name][i_name] = v
|
||||
else:
|
||||
i_name = uniques["id"]
|
||||
nested[i_name] = v
|
||||
|
||||
return nested</code></pre>
|
||||
</details>
|
||||
<div class="desc"><p>Export nodes/folders to a dictionary.</p></div>
|
||||
</dd>
|
||||
@@ -261,44 +403,96 @@ el.replaceWith(d);
|
||||
<span>Expand source code</span>
|
||||
</summary>
|
||||
<pre><code class="python">def import_from_dict(self, data):
|
||||
"""Import nodes/folders from a dictionary."""
|
||||
"""Import nodes/folders from a dictionary atomically with context pre-validation."""
|
||||
if not isinstance(data, dict):
|
||||
raise InvalidConfigurationError("Invalid import data format: expected a dictionary of nodes.")
|
||||
raise InvalidConfigurationError(
|
||||
"Invalid import data format: expected a dictionary of nodes."
|
||||
)
|
||||
|
||||
def _traverse_import(node_data, current_folder='', current_subfolder=''):
|
||||
ctx_svc = self._get_context_service()
|
||||
ctx_active = ctx_svc is not None and not ctx_svc.is_default_all_context()
|
||||
raw_folders = self._get_raw_folders() if ctx_active else []
|
||||
planned_ops = []
|
||||
|
||||
def _plan_import(node_data, current_folder="", current_subfolder=""):
|
||||
for k, v in node_data.items():
|
||||
if k == "type":
|
||||
if k == "type" or not isinstance(v, dict):
|
||||
continue
|
||||
if isinstance(v, dict):
|
||||
node_type = v.get("type", "connection")
|
||||
if node_type == "folder":
|
||||
self.config._folder_add(folder=k)
|
||||
_traverse_import(v, current_folder=k, current_subfolder='')
|
||||
elif node_type == "subfolder":
|
||||
self.config._folder_add(folder=current_folder, subfolder=k)
|
||||
_traverse_import(v, current_folder=current_folder, current_subfolder=k)
|
||||
elif node_type == "connection":
|
||||
unique_id = k
|
||||
if current_subfolder:
|
||||
unique_id = f"{k}@{current_subfolder}@{current_folder}"
|
||||
elif current_folder:
|
||||
unique_id = f"{k}@{current_folder}"
|
||||
self._validate_node_name(unique_id)
|
||||
|
||||
kwargs = deepcopy(v)
|
||||
kwargs['id'] = k
|
||||
kwargs['folder'] = current_folder
|
||||
kwargs['subfolder'] = current_subfolder
|
||||
|
||||
self.config._connections_add(**kwargs)
|
||||
else:
|
||||
# Invalid format skip
|
||||
pass
|
||||
node_type = v.get("type", "connection")
|
||||
if node_type == "folder":
|
||||
folder_id = f"@{k}"
|
||||
has_children = any(
|
||||
isinstance(cv, dict) for ck, cv in v.items() if ck != "type"
|
||||
)
|
||||
if ctx_active and (
|
||||
not has_children
|
||||
or (
|
||||
not ctx_svc.matches_active_context(folder_id)
|
||||
and not self._folder_exists(folder_id, raw_folders)
|
||||
)
|
||||
):
|
||||
ctx_svc.validate_in_active_context(folder_id, is_folder=True)
|
||||
planned_ops.append(("folder", k, ""))
|
||||
_plan_import(v, current_folder=k, current_subfolder="")
|
||||
elif node_type == "subfolder":
|
||||
folder_id = f"@{k}@{current_folder}"
|
||||
has_children = any(
|
||||
isinstance(cv, dict) for ck, cv in v.items() if ck != "type"
|
||||
)
|
||||
if ctx_active and (
|
||||
not has_children
|
||||
or (
|
||||
not ctx_svc.matches_active_context(folder_id)
|
||||
and not self._folder_exists(folder_id, raw_folders)
|
||||
)
|
||||
):
|
||||
ctx_svc.validate_in_active_context(folder_id, is_folder=True)
|
||||
planned_ops.append(("folder", current_folder, k))
|
||||
_plan_import(v, current_folder=current_folder, current_subfolder=k)
|
||||
elif node_type == "connection":
|
||||
unique_id = k
|
||||
if current_subfolder:
|
||||
unique_id = f"{k}@{current_subfolder}@{current_folder}"
|
||||
elif current_folder:
|
||||
unique_id = f"{k}@{current_folder}"
|
||||
self._validate_node_name(unique_id)
|
||||
NodeService._validate_node_payload(v)
|
||||
if ctx_svc is not None:
|
||||
ctx_svc.validate_in_active_context(unique_id, is_folder=False)
|
||||
|
||||
_traverse_import(data)
|
||||
self.config._saveconfig(self.config.file)</code></pre>
|
||||
kwargs = deepcopy(v)
|
||||
kwargs["id"] = k
|
||||
kwargs["folder"] = current_folder
|
||||
kwargs["subfolder"] = current_subfolder
|
||||
planned_ops.append(("connection", kwargs))
|
||||
|
||||
_plan_import(data)
|
||||
|
||||
if _supports_transactional_update(self.config):
|
||||
def _mut(cfg):
|
||||
for op in planned_ops:
|
||||
if op[0] == "folder":
|
||||
cfg._folder_add_unlocked(folder=op[1], subfolder=op[2])
|
||||
else:
|
||||
cfg._connections_add_unlocked(**op[1])
|
||||
|
||||
self.config.transactional_update(_mut)
|
||||
return
|
||||
|
||||
snap_connections = deepcopy(self.config.connections)
|
||||
try:
|
||||
for op in planned_ops:
|
||||
if op[0] == "folder":
|
||||
self.config._folder_add(folder=op[1], subfolder=op[2])
|
||||
else:
|
||||
self.config._connections_add(**op[1])
|
||||
self.config._saveconfig(self.config.file)
|
||||
except BaseException:
|
||||
self.config.connections.clear()
|
||||
self.config.connections.update(snap_connections)
|
||||
raise</code></pre>
|
||||
</details>
|
||||
<div class="desc"><p>Import nodes/folders from a dictionary.</p></div>
|
||||
<div class="desc"><p>Import nodes/folders from a dictionary atomically with context pre-validation.</p></div>
|
||||
</dd>
|
||||
<dt id="connpy.services.import_export_service.ImportExportService.import_from_file"><code class="name flex">
|
||||
<span>def <span class="ident">import_from_file</span></span>(<span>self, file_path)</span>
|
||||
|
||||
+749
-275
File diff suppressed because it is too large.
Load diff
@@ -48,7 +48,7 @@ el.replaceWith(d);
|
||||
<dl>
|
||||
<dt id="connpy.services.node_service.NodeService"><code class="flex name class">
|
||||
<span>class <span class="ident">NodeService</span></span>
|
||||
<span>(</span><span>config=None)</span>
|
||||
<span>(</span><span>config=None, enforce_context: bool = True)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<details class="source">
|
||||
@@ -73,8 +73,104 @@ el.replaceWith(d);
|
||||
"type",
|
||||
})
|
||||
|
||||
def __init__(self, config=None):
|
||||
def __init__(self, config=None, enforce_context: bool = True):
|
||||
super().__init__(config)
|
||||
self.enforce_context = bool(enforce_context)
|
||||
|
||||
def _get_context_service(self, cfg=None):
|
||||
target_cfg = cfg or self.config
|
||||
if (
|
||||
not getattr(self, "enforce_context", True)
|
||||
or not getattr(target_cfg, "_enforce_context", True)
|
||||
or (len(sys.argv) > 1 and sys.argv[1] == "api")
|
||||
or not isinstance(getattr(target_cfg, "config", None), dict)
|
||||
):
|
||||
return None
|
||||
from .context_service import ContextService
|
||||
|
||||
return ContextService(target_cfg)
|
||||
|
||||
def _get_raw_folders(self, cfg=None) -> list[str]:
|
||||
target_cfg = cfg or self.config
|
||||
if target_cfg is None:
|
||||
return []
|
||||
if (
|
||||
not hasattr(target_cfg, "assert_called")
|
||||
and callable(getattr(target_cfg, "_getallfolders_unlocked", None))
|
||||
and hasattr(target_cfg, "_mutation_lock")
|
||||
):
|
||||
with target_cfg._mutation_lock:
|
||||
return target_cfg._getallfolders_unlocked()
|
||||
return target_cfg._getallfolders()
|
||||
|
||||
def _get_raw_nodes(self, cfg=None) -> list[str]:
|
||||
target_cfg = cfg or self.config
|
||||
if target_cfg is None:
|
||||
return []
|
||||
if (
|
||||
not hasattr(target_cfg, "assert_called")
|
||||
and callable(getattr(target_cfg, "_getallnodes_unlocked", None))
|
||||
and hasattr(target_cfg, "_mutation_lock")
|
||||
):
|
||||
with target_cfg._mutation_lock:
|
||||
return target_cfg._getallnodes_unlocked()
|
||||
return target_cfg._getallnodes()
|
||||
|
||||
def _derive_parent_folder(self, cfg, unique_id: str, is_folder: bool) -> str | None:
|
||||
explode_fn = (
|
||||
cfg._explode_unique_unlocked
|
||||
if (
|
||||
not hasattr(cfg, "assert_called")
|
||||
and callable(getattr(cfg, "_explode_unique_unlocked", None))
|
||||
)
|
||||
else cfg._explode_unique
|
||||
)
|
||||
uniques = explode_fn(unique_id)
|
||||
if is_folder:
|
||||
if (
|
||||
not isinstance(unique_id, str)
|
||||
or not unique_id.startswith("@")
|
||||
or not isinstance(uniques, dict)
|
||||
or "folder" not in uniques
|
||||
):
|
||||
raise InvalidConfigurationError(f"Invalid folder name '{unique_id}'.")
|
||||
if "subfolder" in uniques:
|
||||
return f"@{uniques['folder']}"
|
||||
return None
|
||||
if (
|
||||
not isinstance(unique_id, str)
|
||||
or unique_id.startswith("@")
|
||||
or not isinstance(uniques, dict)
|
||||
or not uniques.get("id")
|
||||
):
|
||||
raise InvalidConfigurationError(f"Invalid node name '{unique_id}'.")
|
||||
if "subfolder" in uniques and "folder" in uniques:
|
||||
return f"@{uniques['subfolder']}@{uniques['folder']}"
|
||||
if "folder" in uniques:
|
||||
return f"@{uniques['folder']}"
|
||||
return None
|
||||
|
||||
def _folder_exists(self, parent_folder: str, raw_folders: list[str], cfg=None) -> bool:
|
||||
target_cfg = cfg or self.config
|
||||
cfg_dict = getattr(target_cfg, "config", None)
|
||||
case = cfg_dict.get("case", False) if isinstance(cfg_dict, dict) else False
|
||||
if case:
|
||||
return parent_folder in raw_folders
|
||||
return parent_folder.lower() in {f.lower() for f in raw_folders}
|
||||
|
||||
def _ensure_in_active_context(
|
||||
self, unique_id: str, *, is_folder: bool = False, not_found_msg: str | None = None
|
||||
) -> None:
|
||||
ctx_svc = self._get_context_service()
|
||||
if (
|
||||
ctx_svc is not None
|
||||
and not ctx_svc.is_default_all_context()
|
||||
and not ctx_svc.matches_active_context(unique_id)
|
||||
):
|
||||
if not_found_msg is not None:
|
||||
raise NodeNotFoundError(not_found_msg)
|
||||
label = "Folder" if is_folder else "Node"
|
||||
raise NodeNotFoundError(f"{label} '{unique_id}' not found.")
|
||||
|
||||
@staticmethod
|
||||
def _validate_node_payload(data):
|
||||
@@ -112,7 +208,11 @@ el.replaceWith(d);
|
||||
if filter_str:
|
||||
flags = re.IGNORECASE if not case_sensitive else 0
|
||||
nodes = [n for n in nodes if re.search(filter_str, n, flags)]
|
||||
|
||||
|
||||
ctx_svc = self._get_context_service()
|
||||
if ctx_svc is not None and not ctx_svc.is_default_all_context():
|
||||
nodes = ctx_svc.filter_node_list(result=nodes)
|
||||
|
||||
if not format_str:
|
||||
return nodes
|
||||
|
||||
@@ -169,10 +269,14 @@ el.replaceWith(d);
|
||||
else:
|
||||
flags = re.IGNORECASE if not case_sensitive else 0
|
||||
folders = [f for f in folders if re.search(filter_str, f, flags)]
|
||||
ctx_svc = self._get_context_service()
|
||||
if ctx_svc is not None and not ctx_svc.is_default_all_context():
|
||||
folders = ctx_svc.filter_node_list(result=folders)
|
||||
return folders
|
||||
|
||||
def get_node_details(self, unique_id):
|
||||
"""Return full configuration dictionary for a specific node."""
|
||||
self._ensure_in_active_context(unique_id, is_folder=False)
|
||||
try:
|
||||
details = self.config.getitem(unique_id)
|
||||
if not details:
|
||||
@@ -190,50 +294,45 @@ el.replaceWith(d);
|
||||
self.config._generate_nodes_cache(nodes=nodes, folders=folders, profiles=profiles)
|
||||
|
||||
def validate_parent_folder(self, unique_id, is_folder=False):
|
||||
"""Check if parent folder exists for a given node unique ID."""
|
||||
if is_folder:
|
||||
uniques = self.config._explode_unique(unique_id)
|
||||
if uniques and "subfolder" in uniques and "folder" in uniques:
|
||||
parent_folder = f"@{uniques['folder']}"
|
||||
if parent_folder not in self.config._getallfolders():
|
||||
raise NodeNotFoundError(f"Folder '{parent_folder}' not found.")
|
||||
else:
|
||||
node_folder = unique_id.partition("@")[2]
|
||||
if node_folder:
|
||||
parent_folder = f"@{node_folder}"
|
||||
if parent_folder not in self.config._getallfolders():
|
||||
raise NodeNotFoundError(f"Folder '{parent_folder}' not found.")
|
||||
|
||||
"""Check if unique_id is in active context and its parent folder exists."""
|
||||
parent_folder = self._derive_parent_folder(self.config, unique_id, is_folder=is_folder)
|
||||
ctx_svc = self._get_context_service()
|
||||
if ctx_svc is not None:
|
||||
ctx_svc.validate_in_active_context(unique_id, is_folder=is_folder)
|
||||
if parent_folder is not None and not self._folder_exists(
|
||||
parent_folder, self._get_raw_folders(), self.config
|
||||
):
|
||||
raise NodeNotFoundError(f"Folder '{parent_folder}' not found.")
|
||||
|
||||
def add_node(self, unique_id, data, is_folder=False):
|
||||
"""Logic for adding a new node or folder to configuration."""
|
||||
if not is_folder:
|
||||
self._validate_node_name(unique_id)
|
||||
self._validate_node_payload(data)
|
||||
self.validate_parent_folder(unique_id, is_folder=is_folder)
|
||||
|
||||
if _supports_transactional_update(self.config):
|
||||
def _mut(cfg):
|
||||
all_nodes = cfg._getallnodes_unlocked()
|
||||
all_folders = cfg._getallfolders_unlocked()
|
||||
parent_folder = self._derive_parent_folder(cfg, unique_id, is_folder=is_folder)
|
||||
ctx_svc = self._get_context_service(cfg)
|
||||
if ctx_svc is not None:
|
||||
ctx_svc.validate_in_active_context(unique_id, is_folder=is_folder)
|
||||
if parent_folder is not None and not self._folder_exists(
|
||||
parent_folder, all_folders, cfg
|
||||
):
|
||||
raise NodeNotFoundError(f"Folder '{parent_folder}' not found.")
|
||||
if is_folder:
|
||||
if unique_id in all_folders:
|
||||
raise NodeAlreadyExistsError(f"Folder '{unique_id}' already exists.")
|
||||
uniques = cfg._explode_unique_unlocked(unique_id)
|
||||
if not uniques:
|
||||
raise InvalidConfigurationError(f"Invalid folder name '{unique_id}'.")
|
||||
if "subfolder" in uniques:
|
||||
parent_folder = f"@{uniques['folder']}"
|
||||
if parent_folder not in all_folders:
|
||||
raise NodeNotFoundError(f"Folder '{parent_folder}' not found.")
|
||||
cfg._folder_add_unlocked(**uniques)
|
||||
else:
|
||||
if unique_id in all_nodes:
|
||||
raise NodeAlreadyExistsError(f"Node '{unique_id}' already exists.")
|
||||
node_folder = unique_id.partition("@")[2]
|
||||
if node_folder:
|
||||
parent_folder = f"@{node_folder}"
|
||||
if parent_folder not in all_folders:
|
||||
raise NodeNotFoundError(f"Folder '{parent_folder}' not found.")
|
||||
payload = deepcopy(data)
|
||||
if "id" not in payload:
|
||||
uniques = cfg._explode_unique_unlocked(unique_id)
|
||||
@@ -290,6 +389,7 @@ el.replaceWith(d);
|
||||
|
||||
def update_node(self, unique_id, data, save=True):
|
||||
"""Explicitly update an existing node."""
|
||||
self._ensure_in_active_context(unique_id, is_folder=False)
|
||||
if _supports_transactional_update(self.config) and save:
|
||||
def _mut(cfg):
|
||||
all_nodes = cfg._getallnodes_unlocked()
|
||||
@@ -316,6 +416,7 @@ el.replaceWith(d);
|
||||
|
||||
def delete_node(self, unique_id, is_folder=False, save=True):
|
||||
"""Logic for deleting a node or folder."""
|
||||
self._ensure_in_active_context(unique_id, is_folder=is_folder)
|
||||
if _supports_transactional_update(self.config) and save:
|
||||
def _mut(cfg):
|
||||
uniques = cfg._explode_unique_unlocked(unique_id)
|
||||
@@ -346,6 +447,7 @@ el.replaceWith(d);
|
||||
|
||||
def connect_node(self, unique_id, sftp=False, debug=False, logger=None):
|
||||
"""Interact with a node directly."""
|
||||
self._ensure_in_active_context(unique_id, is_folder=False)
|
||||
from connpy.core import node
|
||||
|
||||
from ..auth_utils import resolve_fallback_entries
|
||||
@@ -382,10 +484,28 @@ el.replaceWith(d);
|
||||
|
||||
def move_node(self, src_id, dst_id, copy=False):
|
||||
"""Move or copy a node."""
|
||||
self._ensure_in_active_context(
|
||||
src_id, is_folder=False, not_found_msg=f"Source node '{src_id}' not found."
|
||||
)
|
||||
self._validate_node_name(dst_id)
|
||||
self.validate_parent_folder(dst_id, is_folder=False)
|
||||
|
||||
if _supports_transactional_update(self.config):
|
||||
def _mut(cfg):
|
||||
ctx_svc = self._get_context_service(cfg)
|
||||
if (
|
||||
ctx_svc is not None
|
||||
and not ctx_svc.is_default_all_context()
|
||||
and not ctx_svc.matches_active_context(src_id)
|
||||
):
|
||||
raise NodeNotFoundError(f"Source node '{src_id}' not found.")
|
||||
parent_folder = self._derive_parent_folder(cfg, dst_id, is_folder=False)
|
||||
if ctx_svc is not None:
|
||||
ctx_svc.validate_in_active_context(dst_id, is_folder=False)
|
||||
if parent_folder is not None and not self._folder_exists(
|
||||
parent_folder, cfg._getallfolders_unlocked(), cfg
|
||||
):
|
||||
raise NodeNotFoundError(f"Folder '{parent_folder}' not found.")
|
||||
try:
|
||||
node_data = cfg.getitem_unlocked(src_id)
|
||||
except (KeyError, TypeError):
|
||||
@@ -432,12 +552,23 @@ el.replaceWith(d);
|
||||
def bulk_add(self, ids, hosts, common_data):
|
||||
"""Add multiple nodes with shared common configuration."""
|
||||
self._validate_node_payload(common_data)
|
||||
for uid in ids:
|
||||
self.validate_parent_folder(uid, is_folder=False)
|
||||
|
||||
if _supports_transactional_update(self.config):
|
||||
def _build_entries(cfg):
|
||||
all_nodes = cfg._getallnodes_unlocked()
|
||||
all_folders = cfg._getallfolders_unlocked()
|
||||
ctx_svc = self._get_context_service(cfg)
|
||||
planned = []
|
||||
for i, uid in enumerate(ids):
|
||||
parent_folder = self._derive_parent_folder(cfg, uid, is_folder=False)
|
||||
if ctx_svc is not None:
|
||||
ctx_svc.validate_in_active_context(uid, is_folder=False)
|
||||
if parent_folder is not None and not self._folder_exists(
|
||||
parent_folder, all_folders, cfg
|
||||
):
|
||||
raise NodeNotFoundError(f"Folder '{parent_folder}' not found.")
|
||||
if uid in all_nodes:
|
||||
continue
|
||||
try:
|
||||
@@ -555,30 +686,30 @@ el.replaceWith(d);
|
||||
if not is_folder:
|
||||
self._validate_node_name(unique_id)
|
||||
self._validate_node_payload(data)
|
||||
self.validate_parent_folder(unique_id, is_folder=is_folder)
|
||||
|
||||
if _supports_transactional_update(self.config):
|
||||
def _mut(cfg):
|
||||
all_nodes = cfg._getallnodes_unlocked()
|
||||
all_folders = cfg._getallfolders_unlocked()
|
||||
parent_folder = self._derive_parent_folder(cfg, unique_id, is_folder=is_folder)
|
||||
ctx_svc = self._get_context_service(cfg)
|
||||
if ctx_svc is not None:
|
||||
ctx_svc.validate_in_active_context(unique_id, is_folder=is_folder)
|
||||
if parent_folder is not None and not self._folder_exists(
|
||||
parent_folder, all_folders, cfg
|
||||
):
|
||||
raise NodeNotFoundError(f"Folder '{parent_folder}' not found.")
|
||||
if is_folder:
|
||||
if unique_id in all_folders:
|
||||
raise NodeAlreadyExistsError(f"Folder '{unique_id}' already exists.")
|
||||
uniques = cfg._explode_unique_unlocked(unique_id)
|
||||
if not uniques:
|
||||
raise InvalidConfigurationError(f"Invalid folder name '{unique_id}'.")
|
||||
if "subfolder" in uniques:
|
||||
parent_folder = f"@{uniques['folder']}"
|
||||
if parent_folder not in all_folders:
|
||||
raise NodeNotFoundError(f"Folder '{parent_folder}' not found.")
|
||||
cfg._folder_add_unlocked(**uniques)
|
||||
else:
|
||||
if unique_id in all_nodes:
|
||||
raise NodeAlreadyExistsError(f"Node '{unique_id}' already exists.")
|
||||
node_folder = unique_id.partition("@")[2]
|
||||
if node_folder:
|
||||
parent_folder = f"@{node_folder}"
|
||||
if parent_folder not in all_folders:
|
||||
raise NodeNotFoundError(f"Folder '{parent_folder}' not found.")
|
||||
payload = deepcopy(data)
|
||||
if "id" not in payload:
|
||||
uniques = cfg._explode_unique_unlocked(unique_id)
|
||||
@@ -632,12 +763,23 @@ el.replaceWith(d);
|
||||
<pre><code class="python">def bulk_add(self, ids, hosts, common_data):
|
||||
"""Add multiple nodes with shared common configuration."""
|
||||
self._validate_node_payload(common_data)
|
||||
for uid in ids:
|
||||
self.validate_parent_folder(uid, is_folder=False)
|
||||
|
||||
if _supports_transactional_update(self.config):
|
||||
def _build_entries(cfg):
|
||||
all_nodes = cfg._getallnodes_unlocked()
|
||||
all_folders = cfg._getallfolders_unlocked()
|
||||
ctx_svc = self._get_context_service(cfg)
|
||||
planned = []
|
||||
for i, uid in enumerate(ids):
|
||||
parent_folder = self._derive_parent_folder(cfg, uid, is_folder=False)
|
||||
if ctx_svc is not None:
|
||||
ctx_svc.validate_in_active_context(uid, is_folder=False)
|
||||
if parent_folder is not None and not self._folder_exists(
|
||||
parent_folder, all_folders, cfg
|
||||
):
|
||||
raise NodeNotFoundError(f"Folder '{parent_folder}' not found.")
|
||||
if uid in all_nodes:
|
||||
continue
|
||||
try:
|
||||
@@ -712,6 +854,7 @@ el.replaceWith(d);
|
||||
</summary>
|
||||
<pre><code class="python">def connect_node(self, unique_id, sftp=False, debug=False, logger=None):
|
||||
"""Interact with a node directly."""
|
||||
self._ensure_in_active_context(unique_id, is_folder=False)
|
||||
from connpy.core import node
|
||||
|
||||
from ..auth_utils import resolve_fallback_entries
|
||||
@@ -758,6 +901,7 @@ el.replaceWith(d);
|
||||
</summary>
|
||||
<pre><code class="python">def delete_node(self, unique_id, is_folder=False, save=True):
|
||||
"""Logic for deleting a node or folder."""
|
||||
self._ensure_in_active_context(unique_id, is_folder=is_folder)
|
||||
if _supports_transactional_update(self.config) and save:
|
||||
def _mut(cfg):
|
||||
uniques = cfg._explode_unique_unlocked(unique_id)
|
||||
@@ -874,6 +1018,7 @@ el.replaceWith(d);
|
||||
</summary>
|
||||
<pre><code class="python">def get_node_details(self, unique_id):
|
||||
"""Return full configuration dictionary for a specific node."""
|
||||
self._ensure_in_active_context(unique_id, is_folder=False)
|
||||
try:
|
||||
details = self.config.getitem(unique_id)
|
||||
if not details:
|
||||
@@ -906,6 +1051,9 @@ el.replaceWith(d);
|
||||
else:
|
||||
flags = re.IGNORECASE if not case_sensitive else 0
|
||||
folders = [f for f in folders if re.search(filter_str, f, flags)]
|
||||
ctx_svc = self._get_context_service()
|
||||
if ctx_svc is not None and not ctx_svc.is_default_all_context():
|
||||
folders = ctx_svc.filter_node_list(result=folders)
|
||||
return folders</code></pre>
|
||||
</details>
|
||||
<div class="desc"><p>Return all unique folders, optionally filtered by regex.</p></div>
|
||||
@@ -926,7 +1074,11 @@ el.replaceWith(d);
|
||||
if filter_str:
|
||||
flags = re.IGNORECASE if not case_sensitive else 0
|
||||
nodes = [n for n in nodes if re.search(filter_str, n, flags)]
|
||||
|
||||
|
||||
ctx_svc = self._get_context_service()
|
||||
if ctx_svc is not None and not ctx_svc.is_default_all_context():
|
||||
nodes = ctx_svc.filter_node_list(result=nodes)
|
||||
|
||||
if not format_str:
|
||||
return nodes
|
||||
|
||||
@@ -981,10 +1133,28 @@ el.replaceWith(d);
|
||||
</summary>
|
||||
<pre><code class="python">def move_node(self, src_id, dst_id, copy=False):
|
||||
"""Move or copy a node."""
|
||||
self._ensure_in_active_context(
|
||||
src_id, is_folder=False, not_found_msg=f"Source node '{src_id}' not found."
|
||||
)
|
||||
self._validate_node_name(dst_id)
|
||||
self.validate_parent_folder(dst_id, is_folder=False)
|
||||
|
||||
if _supports_transactional_update(self.config):
|
||||
def _mut(cfg):
|
||||
ctx_svc = self._get_context_service(cfg)
|
||||
if (
|
||||
ctx_svc is not None
|
||||
and not ctx_svc.is_default_all_context()
|
||||
and not ctx_svc.matches_active_context(src_id)
|
||||
):
|
||||
raise NodeNotFoundError(f"Source node '{src_id}' not found.")
|
||||
parent_folder = self._derive_parent_folder(cfg, dst_id, is_folder=False)
|
||||
if ctx_svc is not None:
|
||||
ctx_svc.validate_in_active_context(dst_id, is_folder=False)
|
||||
if parent_folder is not None and not self._folder_exists(
|
||||
parent_folder, cfg._getallfolders_unlocked(), cfg
|
||||
):
|
||||
raise NodeNotFoundError(f"Folder '{parent_folder}' not found.")
|
||||
try:
|
||||
node_data = cfg.getitem_unlocked(src_id)
|
||||
except (KeyError, TypeError):
|
||||
@@ -1040,6 +1210,7 @@ el.replaceWith(d);
|
||||
</summary>
|
||||
<pre><code class="python">def update_node(self, unique_id, data, save=True):
|
||||
"""Explicitly update an existing node."""
|
||||
self._ensure_in_active_context(unique_id, is_folder=False)
|
||||
if _supports_transactional_update(self.config) and save:
|
||||
def _mut(cfg):
|
||||
all_nodes = cfg._getallnodes_unlocked()
|
||||
@@ -1075,21 +1246,17 @@ el.replaceWith(d);
|
||||
<span>Expand source code</span>
|
||||
</summary>
|
||||
<pre><code class="python">def validate_parent_folder(self, unique_id, is_folder=False):
|
||||
"""Check if parent folder exists for a given node unique ID."""
|
||||
if is_folder:
|
||||
uniques = self.config._explode_unique(unique_id)
|
||||
if uniques and "subfolder" in uniques and "folder" in uniques:
|
||||
parent_folder = f"@{uniques['folder']}"
|
||||
if parent_folder not in self.config._getallfolders():
|
||||
raise NodeNotFoundError(f"Folder '{parent_folder}' not found.")
|
||||
else:
|
||||
node_folder = unique_id.partition("@")[2]
|
||||
if node_folder:
|
||||
parent_folder = f"@{node_folder}"
|
||||
if parent_folder not in self.config._getallfolders():
|
||||
raise NodeNotFoundError(f"Folder '{parent_folder}' not found.")</code></pre>
|
||||
"""Check if unique_id is in active context and its parent folder exists."""
|
||||
parent_folder = self._derive_parent_folder(self.config, unique_id, is_folder=is_folder)
|
||||
ctx_svc = self._get_context_service()
|
||||
if ctx_svc is not None:
|
||||
ctx_svc.validate_in_active_context(unique_id, is_folder=is_folder)
|
||||
if parent_folder is not None and not self._folder_exists(
|
||||
parent_folder, self._get_raw_folders(), self.config
|
||||
):
|
||||
raise NodeNotFoundError(f"Folder '{parent_folder}' not found.")</code></pre>
|
||||
</details>
|
||||
<div class="desc"><p>Check if parent folder exists for a given node unique ID.</p></div>
|
||||
<div class="desc"><p>Check if unique_id is in active context and its parent folder exists.</p></div>
|
||||
</dd>
|
||||
</dl>
|
||||
<h3>Inherited members</h3>
|
||||
|
||||
@@ -176,18 +176,13 @@ el.replaceWith(d);
|
||||
resolved = deepcopy(node_data)
|
||||
|
||||
auth_referenced_profiles = []
|
||||
other_referenced_profiles = []
|
||||
for key, value in resolved.items():
|
||||
if key == "fallback":
|
||||
continue
|
||||
target_refs = (
|
||||
auth_referenced_profiles if key in ("user", "password") else other_referenced_profiles
|
||||
)
|
||||
for key in ("user", "password"):
|
||||
value = resolved.get(key)
|
||||
if isinstance(value, str):
|
||||
if not is_compose_expression(value) and value.startswith("@"):
|
||||
ref = value[1:]
|
||||
if key != "password" or ref in profiles:
|
||||
target_refs.append(ref)
|
||||
auth_referenced_profiles.append(ref)
|
||||
elif isinstance(value, (list, tuple)):
|
||||
for item in value:
|
||||
if (
|
||||
@@ -197,7 +192,7 @@ el.replaceWith(d);
|
||||
):
|
||||
ref = item[1:]
|
||||
if key != "password" or ref in profiles:
|
||||
target_refs.append(ref)
|
||||
auth_referenced_profiles.append(ref)
|
||||
|
||||
def _get_resolved_ref(prof_name):
|
||||
if prof_name in _visited or _depth >= MAX_PROFILE_DEPTH:
|
||||
@@ -262,15 +257,16 @@ el.replaceWith(d);
|
||||
resolved_list.append(item)
|
||||
resolved[key] = resolved_list
|
||||
|
||||
ordered_profiles = list(dict.fromkeys(auth_referenced_profiles + other_referenced_profiles))
|
||||
for base_profile_name in ordered_profiles:
|
||||
dedup_auth_profiles = list(dict.fromkeys(auth_referenced_profiles))
|
||||
for base_profile_name in dedup_auth_profiles:
|
||||
with suppress(ProfileNotFoundError):
|
||||
base_profile = _get_resolved_ref(base_profile_name)
|
||||
for key, value in base_profile.items():
|
||||
if (key not in resolved or resolved[key] in ("", [], None)) and (
|
||||
value not in ("", [], None) or key not in resolved
|
||||
):
|
||||
resolved[key] = deepcopy(value)
|
||||
for key in ("user", "password", "fallback"):
|
||||
val = base_profile.get(key)
|
||||
if (
|
||||
key not in resolved or resolved[key] in ("", [], None)
|
||||
) and val not in ("", [], None):
|
||||
resolved[key] = deepcopy(val)
|
||||
|
||||
if resolved.get("protocol") in ("", None):
|
||||
try:
|
||||
@@ -503,18 +499,13 @@ el.replaceWith(d);
|
||||
resolved = deepcopy(node_data)
|
||||
|
||||
auth_referenced_profiles = []
|
||||
other_referenced_profiles = []
|
||||
for key, value in resolved.items():
|
||||
if key == "fallback":
|
||||
continue
|
||||
target_refs = (
|
||||
auth_referenced_profiles if key in ("user", "password") else other_referenced_profiles
|
||||
)
|
||||
for key in ("user", "password"):
|
||||
value = resolved.get(key)
|
||||
if isinstance(value, str):
|
||||
if not is_compose_expression(value) and value.startswith("@"):
|
||||
ref = value[1:]
|
||||
if key != "password" or ref in profiles:
|
||||
target_refs.append(ref)
|
||||
auth_referenced_profiles.append(ref)
|
||||
elif isinstance(value, (list, tuple)):
|
||||
for item in value:
|
||||
if (
|
||||
@@ -524,7 +515,7 @@ el.replaceWith(d);
|
||||
):
|
||||
ref = item[1:]
|
||||
if key != "password" or ref in profiles:
|
||||
target_refs.append(ref)
|
||||
auth_referenced_profiles.append(ref)
|
||||
|
||||
def _get_resolved_ref(prof_name):
|
||||
if prof_name in _visited or _depth >= MAX_PROFILE_DEPTH:
|
||||
@@ -589,15 +580,16 @@ el.replaceWith(d);
|
||||
resolved_list.append(item)
|
||||
resolved[key] = resolved_list
|
||||
|
||||
ordered_profiles = list(dict.fromkeys(auth_referenced_profiles + other_referenced_profiles))
|
||||
for base_profile_name in ordered_profiles:
|
||||
dedup_auth_profiles = list(dict.fromkeys(auth_referenced_profiles))
|
||||
for base_profile_name in dedup_auth_profiles:
|
||||
with suppress(ProfileNotFoundError):
|
||||
base_profile = _get_resolved_ref(base_profile_name)
|
||||
for key, value in base_profile.items():
|
||||
if (key not in resolved or resolved[key] in ("", [], None)) and (
|
||||
value not in ("", [], None) or key not in resolved
|
||||
):
|
||||
resolved[key] = deepcopy(value)
|
||||
for key in ("user", "password", "fallback"):
|
||||
val = base_profile.get(key)
|
||||
if (
|
||||
key not in resolved or resolved[key] in ("", [], None)
|
||||
) and val not in ("", [], None):
|
||||
resolved[key] = deepcopy(val)
|
||||
|
||||
if resolved.get("protocol") in ("", None):
|
||||
try:
|
||||
|
||||
@@ -65,7 +65,7 @@ el.replaceWith(d);
|
||||
</dd>
|
||||
<dt id="connpy.services.provider.ServiceProvider"><code class="flex name class">
|
||||
<span>class <span class="ident">ServiceProvider</span></span>
|
||||
<span>(</span><span>config, mode='local', remote_host=None)</span>
|
||||
<span>(</span><span>config, mode='local', remote_host=None, enforce_context: bool = True)</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<details class="source">
|
||||
@@ -75,26 +75,41 @@ el.replaceWith(d);
|
||||
<pre><code class="python">class ServiceProvider:
|
||||
"""Dynamic service backend. Transparently provides local or remote services."""
|
||||
|
||||
def __init__(self, config, mode="local", remote_host=None):
|
||||
def __init__(self, config, mode="local", remote_host=None, enforce_context: bool = True):
|
||||
from ..auth_utils import AuthAttemptTracker
|
||||
|
||||
self.mode = mode
|
||||
self.config = config
|
||||
self.remote_host = remote_host
|
||||
self.enforce_context = bool(enforce_context)
|
||||
self.auth_tracker = AuthAttemptTracker()
|
||||
self.nodes = None
|
||||
self._system = None
|
||||
self._execution = None
|
||||
self._import_export = None
|
||||
self._sync = None
|
||||
self._users = None
|
||||
self._ai = None
|
||||
|
||||
self.set_enforce_context(self.enforce_context)
|
||||
|
||||
if mode == "local":
|
||||
self._init_local()
|
||||
elif mode == "remote":
|
||||
self._init_remote()
|
||||
else:
|
||||
raise ValueError(f"Unknown service mode: {mode}")
|
||||
|
||||
def set_enforce_context(self, enforce_context: bool) -> None:
|
||||
self.enforce_context = bool(enforce_context)
|
||||
if self.config is not None and not hasattr(self.config, "assert_called"):
|
||||
self.config._enforce_context = self.enforce_context
|
||||
for svc in (
|
||||
getattr(self, "nodes", None),
|
||||
self._execution,
|
||||
self._import_export,
|
||||
):
|
||||
if svc is not None and hasattr(svc, "enforce_context"):
|
||||
svc.enforce_context = self.enforce_context
|
||||
|
||||
def _init_local(self):
|
||||
from .config_service import ConfigService
|
||||
@@ -103,7 +118,7 @@ el.replaceWith(d);
|
||||
from .plugin_service import PluginService
|
||||
from .profile_service import ProfileService
|
||||
|
||||
self.nodes = NodeService(self.config)
|
||||
self.nodes = NodeService(self.config, enforce_context=self.enforce_context)
|
||||
self.profiles = ProfileService(self.config)
|
||||
self.config_svc = ConfigService(self.config)
|
||||
self.plugins = PluginService(self.config)
|
||||
@@ -161,7 +176,12 @@ el.replaceWith(d);
|
||||
self.plugins = PluginStub(channel, remote_host=self.remote_host)
|
||||
self.ai = AIStub(channel, remote_host=self.remote_host)
|
||||
self.system = SystemStub(channel, remote_host=self.remote_host)
|
||||
self.execution = ExecutionStub(channel, remote_host=self.remote_host)
|
||||
self.execution = ExecutionStub(
|
||||
channel,
|
||||
remote_host=self.remote_host,
|
||||
config=self.config,
|
||||
node_stub=self.nodes,
|
||||
)
|
||||
self.import_export = ImportExportStub(channel, remote_host=self.remote_host)
|
||||
self.auth = AuthStub(channel, remote_host=self.remote_host)
|
||||
|
||||
@@ -180,10 +200,13 @@ el.replaceWith(d);
|
||||
def execution(self):
|
||||
if self._execution is None and self.mode == "local":
|
||||
from .execution_service import ExecutionService
|
||||
if "attempt_tracker" in inspect.signature(ExecutionService.__init__).parameters:
|
||||
self._execution = ExecutionService(self.config, attempt_tracker=self.auth_tracker)
|
||||
else:
|
||||
self._execution = ExecutionService(self.config)
|
||||
params = inspect.signature(ExecutionService.__init__).parameters
|
||||
kwargs = {}
|
||||
if "attempt_tracker" in params:
|
||||
kwargs["attempt_tracker"] = self.auth_tracker
|
||||
if "enforce_context" in params:
|
||||
kwargs["enforce_context"] = self.enforce_context
|
||||
self._execution = ExecutionService(self.config, **kwargs)
|
||||
return self._execution
|
||||
|
||||
@execution.setter
|
||||
@@ -194,7 +217,13 @@ el.replaceWith(d);
|
||||
def import_export(self):
|
||||
if self._import_export is None and self.mode == "local":
|
||||
from .import_export_service import ImportExportService
|
||||
self._import_export = ImportExportService(self.config)
|
||||
params = inspect.signature(ImportExportService.__init__).parameters
|
||||
if "enforce_context" in params:
|
||||
self._import_export = ImportExportService(
|
||||
self.config, enforce_context=self.enforce_context
|
||||
)
|
||||
else:
|
||||
self._import_export = ImportExportService(self.config)
|
||||
return self._import_export
|
||||
|
||||
@import_export.setter
|
||||
@@ -262,10 +291,13 @@ def ai(self):
|
||||
def execution(self):
|
||||
if self._execution is None and self.mode == "local":
|
||||
from .execution_service import ExecutionService
|
||||
if "attempt_tracker" in inspect.signature(ExecutionService.__init__).parameters:
|
||||
self._execution = ExecutionService(self.config, attempt_tracker=self.auth_tracker)
|
||||
else:
|
||||
self._execution = ExecutionService(self.config)
|
||||
params = inspect.signature(ExecutionService.__init__).parameters
|
||||
kwargs = {}
|
||||
if "attempt_tracker" in params:
|
||||
kwargs["attempt_tracker"] = self.auth_tracker
|
||||
if "enforce_context" in params:
|
||||
kwargs["enforce_context"] = self.enforce_context
|
||||
self._execution = ExecutionService(self.config, **kwargs)
|
||||
return self._execution</code></pre>
|
||||
</details>
|
||||
<div class="desc"></div>
|
||||
@@ -280,7 +312,13 @@ def execution(self):
|
||||
def import_export(self):
|
||||
if self._import_export is None and self.mode == "local":
|
||||
from .import_export_service import ImportExportService
|
||||
self._import_export = ImportExportService(self.config)
|
||||
params = inspect.signature(ImportExportService.__init__).parameters
|
||||
if "enforce_context" in params:
|
||||
self._import_export = ImportExportService(
|
||||
self.config, enforce_context=self.enforce_context
|
||||
)
|
||||
else:
|
||||
self._import_export = ImportExportService(self.config)
|
||||
return self._import_export</code></pre>
|
||||
</details>
|
||||
<div class="desc"></div>
|
||||
@@ -331,6 +369,31 @@ def users(self):
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
</dl>
|
||||
<h3>Methods</h3>
|
||||
<dl>
|
||||
<dt id="connpy.services.provider.ServiceProvider.set_enforce_context"><code class="name flex">
|
||||
<span>def <span class="ident">set_enforce_context</span></span>(<span>self, enforce_context: bool) ‑> None</span>
|
||||
</code></dt>
|
||||
<dd>
|
||||
<details class="source">
|
||||
<summary>
|
||||
<span>Expand source code</span>
|
||||
</summary>
|
||||
<pre><code class="python">def set_enforce_context(self, enforce_context: bool) -> None:
|
||||
self.enforce_context = bool(enforce_context)
|
||||
if self.config is not None and not hasattr(self.config, "assert_called"):
|
||||
self.config._enforce_context = self.enforce_context
|
||||
for svc in (
|
||||
getattr(self, "nodes", None),
|
||||
self._execution,
|
||||
self._import_export,
|
||||
):
|
||||
if svc is not None and hasattr(svc, "enforce_context"):
|
||||
svc.enforce_context = self.enforce_context</code></pre>
|
||||
</details>
|
||||
<div class="desc"></div>
|
||||
</dd>
|
||||
</dl>
|
||||
</dd>
|
||||
</dl>
|
||||
</section>
|
||||
@@ -356,6 +419,7 @@ def users(self):
|
||||
<li><code><a title="connpy.services.provider.ServiceProvider.ai" href="#connpy.services.provider.ServiceProvider.ai">ai</a></code></li>
|
||||
<li><code><a title="connpy.services.provider.ServiceProvider.execution" href="#connpy.services.provider.ServiceProvider.execution">execution</a></code></li>
|
||||
<li><code><a title="connpy.services.provider.ServiceProvider.import_export" href="#connpy.services.provider.ServiceProvider.import_export">import_export</a></code></li>
|
||||
<li><code><a title="connpy.services.provider.ServiceProvider.set_enforce_context" href="#connpy.services.provider.ServiceProvider.set_enforce_context">set_enforce_context</a></code></li>
|
||||
<li><code><a title="connpy.services.provider.ServiceProvider.sync" href="#connpy.services.provider.ServiceProvider.sync">sync</a></code></li>
|
||||
<li><code><a title="connpy.services.provider.ServiceProvider.system" href="#connpy.services.provider.ServiceProvider.system">system</a></code></li>
|
||||
<li><code><a title="connpy.services.provider.ServiceProvider.users" href="#connpy.services.provider.ServiceProvider.users">users</a></code></li>
|
||||
|
||||
Reference in new issue
Block a user