vantage6 4.0.2__py3-none-any.whl → 4.1.0b0__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.

Potentially problematic release.


This version of vantage6 might be problematic. Click here for more details.

Files changed (39) hide show
  1. tests_cli/test_node_cli.py +60 -55
  2. tests_cli/test_server_cli.py +30 -30
  3. vantage6/cli/_version.py +1 -1
  4. vantage6/cli/cli.py +102 -0
  5. vantage6/cli/{dev.py → dev/create.py} +18 -151
  6. vantage6/cli/dev/remove.py +63 -0
  7. vantage6/cli/dev/start.py +52 -0
  8. vantage6/cli/dev/stop.py +30 -0
  9. vantage6/cli/node/attach.py +58 -0
  10. vantage6/cli/node/clean.py +40 -0
  11. vantage6/cli/node/common/__init__.py +124 -0
  12. vantage6/cli/node/create_private_key.py +139 -0
  13. vantage6/cli/node/files.py +34 -0
  14. vantage6/cli/node/list.py +62 -0
  15. vantage6/cli/node/new.py +46 -0
  16. vantage6/cli/node/remove.py +103 -0
  17. vantage6/cli/node/set_api_key.py +45 -0
  18. vantage6/cli/node/start.py +311 -0
  19. vantage6/cli/node/stop.py +73 -0
  20. vantage6/cli/node/version.py +47 -0
  21. vantage6/cli/server/attach.py +54 -0
  22. vantage6/cli/server/common/__init__.py +146 -0
  23. vantage6/cli/server/files.py +16 -0
  24. vantage6/cli/server/import_.py +144 -0
  25. vantage6/cli/server/list.py +60 -0
  26. vantage6/cli/server/new.py +50 -0
  27. vantage6/cli/server/shell.py +42 -0
  28. vantage6/cli/server/start.py +302 -0
  29. vantage6/cli/server/stop.py +158 -0
  30. vantage6/cli/server/version.py +46 -0
  31. {vantage6-4.0.2.dist-info → vantage6-4.1.0b0.dist-info}/METADATA +7 -6
  32. vantage6-4.1.0b0.dist-info/RECORD +52 -0
  33. vantage6-4.1.0b0.dist-info/entry_points.txt +5 -0
  34. vantage6/cli/node.py +0 -1092
  35. vantage6/cli/server.py +0 -1033
  36. vantage6-4.0.2.dist-info/RECORD +0 -28
  37. vantage6-4.0.2.dist-info/entry_points.txt +0 -4
  38. {vantage6-4.0.2.dist-info → vantage6-4.1.0b0.dist-info}/WHEEL +0 -0
  39. {vantage6-4.0.2.dist-info → vantage6-4.1.0b0.dist-info}/top_level.txt +0 -0
