codecraftai-restclient-nsx 1.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. ccai/restclient/nsx/__init__.py +12 -0
  2. ccai/restclient/nsx/apigroups/__init__.py +11 -0
  3. ccai/restclient/nsx/apigroups/basegroup.py +276 -0
  4. ccai/restclient/nsx/apigroups/dfwgroup.py +240 -0
  5. ccai/restclient/nsx/apigroups/loadbalancersgroup.py +250 -0
  6. ccai/restclient/nsx/apigroups/natgroup.py +151 -0
  7. ccai/restclient/nsx/apigroups/securitygroupsgroup.py +142 -0
  8. ccai/restclient/nsx/apigroups/segmentsgroup.py +120 -0
  9. ccai/restclient/nsx/apigroups/t0routersgroup.py +118 -0
  10. ccai/restclient/nsx/apigroups/t1routersgroup.py +118 -0
  11. ccai/restclient/nsx/aspectsnsx.py +89 -0
  12. ccai/restclient/nsx/model/__init__.py +11 -0
  13. ccai/restclient/nsx/model/gateway.py +39 -0
  14. ccai/restclient/nsx/model/realization.py +32 -0
  15. ccai/restclient/nsx/model/security.py +54 -0
  16. ccai/restclient/nsx/model/segment.py +43 -0
  17. ccai/restclient/nsx/model/services.py +68 -0
  18. ccai/restclient/nsx/nsxclient.py +282 -0
  19. ccai/restclient/nsx/nsxrealizationhandle.py +417 -0
  20. ccai/restclient/nsx/nsxsession.py +113 -0
  21. ccai/restclient/nsx/py.typed +0 -0
  22. ccai/restclient/nsx/specs/__init__.py +12 -0
  23. ccai/restclient/nsx/specs/gatewayspec.py +98 -0
  24. ccai/restclient/nsx/specs/securityspec.py +154 -0
  25. ccai/restclient/nsx/specs/segmentspec.py +66 -0
  26. ccai/restclient/nsx/specs/servicesspec.py +206 -0
  27. codecraftai_restclient_nsx-1.2.0.dist-info/METADATA +71 -0
  28. codecraftai_restclient_nsx-1.2.0.dist-info/RECORD +30 -0
  29. codecraftai_restclient_nsx-1.2.0.dist-info/WHEEL +4 -0
  30. codecraftai_restclient_nsx-1.2.0.dist-info/licenses/LICENSE.md +204 -0
