saltext.noderings 0.1.0__py2.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.
@@ -0,0 +1,323 @@
1
+ """
2
+ Firewall rule validation, conversion and reconciliation.
3
+ """
4
+
5
+ import ipaddress
6
+ import re
7
+
8
+ from saltext.noderings.utils.client import is_not_found
9
+ from saltext.noderings.utils.client import trim_enum
10
+
11
+ PROTOCOLS = [
12
+ "tcp",
13
+ "udp",
14
+ "sctp",
15
+ "ipv6",
16
+ "icmp",
17
+ "icmpv6",
18
+ "esp",
19
+ "ah",
20
+ "ipsec",
21
+ "gre",
22
+ "ipip",
23
+ "vxlan",
24
+ "l2tp",
25
+ "geneve",
26
+ "any",
27
+ "igmp",
28
+ "ggp",
29
+ "ipencap",
30
+ "st",
31
+ "egp",
32
+ "igp",
33
+ "pup",
34
+ "hmp",
35
+ "xns_idp",
36
+ "rdp",
37
+ "iso_tp4",
38
+ "dccp",
39
+ "xtp",
40
+ "ddp",
41
+ "idpr_cmtp",
42
+ "ipv6_route",
43
+ "ipv6_frag",
44
+ "idrp",
45
+ "rsvp",
46
+ "skip",
47
+ "ipv6_icmp",
48
+ "ipv6_nonxt",
49
+ "ipv6_opts",
50
+ "vmtp",
51
+ "eigrp",
52
+ "ospf",
53
+ "ax_25",
54
+ "etherip",
55
+ "encap",
56
+ "pim",
57
+ "ipcomp",
58
+ "vrrp",
59
+ "isis",
60
+ "fc",
61
+ "mobility_header",
62
+ "udplite",
63
+ "mpls_in_ip",
64
+ "hip",
65
+ "shim6",
66
+ "wesp",
67
+ "rohc",
68
+ ]
69
+ PORT_PROTOCOLS = ["tcp", "udp", "sctp", "dccp", "udplite"]
70
+ MAX_RULES = 50
71
+ _PORTS_RE = re.compile(r"^(\d{1,5})(?:-(\d{1,5}))?$")
72
+
73
+
74
+ def parse_prefix(value):
75
+ """'10.0.0.0/8' or '10.0.0.1' -> ip_network (strict=False keeps host bits out)."""
76
+ return ipaddress.ip_network(str(value).strip(), strict=False)
77
+
78
+
79
+ def prefixes_to_api(cidrs):
80
+ out = []
81
+ for c in cidrs:
82
+ net = parse_prefix(c)
83
+ out.append({"ip": str(net.network_address), "prefix": net.prefixlen})
84
+ return out
85
+
86
+
87
+ def prefixes_from_api(prefixes):
88
+ return [f"{p.get('ip')}/{int(p.get('prefix') or 0)}" for p in prefixes or []]
89
+
90
+
91
+ def canonical_cidr(c):
92
+ try:
93
+ return str(parse_prefix(c))
94
+ except ValueError:
95
+ return str(c).strip().lower()
96
+
97
+
98
+ def validate_rule(rule, index):
99
+ """Return an error message for one rule, or None."""
100
+ where = f"rule {index}"
101
+ if (rule.get("protocol") or "tcp") not in PROTOCOLS:
102
+ return (
103
+ f"{where}: unknown protocol {rule.get('protocol')!r}; use one of {', '.join(PROTOCOLS)}"
104
+ )
105
+ src, dst = rule.get("source") or {}, rule.get("destination") or {}
106
+
107
+ def count(e):
108
+ return sum(
109
+ len(e.get(k) or []) for k in ("cidrs", "address_group_ids", "address_groups", "vm_tags")
110
+ )
111
+
112
+ if not count(src) and not count(dst):
113
+ return f"{where} needs a source or destination. To match any IPv4 address use cidrs: ['0.0.0.0/0']; for IPv6 add a second rule with ['::/0']."
114
+ for side, e in (("source", src), ("destination", dst)):
115
+ cidrs = e.get("cidrs") or []
116
+ for c in cidrs:
117
+ try:
118
+ parse_prefix(c)
119
+ except ValueError:
120
+ return f"{where} {side}: {c!r} is not an IP address or CIDR"
121
+ anys = [c for c in cidrs if parse_prefix(c).prefixlen == 0]
122
+ if anys and count(e) > 1:
123
+ return f"{where} {side}: {' and '.join(anys)} matches every address, so it must be the only entry on that side. Write two rules to match both IPv4 and IPv6."
124
+ for name in ("source_ports", "destination_ports"):
125
+ v = rule.get(name)
126
+ if v is None:
127
+ continue
128
+ if rule.get("protocol") not in PORT_PROTOCOLS:
129
+ return f"{where}: protocol {rule.get('protocol')} has no ports; {name} only works with {', '.join(PORT_PROTOCOLS)}"
130
+ m = _PORTS_RE.match(str(v).strip())
131
+ lo = int(m.group(1)) if m else 0
132
+ hi = int(m.group(2) or lo) if m else 0
133
+ if not m or not 1 <= lo <= hi <= 65535:
134
+ return f"{where}: {name} {v!r} must be one port such as 443 or one range such as 8000-8100. Lists such as 80,443 are not supported; write one rule per port or range."
135
+ return None
136
+
137
+
138
+ def _endpoint_to_api(e, group_ids_by_name):
139
+ if not e:
140
+ return None
141
+ out = {}
142
+ cidrs = [canonical_cidr(c) for c in e.get("cidrs") or []]
143
+ if cidrs:
144
+ out["ips"] = {"ips": sorted(cidrs)}
145
+ ids = [i.lower() for i in e.get("address_group_ids") or []]
146
+ for name in e.get("address_groups") or []:
147
+ ids.append(group_ids_by_name[name].lower())
148
+ if ids:
149
+ out["addressGroupIds"] = {"addressGroupIds": sorted(set(ids))}
150
+ tags = e.get("vm_tags") or []
151
+ if tags:
152
+ out["vmTags"] = {"tags": sorted(set(tags))}
153
+ return out or None
154
+
155
+
156
+ def rule_to_api(rule, group_ids_by_name):
157
+ body = {
158
+ "action": f"FIREWALL_ACTION_{rule['action'].upper()}",
159
+ "protocol": f"FIREWALL_PROTOCOL_{(rule.get('protocol') or 'tcp').upper()}",
160
+ "direction": f"FIREWALL_DIRECTION_{rule['direction'].upper()}",
161
+ }
162
+ src = _endpoint_to_api(rule.get("source"), group_ids_by_name)
163
+ dst = _endpoint_to_api(rule.get("destination"), group_ids_by_name)
164
+ if src:
165
+ body["source"] = src
166
+ if dst:
167
+ body["destination"] = dst
168
+ if rule.get("source_ports"):
169
+ body["sourcePorts"] = str(rule["source_ports"]).strip()
170
+ if rule.get("destination_ports"):
171
+ body["destinationPorts"] = str(rule["destination_ports"]).strip()
172
+ return body
173
+
174
+
175
+ def _endpoint_key(e):
176
+ if not e:
177
+ return ""
178
+ parts = []
179
+ ips = sorted(canonical_cidr(c) for c in ((e.get("ips") or {}).get("ips") or []))
180
+ if ips:
181
+ parts.append(f"ips={','.join(ips)}")
182
+ groups = sorted(
183
+ g.lower() for g in ((e.get("addressGroupIds") or {}).get("addressGroupIds") or [])
184
+ )
185
+ if groups:
186
+ parts.append(f"groups={','.join(groups)}")
187
+ tags = sorted((e.get("vmTags") or {}).get("tags") or [])
188
+ if tags:
189
+ parts.append(f"tags={','.join(tags)}")
190
+ return ";".join(parts)
191
+
192
+
193
+ def same_rule(a, b):
194
+ """Compare two API rule bodies, ignoring list order."""
195
+ return (
196
+ a.get("action") == b.get("action")
197
+ and a.get("protocol") == b.get("protocol")
198
+ and a.get("direction") == b.get("direction")
199
+ and (a.get("sourcePorts") or "") == (b.get("sourcePorts") or "")
200
+ and (a.get("destinationPorts") or "") == (b.get("destinationPorts") or "")
201
+ and _endpoint_key(a.get("source")) == _endpoint_key(b.get("source"))
202
+ and _endpoint_key(a.get("destination")) == _endpoint_key(b.get("destination"))
203
+ )
204
+
205
+
206
+ def _endpoint_view(e):
207
+ e = e or {}
208
+ out = {}
209
+ ips = (e.get("ips") or {}).get("ips") or []
210
+ if ips:
211
+ out["cidrs"] = sorted(ips)
212
+ groups = (e.get("addressGroupIds") or {}).get("addressGroupIds") or []
213
+ if groups:
214
+ out["address_group_ids"] = sorted(groups)
215
+ tags = (e.get("vmTags") or {}).get("tags") or []
216
+ if tags:
217
+ out["vm_tags"] = sorted(tags)
218
+ return out or None
219
+
220
+
221
+ def rule_view(r):
222
+ """Salt-facing view of an API rule (with or without id/position)."""
223
+ body = r.get("rule", r)
224
+ out = {
225
+ "direction": trim_enum(body.get("direction"), "FIREWALL_DIRECTION_"),
226
+ "action": trim_enum(body.get("action"), "FIREWALL_ACTION_"),
227
+ "protocol": trim_enum(body.get("protocol"), "FIREWALL_PROTOCOL_"),
228
+ "source": _endpoint_view(body.get("source")),
229
+ "destination": _endpoint_view(body.get("destination")),
230
+ "source_ports": body.get("sourcePorts") or None,
231
+ "destination_ports": body.get("destinationPorts") or None,
232
+ }
233
+ if "id" in r and "rule" in r:
234
+ out["id"] = r.get("id")
235
+ out["position"] = int(r.get("position") or 0)
236
+ return out
237
+
238
+
239
+ def plan_rules(current, desired):
240
+ """Decide what reconcile() would change, without calling the API.
241
+
242
+ Returns True when the ruleset's rules differ from desired (contents or order).
243
+ """
244
+ if len(current) != len(desired):
245
+ return True
246
+ return any(not same_rule(c.get("rule") or {}, d) for c, d in zip(current, desired))
247
+
248
+
249
+ def reconcile(client, ruleset_id, desired):
250
+ """Make the ruleset hold exactly `desired`, in order. Returns the final rules.
251
+
252
+ Matching rules are kept (by body), changed ones are updated in place,
253
+ missing ones are created and extra ones deleted; finally rules are moved
254
+ into order. This keeps rule IDs stable where possible.
255
+ """
256
+ current = client.list_firewall_rules(ruleset_id)
257
+ ids = [""] * len(desired)
258
+ claimed = set()
259
+ # Keep rules whose body already matches, preferring the same position.
260
+ for i, d in enumerate(desired):
261
+ if (
262
+ i < len(current)
263
+ and current[i]["id"] not in claimed
264
+ and same_rule(current[i].get("rule") or {}, d)
265
+ ):
266
+ ids[i] = current[i]["id"]
267
+ claimed.add(ids[i])
268
+ for i, d in enumerate(desired):
269
+ if ids[i]:
270
+ continue
271
+ for c in current:
272
+ if c["id"] not in claimed and same_rule(c.get("rule") or {}, d):
273
+ ids[i] = c["id"]
274
+ claimed.add(c["id"])
275
+ break
276
+ # Reuse leftover rules for changed bodies (update in place) before creating new ones.
277
+ leftovers = [c for c in current if c["id"] not in claimed]
278
+ for i, d in enumerate(desired):
279
+ if ids[i] or not leftovers:
280
+ continue
281
+ c = leftovers.pop(0)
282
+ client.update_firewall_rule(c["id"], d)
283
+ ids[i] = c["id"]
284
+ claimed.add(c["id"])
285
+ for c in leftovers:
286
+ try:
287
+ client.delete_firewall_rule(c["id"])
288
+ except Exception as e: # pylint: disable=broad-except
289
+ if not is_not_found(e):
290
+ raise
291
+ order = [c["id"] for c in current if c["id"] in claimed]
292
+ # New rules land at position 0, so create bottom-up to keep their relative order.
293
+ for i in range(len(desired) - 1, -1, -1):
294
+ if ids[i]:
295
+ continue
296
+ created = client.create_firewall_rule(ruleset_id, desired[i])
297
+ if not created or not created.get("id"):
298
+ fresh = client.list_firewall_rules(ruleset_id)
299
+ created = next(
300
+ (
301
+ r
302
+ for r in fresh
303
+ if r["id"] not in claimed and same_rule(r.get("rule") or {}, desired[i])
304
+ ),
305
+ None,
306
+ )
307
+ if not created:
308
+ raise RuntimeError(f"the API did not return the created firewall rule {i}")
309
+ ids[i] = created["id"]
310
+ claimed.add(ids[i])
311
+ order.insert(0, ids[i])
312
+ for i, rid in enumerate(ids):
313
+ if order[i] == rid:
314
+ continue
315
+ client.move_firewall_rule(rid, order[i])
316
+ order.remove(rid)
317
+ order.insert(i, rid)
318
+ final = client.list_firewall_rules(ruleset_id)
319
+ if [r["id"] for r in final] != ids:
320
+ raise RuntimeError(
321
+ "the ruleset's rules changed while they were being written (another tool or user edited it); run the task again"
322
+ )
323
+ return final
@@ -0,0 +1,182 @@
1
+ """
2
+ Marketplace offer lookup: turn a plan code and a city into a plan and region ID.
3
+ """
4
+
5
+ from saltext.noderings.utils.client import trim_enum
6
+
7
+ BILLING_TYPES = {
8
+ "usage": "BILLING_TYPE_USAGE",
9
+ "subscription": "BILLING_TYPE_SUBSCRIPTION",
10
+ "free": "BILLING_TYPE_FREE",
11
+ }
12
+ ASSET_TYPES = {"virtual_machine": "ASSET_TYPE_VM", "game_server": "ASSET_TYPE_GAME_SERVER"}
13
+
14
+
15
+ class NoOfferError(Exception):
16
+ pass
17
+
18
+
19
+ def _amount(p):
20
+ try:
21
+ return float(p.get("unitAmount"))
22
+ except (TypeError, ValueError):
23
+ return None
24
+
25
+
26
+ def main_price(prices):
27
+ """The price that best represents what the plan costs, for sorting.
28
+
29
+ Usage plans carry several meters (compute-hours, storage GB-hours, traffic,
30
+ IPs); comparing the smallest of them would rank by the cheapest meter, not
31
+ the cheapest server. Prefer the compute meter, then a recurring flat price,
32
+ then fall back to the smallest amount.
33
+ """
34
+ prices = [p for p in prices or [] if _amount(p) is not None]
35
+ if not prices:
36
+ return float("inf")
37
+ compute = [p for p in prices if "compute" in (p.get("unitName") or "").lower()]
38
+ if compute:
39
+ return min(_amount(p) for p in compute)
40
+ flat = [
41
+ p
42
+ for p in prices
43
+ if (p.get("pricingModel") or "").endswith(("FLAT", "FLAT_RATE", "FIXED", "PER_UNIT"))
44
+ or (p.get("chargeTiming") or "").endswith("IN_ADVANCE")
45
+ ]
46
+ if flat:
47
+ return min(_amount(p) for p in flat)
48
+ return min(_amount(p) for p in prices)
49
+
50
+
51
+ def price_view(p):
52
+ return {
53
+ "unit_amount": p.get("unitAmount") or "",
54
+ "currency": p.get("currency") or "",
55
+ "unit_name": p.get("unitName") or "",
56
+ "billing_period": trim_enum(p.get("billingPeriod"), "BILLING_PERIOD_"),
57
+ "pricing_model": trim_enum(p.get("pricingModel"), "PRICING_MODEL_"),
58
+ "charge_timing": trim_enum(p.get("chargeTiming"), "CHARGE_TIMING_"),
59
+ "minimum_charge": p.get("minimumCharge") or "",
60
+ }
61
+
62
+
63
+ def find_offers(
64
+ client,
65
+ plan_code,
66
+ country,
67
+ city,
68
+ billing_type=None,
69
+ asset_type="virtual_machine",
70
+ provider_id=None,
71
+ storefront_slug=None,
72
+ require_capabilities=None,
73
+ require_ipv6=False,
74
+ sort="price",
75
+ ):
76
+ """Return (offers, located) where offers are sorted best first and located
77
+ counts the offers that matched the location before capability/IPv6 filters."""
78
+ billing = BILLING_TYPES.get(billing_type or "", "")
79
+ asset = ASSET_TYPES.get(asset_type or "virtual_machine", "ASSET_TYPE_VM")
80
+ if storefront_slug:
81
+ sf = client.get_public_storefront(storefront_slug)
82
+ if not sf:
83
+ raise NoOfferError(f"no storefront is named {storefront_slug}")
84
+ provider_id = sf.get("providerId")
85
+ found = []
86
+ if provider_id:
87
+ p = client.get_provider(provider_id) or {}
88
+ info = p.get("provider") or {}
89
+ for pl in p.get("availablePlans") or []:
90
+ if pl.get("planCode") != plan_code or (billing and pl.get("billingType") != billing):
91
+ continue
92
+ if pl.get("assetType") and pl.get("assetType") != asset:
93
+ continue
94
+ for r in pl.get("regions") or []:
95
+ if (r.get("country") or "").lower() == country.lower() and (
96
+ r.get("city") or ""
97
+ ).lower() == city.lower():
98
+ found.append(
99
+ {
100
+ "provider_id": info.get("organizationId"),
101
+ "provider_name": info.get("organizationName"),
102
+ "plan_id": pl.get("planId"),
103
+ "region_id": r.get("regionId"),
104
+ "billing_type": pl.get("billingType"),
105
+ "platform_driver": info.get("platformDriver"),
106
+ "capabilities": info.get("capabilities") or [],
107
+ "ipv6": bool(p.get("hasIpv6")),
108
+ "rating": float(info.get("rating") or 0),
109
+ "total_reviews": int(info.get("totalReviews") or 0),
110
+ "prices": pl.get("planPrices") or [],
111
+ }
112
+ )
113
+ else:
114
+ for p in client.list_providers(plan_code, country, city, billing or None, require_ipv6):
115
+ region_id = ""
116
+ for r in p.get("planRegions") or []:
117
+ if (r.get("city") or "").lower() == city.lower() and (
118
+ r.get("country") or ""
119
+ ).lower() == country.lower():
120
+ region_id = r.get("regionId")
121
+ if not region_id and p.get("planRegions"):
122
+ region_id = p["planRegions"][0].get("regionId")
123
+ found.append(
124
+ {
125
+ "provider_id": p.get("organizationId"),
126
+ "provider_name": p.get("organizationName"),
127
+ "plan_id": p.get("planId"),
128
+ "region_id": region_id,
129
+ "billing_type": billing,
130
+ "platform_driver": p.get("platformDriver"),
131
+ "capabilities": p.get("capabilities") or [],
132
+ "ipv6": bool(p.get("ipv6AvailableInFilteredRegion")),
133
+ "rating": float(p.get("rating") or 0),
134
+ "total_reviews": int(p.get("totalReviews") or 0),
135
+ "prices": p.get("planPrices") or [],
136
+ }
137
+ )
138
+ located = len(found)
139
+ need = set(require_capabilities or [])
140
+ out = [
141
+ o
142
+ for o in found
143
+ if need.issubset(set(o["capabilities"])) and (not require_ipv6 or o["ipv6"])
144
+ ]
145
+
146
+ def key(o):
147
+ price = main_price(o["prices"])
148
+ if sort == "rating":
149
+ return (-o["rating"], price, o["provider_name"] or "", o["plan_id"] or "")
150
+ return (price, -o["rating"], o["provider_name"] or "", o["plan_id"] or "")
151
+
152
+ out.sort(key=key)
153
+ return out, located
154
+
155
+
156
+ def offer_view(o):
157
+ return {
158
+ "provider_id": o["provider_id"],
159
+ "provider_name": o["provider_name"],
160
+ "plan_id": o["plan_id"],
161
+ "region_id": o["region_id"],
162
+ "billing_type": trim_enum(o.get("billing_type"), "BILLING_TYPE_"),
163
+ "platform_driver": trim_enum(o.get("platform_driver"), "PLATFORM_DRIVER_"),
164
+ "capabilities": o["capabilities"],
165
+ "ipv6": o["ipv6"],
166
+ "rating": o["rating"],
167
+ "total_reviews": o["total_reviews"],
168
+ "prices": [price_view(p) for p in o["prices"]],
169
+ }
170
+
171
+
172
+ def no_offer_message(plan_code, country, city, billing_type, located):
173
+ msg = f"No offer for plan code {plan_code} in {city}, {country}"
174
+ if billing_type:
175
+ msg += f" with billing type {billing_type}"
176
+ msg += "."
177
+ if located:
178
+ msg += (
179
+ f" {located} offer(s) matched the location but not the required capabilities or IPv6."
180
+ )
181
+ msg += " List what is sold with noderings.list_plans and noderings.list_regions."
182
+ return msg
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"