vantage6/cli/node.py DELETED
@@ -1,1092 +0,0 @@
1
- """
2
- The node module contains the CLI commands for the node manager. The following
3
- commands are available:
4
-
5
- * vnode new
6
- * vnode list
7
- * vnode files
8
- * vnode start
9
- * vnode stop
10
- * vnode attach
11
- * vnode clean
12
- * vnode remove
13
- * vnode version
14
- * vnode create-private-key
15
- """
16
- import click
17
- import sys
18
- import questionary as q
19
- import docker
20
- import time
21
- import os.path
22
- import itertools
23
-
24
- from typing import Iterable
25
- from pathlib import Path
26
- from threading import Thread
27
- from colorama import Fore, Style
28
- from shutil import rmtree
29
-
30
- from vantage6.common import (
31
- warning, error, info, debug,
32
- bytes_to_base64s, check_config_writeable,
33
- get_database_config
34
- )
35
- from vantage6.common.globals import (
36
- STRING_ENCODING,
37
- APPNAME,
38
- DEFAULT_DOCKER_REGISTRY,
39
- DEFAULT_NODE_IMAGE,
40
- DEFAULT_NODE_IMAGE_WO_TAG,
41
- )
42
- from vantage6.common.globals import VPN_CONFIG_FILE
43
- from vantage6.common.docker.addons import (
44
- pull_if_newer,
45
- remove_container_if_exists,
46
- check_docker_running
47
- )
48
- from vantage6.common.encryption import RSACryptor
49
- from vantage6.client import UserClient
50
-
51
- from vantage6.cli.context import NodeContext
52
- from vantage6.cli.globals import (
53
- DEFAULT_NODE_SYSTEM_FOLDERS as N_FOL
54
- )
55
- from vantage6.cli.configuration_wizard import (
56
- configuration_wizard,
57
- select_configuration_questionaire,
58
- NodeConfigurationManager
59
- )
60
- from vantage6.cli.utils import (
61
- check_config_name_allowed, check_if_docker_daemon_is_running,
62
- prompt_config_name, remove_file
63
- )
64
- from vantage6.cli import __version__
65
-
66
-
67
- @click.group(name="node")
68
- def cli_node() -> None:
69
- """
70
- The `vnode` commands allow you to manage your vantage6 node instances.
71
- """
72
- pass
73
-
74
-
75
- #
76
- # list
77
- #
78
- @cli_node.command(name="list")
79
- def cli_node_list() -> None:
80
- """
81
- Lists all node configurations.
82
-
83
- Note that this command cannot find node configuration files in custom
84
- directories.
85
- """
86
-
87
- check_docker_running()
88
- client = docker.from_env()
89
-
90
- running_node_names = _find_running_node_names(client)
91
-
92
- header = \
93
- "\nName"+(21*" ") + \
94
- "Status"+(10*" ") + \
95
- "System/User"
96
-
97
- click.echo(header)
98
- click.echo("-"*len(header))
99
-
100
- running = Fore.GREEN + "Running" + Style.RESET_ALL
101
- stopped = Fore.RED + "Not running" + Style.RESET_ALL
102
-
103
- # system folders
104
- configs, f1 = NodeContext.available_configurations(
105
- system_folders=True)
106
- for config in configs:
107
- status = running if f"{APPNAME}-{config.name}-system" in \
108
- running_node_names else stopped
109
- click.echo(
110
- f"{config.name:25}"
111
- f"{status:25}System "
112
- )
113
-
114
- # user folders
115
- configs, f2 = NodeContext.available_configurations(
116
- system_folders=False)
117
- for config in configs:
118
- status = running if f"{APPNAME}-{config.name}-user" in \
119
- running_node_names else stopped
120
- click.echo(
121
- f"{config.name:25}"
122
- f"{status:25}User "
123
- )
124
-
125
- click.echo("-"*53)
126
- if len(f1)+len(f2):
127
- warning(
128
- f"{Fore.RED}Failed imports: {len(f1)+len(f2)}{Style.RESET_ALL}")
129
-
130
-
131
- #
132
- # new
133
- #
134
- @cli_node.command(name="new")
135
- @click.option("-n", "--name", default=None, help="Configuration name")
136
- @click.option('--system', 'system_folders', flag_value=True,
137
- help="Store this configuration in the system folders")
138
- @click.option('--user', 'system_folders', flag_value=False, default=N_FOL,
139
- help="Store this configuration in the user folders. This is the "
140
- "default")
141
- def cli_node_new_configuration(name: str, system_folders: bool) -> None:
142
- """
143
- Create a new node configuration.
144
-
145
- Checks if the configuration already exists. If this is not the case
146
- a questionnaire is invoked to create a new configuration file.
147
- """
148
- name = prompt_config_name(name)
149
- # check if config name is allowed docker name
150
- check_config_name_allowed(name)
151
-
152
- # check that this config does not exist
153
- if NodeContext.config_exists(name, system_folders):
154
- error(f"Configuration {name} already exists!")
155
- exit(1)
156
-
157
- # Check that we can write in this folder
158
- if not check_config_writeable(system_folders):
159
- error("Cannot write configuration file. Exiting...")
160
- exit(1)
161
-
162
- # create config in ctx location
163
- flag = "--system" if system_folders else ""
164
- cfg_file = configuration_wizard("node", name, system_folders)
165
- info(f"New configuration created: {Fore.GREEN}{cfg_file}{Style.RESET_ALL}")
166
- info(f"You can start the node by running "
167
- f"{Fore.GREEN}vnode start {flag}{Style.RESET_ALL}")
168
-
169
-
170
- #
171
- # files
172
- #
173
- @cli_node.command(name="files")
174
- @click.option("-n", "--name", default=None, help="Configuration name")
175
- @click.option('--system', 'system_folders', flag_value=True,
176
- help="Search for the configuration in the system folders")
177
- @click.option('--user', 'system_folders', flag_value=False, default=N_FOL,
178
- help="Search for the configuration in the user folders. This is "
179
- "the default")
180
- def cli_node_files(name: str, system_folders: bool) -> None:
181
- """
182
- Prints the location of important node files.
183
-
184
- If the specified configuration cannot be found, it exits. Otherwise
185
- it returns the absolute path to the output.
186
- """
187
- name = _select_node(name, system_folders)
188
-
189
- # create node context
190
- ctx = NodeContext(name, system_folders=system_folders)
191
-
192
- # return path of the configuration
193
- info(f"Configuration file = {ctx.config_file}")
194
- info(f"Log file = {ctx.log_file}")
195
- info(f"data folders = {ctx.data_dir}")
196
- info("Database labels and files")
197
- for db in ctx.databases:
198
- info(f" - {db['label']:15} = {db['uri']} (type: {db['type']})")
199
-
200
-
201
- #
202
- # start
203
- #
204
- @cli_node.command(name='start')
205
- @click.option("-n", "--name", default=None, help="Configuration name")
206
- @click.option("-c", "--config", default=None,
207
- help='Absolute path to configuration-file; overrides NAME')
208
- @click.option('--system', 'system_folders', flag_value=True,
209
- help="Search for the configuration in the system folders")
210
- @click.option('--user', 'system_folders', flag_value=False, default=N_FOL,
211
- help="Search for the configuration in the user folders. This is "
212
- "the default")
213
- @click.option('-i', '--image', default=None, help="Node Docker image to use")
214
- @click.option('--keep/--auto-remove', default=False,
215
- help="Keep node container after finishing. Useful for debugging")
216
- @click.option('--force-db-mount', is_flag=True,
217
- help="Always mount node databases; skip the check if they are "
218
- "existing files.")
219
- @click.option('--attach/--detach', default=False,
220
- help="Show node logs on the current console after starting the "
221
- "node")
222
- @click.option('--mount-src', default='',
223
- help="Override vantage6 source code in container with the source"
224
- " code in this path")
225
- def cli_node_start(name: str, config: str, system_folders: bool, image: str,
226
- keep: bool, mount_src: str, attach: bool,
227
- force_db_mount: bool) -> None:
228
- """
229
- Start the node.
230
- """
231
- vnode_start(name, config, system_folders, image, keep, mount_src, attach,
232
- force_db_mount)
233
-
234
-
235
- def vnode_start(name: str, config: str, system_folders: bool,
236
- image: str, keep: bool, mount_src: str, attach: bool,
237
- force_db_mount: bool) -> None:
238
- """
239
- Start the node instance inside a Docker container.
240
-
241
- Parameters
242
- ----------
243
- name : str
244
- Name of the configuration file.
245
- config : str
246
- Absolute path to configuration-file; overrides NAME
247
- system_folders : bool
248
- Is this configuration stored in the system or in the user folders.
249
- image : str
250
- Node Docker image to use.
251
- keep : bool
252
- Keep container when finished or in the event of a crash. This is useful
253
- for debugging.
254
- mount_src : str
255
- Mount vantage6 package source that replaces the source inside the
256
- container. This is useful for debugging.
257
- attach : bool
258
- Attach node logs to the console after start.
259
- force_db_mount : bool
260
- Skip the check of the existence of the DB (always try to mount).
261
- """
262
- check_docker_running()
263
- info("Starting node...")
264
- info("Finding Docker daemon")
265
- docker_client = docker.from_env()
266
- NodeContext.LOGGING_ENABLED = False
267
- if config:
268
- name = Path(config).stem
269
- ctx = NodeContext(name, system_folders, config)
270
-
271
- else:
272
- # in case no name is supplied, ask the user to select one
273
- if not name:
274
- name = select_configuration_questionaire("node", system_folders)
275
-
276
- # check that config exists, if not a questionaire will be invoked
277
- if not NodeContext.config_exists(name, system_folders):
278
- warning(f"Configuration {Fore.RED}{name}{Style.RESET_ALL} does not"
279
- " exist.")
280
-
281
- if q.confirm("Create this configuration now?").ask():
282
- configuration_wizard("node", name, system_folders)
283
-
284
- else:
285
- error("Config file couldn't be loaded")
286
- sys.exit(0)
287
-
288
- ctx = NodeContext(name, system_folders)
289
-
290
- # check if config name is allowed docker name, else exit
291
- check_config_name_allowed(ctx.name)
292
-
293
- # check that this node is not already running
294
- running_nodes = docker_client.containers.list(
295
- filters={"label": f"{APPNAME}-type=node"}
296
- )
297
-
298
- suffix = "system" if system_folders else "user"
299
- for node in running_nodes:
300
- if node.name == f"{APPNAME}-{name}-{suffix}":
301
- error(f"Node {Fore.RED}{name}{Style.RESET_ALL} is already running")
302
- exit(1)
303
-
304
- # make sure the (host)-task and -log dir exists
305
- info("Checking that data and log dirs exist")
306
- ctx.data_dir.mkdir(parents=True, exist_ok=True)
307
- ctx.log_dir.mkdir(parents=True, exist_ok=True)
308
-
309
- # Determine image-name. First we check if the option --image has been used.
310
- # Then we check if the image has been specified in the config file, and
311
- # finally we use the default settings from the package.
312
- if not image:
313
- custom_images: dict = ctx.config.get('images')
314
- if custom_images:
315
- image = custom_images.get("node")
316
-
317
- # if no custom image is specified, find the server version and use
318
- # the latest images from that minor version
319
- client = _create_client(ctx)
320
- major_minor = None
321
- try:
322
- # try to get server version, skip if can't get a connection
323
- version = client.util.get_server_version(
324
- attempts_on_timeout=3
325
- )['version']
326
- major_minor = '.'.join(version.split('.')[:2])
327
- image = (f"{DEFAULT_DOCKER_REGISTRY}/{DEFAULT_NODE_IMAGE_WO_TAG}"
328
- f":{major_minor}")
329
- except Exception:
330
- warning("Could not determine server version. Using default node "
331
- "image")
332
- pass # simply use the default image
333
-
334
- if major_minor and not __version__.startswith(major_minor):
335
- warning(
336
- "Version mismatch between CLI and server/node. CLI is running "
337
- f"on version {__version__}, while node and server are on "
338
- f"version {major_minor}. This might cause unexpected issues; "
339
- f"changing to {major_minor}.<latest> is recommended."
340
- )
341
-
342
- if not image:
343
- image = f"{DEFAULT_DOCKER_REGISTRY}/{DEFAULT_NODE_IMAGE}"
344
-
345
- info(f"Pulling latest node image '{image}'")
346
- try:
347
- # docker_client.images.pull(image)
348
- pull_if_newer(docker.from_env(), image)
349
-
350
- except Exception as e:
351
- warning(' ... Getting latest node image failed:')
352
- warning(f" {e}")
353
- else:
354
- info(" ... success!")
355
-
356
- info("Creating Docker data volume")
357
-
358
- data_volume = docker_client.volumes.create(ctx.docker_volume_name)
359
- vpn_volume = docker_client.volumes.create(ctx.docker_vpn_volume_name)
360
- ssh_volume = docker_client.volumes.create(ctx.docker_ssh_volume_name)
361
- squid_volume = docker_client.volumes.create(ctx.docker_squid_volume_name)
362
-
363
- info("Creating file & folder mounts")
364
- # FIXME: should obtain mount points from DockerNodeContext
365
- mounts = [
366
- # (target, source)
367
- ("/mnt/log", str(ctx.log_dir)),
368
- ("/mnt/data", data_volume.name),
369
- ("/mnt/vpn", vpn_volume.name),
370
- ("/mnt/ssh", ssh_volume.name),
371
- ("/mnt/squid", squid_volume.name),
372
- ("/mnt/config", str(ctx.config_dir)),
373
- ("/var/run/docker.sock", "/var/run/docker.sock"),
374
- ]
375
-
376
- if mount_src:
377
- # If mount_src is a relative path, docker will consider it a volume.
378
- mount_src = os.path.abspath(mount_src)
379
- mounts.append(('/vantage6', mount_src))
380
-
381
- # FIXME: Code duplication: Node.__init__() (vantage6/node/__init__.py)
382
- # uses a lot of the same logic. Suggest moving this to
383
- # ctx.get_private_key()
384
- filename = ctx.config.get("encryption", {}).get("private_key")
385
- # filename may be set to an empty string
386
- if not filename:
387
- filename = 'private_key.pem'
388
-
389
- # Location may be overridden by the environment
390
- filename = os.environ.get('PRIVATE_KEY', filename)
391
-
392
- # If ctx.get_data_file() receives an absolute path, it is returned as-is
393
- fullpath = Path(ctx.get_data_file(filename))
394
- if fullpath:
395
- if Path(fullpath).exists():
396
- mounts.append(("/mnt/private_key.pem", str(fullpath)))
397
- else:
398
- warning(f"private key file provided {fullpath}, "
399
- "but does not exists")
400
-
401
- # Mount private keys for ssh tunnels
402
- ssh_tunnels = ctx.config.get("ssh-tunnels", [])
403
- for ssh_tunnel in ssh_tunnels:
404
- hostname = ssh_tunnel.get("hostname")
405
- key_path = ssh_tunnel.get("ssh", {}).get("identity", {}).get("key")
406
- if not key_path:
407
- error(f"SSH tunnel identity {Fore.RED}{hostname}{Style.RESET_ALL} "
408
- "key not provided. Continuing to start without this tunnel.")
409
- key_path = Path(key_path)
410
- if not key_path.exists():
411
- error(f"SSH tunnel identity {Fore.RED}{hostname}{Style.RESET_ALL} "
412
- "key does not exist. Continuing to start without this "
413
- "tunnel.")
414
-
415
- info(f" Mounting private key for {hostname} at {key_path}")
416
-
417
- # we remove the .tmp in the container, this is because the file is
418
- # mounted in a volume mount point. Somehow the file is than empty in
419
- # the volume but not for the node instance. By removing the .tmp we
420
- # make sure that the file is not empty in the volume.
421
- mounts.append((f"/mnt/ssh/{hostname}.pem.tmp", str(key_path)))
422
-
423
- env = {
424
- "DATA_VOLUME_NAME": data_volume.name,
425
- "VPN_VOLUME_NAME": vpn_volume.name,
426
- "PRIVATE_KEY": "/mnt/private_key.pem"
427
- }
428
-
429
- # only mount the DB if it is a file
430
- info("Setting up databases")
431
- db_labels = [db['label'] for db in ctx.databases]
432
- for label in db_labels:
433
-
434
- db_config = get_database_config(ctx.databases, label)
435
- uri = db_config['uri']
436
- db_type = db_config['type']
437
-
438
- info(f" Processing {Fore.GREEN}{db_type}{Style.RESET_ALL} database "
439
- f"{Fore.GREEN}{label}:{uri}{Style.RESET_ALL}")
440
- label_capitals = label.upper()
441
-
442
- try:
443
- file_based = Path(uri).exists()
444
- except Exception:
445
- # If the database uri cannot be parsed, it is definitely not a
446
- # file. In case of http servers or sql servers, checking the path
447
- # of the the uri will lead to an OS-dependent error, which is why
448
- # we catch all exceptions here.
449
- file_based = False
450
-
451
- if not file_based and not force_db_mount:
452
- debug(' - non file-based database added')
453
- env[f'{label_capitals}_DATABASE_URI'] = uri
454
- else:
455
- debug(' - file-based database added')
456
- suffix = Path(uri).suffix
457
- env[f'{label_capitals}_DATABASE_URI'] = f'{label}{suffix}'
458
- mounts.append((f'/mnt/{label}{suffix}', str(uri)))
459
-
460
- system_folders_option = "--system" if system_folders else "--user"
461
- cmd = f'vnode-local start -c /mnt/config/{name}.yaml -n {name} '\
462
- f' --dockerized {system_folders_option}'
463
-
464
- info("Running Docker container")
465
- volumes = []
466
- for mount in mounts:
467
- volumes.append(f'{mount[1]}:{mount[0]}')
468
-
469
- remove_container_if_exists(
470
- docker_client=docker_client, name=ctx.docker_container_name
471
- )
472
-
473
- container = docker_client.containers.run(
474
- image,
475
- command=cmd,
476
- volumes=volumes,
477
- detach=True,
478
- labels={
479
- f"{APPNAME}-type": "node",
480
- "system": str(system_folders),
481
- "name": ctx.config_file_name
482
- },
483
- environment=env,
484
- name=ctx.docker_container_name,
485
- auto_remove=not keep,
486
- tty=True
487
- )
488
-
489
- info(f"Success! container id = {container}")
490
-
491
- if attach:
492
- logs = container.attach(stream=True, logs=True)
493
- Thread(target=_print_log_worker, args=(logs,), daemon=True).start()
494
- while True:
495
- try:
496
- time.sleep(1)
497
- except KeyboardInterrupt:
498
- info("Closing log file. Keyboard Interrupt.")
499
- info("Note that your node is still running! Shut it down with "
500
- f"'{Fore.RED}vnode stop{Style.RESET_ALL}'")
501
- exit(0)
502
-
503
-
504
- #
505
- # stop
506
- #
507
- @cli_node.command(name='stop')
508
- @click.option("-n", "--name", default=None, help="Configuration name")
509
- @click.option('--system', 'system_folders', flag_value=True,
510
- help="Search for configuration in system folders instead of "
511
- "user folders")
512
- @click.option('--user', 'system_folders', flag_value=False, default=N_FOL,
513
- help="Search for configuration in the user folders instead of "
514
- "system folders. This is the default.")
515
- @click.option('--all', 'all_nodes', flag_value=True,
516
- help="Stop all running nodes")
517
- @click.option('--force', 'force', flag_value=True,
518
- help="Kill nodes instantly; don't wait for them to shut down")
519
- def cli_node_stop(name: str, system_folders: bool, all_nodes: bool,
520
- force: bool) -> None:
521
- """
522
- Stop one or all running nodes.
523
- """
524
- vnode_stop(name, system_folders, all_nodes, force)
525
-
526
-
527
- def vnode_stop(name: str, system_folders: bool, all_nodes: bool,
528
- force: bool) -> None:
529
- """
530
- Stop a running node container.
531
-
532
- Parameters
533
- ----------
534
- name : str
535
- Name of the configuration file.
536
- system_folders : bool
537
- Is this configuration stored in the system or in the user folders.
538
- all_nodes : bool
539
- If set to true, all running nodes will be stopped.
540
- force : bool
541
- If set to true, the node will not be stopped gracefully.
542
- """
543
- check_docker_running()
544
- client = docker.from_env()
545
-
546
- running_node_names = _find_running_node_names(client)
547
-
548
- if not running_node_names:
549
- warning("No nodes are currently running.")
550
- return
551
-
552
- if force:
553
- warning('Forcing the node to stop will not terminate helper '
554
- 'containers, neither will it remove routing rules made on the '
555
- 'host!')
556
-
557
- if all_nodes:
558
- for name in running_node_names:
559
- container = client.containers.get(name)
560
- if force:
561
- container.kill()
562
- else:
563
- container.stop()
564
- info(f"Stopped the {Fore.GREEN}{name}{Style.RESET_ALL} Node.")
565
- else:
566
- if not name:
567
- name = q.select("Select the node you wish to stop:",
568
- choices=running_node_names).ask()
569
- else:
570
-
571
- post_fix = "system" if system_folders else "user"
572
- name = f"{APPNAME}-{name}-{post_fix}"
573
-
574
- if name in running_node_names:
575
- container = client.containers.get(name)
576
- # Stop the container. Using stop() gives the container 10s to exit
577
- # itself, if not then it will be killed
578
- if force:
579
- container.kill()
580
- else:
581
- container.stop()
582
- info(f"Stopped the {Fore.GREEN}{name}{Style.RESET_ALL} Node.")
583
- else:
584
- error(f"{Fore.RED}{name}{Style.RESET_ALL} is not running?")
585
-
586
-
587
- #
588
- # attach
589
- #
590
- @cli_node.command(name='attach')
591
- @click.option("-n", "--name", default=None, help="Configuration name")
592
- @click.option('--system', 'system_folders', flag_value=True,
593
- help="Search for configuration in system folders rather than "
594
- "user folders")
595
- @click.option('--user', 'system_folders', flag_value=False, default=N_FOL,
596
- help="Search for configuration in user folders rather than "
597
- "system folders. This is the default")
598
- def cli_node_attach(name: str, system_folders: bool) -> None:
599
- """
600
- Show the node logs in the current console.
601
- """
602
- check_docker_running()
603
- client = docker.from_env()
604
-
605
- running_node_names = _find_running_node_names(client)
606
-
607
- if not running_node_names:
608
- warning("No nodes are currently running. Cannot show any logs!")
609
- return
610
-
611
- if not name:
612
- name = q.select("Select the node you wish to inspect:",
613
- choices=running_node_names).ask()
614
- else:
615
- post_fix = "system" if system_folders else "user"
616
- name = f"{APPNAME}-{name}-{post_fix}"
617
-
618
- if name in running_node_names:
619
- container = client.containers.get(name)
620
- logs = container.attach(stream=True, logs=True)
621
- Thread(target=_print_log_worker, args=(logs,), daemon=True).start()
622
- while True:
623
- try:
624
- time.sleep(1)
625
- except KeyboardInterrupt:
626
- info("Closing log file. Keyboard Interrupt.")
627
- info("Note that your node is still running! Shut it down with "
628
- f"'{Fore.RED}vnode stop{Style.RESET_ALL}'")
629
- exit(0)
630
- else:
631
- error(f"{Fore.RED}{name}{Style.RESET_ALL} was not running!?")
632
-
633
-
634
- #
635
- # create-private-key
636
- #
637
- @cli_node.command(name='create-private-key')
638
- @click.option("-n", "--name", default=None, help="Configuration name")
639
- @click.option("-c", "--config", default=None,
640
- help='Absolute path to configuration-file; overrides NAME')
641
- @click.option('--system', 'system_folders', flag_value=True,
642
- help="Search for configuration in system folders rather than "
643
- "user folders")
644
- @click.option('--user', 'system_folders', flag_value=False, default=N_FOL,
645
- help="Search for configuration in user folders rather than "
646
- "system folders. This is the default")
647
- @click.option('--no-upload', 'upload', flag_value=False, default=True,
648
- help="Don't upload the public key to the server")
649
- @click.option("-o", "--organization-name", default=None,
650
- help="Organization name. Used in the filename of the private key"
651
- " so that it can easily be recognized again later")
652
- @click.option('--overwrite', 'overwrite', flag_value=True, default=False,
653
- help="Overwrite existing private key if present")
654
- def cli_node_create_private_key(
655
- name: str, config: str, system_folders: bool, upload: bool,
656
- organization_name: str, overwrite: bool) -> None:
657
- """
658
- Create and upload a new private key
659
-
660
- Use this command with caution! Uploading a new key has several
661
- consequences, e.g. you and other users of your organization
662
- will no longer be able to read the results of tasks encrypted with current
663
- key.
664
- """
665
- NodeContext.LOGGING_ENABLED = False
666
- if config:
667
- name = Path(config).stem
668
- ctx = NodeContext(name, system_folders, config)
669
- else:
670
- # retrieve context
671
- name = _select_node(name, system_folders)
672
-
673
- # raise error if config could not be found
674
- if not NodeContext.config_exists(name, system_folders):
675
- error(
676
- f"The configuration {Fore.RED}{name}{Style.RESET_ALL} could "
677
- "not be found."
678
- )
679
- exit(1)
680
-
681
- # Create node context
682
- ctx = NodeContext(name, system_folders)
683
-
684
- # Authenticate with the server to obtain organization name if it wasn't
685
- # provided
686
- if organization_name is None:
687
- client = _create_client_and_authenticate(ctx)
688
- organization_name = client.whoami.organization_name
689
-
690
- # create directory where private key goes if it doesn't exist yet
691
- ctx.type_data_folder(system_folders).mkdir(parents=True, exist_ok=True)
692
-
693
- # generate new key, and save it
694
- filename = f"privkey_{organization_name}.pem"
695
- file_ = ctx.type_data_folder(system_folders) / filename
696
-
697
- if file_.exists():
698
- warning(f"File '{Fore.CYAN}{file_}{Style.RESET_ALL}' exists!")
699
-
700
- if overwrite:
701
- warning("'--override' specified, so it will be overwritten ...")
702
-
703
- if file_.exists() and not overwrite:
704
- error("Could not create private key!")
705
- warning(
706
- "If you're **sure** you want to create a new key, "
707
- "please run this command with the '--overwrite' flag"
708
- )
709
- warning("Continuing with existing key instead!")
710
- private_key = RSACryptor(file_).private_key
711
-
712
- else:
713
- try:
714
- info("Generating new private key")
715
- private_key = RSACryptor.create_new_rsa_key(file_)
716
-
717
- except Exception as e:
718
- error(f"Could not create new private key '{file_}'!?")
719
- debug(e)
720
- info("Bailing out ...")
721
- exit(1)
722
-
723
- warning(f"Private key written to '{file_}'")
724
- warning(
725
- "If you're running multiple nodes, be sure to copy the private "
726
- "key to the appropriate directories!"
727
- )
728
-
729
- # create public key
730
- info("Deriving public key")
731
- public_key = RSACryptor.create_public_key_bytes(private_key)
732
-
733
- # update config file
734
- info("Updating configuration")
735
- ctx.config["encryption"]["private_key"] = str(file_)
736
- ctx.config_manager.put(ctx.config)
737
- ctx.config_manager.save(ctx.config_file)
738
-
739
- # upload key to the server
740
- if upload:
741
- info(
742
- "Uploading public key to the server. "
743
- "This will overwrite any previously existing key!"
744
- )
745
-
746
- if 'client' not in locals():
747
- client = _create_client_and_authenticate(ctx)
748
-
749
- # TODO what happens if the user doesn't have permission to upload key?
750
- # Does that lead to an exception or not?
751
- try:
752
- client.request(
753
- f"/organization/{client.whoami.organization_id}",
754
- method="patch",
755
- json={"public_key": bytes_to_base64s(public_key)}
756
- )
757
-
758
- except Exception as e:
759
- error("Could not upload the public key!")
760
- debug(e)
761
- exit(1)
762
-
763
- else:
764
- warning("Public key not uploaded!")
765
-
766
- info("[Done]")
767
-
768
-
769
- #
770
- # clean
771
- #
772
- @cli_node.command(name='clean')
773
- def cli_node_clean() -> None:
774
- """
775
- Erase temporary Docker volumes.
776
- """
777
- check_docker_running()
778
- client = docker.from_env()
779
-
780
- # retrieve all volumes
781
- volumes = client.volumes.list()
782
- candidates = []
783
- msg = "This would remove the following volumes: "
784
- for volume in volumes:
785
- if volume.name[-6:] == "tmpvol":
786
- candidates.append(volume)
787
- msg += volume.name + ","
788
- info(msg)
789
-
790
- confirm = q.confirm("Are you sure?")
791
- if confirm.ask():
792
- for volume in candidates:
793
- try:
794
- volume.remove()
795
- # info(volume.name)
796
- except docker.errors.APIError as e:
797
- error(f"Failed to remove volume {Fore.RED}'{volume.name}'"
798
- f"{Style.RESET_ALL}. Is it still in use?")
799
- debug(e)
800
- exit(1)
801
- info("Done!")
802
-
803
-
804
- #
805
- # remove
806
- #
807
- @cli_node.command(name="remove")
808
- @click.option("-n", "--name", default=None, help="Configuration name")
809
- @click.option('--system', 'system_folders', flag_value=True,
810
- help="Search for configuration in system folders rather than "
811
- "user folders")
812
- @click.option('--user', 'system_folders', flag_value=False, default=N_FOL,
813
- help="Search for configuration in user folders rather than "
814
- "system folders. This is the default")
815
- @click.option('-f', "--force", type=bool, flag_value=True,
816
- help='Don\'t ask for confirmation')
817
- def cli_node_remove(name: str, system_folders: bool, force: bool) -> None:
818
- """
819
- Delete a node permanently.
820
-
821
- Remove the configuration file, log file, and docker volumes attached to
822
- the node.
823
- """
824
- vnode_remove(name, system_folders, force)
825
-
826
-
827
- def vnode_remove(name: str, system_folders: bool, force: bool):
828
- """
829
- Delete a node permanently
830
-
831
- * if the node is still running, exit and tell user to run vnode stop first
832
- * remove configuration file
833
- * remove log file
834
- * remove docker volumes attached to the node
835
-
836
- Parameters
837
- ----------
838
- name : str
839
- Configuration name
840
- system_folders : bool
841
- If True, use system folders, otherwise use user folders
842
- force : bool
843
- If True, don't ask for confirmation before removing the node
844
- """
845
- # select configuration name if none supplied
846
- name = _select_node(name, system_folders)
847
-
848
- client = docker.from_env()
849
- check_if_docker_daemon_is_running(client)
850
-
851
- # check if node is still running, otherwise don't allow deleting it
852
- running_node_names = _find_running_node_names(client)
853
-
854
- post_fix = "system" if system_folders else "user"
855
- node_container_name = f"{APPNAME}-{name}-{post_fix}"
856
- if node_container_name in running_node_names:
857
- error(f"Node {name} is still running! Please stop the node before "
858
- "deleting it.")
859
- exit(1)
860
-
861
- if not force:
862
- if not q.confirm(
863
- "This node will be deleted permanently including its "
864
- "configuration. Are you sure?", default=False
865
- ).ask():
866
- info("Node will not be deleted")
867
- exit(0)
868
-
869
- # create node context
870
- ctx = NodeContext(name, system_folders=system_folders)
871
-
872
- # remove the docker volume and any temporary volumes
873
- debug("Deleting docker volumes")
874
- volumes = client.volumes.list()
875
- for vol in volumes:
876
- if vol.name.startswith(ctx.docker_volume_name): # includes tmp volumes
877
- info(f"Deleting docker volume {vol.name}")
878
- vol.remove()
879
- # remove docker vpn volume
880
- if vol.name == ctx.docker_vpn_volume_name:
881
- info(f"Deleting VPN docker volume {vol.name}")
882
- vol.remove()
883
-
884
- # remove the VPN configuration file
885
- vpn_config_file = os.path.join(ctx.data_dir, 'vpn', VPN_CONFIG_FILE)
886
- remove_file(vpn_config_file, 'VPN configuration')
887
-
888
- # remove the config file
889
- remove_file(ctx.config_file, 'configuration')
890
-
891
- # remove the log file. As this process opens the log file above, the log
892
- # handlers need to be closed before deleting
893
- info(f"Removing log file {ctx.log_file}")
894
- for handler in itertools.chain(ctx.log.handlers, ctx.log.root.handlers):
895
- handler.close()
896
- # remove_file(ctx.log_file, 'log')
897
-
898
- # removes the whole folder
899
- rmtree(Path(ctx.log_file.parent))
900
-
901
- # remove the folder: if it hasn't been started yet this won't exist...
902
- if Path.exists(ctx.config_dir / name):
903
- rmtree(ctx.config_dir / name)
904
-
905
-
906
- #
907
- # version
908
- #
909
- @cli_node.command(name='version')
910
- @click.option("-n", "--name", default=None, help="Configuration name")
911
- @click.option('--system', 'system_folders', flag_value=True,
912
- help="Search for configuration in system folders rather than "
913
- "user folders")
914
- @click.option('--user', 'system_folders', flag_value=False, default=N_FOL,
915
- help="Search for configuration in user folders rather than "
916
- "system folders. This is the default")
917
- def cli_node_version(name: str, system_folders: bool) -> None:
918
- """
919
- Returns current version of a vantage6 node.
920
- """
921
- check_docker_running()
922
- client = docker.from_env()
923
-
924
- running_node_names = _find_running_node_names(client)
925
-
926
- if not name:
927
- if not running_node_names:
928
- error("No nodes are running! You can only check the version for "
929
- "nodes that are running")
930
- exit(1)
931
- name = q.select("Select the node you wish to inspect:",
932
- choices=running_node_names).ask()
933
- else:
934
- post_fix = "system" if system_folders else "user"
935
- name = f"{APPNAME}-{name}-{post_fix}"
936
-
937
- if name in running_node_names:
938
- container = client.containers.get(name)
939
- version = container.exec_run(cmd='vnode-local version', stdout=True)
940
- click.echo(
941
- {"node": version.output.decode('utf-8'), "cli": __version__})
942
- else:
943
- error(f"Node {name} is not running! Cannot provide version...")
944
-
945
-
946
- #
947
- # set-api-key
948
- #
949
- @cli_node.command(name='set-api-key')
950
- @click.option("-n", "--name", default=None, help="Configuration name")
951
- @click.option("--api-key", default=None, help="New API key")
952
- @click.option('--system', 'system_folders', flag_value=True,
953
- help="Search for configuration in system folders rather than "
954
- "user folders")
955
- @click.option('--user', 'system_folders', flag_value=False, default=N_FOL,
956
- help="Search for configuration in user folders rather than "
957
- "system folders. This is the default")
958
- def cli_node_set_api_key(name: str, api_key: str,
959
- system_folders: bool) -> None:
960
- """
961
- Put a new API key into the node configuration file
962
- """
963
- # select node name
964
- name = _select_node(name, system_folders)
965
-
966
- # Check that we can write in the config folder
967
- if not check_config_writeable(system_folders):
968
- error("Your user does not have write access to all folders. Exiting")
969
- exit(1)
970
-
971
- if not api_key:
972
- api_key = q.text("Please enter your new API key:").ask()
973
-
974
- # get configuration manager
975
- ctx = NodeContext(name, system_folders=system_folders)
976
- conf_mgr = NodeConfigurationManager.from_file(ctx.config_file)
977
-
978
- # set new api key, and save the file
979
- ctx.config['api_key'] = api_key
980
- conf_mgr.put(ctx.config)
981
- conf_mgr.save(ctx.config_file)
982
- info("Your new API key has been uploaded to the config file "
983
- f"{ctx.config_file}.")
984
-
985
-
986
- # helper functions
987
- def _print_log_worker(logs_stream: Iterable[bytes]) -> None:
988
- """
989
- Print the logs from the logs stream.
990
-
991
- Parameters
992
- ----------
993
- logs_stream : Iterable[bytes]
994
- Output of the container.attach() method
995
- """
996
- for log in logs_stream:
997
- print(log.decode(STRING_ENCODING), end="")
998
-
999
-
1000
- def _create_client(ctx: NodeContext) -> UserClient:
1001
- """
1002
- Create a client instance.
1003
-
1004
- Parameters
1005
- ----------
1006
- ctx : NodeContext
1007
- Context of the node loaded from the configuration file
1008
- Returns
1009
- -------
1010
- UserClient
1011
- vantage6 client
1012
- """
1013
- host = ctx.config['server_url']
1014
- # if the server is run locally, we need to use localhost here instead of
1015
- # the host address of docker
1016
- if host in ['http://host.docker.internal', 'http://172.17.0.1']:
1017
- host = 'http://localhost'
1018
- port = ctx.config['port']
1019
- api_path = ctx.config['api_path']
1020
- info(f"Connecting to server at '{host}:{port}{api_path}'")
1021
- return UserClient(host, port, api_path, log_level='warn')
1022
-
1023
-
1024
- def _create_client_and_authenticate(ctx: NodeContext) -> UserClient:
1025
- """
1026
- Generate a client and authenticate with the server.
1027
-
1028
- Parameters
1029
- ----------
1030
- ctx : NodeContext
1031
- Context of the node loaded from the configuration file
1032
-
1033
- Returns
1034
- -------
1035
- UserClient
1036
- vantage6 client
1037
- """
1038
- client = _create_client(ctx)
1039
-
1040
- username = q.text("Username:").ask()
1041
- password = q.password("Password:").ask()
1042
-
1043
- try:
1044
- client.authenticate(username, password)
1045
-
1046
- except Exception as exc:
1047
- error("Could not authenticate with server!")
1048
- debug(exc)
1049
- exit(1)
1050
-
1051
- return client
1052
-
1053
-
1054
- def _select_node(name: str, system_folders: bool) -> tuple[str, str]:
1055
- """
1056
- Let user select node through questionnaire if name is not given.
1057
-
1058
- Returns
1059
- -------
1060
- str
1061
- Name of the configuration file
1062
- """
1063
- name = name if name else \
1064
- select_configuration_questionaire("node", system_folders)
1065
-
1066
- # raise error if config could not be found
1067
- if not NodeContext.config_exists(name, system_folders):
1068
- error(
1069
- f"The configuration {Fore.RED}{name}{Style.RESET_ALL} could "
1070
- f"not be found."
1071
- )
1072
- exit(1)
1073
- return name
1074
-
1075
-
1076
- def _find_running_node_names(client: docker.DockerClient) -> list[str]:
1077
- """
1078
- Returns a list of names of running nodes.
1079
-
1080
- Parameters
1081
- ----------
1082
- client : docker.DockerClient
1083
- Docker client instance
1084
-
1085
- Returns
1086
- -------
1087
- list[str]
1088
- List of names of running nodes
1089
- """
1090
- running_nodes = client.containers.list(
1091
- filters={"label": f"{APPNAME}-type=node"})
1092
- return [node.name for node in running_nodes]