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,28 @@
1
+ # pylint: disable=missing-module-docstring
2
+ import pathlib
3
+
4
+ PACKAGE_ROOT = pathlib.Path(__file__).resolve().parent
5
+ try:
6
+ from .version import __version__
7
+ except ImportError: # pragma: no cover
8
+ __version__ = "0.0.0.not-installed"
9
+ try:
10
+ from importlib.metadata import version, PackageNotFoundError
11
+
12
+ try:
13
+ __version__ = version(__name__)
14
+ except PackageNotFoundError:
15
+ # package is not installed
16
+ pass
17
+ except ImportError:
18
+ try:
19
+ from pkg_resources import get_distribution, DistributionNotFound
20
+
21
+ try:
22
+ __version__ = get_distribution(__name__).version
23
+ except DistributionNotFound:
24
+ # package is not installed
25
+ pass
26
+ except ImportError:
27
+ # pkg resources isn't even available?!
28
+ pass
File without changes
@@ -0,0 +1,457 @@
1
+ """
2
+ Salt Cloud driver for NodeRings.
3
+
4
+ Orders servers from the NodeRings marketplace and bootstraps a Salt minion on
5
+ them over SSH.
6
+
7
+ Provider configuration, for example ``/etc/salt/cloud.providers.d/noderings.conf``:
8
+
9
+ .. code-block:: yaml
10
+
11
+ my-noderings:
12
+ driver: noderings
13
+ token: <service account token> # or the NODERINGS_TOKEN environment variable
14
+ # organization_id: <id> # optional
15
+ # minion:
16
+ # master: salt.example.com
17
+
18
+ Profile configuration, for example ``/etc/salt/cloud.profiles.d/noderings.conf``:
19
+
20
+ .. code-block:: yaml
21
+
22
+ noderings-ashburn-small:
23
+ provider: my-noderings
24
+ size: SC-GC-1C-1G-20 # plan code, see salt-cloud --list-sizes my-noderings
25
+ location: United States/Ashburn # country/city, see salt-cloud --list-locations my-noderings
26
+ image: ubuntu_24_04 # distro, see salt-cloud --list-images my-noderings
27
+ billing_type: usage # hourly, from prepaid credit
28
+ ssh_keys: [laptop] # names of SSH keys stored in NodeRings
29
+ private_key: /root/.ssh/id_ed25519 # matching private key, for the bootstrap
30
+ firewall_ruleset: web # optional
31
+ tags: [web] # optional
32
+
33
+ Then:
34
+
35
+ .. code-block:: bash
36
+
37
+ salt-cloud -p noderings-ashburn-small web-1
38
+ salt-cloud -d web-1
39
+ """
40
+
41
+ import logging
42
+ import time
43
+
44
+ from salt import config
45
+ from salt.exceptions import SaltCloudException
46
+ from salt.exceptions import SaltCloudNotFound
47
+ from salt.exceptions import SaltCloudSystemExit
48
+
49
+ from saltext.noderings import __version__
50
+ from saltext.noderings.utils import compute
51
+ from saltext.noderings.utils.client import NodeRingsError
52
+ from saltext.noderings.utils.client import TimeoutError_
53
+ from saltext.noderings.utils.client import client_from_config
54
+ from saltext.noderings.utils.client import snake
55
+ from saltext.noderings.utils.client import trim_enum
56
+
57
+ log = logging.getLogger(__name__)
58
+
59
+ __virtualname__ = "noderings"
60
+
61
+ USER_AGENT = (
62
+ f"saltext-noderings-cloud/{__version__} (+https://github.com/noderings/saltext-noderings)"
63
+ )
64
+
65
+
66
+ def __virtual__():
67
+ if get_configured_provider() is False:
68
+ return False
69
+ return __virtualname__
70
+
71
+
72
+ def _get_active_provider_name():
73
+ try:
74
+ return __active_provider_name__.value()
75
+ except AttributeError:
76
+ return __active_provider_name__
77
+
78
+
79
+ def get_configured_provider():
80
+ """
81
+ Return the first configured NodeRings provider. A token may come from the
82
+ provider block or the ``NODERINGS_TOKEN`` environment variable, so no key
83
+ is required in the block.
84
+ """
85
+ return config.is_provider_configured(
86
+ __opts__, _get_active_provider_name() or __virtualname__, ()
87
+ )
88
+
89
+
90
+ def get_dependencies():
91
+ """
92
+ The driver only needs the standard library.
93
+ """
94
+ return True
95
+
96
+
97
+ def _provider_value(key, default=None):
98
+ return config.get_cloud_config_value(
99
+ key, get_configured_provider(), __opts__, search_global=False, default=default
100
+ )
101
+
102
+
103
+ def _client():
104
+ conf = {
105
+ key: _provider_value(key)
106
+ for key in ("token", "api_url", "organization_id", "timeout", "retries")
107
+ }
108
+ try:
109
+ return client_from_config(conf, user_agent=USER_AGENT)
110
+ except ValueError as exc:
111
+ raise SaltCloudSystemExit(str(exc)) from exc
112
+
113
+
114
+ def _guard(call, allowed, func):
115
+ if call not in allowed:
116
+ raise SaltCloudSystemExit(
117
+ f"The {func} {'action' if call == 'action' else 'function'} must be called with "
118
+ f"{' or '.join('-' + ('a' if a == 'action' else 'f') for a in allowed)}."
119
+ )
120
+
121
+
122
+ def _node(vm):
123
+ view = compute.vm_view(vm)
124
+ return {
125
+ "id": view.get("id"),
126
+ "image": view.get("distro"),
127
+ "size": view.get("plan_code") or view.get("plan_id"),
128
+ "state": view.get("power_state"),
129
+ "private_ips": [],
130
+ "public_ips": [ip for ip in (view.get("ipv4"), view.get("ipv6")) if ip],
131
+ }
132
+
133
+
134
+ def _vms_by_name(client):
135
+ out = {}
136
+ for vm in client.list_virtual_machines():
137
+ out[vm.get("hostname")] = vm
138
+ return out
139
+
140
+
141
+ # -- listing ----------------------------------------------------------------------
142
+
143
+
144
+ def avail_locations(call=None):
145
+ """
146
+ List the cities with servers for sale, as ``Country/City``.
147
+
148
+ .. code-block:: bash
149
+
150
+ salt-cloud --list-locations my-noderings
151
+ """
152
+ _guard(call, (None, "function"), "avail_locations")
153
+ out = {}
154
+ for region in _client().list_marketplace_regions("ASSET_TYPE_VM"):
155
+ country = region.get("country") or ""
156
+ city = region.get("city") or ""
157
+ out[f"{country}/{city}"] = snake(region)
158
+ return out
159
+
160
+
161
+ def avail_images(call=None):
162
+ """
163
+ List the operating systems a server can be ordered with.
164
+
165
+ .. code-block:: bash
166
+
167
+ salt-cloud --list-images my-noderings
168
+ """
169
+ _guard(call, (None, "function"), "avail_images")
170
+ out = {}
171
+ for distro in _client().list_distros():
172
+ name = trim_enum(distro.get("distro"), "DISTRO_")
173
+ out[name] = snake(distro)
174
+ return out
175
+
176
+
177
+ def avail_sizes(call=None):
178
+ """
179
+ List the plan codes for sale, with their size.
180
+
181
+ .. code-block:: bash
182
+
183
+ salt-cloud --list-sizes my-noderings
184
+ """
185
+ _guard(call, (None, "function"), "avail_sizes")
186
+ out = {}
187
+ for plan in _client().list_available_plans(asset_type="ASSET_TYPE_VM"):
188
+ code = plan.get("planCode") or plan.get("code")
189
+ if code and code not in out:
190
+ out[code] = snake(plan)
191
+ return out
192
+
193
+
194
+ def list_nodes(call=None):
195
+ """
196
+ List servers with their basic details.
197
+
198
+ .. code-block:: bash
199
+
200
+ salt-cloud -Q
201
+ """
202
+ _guard(call, (None, "function"), "list_nodes")
203
+ return {name: _node(vm) for name, vm in _vms_by_name(_client()).items()}
204
+
205
+
206
+ def list_nodes_full(call=None):
207
+ """
208
+ List servers with every field.
209
+
210
+ .. code-block:: bash
211
+
212
+ salt-cloud -F
213
+ """
214
+ _guard(call, (None, "function"), "list_nodes_full")
215
+ return {
216
+ name: {**compute.vm_view(vm), **_node(vm)} for name, vm in _vms_by_name(_client()).items()
217
+ }
218
+
219
+
220
+ def list_nodes_select(call=None):
221
+ """
222
+ List servers with the fields in ``query.selection``.
223
+
224
+ .. code-block:: bash
225
+
226
+ salt-cloud -S
227
+ """
228
+ return __utils__["cloud.list_nodes_select"](
229
+ list_nodes_full("function"), __opts__["query.selection"], call
230
+ )
231
+
232
+
233
+ def show_instance(name, call=None):
234
+ """
235
+ Show one server.
236
+
237
+ .. code-block:: bash
238
+
239
+ salt-cloud -a show_instance web-1
240
+ """
241
+ _guard(call, ("action",), "show_instance")
242
+ try:
243
+ vm = compute.find_vm(_client(), name)
244
+ except (NodeRingsError, compute.NodeRingsUsageError) as exc:
245
+ raise SaltCloudSystemExit(str(exc)) from exc
246
+ if not vm:
247
+ raise SaltCloudNotFound(f"The specified instance {name} could not be found.")
248
+ view = compute.vm_view(vm)
249
+ __utils__["cloud.cache_node"](view, _get_active_provider_name(), __opts__)
250
+ return view
251
+
252
+
253
+ # -- create and destroy -----------------------------------------------------------
254
+
255
+
256
+ def _profile_value(vm_, key, default=None):
257
+ return config.get_cloud_config_value(key, vm_, __opts__, default=default, search_global=False)
258
+
259
+
260
+ def create(vm_):
261
+ """
262
+ Order a server and bootstrap a Salt minion on it.
263
+
264
+ .. code-block:: bash
265
+
266
+ salt-cloud -p noderings-ashburn-small web-1
267
+ """
268
+ name = vm_["name"]
269
+ try:
270
+ if (
271
+ vm_["profile"]
272
+ and config.is_profile_configured(
273
+ __opts__, _get_active_provider_name() or __virtualname__, vm_["profile"], vm_=vm_
274
+ )
275
+ is False
276
+ ):
277
+ return False
278
+ except AttributeError:
279
+ pass
280
+
281
+ __utils__["cloud.fire_event"](
282
+ "event",
283
+ "starting create",
284
+ f"salt/cloud/{name}/creating",
285
+ args=__utils__["cloud.filter_event"](
286
+ "creating", vm_, ["name", "profile", "provider", "driver"]
287
+ ),
288
+ sock_dir=__opts__["sock_dir"],
289
+ transport=__opts__["transport"],
290
+ )
291
+
292
+ client = _client()
293
+ size = _profile_value(vm_, "size")
294
+ location = _profile_value(vm_, "location") or ""
295
+ plan_id = _profile_value(vm_, "plan_id")
296
+ region_id = _profile_value(vm_, "region_id")
297
+ if not plan_id:
298
+ if not size or "/" not in location:
299
+ raise SaltCloudSystemExit(
300
+ "The profile needs size (a plan code) and location (Country/City), or plan_id and region_id."
301
+ )
302
+ country, city = location.split("/", 1)
303
+ timeout = int(_profile_value(vm_, "wait_timeout", 900))
304
+ try:
305
+ if compute.find_vm(client, name):
306
+ raise SaltCloudSystemExit(f"A server named {name} already exists.")
307
+ ruleset_id = compute.resolve_ruleset(client, _profile_value(vm_, "firewall_ruleset"))
308
+ if not plan_id:
309
+ plan_id, region_id, offer = compute.choose_offer(
310
+ client,
311
+ size,
312
+ country,
313
+ city,
314
+ billing_type=_profile_value(vm_, "billing_type", "usage"),
315
+ provider_id=_profile_value(vm_, "provider_id"),
316
+ require_capabilities=["guest_firewall"] if ruleset_id else [],
317
+ sort=_profile_value(vm_, "sort", "price"),
318
+ )
319
+ log.info("Ordering %s from %s", name, offer.get("provider_name"))
320
+ key_ids = compute.resolve_ssh_keys(client, _profile_value(vm_, "ssh_keys") or [])
321
+ vm = compute.order_vm(
322
+ client,
323
+ name,
324
+ plan_id,
325
+ region_id,
326
+ distro=_profile_value(vm_, "image", "ubuntu_24_04"),
327
+ ssh_key_ids=key_ids,
328
+ password=_profile_value(vm_, "password"),
329
+ tags=_profile_value(vm_, "tags") or [],
330
+ ruleset_id=ruleset_id,
331
+ wait=True,
332
+ timeout=timeout,
333
+ )
334
+ except (NodeRingsError, compute.NodeRingsUsageError, RuntimeError, TimeoutError_) as exc:
335
+ raise SaltCloudSystemExit(f"Error creating {name} on NodeRings: {exc}") from exc
336
+
337
+ data = compute.vm_view(vm)
338
+ ip = data.get("ipv4") or data.get("ipv6")
339
+ if not ip:
340
+ raise SaltCloudSystemExit(
341
+ f"{name} was created but has no IP address yet; destroy it and try again."
342
+ )
343
+
344
+ vm_["ssh_host"] = ip
345
+ vm_["ssh_username"] = _profile_value(vm_, "ssh_username", "root")
346
+ vm_["key_filename"] = _profile_value(vm_, "private_key")
347
+ if _profile_value(vm_, "password"):
348
+ vm_["password"] = _profile_value(vm_, "password")
349
+
350
+ if _profile_value(vm_, "deploy", True) is not False:
351
+ __utils__["cloud.wait_for_port"](
352
+ ip, timeout=int(_profile_value(vm_, "ssh_connect_timeout", 300))
353
+ )
354
+ # The SSH port opens before cloud-init has written the authorized key.
355
+ time.sleep(int(_profile_value(vm_, "ssh_ready_delay", 20)))
356
+
357
+ ret = __utils__["cloud.bootstrap"](vm_, __opts__)
358
+ ret.update(data)
359
+
360
+ __utils__["cloud.fire_event"](
361
+ "event",
362
+ "created instance",
363
+ f"salt/cloud/{name}/created",
364
+ args=__utils__["cloud.filter_event"](
365
+ "created", vm_, ["name", "profile", "provider", "driver"]
366
+ ),
367
+ sock_dir=__opts__["sock_dir"],
368
+ transport=__opts__["transport"],
369
+ )
370
+ return ret
371
+
372
+
373
+ def destroy(name, call=None):
374
+ """
375
+ Delete a server. An hourly server stops billing; a monthly subscription is
376
+ cancelled without a refund.
377
+
378
+ .. code-block:: bash
379
+
380
+ salt-cloud -d web-1
381
+ """
382
+ _guard(call, (None, "action"), "destroy")
383
+ __utils__["cloud.fire_event"](
384
+ "event",
385
+ "destroying instance",
386
+ f"salt/cloud/{name}/destroying",
387
+ args={"name": name},
388
+ sock_dir=__opts__["sock_dir"],
389
+ transport=__opts__["transport"],
390
+ )
391
+ client = _client()
392
+ try:
393
+ vm = compute.find_vm(client, name)
394
+ if not vm:
395
+ raise SaltCloudNotFound(f"The specified instance {name} could not be found.")
396
+ client.delete_virtual_machine(vm["id"])
397
+ except (NodeRingsError, compute.NodeRingsUsageError) as exc:
398
+ raise SaltCloudException(f"Error destroying {name}: {exc}") from exc
399
+
400
+ __utils__["cloud.fire_event"](
401
+ "event",
402
+ "destroyed instance",
403
+ f"salt/cloud/{name}/destroyed",
404
+ args={"name": name},
405
+ sock_dir=__opts__["sock_dir"],
406
+ transport=__opts__["transport"],
407
+ )
408
+ if __opts__.get("update_cachedir", False) is True:
409
+ __utils__["cloud.delete_minion_cachedir"](
410
+ name, _get_active_provider_name().split(":")[0], __opts__
411
+ )
412
+ return {"destroyed": name}
413
+
414
+
415
+ def _power(name, call, want):
416
+ _guard(call, ("action",), want)
417
+ client = _client()
418
+ try:
419
+ vm = compute.find_vm(client, name)
420
+ if not vm:
421
+ raise SaltCloudNotFound(f"The specified instance {name} could not be found.")
422
+ return compute.vm_view(compute.set_power(client, vm["id"], want))
423
+ except (NodeRingsError, compute.NodeRingsUsageError, TimeoutError_) as exc:
424
+ raise SaltCloudSystemExit(f"Error changing the power of {name}: {exc}") from exc
425
+
426
+
427
+ def start(name, call=None):
428
+ """
429
+ Start a stopped server.
430
+
431
+ .. code-block:: bash
432
+
433
+ salt-cloud -a start web-1
434
+ """
435
+ return _power(name, call, "running")
436
+
437
+
438
+ def stop(name, call=None):
439
+ """
440
+ Stop a server. Its disk and IP addresses are kept.
441
+
442
+ .. code-block:: bash
443
+
444
+ salt-cloud -a stop web-1
445
+ """
446
+ return _power(name, call, "stopped")
447
+
448
+
449
+ def reboot(name, call=None):
450
+ """
451
+ Restart a server.
452
+
453
+ .. code-block:: bash
454
+
455
+ salt-cloud -a reboot web-1
456
+ """
457
+ return _power(name, call, "restarted")
File without changes