@@ -0,0 +1,12 @@
1
+ """
2
+ .. module:: nsx
3
+ :platform: Darwin, Linux, Unix, Windows
4
+ :synopsis: The ``ccai.restclient.nsx`` package — the typed,
5
+ aspect-driven VMware NSX REST client.
6
+
7
+ .. moduleauthor:: Myron Walker <myron.walker@gmail.com>
8
+ """
9
+
10
+ __author__ = "Myron Walker"
11
+ __copyright__ = "Copyright 2026, Code Craft AI LLC"
12
+ __credits__ = []
@@ -0,0 +1,11 @@
1
+ """
2
+ .. module:: apigroups
3
+ :platform: Darwin, Linux, Unix, Windows
4
+ :synopsis: NSX-T Policy API operation groups.
5
+
6
+ .. moduleauthor:: Myron Walker <myron.walker@gmail.com>
7
+ """
8
+
9
+ __author__ = "Myron Walker"
10
+ __copyright__ = "Copyright 2025, Code Craft AI LLC"
11
+ __credits__ = []
@@ -0,0 +1,276 @@
1
+ """
2
+ .. module:: basegroup
3
+ :platform: Darwin, Linux, Unix, Windows
4
+ :synopsis: Shared base class for every NSX-T ``*Group`` API surface.
5
+ Adds Policy-API URL composition and cursor-paging helpers on top
6
+ of the generic :class:`RestApiGroup`.
7
+
8
+ .. moduleauthor:: Myron Walker <myron.walker@gmail.com>
9
+ """
10
+
11
+ __author__ = "Myron Walker"
12
+ __copyright__ = "Copyright 2025, Code Craft AI LLC"
13
+ __credits__ = []
14
+
15
+
16
+ import os
17
+
18
+ from http import HTTPStatus
19
+ from typing import Any, Dict, List, Optional, TYPE_CHECKING
20
+
21
+ from ccai.errors.exceptions import SemanticError
22
+ from ccai.errors.raising import raise_for_http_status
23
+ from ccai.restclient.base.restapigroup import RestApiGroup
24
+
25
+
26
+ if TYPE_CHECKING:
27
+ from ccai.restclient.nsx.aspectsnsx import AspectsNsx
28
+ from ccai.restclient.nsx.nsxclient import NsxClient
29
+
30
+
31
+ _POLICY_PREFIX = "/policy/api/v1/"
32
+
33
+
34
+ class BaseGroup(RestApiGroup):
35
+ """
36
+ Common ancestor for every NSX-T Policy API group.
37
+
38
+ Subclasses MUST set :data:`BASE_LEAF` to a value that begins
39
+ with ``/policy/api/v1/`` so the client knows it is composing
40
+ against the Policy API root. The prefix is validated at
41
+ subclass-registration time so misconfiguration fails fast.
42
+ """
43
+
44
+ BASE_LEAF: str = ""
45
+
46
+ def __init_subclass__(cls, **kwargs) -> None:
47
+ """
48
+ Validate ``BASE_LEAF`` of subclasses at class-definition
49
+ time.
50
+
51
+ :returns: ``None``
52
+
53
+ :raises: SemanticError
54
+ """
55
+ super().__init_subclass__(**kwargs)
56
+ if cls is BaseGroup:
57
+ return None
58
+
59
+ base = cls.BASE_LEAF
60
+ if base is None or len(base) == 0:
61
+ err_msg_lines = [
62
+ "NSX API group must declare a non-empty BASE_LEAF.",
63
+ "CLASS: {}".format(cls.__name__),
64
+ ]
65
+ err_msg = os.linesep.join(err_msg_lines)
66
+ raise SemanticError(err_msg)
67
+
68
+ if not base.startswith(_POLICY_PREFIX):
69
+ err_msg_lines = [
70
+ "NSX API group BASE_LEAF must begin with "
71
+ "'/policy/api/v1/'.",
72
+ "CLASS: {}".format(cls.__name__),
73
+ "GOT: {!r}".format(base),
74
+ ]
75
+ err_msg = os.linesep.join(err_msg_lines)
76
+ raise SemanticError(err_msg)
77
+
78
+ return None
79
+
80
+ def __init__(self, client: "NsxClient") -> None:
81
+ """
82
+ Initialise the group with a back-reference to the client.
83
+
84
+ :param client: Owning :class:`NsxClient` instance.
85
+
86
+ :returns: ``None``
87
+ """
88
+ super().__init__(client)
89
+ return
90
+
91
+ # ------------------------------------------------------------------
92
+ # URL composition
93
+ # ------------------------------------------------------------------
94
+
95
+ def compose_url(self, *, parts: Optional[List[str]] = None) -> str:
96
+ """
97
+ Compose an absolute URL by joining BASE_LEAF with any
98
+ additional path parts.
99
+
100
+ :param parts: Optional list of additional path segments
101
+ appended after BASE_LEAF.
102
+
103
+ :returns: The absolute URL composed against the client.
104
+ """
105
+ client = self.client
106
+ if parts is None or len(parts) == 0:
107
+ leaf = self.BASE_LEAF
108
+ else:
109
+ leaf = self.build_leaf(parts=parts)
110
+ if not leaf.startswith("/"):
111
+ leaf = "/" + leaf
112
+
113
+ rtnval = client.build_url(leaf=leaf)
114
+ return rtnval
115
+
116
+ # ------------------------------------------------------------------
117
+ # HTTP helpers
118
+ # ------------------------------------------------------------------
119
+
120
+ def get_json(
121
+ self,
122
+ *,
123
+ url: str,
124
+ aspects: "AspectsNsx",
125
+ params: Optional[Dict[str, Any]] = None,
126
+ context: str,
127
+ ) -> Any:
128
+ """
129
+ Issue a GET, validate the status, and return the parsed
130
+ JSON body.
131
+
132
+ :param url: Fully-qualified request URL.
133
+ :param aspects: Behaviour controls.
134
+ :param params: Optional query parameters.
135
+ :param context: Context string used in error reporting.
136
+
137
+ :returns: The parsed JSON body.
138
+ """
139
+ client = self.client
140
+ session = client.ensure_session(aspects=aspects)
141
+ resp = session.get(
142
+ url,
143
+ params=params,
144
+ timeout=aspects.completion_timeout,
145
+ )
146
+ if resp.status_code != HTTPStatus.OK:
147
+ raise_for_http_status(
148
+ resp.status_code, resp.content, url, context=context
149
+ )
150
+ rtnval = resp.json()
151
+ return rtnval
152
+
153
+ def patch_json(
154
+ self,
155
+ *,
156
+ url: str,
157
+ body: Dict[str, Any],
158
+ aspects: "AspectsNsx",
159
+ context: str,
160
+ ) -> Any:
161
+ """
162
+ Issue a PATCH (the NSX-T policy upsert verb), validate the
163
+ status, and return the parsed JSON body.
164
+
165
+ :param url: Fully-qualified request URL.
166
+ :param body: Request body dictionary.
167
+ :param aspects: Behaviour controls.
168
+ :param context: Context string used in error reporting.
169
+
170
+ :returns: The parsed JSON body, or ``None`` when the manager
171
+ returns an empty body.
172
+ """
173
+ client = self.client
174
+ session = client.ensure_session(aspects=aspects)
175
+ resp = session.patch(
176
+ url,
177
+ json=body,
178
+ timeout=aspects.completion_timeout,
179
+ )
180
+ if resp.status_code not in (HTTPStatus.OK, HTTPStatus.CREATED):
181
+ raise_for_http_status(
182
+ resp.status_code, resp.content, url, context=context
183
+ )
184
+ rtnval: Any = None
185
+ content = resp.content
186
+ if content is not None and len(content) > 0:
187
+ rtnval = resp.json()
188
+ return rtnval
189
+
190
+ def delete_resource(
191
+ self,
192
+ *,
193
+ url: str,
194
+ aspects: "AspectsNsx",
195
+ context: str,
196
+ ) -> None:
197
+ """
198
+ Issue a DELETE and validate the status.
199
+
200
+ :param url: Fully-qualified request URL.
201
+ :param aspects: Behaviour controls.
202
+ :param context: Context string used in error reporting.
203
+
204
+ :returns: ``None``
205
+ """
206
+ client = self.client
207
+ session = client.ensure_session(aspects=aspects)
208
+ resp = session.delete(url, timeout=aspects.completion_timeout)
209
+ if resp.status_code not in (HTTPStatus.OK, HTTPStatus.NO_CONTENT):
210
+ raise_for_http_status(
211
+ resp.status_code, resp.content, url, context=context
212
+ )
213
+ return None
214
+
215
+ # ------------------------------------------------------------------
216
+ # Cursor paging
217
+ # ------------------------------------------------------------------
218
+
219
+ def list_all(
220
+ self,
221
+ *,
222
+ url: str,
223
+ aspects: "AspectsNsx",
224
+ context: str,
225
+ page_size: Optional[int] = None,
226
+ ) -> List[Dict[str, Any]]:
227
+ """
228
+ Enumerate every item of an NSX-T Policy list endpoint,
229
+ following the ``cursor`` token across pages.
230
+
231
+ NSX-T Policy list responses carry a ``results`` array and an
232
+ optional ``cursor`` string. When the ``cursor`` is absent
233
+ the final page has been reached.
234
+
235
+ :param url: Fully-qualified list-endpoint URL.
236
+ :param aspects: Behaviour controls.
237
+ :param context: Context string used in error reporting.
238
+ :param page_size: Optional ``page_size`` query parameter.
239
+
240
+ :returns: The accumulated list of result dictionaries.
241
+ """
242
+ rtnval: List[Dict[str, Any]] = []
243
+ cursor: Optional[str] = None
244
+
245
+ while True:
246
+ params: Dict[str, Any] = {}
247
+ if page_size is not None:
248
+ params["page_size"] = page_size
249
+ if cursor is not None:
250
+ params["cursor"] = cursor
251
+
252
+ page = self.get_json(
253
+ url=url,
254
+ aspects=aspects,
255
+ params=params,
256
+ context=context,
257
+ )
258
+
259
+ results = page.get("results")
260
+ if results is None:
261
+ err_msg_lines = [
262
+ "NSX-T list response missing 'results' field.",
263
+ "CONTEXT: {}".format(context),
264
+ "URL: {}".format(url),
265
+ ]
266
+ err_msg = os.linesep.join(err_msg_lines)
267
+ raise SemanticError(err_msg)
268
+
269
+ for item in results:
270
+ rtnval.append(item)
271
+
272
+ cursor = page.get("cursor")
273
+ if cursor is None:
274
+ break
275
+
276
+ return rtnval
@@ -0,0 +1,240 @@
1
+ """
2
+ .. module:: dfwgroup
3
+ :platform: Darwin, Linux, Unix, Windows
4
+ :synopsis: Distributed-firewall API group for :class:`NsxClient`.
5
+
6
+ .. moduleauthor:: Myron Walker <myron.walker@gmail.com>
7
+ """
8
+
9
+ __author__ = "Myron Walker"
10
+ __copyright__ = "Copyright 2025, Code Craft AI LLC"
11
+ __credits__ = []
12
+
13
+
14
+ from typing import List
15
+
16
+ from ccai.restclient.nsx.apigroups.basegroup import BaseGroup
17
+ from ccai.restclient.nsx.aspectsnsx import AspectsNsx, DEFAULT_NSX_ASPECTS
18
+ from ccai.restclient.nsx.model.security import DfwPolicy, DfwRule
19
+ from ccai.restclient.nsx.nsxrealizationhandle import NsxRealizationHandle
20
+ from ccai.restclient.nsx.specs.securityspec import DfwPolicySpec, DfwRuleSpec
21
+
22
+
23
+ _DEFAULT_DOMAIN = "default"
24
+
25
+
26
+ class DfwGroup(BaseGroup):
27
+ """
28
+ Operations on the NSX-T distributed firewall: security policies
29
+ and their rules
30
+ (``/policy/api/v1/infra/domains/default/security-policies``).
31
+ """
32
+
33
+ BASE_LEAF = "/policy/api/v1/infra/domains"
34
+
35
+ # ------------------------------------------------------------------
36
+ # Security policies
37
+ # ------------------------------------------------------------------
38
+
39
+ def list_policies(
40
+ self,
41
+ *,
42
+ domain: str = _DEFAULT_DOMAIN,
43
+ aspects: AspectsNsx = DEFAULT_NSX_ASPECTS,
44
+ ) -> List[DfwPolicy]:
45
+ """
46
+ List every DFW security policy within a domain.
47
+
48
+ :param domain: The policy domain id.
49
+ :param aspects: Behaviour controls.
50
+
51
+ :returns: List of :class:`DfwPolicy`.
52
+ """
53
+ url = self.compose_url(parts=[domain, "security-policies"])
54
+ items = self.list_all(
55
+ url=url, aspects=aspects, context="DfwGroup.list_policies"
56
+ )
57
+ rtnval = [DfwPolicy.from_dict(item) for item in items]
58
+ return rtnval
59
+
60
+ def get_policy(
61
+ self,
62
+ *,
63
+ policy_id: str,
64
+ domain: str = _DEFAULT_DOMAIN,
65
+ aspects: AspectsNsx = DEFAULT_NSX_ASPECTS,
66
+ ) -> DfwPolicy:
67
+ """
68
+ Retrieve a single DFW security policy by id.
69
+
70
+ :param policy_id: The security policy identifier.
71
+ :param domain: The policy domain id.
72
+ :param aspects: Behaviour controls.
73
+
74
+ :returns: A :class:`DfwPolicy`.
75
+ """
76
+ url = self.compose_url(
77
+ parts=[domain, "security-policies", policy_id]
78
+ )
79
+ body = self.get_json(
80
+ url=url, aspects=aspects, context="DfwGroup.get_policy"
81
+ )
82
+ rtnval = DfwPolicy.from_dict(body)
83
+ return rtnval
84
+
85
+ def create_or_update_policy(
86
+ self,
87
+ *,
88
+ policy_id: str,
89
+ spec: DfwPolicySpec,
90
+ domain: str = _DEFAULT_DOMAIN,
91
+ aspects: AspectsNsx = DEFAULT_NSX_ASPECTS,
92
+ ) -> NsxRealizationHandle:
93
+ """
94
+ Create or update a DFW security policy (upsert via PATCH).
95
+
96
+ :param policy_id: The security policy identifier.
97
+ :param spec: A :class:`DfwPolicySpec`.
98
+ :param domain: The policy domain id.
99
+ :param aspects: Behaviour controls.
100
+
101
+ :returns: An :class:`NsxRealizationHandle`.
102
+ """
103
+ url = self.compose_url(
104
+ parts=[domain, "security-policies", policy_id]
105
+ )
106
+ self.patch_json(
107
+ url=url,
108
+ body=spec.to_dict(),
109
+ aspects=aspects,
110
+ context="DfwGroup.create_or_update_policy",
111
+ )
112
+ intent_path = "/infra/domains/{}/security-policies/{}".format(
113
+ domain, policy_id
114
+ )
115
+ rtnval = NsxRealizationHandle(
116
+ intent_path=intent_path, client=self.client
117
+ )
118
+ return rtnval
119
+
120
+ def delete_policy(
121
+ self,
122
+ *,
123
+ policy_id: str,
124
+ domain: str = _DEFAULT_DOMAIN,
125
+ aspects: AspectsNsx = DEFAULT_NSX_ASPECTS,
126
+ ) -> None:
127
+ """
128
+ Delete a DFW security policy by id.
129
+
130
+ :param policy_id: The security policy identifier.
131
+ :param domain: The policy domain id.
132
+ :param aspects: Behaviour controls.
133
+
134
+ :returns: ``None``
135
+ """
136
+ url = self.compose_url(
137
+ parts=[domain, "security-policies", policy_id]
138
+ )
139
+ self.delete_resource(
140
+ url=url, aspects=aspects, context="DfwGroup.delete_policy"
141
+ )
142
+ return None
143
+
144
+ # ------------------------------------------------------------------
145
+ # Rules
146
+ # ------------------------------------------------------------------
147
+
148
+ def list_rules(
149
+ self,
150
+ *,
151
+ policy_id: str,
152
+ domain: str = _DEFAULT_DOMAIN,
153
+ aspects: AspectsNsx = DEFAULT_NSX_ASPECTS,
154
+ ) -> List[DfwRule]:
155
+ """
156
+ List every rule within a DFW security policy.
157
+
158
+ :param policy_id: The security policy identifier.
159
+ :param domain: The policy domain id.
160
+ :param aspects: Behaviour controls.
161
+
162
+ :returns: List of :class:`DfwRule`.
163
+ """
164
+ url = self.compose_url(
165
+ parts=[domain, "security-policies", policy_id, "rules"]
166
+ )
167
+ items = self.list_all(
168
+ url=url, aspects=aspects, context="DfwGroup.list_rules"
169
+ )
170
+ rtnval = [DfwRule.from_dict(item) for item in items]
171
+ return rtnval
172
+
173
+ def create_or_update_rule(
174
+ self,
175
+ *,
176
+ policy_id: str,
177
+ rule_id: str,
178
+ spec: DfwRuleSpec,
179
+ domain: str = _DEFAULT_DOMAIN,
180
+ aspects: AspectsNsx = DEFAULT_NSX_ASPECTS,
181
+ ) -> NsxRealizationHandle:
182
+ """
183
+ Create or update a DFW rule (policy upsert via PATCH).
184
+
185
+ :param policy_id: The owning security policy identifier.
186
+ :param rule_id: The rule identifier.
187
+ :param spec: A :class:`DfwRuleSpec`.
188
+ :param domain: The policy domain id.
189
+ :param aspects: Behaviour controls.
190
+
191
+ :returns: An :class:`NsxRealizationHandle`.
192
+ """
193
+ url = self.compose_url(
194
+ parts=[
195
+ domain, "security-policies", policy_id, "rules", rule_id
196
+ ]
197
+ )
198
+ self.patch_json(
199
+ url=url,
200
+ body=spec.to_dict(),
201
+ aspects=aspects,
202
+ context="DfwGroup.create_or_update_rule",
203
+ )
204
+ intent_path = (
205
+ "/infra/domains/{}/security-policies/{}/rules/{}".format(
206
+ domain, policy_id, rule_id
207
+ )
208
+ )
209
+ rtnval = NsxRealizationHandle(
210
+ intent_path=intent_path, client=self.client
211
+ )
212
+ return rtnval
213
+
214
+ def delete_rule(
215
+ self,
216
+ *,
217
+ policy_id: str,
218
+ rule_id: str,
219
+ domain: str = _DEFAULT_DOMAIN,
220
+ aspects: AspectsNsx = DEFAULT_NSX_ASPECTS,
221
+ ) -> None:
222
+ """
223
+ Delete a DFW rule by id.
224
+
225
+ :param policy_id: The owning security policy identifier.
226
+ :param rule_id: The rule identifier.
227
+ :param domain: The policy domain id.
228
+ :param aspects: Behaviour controls.
229
+
230
+ :returns: ``None``
231
+ """
232
+ url = self.compose_url(
233
+ parts=[
234
+ domain, "security-policies", policy_id, "rules", rule_id
235
+ ]
236
+ )
237
+ self.delete_resource(
238
+ url=url, aspects=aspects, context="DfwGroup.delete_rule"
239
+ )
240
+ return None