libcloud-noderings 0.1.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.
@@ -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 libcloud_noderings._api.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 driver.list_sizes() and driver.list_locations()."
182
+ return msg
@@ -0,0 +1,8 @@
1
+ """The package version, from the installed metadata (set by setuptools-scm from the git tag)."""
2
+
3
+ from importlib.metadata import PackageNotFoundError, version
4
+
5
+ try:
6
+ __version__ = version("libcloud-noderings")
7
+ except PackageNotFoundError: # pragma: no cover - running from a source tree
8
+ __version__ = "0.0.0"
@@ -0,0 +1,95 @@
1
+ """
2
+ The connection the NodeRings drivers share.
3
+
4
+ Requests go through Libcloud's own connection class, so proxies, timeouts and
5
+ ``LIBCLOUD_DEBUG`` logging behave as they do for every other Libcloud driver.
6
+ Retries, idempotent orders and waits come from the NodeRings API client.
7
+ """
8
+
9
+ import io
10
+ import os
11
+ from urllib.error import HTTPError
12
+ from urllib.parse import urlsplit
13
+
14
+ from libcloud.common.base import ConnectionKey, Response
15
+ from libcloud.common.types import InvalidCredsError
16
+
17
+ from libcloud_noderings._api.client import TOKEN_ENV_VARS, NodeRingsClient, NodeRingsError
18
+ from libcloud_noderings._version import __version__
19
+
20
+ DEFAULT_HOST = "api.noderings.com"
21
+
22
+
23
+ class NodeRingsResponse(Response):
24
+ """Hands every status to the API client, which decodes errors and retries."""
25
+
26
+ def success(self):
27
+ return True
28
+
29
+ def parse_body(self):
30
+ return self.body
31
+
32
+
33
+ class NodeRingsConnection(ConnectionKey):
34
+ host = DEFAULT_HOST
35
+ responseCls = NodeRingsResponse
36
+
37
+ def add_default_headers(self, headers):
38
+ headers["Authorization"] = f"Bearer {self.key}"
39
+ headers["Accept"] = "application/json"
40
+ return headers
41
+
42
+
43
+ class _RawResponse:
44
+ """What the API client reads: a context manager with read()."""
45
+
46
+ def __init__(self, body):
47
+ self._body = body
48
+
49
+ def read(self):
50
+ return self._body
51
+
52
+ def __enter__(self):
53
+ return self
54
+
55
+ def __exit__(self, *exc):
56
+ return False
57
+
58
+
59
+ class NodeRingsDriverMixin:
60
+ """Builds the API client on top of the driver's Libcloud connection."""
61
+
62
+ connectionCls = NodeRingsConnection
63
+
64
+ def _setup_noderings(self, key, ex_organization_id=None, ex_wait_timeout=900):
65
+ token = key or next((os.environ[v] for v in TOKEN_ENV_VARS if os.environ.get(v)), None)
66
+ if not token:
67
+ raise InvalidCredsError("A NodeRings API token is required as the driver's key, or in NODERINGS_TOKEN")
68
+ self.connection.user_agent_append(f"libcloud-noderings/{__version__}")
69
+ self.ex_wait_timeout = ex_wait_timeout
70
+ self._client = NodeRingsClient(
71
+ token=token,
72
+ api_url=f"{'https' if self.connection.secure else 'http'}://{self.connection.host}"
73
+ + (f":{self.connection.port}" if self.connection.port not in (None, 443, 80) else ""),
74
+ organization_id=ex_organization_id or os.environ.get("NODERINGS_ORGANIZATION_ID"),
75
+ user_agent=None,
76
+ opener=self._open,
77
+ )
78
+ return token
79
+
80
+ def _open(self, url, method, data, headers, timeout): # pylint: disable=unused-argument
81
+ parts = urlsplit(url)
82
+ action = parts.path + (f"?{parts.query}" if parts.query else "")
83
+ send = {k: v for k, v in headers.items() if k.lower() not in ("authorization", "user-agent")}
84
+ response = self.connection.request(action, data=data, headers=send, method=method, raw=False)
85
+ body = response.body if isinstance(response.body, bytes) else (response.body or "").encode("utf-8")
86
+ if response.status == 401:
87
+ raise InvalidCredsError("NodeRings rejected the API token")
88
+ if response.status >= 400:
89
+ raise HTTPError(url, response.status, "error", {}, io.BytesIO(body))
90
+ return _RawResponse(body)
91
+
92
+
93
+ def error_message(err):
94
+ """A readable message for an API error."""
95
+ return str(err) if isinstance(err, NodeRingsError) else f"{type(err).__name__}: {err}"
@@ -0,0 +1,404 @@
1
+ """
2
+ Apache Libcloud compute driver for NodeRings virtual machines.
3
+
4
+ Sizes are NodeRings plan codes, locations are the cities where plans are sold,
5
+ and images are the operating systems a server can be ordered with.
6
+ ``create_node`` orders the cheapest matching marketplace offer (or the best
7
+ rated one with ``ex_sort="rating"``) with an idempotency key, so a lost
8
+ response never orders a second server.
9
+ """
10
+
11
+ import re
12
+
13
+ from libcloud.common.types import LibcloudError
14
+ from libcloud.compute.base import KeyPair, Node, NodeAuthPassword, NodeAuthSSHKey, NodeDriver, NodeImage, NodeLocation, NodeSize
15
+ from libcloud.compute.types import KeyPairDoesNotExistError, NodeState
16
+
17
+ from libcloud_noderings import PROVIDER
18
+ from libcloud_noderings._api import compute as api_compute
19
+ from libcloud_noderings._api.client import CODE_ALREADY_EXISTS, NodeRingsError, TimeoutError_, is_not_found, trim_enum
20
+ from libcloud_noderings._api.compute import NodeRingsUsageError
21
+ from libcloud_noderings.common import NodeRingsDriverMixin, error_message
22
+
23
+ __all__ = ["NodeRingsNodeDriver"]
24
+
25
+ # SC-GC-1C-1G-20: 1 vCPU, 1 GB memory, 20 GB disk.
26
+ _PLAN_RE = re.compile(r"-(\d+)C-(\d+)G-(\d+)$", re.I)
27
+
28
+ _DISTRO_NAMES = {
29
+ "ubuntu": "Ubuntu",
30
+ "debian": "Debian",
31
+ "fedora": "Fedora",
32
+ "centos": "CentOS Stream",
33
+ "almalinux": "AlmaLinux",
34
+ "rocky": "Rocky Linux",
35
+ }
36
+
37
+
38
+ class NodeRingsNodeDriver(NodeRingsDriverMixin, NodeDriver):
39
+ """
40
+ NodeRings compute driver.
41
+
42
+ :param key: a NodeRings service account token (or set ``NODERINGS_TOKEN``)
43
+ :param ex_organization_id: the organization to act in, for tokens that reach several
44
+ :param ex_wait_timeout: seconds to wait for each operation (default 900)
45
+ """
46
+
47
+ type = PROVIDER
48
+ name = "NodeRings"
49
+ website = "https://noderings.com"
50
+ features = {"create_node": ["ssh_key", "password"]}
51
+
52
+ NODE_STATE_MAP = {
53
+ "running": NodeState.RUNNING,
54
+ "created": NodeState.RUNNING,
55
+ "stopped": NodeState.STOPPED,
56
+ "restarted": NodeState.RUNNING,
57
+ "reinstalling": NodeState.REBOOTING,
58
+ }
59
+
60
+ def __init__(self, key=None, secure=True, host=None, port=None, ex_organization_id=None, ex_wait_timeout=900, **kwargs):
61
+ super().__init__(key or "-", secure=secure, host=host, port=port, **kwargs)
62
+ self.connection.key = self._setup_noderings(key, ex_organization_id, ex_wait_timeout)
63
+
64
+ # -- helpers ----------------------------------------------------------------
65
+
66
+ def _call(self, what, func, *args, **kwargs):
67
+ try:
68
+ return func(*args, **kwargs)
69
+ except (NodeRingsError, NodeRingsUsageError, TimeoutError_, OSError) as err:
70
+ raise LibcloudError(f"NodeRings: {what}: {error_message(err)}", driver=self) from err
71
+
72
+ def _to_node(self, vm):
73
+ view = api_compute.vm_view(vm)
74
+ state = self.NODE_STATE_MAP.get(view["power_state"], NodeState.UNKNOWN)
75
+ if vm.get("crStatus") in ("CR_STATUS_PENDING", "CR_STATUS_PROCESSING") and not vm.get("ipv4"):
76
+ state = NodeState.PENDING
77
+ public = [ip for ip in (vm.get("ipv4"), vm.get("ipv6")) if ip]
78
+ extra = {
79
+ "plan_code": vm.get("planCode"),
80
+ "plan_id": vm.get("planId"),
81
+ "region_id": vm.get("regionId"),
82
+ "distro": view["distro"],
83
+ "power_state": view["power_state"],
84
+ "provisioning_status": view["provisioning_status"],
85
+ "billing_type": view["billing_type"],
86
+ "tags": view["tags"],
87
+ "firewall_ruleset_id": vm.get("firewallRulesetId") or None,
88
+ "provider_name": vm.get("providerName"),
89
+ "country": vm.get("regionCountry"),
90
+ "city": vm.get("regionCity"),
91
+ }
92
+ return Node(
93
+ id=vm["id"],
94
+ name=vm.get("hostname"),
95
+ state=state,
96
+ public_ips=public,
97
+ private_ips=[],
98
+ driver=self,
99
+ size=None,
100
+ image=None,
101
+ extra=extra,
102
+ )
103
+
104
+ @staticmethod
105
+ def _location_id(country, city):
106
+ return f"{country}/{city}"
107
+
108
+ # -- catalog ------------------------------------------------------------------
109
+
110
+ def list_locations(self):
111
+ """Cities where virtual machines are sold. The ID is ``Country/City``."""
112
+ regions = self._call("listing locations", self._client.list_marketplace_regions, "ASSET_TYPE_VM")
113
+ out = []
114
+ for r in regions:
115
+ country, city = r.get("country") or "", r.get("city") or ""
116
+ out.append(
117
+ NodeLocation(
118
+ id=self._location_id(country, city),
119
+ name=city,
120
+ country=country,
121
+ driver=self,
122
+ extra={"country": country, "city": city},
123
+ )
124
+ )
125
+ return out
126
+
127
+ def list_sizes(self, location=None):
128
+ """
129
+ Plans that are sold, optionally only in one location. The size ID is the
130
+ plan code. vCPU, memory (MB) and disk (GB) are read from the code.
131
+ """
132
+ country = city = None
133
+ if location is not None:
134
+ country, city = location.extra.get("country"), location.extra.get("city")
135
+ plans = self._call(
136
+ "listing sizes", self._client.list_available_plans, country=country, city=city, asset_type="ASSET_TYPE_VM"
137
+ )
138
+ out, seen = [], set()
139
+ for plan in plans:
140
+ code = plan.get("planCode")
141
+ if not code or code in seen:
142
+ continue
143
+ seen.add(code)
144
+ m = _PLAN_RE.search(code)
145
+ vcpus, ram_gb, disk_gb = (int(m.group(1)), int(m.group(2)), int(m.group(3))) if m else (None, None, None)
146
+ out.append(
147
+ NodeSize(
148
+ id=code,
149
+ name=code,
150
+ ram=ram_gb * 1024 if ram_gb else None,
151
+ disk=disk_gb,
152
+ bandwidth=None,
153
+ price=None,
154
+ driver=self,
155
+ extra={
156
+ "vcpus": vcpus,
157
+ "billing_type": trim_enum(plan.get("billingType"), "BILLING_TYPE_"),
158
+ "compute_type": trim_enum(plan.get("computeType"), "COMPUTE_TYPE_"),
159
+ "compute_category": trim_enum(plan.get("computeCategory"), "COMPUTE_CATEGORY_"),
160
+ },
161
+ )
162
+ )
163
+ return out
164
+
165
+ def list_images(self, location=None, ex_only_active=True): # pylint: disable=unused-argument
166
+ """Operating systems a server can be ordered with, such as ``ubuntu_24_04``."""
167
+ distros = self._call("listing images", self._client.list_distros)
168
+ out = []
169
+ for d in distros:
170
+ slug = trim_enum(d.get("distro"), "DISTRO_")
171
+ if not slug:
172
+ continue
173
+ family, _, ver = slug.partition("_")
174
+ name = f"{_DISTRO_NAMES.get(family, family.title())} {ver.replace('_', '.')}".strip()
175
+ out.append(NodeImage(id=slug, name=name, driver=self, extra={"distro": d.get("distro")}))
176
+ return out
177
+
178
+ # -- nodes ----------------------------------------------------------------------
179
+
180
+ def list_nodes(self):
181
+ return [self._to_node(vm) for vm in self._call("listing nodes", self._client.list_virtual_machines)]
182
+
183
+ def ex_get_node(self, node_id):
184
+ """The node with this ID or unique hostname, or ``None``."""
185
+ vm = self._call("finding the node", api_compute.find_vm, self._client, node_id)
186
+ return self._to_node(vm) if vm else None
187
+
188
+ def create_node(
189
+ self,
190
+ name,
191
+ size,
192
+ image,
193
+ location=None,
194
+ auth=None,
195
+ ex_ssh_keys=None,
196
+ ex_tags=None,
197
+ ex_firewall_ruleset=None,
198
+ ex_billing_type="usage",
199
+ ex_sort="price",
200
+ ex_provider_id=None,
201
+ ex_plan_id=None,
202
+ ex_region_id=None,
203
+ ex_wait=True,
204
+ ):
205
+ """
206
+ Order a NodeRings virtual machine.
207
+
208
+ :param name: hostname of the server
209
+ :param size: a :class:`NodeSize` from ``list_sizes`` (or a plan code string)
210
+ :param image: a :class:`NodeImage` from ``list_images`` (or a distro such as ``ubuntu_24_04``)
211
+ :param location: a :class:`NodeLocation` from ``list_locations``; required unless
212
+ ``ex_plan_id`` and ``ex_region_id`` are given
213
+ :param auth: :class:`NodeAuthSSHKey` (stored as a NodeRings key if new) or
214
+ :class:`NodeAuthPassword`
215
+ :param ex_ssh_keys: names or IDs of NodeRings SSH keys to install
216
+ :param ex_tags: tags on the server
217
+ :param ex_firewall_ruleset: name or ID of a firewall ruleset to attach
218
+ :param ex_billing_type: ``usage`` (hourly, default), ``subscription`` or ``free``
219
+ :param ex_sort: ``price`` (cheapest, default) or ``rating`` (best rated)
220
+ :param ex_provider_id: only consider offers from this provider
221
+ :param ex_plan_id: exact plan ID, instead of size and location
222
+ :param ex_region_id: exact region ID, with ``ex_plan_id``
223
+ :param ex_wait: wait until the server is provisioned and has an address (default True)
224
+ """
225
+ client = self._client
226
+ if ex_plan_id and ex_region_id:
227
+ plan_id, region_id = ex_plan_id, ex_region_id
228
+ else:
229
+ if location is None:
230
+ raise LibcloudError(
231
+ "create_node needs a location from list_locations(), or ex_plan_id and ex_region_id", driver=self
232
+ )
233
+ plan_code = size.id if isinstance(size, NodeSize) else str(size)
234
+ plan_id, region_id, _ = self._call(
235
+ "finding an offer",
236
+ api_compute.choose_offer,
237
+ client,
238
+ plan_code,
239
+ location.extra.get("country"),
240
+ location.extra.get("city"),
241
+ billing_type=ex_billing_type,
242
+ provider_id=ex_provider_id,
243
+ sort=ex_sort,
244
+ )
245
+ distro = image.id if isinstance(image, NodeImage) else str(image)
246
+
247
+ key_ids = self._call("resolving SSH keys", api_compute.resolve_ssh_keys, client, ex_ssh_keys or [])
248
+ password = None
249
+ if isinstance(auth, NodeAuthSSHKey):
250
+ key_ids.append(self._ensure_key(f"libcloud-{name}", auth.pubkey).extra["id"])
251
+ elif isinstance(auth, NodeAuthPassword):
252
+ password = auth.password
253
+ if not key_ids and not password:
254
+ raise LibcloudError("create_node needs auth (an SSH key or a password) or ex_ssh_keys", driver=self)
255
+
256
+ ruleset_id = None
257
+ if ex_firewall_ruleset:
258
+ ruleset_id = self._call("resolving the firewall ruleset", api_compute.resolve_ruleset, client, ex_firewall_ruleset)
259
+
260
+ vm = self._call(
261
+ f"ordering {name}",
262
+ api_compute.order_vm,
263
+ client,
264
+ name,
265
+ plan_id,
266
+ region_id,
267
+ distro=distro,
268
+ ssh_key_ids=key_ids,
269
+ password=password,
270
+ tags=ex_tags,
271
+ wait=False,
272
+ timeout=self.ex_wait_timeout,
273
+ )
274
+ if ex_wait or ruleset_id:
275
+ vm = self._wait_address(vm["id"])
276
+ if ruleset_id:
277
+ vm = self._call(
278
+ "attaching the firewall", api_compute.attach_firewall, client, vm["id"], ruleset_id, True, self.ex_wait_timeout
279
+ )
280
+ return self._to_node(vm)
281
+
282
+ def _wait_address(self, vm_id):
283
+ client = self._client
284
+
285
+ def check():
286
+ vm = client.get_virtual_machine(vm_id)
287
+ if vm.get("crStatus") == "CR_STATUS_FAILED":
288
+ raise NodeRingsUsageError(f"provisioning of {vm_id} failed; delete it and try another offer")
289
+ return (vm.get("crStatus") == "CR_STATUS_APPLIED" and bool(vm.get("ipv4") or vm.get("ipv6"))), vm
290
+
291
+ from libcloud_noderings._api.client import Waiter # pylint: disable=import-outside-toplevel
292
+
293
+ return self._call("waiting for the server", Waiter(self.ex_wait_timeout).wait, "the server to get an address", check)
294
+
295
+ def _power(self, node, want):
296
+ self._call(
297
+ f"changing the power of {node.name}", api_compute.set_power, self._client, node.id, want, True, self.ex_wait_timeout
298
+ )
299
+ return True
300
+
301
+ def reboot_node(self, node):
302
+ return self._power(node, "restarted")
303
+
304
+ def start_node(self, node):
305
+ return self._power(node, "running")
306
+
307
+ def stop_node(self, node):
308
+ return self._power(node, "stopped")
309
+
310
+ def destroy_node(self, node):
311
+ def delete():
312
+ try:
313
+ self._client.delete_virtual_machine(node.id)
314
+ except NodeRingsError as err:
315
+ if not is_not_found(err):
316
+ raise
317
+ return True
318
+
319
+ from libcloud_noderings._api.client import Waiter # pylint: disable=import-outside-toplevel
320
+
321
+ return self._call(f"deleting {node.name}", Waiter(self.ex_wait_timeout).retry_busy, delete)
322
+
323
+ def ex_set_tags(self, node, tags):
324
+ """Replace the node's tags."""
325
+ have = set(node.extra.get("tags") or [])
326
+ want = set(tags or [])
327
+ self._call(
328
+ "updating tags",
329
+ self._client.update_virtual_machine_tags,
330
+ node.id,
331
+ add=sorted(want - have),
332
+ remove=sorted(have - want),
333
+ )
334
+ node.extra["tags"] = sorted(want)
335
+ return True
336
+
337
+ def ex_attach_firewall(self, node, ruleset):
338
+ """Attach a firewall ruleset (name or ID) to the node."""
339
+ ruleset_id = self._call("resolving the firewall ruleset", api_compute.resolve_ruleset, self._client, ruleset)
340
+ self._call(
341
+ "attaching the firewall", api_compute.attach_firewall, self._client, node.id, ruleset_id, True, self.ex_wait_timeout
342
+ )
343
+ return True
344
+
345
+ def ex_detach_firewall(self, node):
346
+ """Detach the node's firewall ruleset."""
347
+ vm = self._call("reading the node", self._client.get_virtual_machine, node.id)
348
+ current = vm.get("firewallRulesetId")
349
+ if current:
350
+ self._call(
351
+ "detaching the firewall", api_compute.detach_firewall, self._client, node.id, current, True, self.ex_wait_timeout
352
+ )
353
+ return True
354
+
355
+ # -- key pairs ----------------------------------------------------------------------
356
+
357
+ def _to_key_pair(self, key):
358
+ return KeyPair(
359
+ name=key.get("name"),
360
+ public_key=key.get("publicKey"),
361
+ fingerprint=key.get("fingerprint"),
362
+ driver=self,
363
+ extra={"id": key.get("id"), "key_type": key.get("keyType")},
364
+ )
365
+
366
+ def list_key_pairs(self):
367
+ return [self._to_key_pair(k) for k in self._call("listing SSH keys", self._client.list_ssh_keys)]
368
+
369
+ def get_key_pair(self, name):
370
+ for key in self.list_key_pairs():
371
+ if key.name == name:
372
+ return key
373
+ raise KeyPairDoesNotExistError(name=name, driver=self)
374
+
375
+ def import_key_pair_from_string(self, name, key_material):
376
+ key = self._call("importing the SSH key", self._client.create_ssh_key, name, key_material.strip())
377
+ return self._to_key_pair(key)
378
+
379
+ def delete_key_pair(self, key_pair):
380
+ key_id = key_pair.extra.get("id") or self.get_key_pair(key_pair.name).extra["id"]
381
+
382
+ def delete():
383
+ try:
384
+ self._client.delete_ssh_key(key_id)
385
+ except NodeRingsError as err:
386
+ if not is_not_found(err):
387
+ raise
388
+ return True
389
+
390
+ return self._call("deleting the SSH key", delete)
391
+
392
+ def _ensure_key(self, name, public_key):
393
+ """The stored key with this public key, imported under ``name`` if it is new."""
394
+ material = " ".join(public_key.split()[:2])
395
+ for key in self.list_key_pairs():
396
+ if " ".join((key.public_key or "").split()[:2]) == material:
397
+ return key
398
+ try:
399
+ return self.import_key_pair_from_string(name, public_key)
400
+ except LibcloudError as err:
401
+ cause = err.__cause__
402
+ if isinstance(cause, NodeRingsError) and cause.code == CODE_ALREADY_EXISTS:
403
+ return self.get_key_pair(name)
404
+ raise