building_manager.py 64.5 KB
Newer Older
1
#!/usr/bin/env python3
2
""" Python module to assist creating and maintaining docker openHab stacks."""
3
import crypt
dobli's avatar
dobli committed
4
from enum import Enum
dobli's avatar
dobli committed
5
from typing import NamedTuple
6
import logging
7
import os
Dobli's avatar
Dobli committed
8
import sys
dobli's avatar
dobli committed
9
from hashlib import md5
10
from shutil import copy2
11
from subprocess import PIPE, run
dobli's avatar
dobli committed
12
from time import sleep
13
14
15

import bcrypt
import docker
16
import questionary as qust
17
from ruamel.yaml import YAML
18
from prompt_toolkit.styles import Style
19
20
21
22

# Configure YAML
yaml = YAML()
yaml.indent(mapping=4, sequence=4, offset=2)
23
24
25

# Log level during development is info
logging.basicConfig(level=logging.WARNING)
26

27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# Prompt style
st = Style([
    ('qmark', 'fg:#00c4b4 bold'),     # token in front of question
    ('question', 'bold'),             # question text
    ('answer', 'fg:#00c4b4 bold'),    # submitted answer question
    ('pointer', 'fg:#00c4b4 bold'),   # pointer for select and checkbox
    ('selected', 'fg:#00c4b4'),       # selected item checkbox
    ('separator', 'fg:#00c4b4'),      # separator in lists
    ('instruction', '')               # user instructions for selections
])

# ******************************
# Constants <<<
# ******************************

42
# Directories for config generation
43
44
CUSTOM_DIR = 'custom_configs'
TEMPLATE_DIR = 'template_configs'
45
46
47
COMPOSE_NAME = 'docker-stack.yml'
SKELETON_NAME = 'docker-skeleton.yml'
TEMPLATES_NAME = 'docker-templates.yml'
Dobli's avatar
Dobli committed
48
CONFIG_DIRS = ['mosquitto', 'nodered', 'ssh', 'filebrowser',
dobli's avatar
dobli committed
49
               'traefik', 'volumerize', 'postgres', 'pb-framr']
Dobli's avatar
Dobli committed
50
51
TEMPLATE_FILES = [
    'mosquitto/mosquitto.conf', 'nodered/nodered_package.json',
dobli's avatar
dobli committed
52
53
    'pb-framr/logo.svg', 'nodered/nodered_settings.js',
    'ssh/sshd_config', 'traefik/traefik.toml'
54
]
55
56
EDIT_FILES = {
    "mosquitto_passwords": "mosquitto/mosquitto_passwords",
57
    "sftp_users": "ssh/sftp_users.conf",
58
59
60
    "traefik_users": "traefik/traefik_users",
    "id_rsa": "ssh/id_rsa",
    "host_key": "ssh/ssh_host_ed25519_key",
61
    "known_hosts": "ssh/known_hosts",
dobli's avatar
dobli committed
62
    "backup_config": "volumerize/backup_config",
dobli's avatar
dobli committed
63
    "postgres_user": "postgres/user",
dobli's avatar
dobli committed
64
    "postgres_passwd": "postgres/passwd",
Dobli's avatar
Dobli committed
65
66
    "pb_framr_pages": "pb-framr/pages.json",
    "filebrowser_conf": "filebrowser/filebrowser.json"
67
}
Dobli's avatar
Dobli committed
68
CONSTRAINTS = {"building": "node.labels.building"}
69

70
# Default Swarm port
dobli's avatar
dobli committed
71
SWARM_PORT = 2377
72
73
# UID for admin
UID = 9001
Dobli's avatar
Dobli committed
74
75
# Username for admin
ADMIN_USER = 'ohadmin'
dobli's avatar
dobli committed
76

dobli's avatar
dobli committed
77
78
79
80
81
82
# USB DEVICES (e.g. Zwave stick)
USB_DEVICES = [{
    "name": "Aeotec Z-Stick Gen5 (ttyACM0)",
    "value": "zwave_stick"
}]

dobli's avatar
dobli committed
83

dobli's avatar
dobli committed
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
class ServiceBody(NamedTuple):
    fullname: str
    prefix: str
    additional: bool
    frontend: bool
    sftp: bool = False
    icon: str = None


class Service(ServiceBody, Enum):
    SFTP = ServiceBody("SFTP", "sftp", False, False)
    OPENHAB = ServiceBody("OpenHAB", "openhab", True,
                          True, icon='dashboard', sftp=True)
    NODERED = ServiceBody("Node-RED", "nodered", False,
                          True, icon='ballot', sftp=True)
    POSTGRES = ServiceBody("Postgre SQL", "postgres", True, False)
    MQTT = ServiceBody("Mosquitto MQTT Broker", "mqtt", True, False)
    FILES = ServiceBody("File Manager", "files", False, True, icon='folder')
dobli's avatar
dobli committed
102
103
    BACKUP = ServiceBody("Volumerize Backups", "backup",
                         False, False, sftp=True)
dobli's avatar
dobli committed
104
105
106
107
108

    @classmethod
    def service_by_prefix(cls, prefix):
        # cls here is the enumeration
        return next(service for service in cls if service.prefix == prefix)
109
110
# >>>

111
112

# ******************************
113
# Compose file functions <<<
114
# ******************************
Dobli's avatar
Dobli committed
115
116

# Functions to generate initial file
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
def generate_initial_compose(base_dir):
    """Creates the initial compose using the skeleton

    :base_dir: Folder to place configuration files into
    """
    base_path = base_dir + '/' + CUSTOM_DIR
    template_path = base_dir + '/' + TEMPLATE_DIR
    # compose file
    compose = base_path + '/' + COMPOSE_NAME
    # skeleton file
    skeleton = template_path + '/' + SKELETON_NAME

    with open(skeleton, 'r') as skeleton_f, open(compose, 'w+') as compose_f:
        init_content = yaml.load(skeleton_f)
        yaml.dump(init_content, compose_f)


def add_sftp_service(base_dir, hostname, number=0):
    """Generates an sftp entry and adds it to the compose file

    :base_dir: base directory for configuration files
    :hostname: names of host that the services is added to
    :number: increment of exposed port to prevent overlaps
    """
    base_path = base_dir + '/' + CUSTOM_DIR
    # compose file
    compose_path = base_path + '/' + COMPOSE_NAME
    # service name
    service_name = f'sftp_{hostname}'
146
    # template
147
    template = get_service_template(base_dir, Service.SFTP.prefix)
148
149
150
151
    # only label contraint is building
    template['deploy']['placement']['constraints'][0] = (
        f"{CONSTRAINTS['building']} == {hostname}")
    template['ports'] = [f'{2222 + number}:22']
152

dobli's avatar
dobli committed
153
154
155
156
157
    # attach volumes
    volume_base = '/home/ohadmin/'
    template['volumes'] = get_attachable_volume_list(
        base_dir, volume_base, hostname)

158
    add_or_update_compose_service(compose_path, service_name, template)
159
160
161
162
163
164
165
166
167
168
169
170
171


def add_openhab_service(base_dir, hostname):
    """Generates an openhab entry and adds it to the compose file

    :base_dir: base directory for configuration files
    :hostname: names of host that the services is added to
    """
    base_path = base_dir + '/' + CUSTOM_DIR
    # compose file
    compose_path = base_path + '/' + COMPOSE_NAME
    # service name
    service_name = f'openhab_{hostname}'
172
    # template
173
    template = get_service_template(base_dir, Service.OPENHAB.prefix)
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
    # only label contraint is building
    template['deploy']['placement']['constraints'][0] = (
        f"{CONSTRAINTS['building']} == {hostname}")
    # include in backups of this building
    template['deploy']['labels'].append(f'backup={hostname}')
    # traefik backend
    template['deploy']['labels'].append(f'traefik.backend={service_name}')
    # traefik frontend domain->openhab
    template['deploy']['labels'].extend(
        generate_traefik_host_labels(hostname, segment='main'))
    # traefik frontend subdomain openhab_hostname.* -> openhab
    template['deploy']['labels'].append(
        f'traefik.sub.frontend.rule=HostRegexp:'
        f'{service_name}.{{domain:[a-zA-z0-9-]+}}')
    template['deploy']['labels'].append('traefik.sub.frontend.priority=2')

dobli's avatar
dobli committed
190
191
192
193
    # replace volumes with named entries in template
    template['volumes'] = generate_named_volumes(
        template['volumes'], service_name, compose_path)

194
    add_or_update_compose_service(compose_path, service_name, template)
195
196
197
198
199
200
201
202
203
204
205
206
207


def add_nodered_service(base_dir, hostname):
    """Generates an nodered entry and adds it to the compose file

    :base_dir: base directory for configuration files
    :hostname: names of host that the services is added to
    """
    base_path = base_dir + '/' + CUSTOM_DIR
    # compose file
    compose_path = base_path + '/' + COMPOSE_NAME
    # service name
    service_name = f'nodered_{hostname}'
208
    # template
209
    template = get_service_template(base_dir, Service.NODERED.prefix)
210
211
212
213
214
215
216
    # only label contraint is building
    template['deploy']['placement']['constraints'][0] = (
        f"{CONSTRAINTS['building']} == {hostname}")
    template['deploy']['labels'].append(f'traefik.backend={service_name}')
    template['deploy']['labels'].append(f'backup={hostname}')
    template['deploy']['labels'].extend(
        generate_traefik_path_labels(service_name, segment='main'))
Dobli's avatar
Dobli committed
217
218
    template['deploy']['labels'].extend(
        generate_traefik_subdomain_labels(service_name, segment='sub'))
219

dobli's avatar
dobli committed
220
221
222
223
    # replace volumes with named entries in template
    template['volumes'] = generate_named_volumes(
        template['volumes'], service_name, compose_path)

224
    add_or_update_compose_service(compose_path, service_name, template)
225
226
227
228
229
230
231
232
233
234
235
236
237
238


def add_mqtt_service(base_dir, hostname, number=0):
    """Generates an mqtt entry and adds it to the compose file

    :base_dir: base directory for configuration files
    :hostname: names of host that the services is added to
    :number: increment of exposed port to prevent overlaps
    """
    base_path = base_dir + '/' + CUSTOM_DIR
    # compose file
    compose_path = base_path + '/' + COMPOSE_NAME
    # service name
    service_name = f'mqtt_{hostname}'
239
    # template
240
    template = get_service_template(base_dir, Service.MQTT.prefix)
241
242
243
244
245
    # only label contraint is building
    template['deploy']['placement']['constraints'][0] = (
        f"{CONSTRAINTS['building']} == {hostname}")
    # ports incremented by number of services
    template['ports'] = [f'{1883 + number}:1883', f'{9001 + number}:9001']
246

dobli's avatar
dobli committed
247
248
249
250
    # replace volumes with named entries in template
    template['volumes'] = generate_named_volumes(
        template['volumes'], service_name, compose_path)

251
    add_or_update_compose_service(compose_path, service_name, template)
252
253


254
def add_postgres_service(base_dir, hostname, postfix=None):
dobli's avatar
dobli committed
255
256
257
258
    """Generates an postgres entry and adds it to the compose file

    :base_dir: base directory for configuration files
    :hostname: names of host that the services is added to
259
    :postfix: an identifier for this service
dobli's avatar
dobli committed
260
261
262
263
    """
    base_path = base_dir + '/' + CUSTOM_DIR
    # compose file
    compose_path = base_path + '/' + COMPOSE_NAME
264
    # use hostname as postfix when empty
dobli's avatar
dobli committed
265
266
267
268
269
    if postfix is None:
        service_name = f'postgres_{hostname}'
    else:
        service_name = f'postgres_{postfix}'

dobli's avatar
dobli committed
270
    # template
271
    template = get_service_template(base_dir, Service.POSTGRES.prefix)
Dobli's avatar
Dobli committed
272
    # only label constraint is building
dobli's avatar
dobli committed
273
274
275
    template['deploy']['placement']['constraints'][0] = (
        f"{CONSTRAINTS['building']} == {hostname}")

dobli's avatar
dobli committed
276
277
278
279
    # replace volumes with named entries in template
    template['volumes'] = generate_named_volumes(
        template['volumes'], service_name, compose_path)

dobli's avatar
dobli committed
280
281
282
    add_or_update_compose_service(compose_path, service_name, template)


283
def add_file_service(base_dir, hostname):
dobli's avatar
dobli committed
284
    """Generates a file manager entry and adds it to the compose file
285
286
287
288
289
290
291
292

    :base_dir: base directory for configuration files
    :hostname: names of host that the services is added to
    """
    base_path = base_dir + '/' + CUSTOM_DIR
    # compose file
    compose_path = base_path + '/' + COMPOSE_NAME
    # service name
dobli's avatar
dobli committed
293
    service_name = f'{Service.FILES.prefix}_{hostname}'
294
295
296
297
298
299
300
301
302
303
304
305
    # template
    template = get_service_template(base_dir, Service.FILES.prefix)
    # add command that sets base url
    template['command'] = f'-b /{service_name}'
    # only label contraint is building
    template['deploy']['placement']['constraints'][0] = (
        f"{CONSTRAINTS['building']} == {hostname}")
    template['deploy']['labels'].append(f'traefik.backend={service_name}')
    template['deploy']['labels'].extend(
        generate_traefik_path_labels(service_name, segment='main',
                                     redirect=False))

dobli's avatar
dobli committed
306
307
308
309
310
    # attach volumes
    volume_base = '/srv/'
    template['volumes'] = get_attachable_volume_list(
        base_dir, volume_base, hostname)

311
312
313
    add_or_update_compose_service(compose_path, service_name, template)


dobli's avatar
dobli committed
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
def add_volumerize_service(base_dir, hostname):
    """Generates a volumerize backup entry and adds it to the compose file

    :base_dir: base directory for configuration files
    :hostname: names of host that the services is added to
    """
    base_path = base_dir + '/' + CUSTOM_DIR
    # compose file
    compose_path = base_path + '/' + COMPOSE_NAME
    # service name
    service_name = f'{Service.BACKUP.prefix}_{hostname}'
    # template
    template = get_service_template(base_dir, Service.BACKUP.prefix)

    # only label contraint is building
    template['deploy']['placement']['constraints'][0] = (
        f"{CONSTRAINTS['building']} == {hostname}")

    # attach volumes
    volume_base = '/source/'
    template['volumes'].extend(get_attachable_volume_list(
        base_dir, volume_base, hostname))

dobli's avatar
dobli committed
337
338
339
340
341
342
343
344
    # adjust config
    config_list = template['configs']
    # get backup entry from configs
    index, entry = next((i, c) for i, c in enumerate(config_list)
                        if c['source'] == 'backup_config')
    entry['source'] = f'backup_config_{hostname}'
    template['configs'][index] = entry

dobli's avatar
dobli committed
345
346
347
    add_or_update_compose_service(compose_path, service_name, template)


Dobli's avatar
Dobli committed
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
# Functions to delete services
def delete_service(base_dir, service_name):
    """Deletes a service from the compose file

    :base_dir: dir to find files in
    :returns: list of current services
    """
    base_path = base_dir + '/' + CUSTOM_DIR
    # compose file
    compose_path = base_path + '/' + COMPOSE_NAME
    with open(compose_path, 'r+') as compose_f:
        # load compose file
        compose = yaml.load(compose_f)
        # generate list of names
        compose['services'].pop(service_name, None)
        # start writing from file start
        compose_f.seek(0)
        # write new compose content
        yaml.dump(compose, compose_f)
        # reduce file to new size
        compose_f.truncate()


# Functions to extract information
dobli's avatar
dobli committed
372
def get_current_services(base_dir, placement=None):
Dobli's avatar
Dobli committed
373
374
375
376
377
378
379
380
381
382
383
384
    """Gets a list of currently used services

    :base_dir: dir to find files in
    :returns: list of current services
    """
    base_path = base_dir + '/' + CUSTOM_DIR
    # compose file
    compose_path = base_path + '/' + COMPOSE_NAME
    with open(compose_path, 'r') as compose_f:
        # load compose file
        compose = yaml.load(compose_f)
        # generate list of names
dobli's avatar
dobli committed
385
386
387
388
389
        service_names = []
        for (name, entry) in compose['services'].items():
            if placement is None or get_building_of_entry(entry) == placement:
                service_names.append(name)

Dobli's avatar
Dobli committed
390
391
392
        return service_names


dobli's avatar
dobli committed
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
def get_building_of_entry(service_dict):
    """Extract the configured building constraint from an yaml service entry

    :service_dict: service dict from yaml
    :returns: building that is set
    """
    # get constraints
    constraint_list = service_dict['deploy']['placement']['constraints']
    # convert them to dicts
    label_dict = {i.split("==")[0].strip(): i.split("==")[1].strip()
                  for i in constraint_list}
    return label_dict.get('node.labels.building')


def get_service_entry_info(service_entry):
    """Gets service name and instance of a service entry

    :service_entry: service entry name
    :return: tuple with service_name and instance name
    """
    entry_split = service_entry.split("_")
    name = entry_split[0]
    instance = entry_split[1]
    return name, instance


def get_service_volumes(base_dir, service_name):
    """Gets a list of volumes of a service

    :base_dir: dir to find files in
    :returns: list of volumes
    """
    base_path = base_dir + '/' + CUSTOM_DIR
    # compose file
    compose_path = base_path + '/' + COMPOSE_NAME
    with open(compose_path, 'r') as compose_f:
        # load compose file
        compose = yaml.load(compose_f)
        # load service
        service = compose['services'].get(service_name)

        # extract volume names
        volume_dict = yaml_list_to_dict(service['volumes'])
        volumes = list(volume_dict.keys())
        # filter only named volumes
        named_volumes = [v for v in volumes if '/' not in v]

        return named_volumes


443
# Helper functions
dobli's avatar
dobli committed
444
445
446
447
448
449
450
451
452
453
454
455
456
def get_attachable_volume_list(base_dir, volume_base, host):
    """Get a list of volumes from a host that can be attatched for file acccess

    :base_dir: Base config dir
    :volume_base: Base path of volumes
    :host: host to consider
    :returns: list of attachable volume entries
    """
    volume_list = []
    host_services = get_current_services(base_dir, host)
    for host_service in host_services:
        name, instance = get_service_entry_info(host_service)
        volume_service = Service.service_by_prefix(name)
dobli's avatar
dobli committed
457
        # only apply to services that want their volumes attatched
dobli's avatar
dobli committed
458
459
        if volume_service.sftp:
            volumes = get_service_volumes(base_dir, host_service)
dobli's avatar
dobli committed
460
461
462
463
            # collect volumes not already in list
            vlist = [
                f'{v}:{volume_base}{v}' for v in volumes
                if f'{v}:{volume_base}{v}' not in volume_list]
dobli's avatar
dobli committed
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
            volume_list.extend(vlist)
    return volume_list


def generate_named_volumes(template_volume_list, service_name, compose_path):
    """Generates volumes including name of services and ads them to
    the compose file

    :template_volume_list: List of volume entries from template
    :service_name: Name of the service instance
    :compose_path: path to compose file
    :returns: list of named entries

    """
    volume_entries = yaml_list_to_dict(template_volume_list)
    # add name to entries (that are named volumes
    named_volume_entries = {}
    for (volume, target) in volume_entries.items():
        if "/" not in volume:
            named_volume_entries[f"{service_name}_{volume}"] = target
        else:
            named_volume_entries[f"{volume}"] = target

    for (volume, target) in named_volume_entries.items():
        # declare volume if it is a named one
        if "/" not in volume:
            add_volume_entry(compose_path, volume)

    return dict_to_yaml_list(named_volume_entries)


def yaml_list_to_dict(yaml_list):
    """Converts a yaml list (volumes, configs etc) into a python dict

    :yaml_list: list of a yaml containing colon separated entries
    :return: python dict
    """
    return {i.split(":")[0]: i.split(":")[1] for i in yaml_list}


def dict_to_yaml_list(pdict):
    """Converts a python dict into a yaml list (volumes, configs etc)

    :pdict: python dict
    :return: list of a yaml containing colon separated entries
    """
    return [f'{k}:{v}' for (k, v) in pdict.items()]


513
514
515
516
517
518
519
520
521
522
523
524
def get_service_template(base_dir, service_name):
    """Gets a service template entry from the template yaml

    :return: yaml entry of a service
    """
    template_path = base_dir + '/' + TEMPLATE_DIR
    templates = template_path + '/' + TEMPLATES_NAME

    with open(templates, 'r') as templates_file:
        template_content = yaml.load(templates_file)

    return template_content['services'][service_name]
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544


def generate_traefik_host_labels(hostname, segment=None, priority=1):
    """Generates a traefik path url with necessary redirects

    :hostname: Hostname that gets assigned by the label
    :segment: Optional traefik segment when using multiple rules
    :priority: Priority of frontend rule
    :returns: list of labels for traefik
    """
    label_list = []
    # check segment
    segment = f'.{segment}' if segment is not None else ''
    # fill list
    label_list.append(
        f'traefik{segment}.frontend.rule=HostRegexp:{{domain:{hostname}}}')
    label_list.append(f'traefik{segment}.frontend.priority={priority}')
    return label_list


Dobli's avatar
Dobli committed
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
def generate_traefik_subdomain_labels(subdomain, segment=None, priority=2):
    """Generates a traefik subdomain with necessary redirects

    :subdomain: subdomain that will be assigned to a service
    :segment: Optional traefik segment when using multiple rules
    :priority: Priority of frontend rule
    :returns: list of labels for traefik
    """
    label_list = []
    # check segment
    segment = f'.{segment}' if segment is not None else ''
    # fill list
    label_list.append(
        f'traefik{segment}.frontend.rule='
        f'HostRegexp:{subdomain}.{{domain:[a-zA-z0-9-]+}}')
    label_list.append(f'traefik{segment}.frontend.priority={priority}')
    return label_list


564
565
def generate_traefik_path_labels(url_path, segment=None, priority=2,
                                 redirect=True):
566
567
568
569
570
    """Generates a traefik path url with necessary redirects

    :url_path: path that should be used for the site
    :segment: Optional traefik segment when using multiple rules
    :priority: Priority of frontend rule
571
    :redirect: Redirect to path with trailing slash
572
573
574
575
576
577
578
    :returns: list of labels for traefik
    """
    label_list = []
    # check segment
    segment = f'.{segment}' if segment is not None else ''
    # fill list
    label_list.append(f'traefik{segment}.frontend.priority={priority}')
579
580
581
582
583
584
585
586
587
588
589
    if redirect:
        label_list.append(
            f'traefik{segment}.frontend.redirect.regex=^(.*)/{url_path}$$')
        label_list.append(
            f'traefik{segment}.frontend.redirect.replacement=$$1/{url_path}/')
        label_list.append(
            f'traefik{segment}.frontend.rule=PathPrefix:/{url_path};'
            f'ReplacePathRegex:^/{url_path}/(.*) /$$1')
    else:
        label_list.append(
            f'traefik{segment}.frontend.rule=PathPrefix:/{url_path}')
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
    return label_list


def add_or_update_compose_service(compose_path, service_name, service_content):
    """Adds or replaces a service in a compose file

    :compose_path: path of the compose file to change
    :service_name: name of the service to add/replace
    :service_content: service definition to add
    """
    with open(compose_path, 'r+') as compose_f:
        # load compose file
        compose = yaml.load(compose_f)
        # add / update service with template
        compose['services'][service_name] = service_content
        # write content starting from first line
        compose_f.seek(0)
        # write new compose content
        yaml.dump(compose, compose_f)
        # reduce file to new size
        compose_f.truncate()
dobli's avatar
dobli committed
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629


def add_volume_entry(compose_path, volume_name):
    """Creates an additional volume entry in the stack file

    :compose_path: path of the compose file to change
    :volume_name: name of the additional volume
    """
    with open(compose_path, 'r+') as compose_f:
        # load compose file
        compose = yaml.load(compose_f)
        # add volume
        compose['volumes'][volume_name] = None
        # write content starting from first line
        compose_f.seek(0)
        # write new compose content
        yaml.dump(compose, compose_f)
        # reduce file to new size
        compose_f.truncate()
dobli's avatar
dobli committed
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649


def add_config_entry(compose_path, config_name, config_path):
    """Creates an additional config entry in the stack file or updates it

    :compose_path: path of the compose file to change
    :config_name: name of the additional config
    :config_path: path of the additional config
    """
    with open(compose_path, 'r+') as compose_f:
        # load compose file
        compose = yaml.load(compose_f)
        # add config
        compose['configs'][config_name] = {"file": config_path}
        # write content starting from first line
        compose_f.seek(0)
        # write new compose content
        yaml.dump(compose, compose_f)
        # reduce file to new size
        compose_f.truncate()
650
# >>>
dobli's avatar
dobli committed
651

652

653
# ******************************
654
# Config file functions <<<
655
# ******************************
656
def generate_config_folders(base_dir):
657
658
    """Generate folders for configuration files

659
    :base_dir: Path to add folders to
660
    """
661
662
663
664
665
666
    base_path = base_dir + '/' + CUSTOM_DIR
    if not os.path.exists(base_dir):
        os.makedirs(base_dir)

    print(f'Initialize configuration in {base_path}')

667
    # generate empty config dirs
668
669
670
671
672
    for d in CONFIG_DIRS:
        new_dir = base_path + '/' + d
        if not os.path.exists(new_dir):
            os.makedirs(new_dir)

673
674
675
676
    # copy template configs
    for template_file in TEMPLATE_FILES:
        copy_template_config(base_dir, template_file)

677

678
679
680
681
682
683
def copy_template_config(base_dir, config_path):
    """Copies template configuration files into custom folder

    :base_dir: path that contains template and custom folders
    :config_path: relative path of config to copy from template
    """
Dobli's avatar
Dobli committed
684
685
686
687
688
    custom_path = base_dir + '/' + CUSTOM_DIR + "/" + config_path
    template_path = base_dir + '/' + TEMPLATE_DIR + "/" + config_path

    logging.info(f'Copy {config_path} from {custom_path} to {template_path}')
    copy2(template_path, custom_path)
689
690


691
692
693
694
695
696
def generate_mosquitto_user_line(username, password):
    """Generates a line for a mosquitto user with a crypt hashed password

    :username: username to use
    :password: password that will be hashed (SHA512)

697
    :returns: a line as expected by mosquitto
698
699
700
701
702
703
    """
    password_hash = crypt.crypt(password, crypt.mksalt(crypt.METHOD_SHA512))
    line = f"{username}:{password_hash}"
    return line


704
705
706
707
def generate_sftp_user_line(username, password, directories=None):
    """Generates a line for a sftp user with a hashed password

    :username: username to use
708
    :password: password that will be hashed (SHA512)
709
710
    :directories: list of directories which the user should have

711
    :returns: a line as expected by sshd
712
713
714
    """
    # generate user line with hashed password
    password_hash = crypt.crypt(password, crypt.mksalt(crypt.METHOD_SHA512))
715
    line = f"{username}:{password_hash}:e:{UID}:{UID}"
716
717
718
719
720
721
722
723
    # add directory entries when available
    if directories:
        # create comma separated string from list
        dir_line = ','.join(d for d in directories)
        line = f"{line}:{dir_line}"
    return line


724
725
726
727
728
729
730
731
def generate_traefik_user_line(username, password):
    """Generates a line for a traefik user with a bcrypt hashed password

    :username: username to use
    :password: password that will be hashed (bcrypt)

    :returns: a line as expected by traefik
    """
Dobli's avatar
Dobli committed
732
733
    password_hash = get_bcrypt_hash(password)
    line = f"{username}:{password_hash}"
734
735
736
    return line


dobli's avatar
dobli committed
737
738
739
740
741
742
743
744
745
746
def generate_pb_framr_entry(host, service):
    """Generates a single entry of the framr file

    :host: host this entry is intended for
    :service: entry from service enum
    :returns: a dict fitting the asked entry

    """
    entry = {}
    entry['title'] = service.fullname
747
    if service == Service.OPENHAB:
dobli's avatar
dobli committed
748
749
750
        entry['url'] = f'http://{host}/'
        pass
    else:
751
        entry['url'] = f'/{service.prefix}_{host}/'
dobli's avatar
dobli committed
752
753
754
755
    entry['icon'] = service.icon
    return entry


756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
def generate_mosquitto_file(base_dir, username, password):
    """Generates a mosquitto password file using mosquitto_passwd system tool

    :base_dir: path that contains custom config folder
    :username: username to use
    :password: password that will be used
    """
    passwd_path = base_dir + '/' + CUSTOM_DIR + "/" + EDIT_FILES[
        'mosquitto_passwords']

    # ensure file exists
    if not os.path.exists(passwd_path):
        open(passwd_path, 'a').close()

    # execute mosquitto passwd
    mos_result = run(
        ['mosquitto_passwd', '-b', passwd_path, username, password],
773
        universal_newlines=True)
774
775
776
777
    return mos_result.returncode == 0


def generate_sftp_file(base_dir, username, password, direcories=None):
778
    """Generates a sftp password file
779
780
781
782
783
784
785
786
787
788
789
790

    :base_dir: path that contains custom config folder
    :username: username to use
    :password: password that will be used
    :directories: list of directories which the user should have
    """
    # generate line and save it into a file
    file_content = generate_sftp_user_line(username, password, direcories)
    create_or_replace_config_file(base_dir, EDIT_FILES['sftp_users'],
                                  file_content)


dobli's avatar
dobli committed
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
def generate_postgres_files(base_dir, username, password):
    """Generates postgres user and password files

    :base_dir: path that contains custom config folder
    :username: username to use
    :password: password that will be used
    """
    # content is purely username and (hashed) password
    hashed_password = 'md5' + \
        md5(username.encode() + password.encode()).hexdigest()
    create_or_replace_config_file(
        base_dir, EDIT_FILES['postgres_user'], username)
    create_or_replace_config_file(
        base_dir, EDIT_FILES['postgres_passwd'], hashed_password)


807
808
809
810
811
812
813
814
815
def generate_id_rsa_files(base_dir):
    """Generates id_rsa and id_rsa.pub private/public keys using ssh-keygen

    :base_dir: path that contains custom config folder
    """
    id_path = base_dir + '/' + CUSTOM_DIR + "/" + EDIT_FILES['id_rsa']

    # execute ssh-keygen
    id_result = run(
dobli's avatar
dobli committed
816
817
        ['ssh-keygen', '-m', 'PEM', '-t', 'rsa',
            '-b', '4096', '-f', id_path, '-N', ''],
818
        universal_newlines=True, stdout=PIPE)
819
820
821
822
823
824
825
826
827
828
829
    return id_result.returncode == 0


def generate_host_key_files(base_dir, hosts):
    """Generates ssh host keys and matching known_hosts using ssh-keygen

    :base_dir: path that contains custom config folder
    """
    key_path = base_dir + '/' + CUSTOM_DIR + "/" + EDIT_FILES['host_key']
    # ssh-keygen generates public key with .pub postfix
    pub_path = key_path + '.pub'
830
831
    # host_names with sftp_ postfix
    sftp_hosts = [f'sftp_{host}' for host in hosts]
832
833
834

    # execute ssh-keygen
    id_result = run(['ssh-keygen', '-t', 'ed25519', '-f', key_path, '-N', ''],
835
                    universal_newlines=True, stdout=PIPE)
836
837
838
839
840
841
842
843

    # read content of public key as known line
    known_line = ""
    with open(pub_path, 'r') as pub_file:
        pub_line = pub_file.readline()
        split_line = pub_line.split()
        # delete last list element
        del split_line[-1]
844
845
        # collect sftp hosts as comma separated string
        hosts_line = ','.join(h for h in sftp_hosts)
846
847
848
849
850
851
852
853
854
855
856
        split_line.insert(0, hosts_line)
        # collect parts as space separated string
        known_line = ' '.join(sp for sp in split_line)

    # write new known_line file
    create_or_replace_config_file(base_dir, EDIT_FILES['known_hosts'],
                                  known_line)

    return id_result.returncode == 0


Dobli's avatar
Dobli committed
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
def generate_filebrowser_file(base_dir, username, password):
    """Generates a configuration for the filebrowser web app

    :base_dir: path that contains custom config folder
    :username: username to use
    :password: password that will be used
    """
    # generate line and save it into a file
    file_content = {
        "port": "80",
        "address": "",
        "username": f"{username}",
        "password": f"{get_bcrypt_hash(password)}",
        "log": "stdout",
        "root": "/srv"
    }

    create_or_replace_config_file(base_dir, EDIT_FILES['filebrowser_conf'],
                                  file_content, json=True)


878
879
880
881
882
883
884
885
886
887
888
889
890
def generate_traefik_file(base_dir, username, password):
    """Generates a traefik password file

    :base_dir: path that contains custom config folder
    :username: username to use
    :password: password that will be used
    """
    # generate line and save it into a file
    file_content = generate_traefik_user_line(username, password)
    create_or_replace_config_file(base_dir, EDIT_FILES['traefik_users'],
                                  file_content)


dobli's avatar
dobli committed
891
def generate_volumerize_files(base_dir, hosts):
892
893
894
895
896
    """Generates config for volumerize backups

    :base_dir: path that contains custom config folder
    :hosts: names of backup hosts
    """
dobli's avatar
dobli committed
897
898
    compose_path = base_dir + '/' + CUSTOM_DIR + "/" + COMPOSE_NAME
    # create one config per host
899
    for h in hosts:
dobli's avatar
dobli committed
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
        configs = []
        # Each host knows other hosts
        for t in hosts:
            host_config = {
                'description': f'Backup Server on {t}',
                'url': f'sftp://ohadmin@sftp_{t}:'
                f'//home/ohadmin/backup_data/backup/{h}'
            }
            configs.append(host_config)

        config_file = f"{EDIT_FILES['backup_config']}_{h}.json"
        create_or_replace_config_file(
            base_dir, config_file, configs, json=True)
        add_config_entry(
            compose_path, f'backup_config_{h}', f"./{config_file}")
915
916


dobli's avatar
dobli committed
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
def generate_pb_framr_file(base_dir, frames):
    """Generates config for pb framr landing page

    :base_dir: path that contains custom config folder
    :frames: a dict that contains hosts with matching name and services
    """
    configs = []

    for f in frames:
        building = {
            'instance': f['building'],
            'entries': [generate_pb_framr_entry(f['host'], s)
                        for s in f['services'] if s.frontend]
        }
        configs.append(building)

    create_or_replace_config_file(
        base_dir, EDIT_FILES['pb_framr_pages'], configs, json=True)


937
def create_or_replace_config_file(base_dir, config_path, content, json=False):
938
939
940
941
942
943
944
945
    """Creates or replaces a config file with new content

    :base_dir: path that contains custom config folder
    :config_path: relative path of config
    :content: content of the file as a string
    """
    custom_path = base_dir + '/' + CUSTOM_DIR + "/" + config_path
    with open(custom_path, 'w+') as file:
946
947
948
949
950
        if json:
            import json
            json.dump(content, file, indent=2)
        else:
            file.write(content)
Dobli's avatar
Dobli committed
951
952
953
954
955
956
957
958
959
960


# Functions to modify existing files
def add_user_to_traefik_file(base_dir, username, password):
    """Adds or modifies user in traefik file

    :base_dir: path that contains custom config folder
    :username: username to use
    :password: password that will be used
    """
Dobli's avatar
Dobli committed
961
    # get current users
Dobli's avatar
Dobli committed
962
    current_users = get_traefik_users(base_dir)
Dobli's avatar
Dobli committed
963
    # ensure to delete old entry if user exists
Dobli's avatar
Dobli committed
964
    users = [u for u in current_users if u['username'] != username]
Dobli's avatar
Dobli committed
965
966
967
968
969
970
971
972
973
974
975
976
    # collect existing users lines
    user_lines = []
    for u in users:
        user_lines.append(f"{u['username']}:{u['password']}")
    # add new/modified user
    user_lines.append(generate_traefik_user_line(username, password))
    # generate content
    file_content = "\n".join(user_lines)
    create_or_replace_config_file(base_dir, EDIT_FILES['traefik_users'],
                                  file_content)


Dobli's avatar
Dobli committed
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
def remove_user_from_traefik_file(base_dir, username):
    """Removes user from traefik file

    :base_dir: path that contains custom config folder
    :username: username to delete
    """
    # get current users
    current_users = get_traefik_users(base_dir)
    # ensure to delete entry if user exists
    users = [u for u in current_users if u['username'] != username]
    # collect other user lines
    user_lines = []
    for u in users:
        user_lines.append(f"{u['username']}:{u['password']}")
    # generate content and write file
    file_content = "\n".join(user_lines)
    create_or_replace_config_file(base_dir, EDIT_FILES['traefik_users'],
                                  file_content)


Dobli's avatar
Dobli committed
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
# Functions to get content from files
def get_users_from_files(base_dir):
    """Gets a list of users in files

    :base_dir: dir to find files in
    :returns: list of users
    """
    users = []

    # add treafik users
    users.extend([u['username'] for u in get_traefik_users(base_dir)])

    return users


def get_traefik_users(base_dir):
    """Gets a list of dicts containing users and password hashes

    :base_dir: dir to find files in
    :returns: list of users / password dicts
    """
    users = []

    # get treafik users
    traefik_file = f"{base_dir}/{CUSTOM_DIR}/{EDIT_FILES['traefik_users']}"
    with open(traefik_file, 'r') as file:
        lines = file.read().splitlines()
        for line in lines:
            # username in traefik file is first entry unitl colon
            username = line.split(':')[0]
            password = line.split(':')[1]
            users.append({"username": username, "password": password})
    return users
Dobli's avatar
Dobli committed
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041


# Additional helper functions
def get_bcrypt_hash(password):
    """Returns bcrypt hash for a password

    :password: password to hash
    :returns: bcrypt hash of password

    """
    return bcrypt.hashpw(password.encode(), bcrypt.gensalt()).decode()

1042
# >>>
dobli's avatar
dobli committed
1043
1044


1045
# ******************************
1046
# Docker machine functions <<<
1047
# ******************************
1048
1049
1050
1051
1052
1053
def get_machine_list():
    """Get a list of docker machine names using the docker-machine system command

    :returns: a list of machine names managed by docker-machine
    """
    machine_result = run(['docker-machine', 'ls', '-q'],
1054
1055
                         universal_newlines=True,
                         stdout=PIPE)
1056
1057
1058
1059
1060
1061
1062
    return machine_result.stdout.splitlines()


def check_machine_exists(machine_name):
    """Checks weather a docker machine exists and is available

    :machine_name: Name of the machine to check
dobli's avatar
dobli committed
1063
    :returns: True when machine is available
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
    """
    machines = get_machine_list()

    return machine_name in machines


def get_machine_env(machine_name):
    """Gets dict of env settings from a machine

    :machine_name: Name of the machine to check
    :returns: Dict of env variables for this machine
    """
    env_result = run(['docker-machine', 'env', machine_name],
1077
1078
                     universal_newlines=True,
                     stdout=PIPE)
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090

    machine_envs = {}

    lines = env_result.stdout.splitlines()
    for line in lines:
        if 'export' in line:
            assign = line.split('export ', 1)[1]
            env_entry = [a.strip('"') for a in assign.split('=', 1)]
            machine_envs[env_entry[0]] = env_entry[1]
    return machine_envs


dobli's avatar
dobli committed
1091
1092
1093
1094
1095
1096
def get_machine_ip(machine_name):
    """Asks for the ip of the docker machine

    :machine_name: Name of the machine to use for init
    """
    machine_result = run(['docker-machine', 'ip', machine_name],
1097
1098
                         universal_newlines=True,
                         stdout=PIPE)
1099
    return machine_result.stdout.strip()
dobli's avatar
dobli committed
1100
1101
1102
1103
1104
1105


def init_swarm_machine(machine_name):
    """Creates a new swarm with the specified machine as leader

    :machine_name: Name of the machine to use for init
1106
    :return: True if swarm init was successful
dobli's avatar
dobli committed
1107
1108
1109
    """
    machine_ip = get_machine_ip(machine_name)
    init_command = 'docker swarm init --advertise-addr ' + machine_ip
1110
    init_result = run(['docker-machine', 'ssh', machine_name, init_command],
1111
                      universal_newlines=True)
1112
    return init_result.returncode == 0
dobli's avatar
dobli committed
1113
1114
1115
1116
1117
1118
1119


def join_swarm_machine(machine_name, leader_name):
    """Joins the swarm of the specified leader

    :machine_name: Name of the machine to join a swarm
    :leader_name: Name of the swarm leader machine
1120
    :return: True if join to swarm was successful
dobli's avatar
dobli committed
1121
1122
1123
    """
    token_command = 'docker swarm join-token manager -q'
    token_result = run(['docker-machine', 'ssh', leader_name, token_command],
1124
1125
                       universal_newlines=True,
                       stdout=PIPE)
1126
    token = token_result.stdout.strip()
dobli's avatar
dobli committed
1127
    leader_ip = get_machine_ip(leader_name)
1128
    logging.info(f"Swarm leader with ip {leader_ip} uses token {token}")
dobli's avatar
dobli committed
1129

1130
1131
1132
    join_cmd = f'docker swarm join --token {token} {leader_ip}:{SWARM_PORT}'
    logging.info(f'Machine {machine_name} joins using command {join_cmd}')
    join_result = run(['docker-machine', 'ssh', machine_name, join_cmd],
1133
                      universal_newlines=True)
dobli's avatar
dobli committed
1134

1135
    return join_result.returncode == 0
dobli's avatar
dobli committed
1136
1137


1138
1139
1140
1141
1142
1143
def generate_swarm(machines):
    """Generates a swarm, the first machine will be the initial leader

    :machines: list of machines in the swarm
    """
    leader = None
1144
    for machine in machines:
1145
1146
1147
1148
1149
1150
        # init swarm with first machine
        if leader is None:
            leader = machine
            print(f'Create initial swarm with leader {leader}')
            if init_swarm_machine(leader):
                print('Swarm init successful\n')
1151
1152
                assign_label_to_node(leader, 'building',
                                     leader, manager=leader)
1153
1154
1155
1156
        else:
            print(f'Machine {machine} joins swarm of leader {leader}')
            if (join_swarm_machine(machine, leader)):
                print('Joining swarm successful\n')
1157
1158
                assign_label_to_node(machine, 'building',
                                     machine, manager=leader)
Dobli's avatar
Dobli committed
1159
1160


1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
def check_dir_on_machine(dirpath, machine):
    """Checks weather a dir exists on a machine

    :dirpath: Directory to check
    :machine: Machine to check
    :returns: True when dir exists false otherwise
    """
    check_command = f"[ -d {dirpath} ]"
    check_result = run(['docker-machine', 'ssh', machine, check_command])
    return check_result.returncode == 0


def check_file_on_machine(filepath, machine):
    """Checks weather a file exists on a machine

    :filepath: File to check
    :machine: Machine to check
    :returns: True when file exists false otherwise
    """
    check_command = f"[ -f {filepath} ]"
    check_result = run(['docker-machine', 'ssh', machine, check_command])
    return check_result.returncode == 0


def copy_files_to_machine(filepath, machine):
    """Copyies a directory and its content or a file to a machine

    :filepath: Direcotry or file to copy
    :machine: Machine to copy to
    """
    run(['docker-machine', 'scp', '-r', filepath, f'{machine}:'])


def execute_command_on_machine(command, machine):
    """Executes a command on a docker machine

    :command: Command to execute
    :machine: Machine to execute command
    """
    run([f'docker-machine ssh {machine} {command}'], shell=True)
1201
# >>>
dobli's avatar
dobli committed
1202

dobli's avatar
dobli committed
1203

dobli's avatar
dobli committed
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
# ******************************
# Systemd functions <<<
# ******************************
def list_enabled_devices():
    """Presents a list of enabled devices (systemd services)
    :returns: list of enabled devices

    """
    list_result = run(['systemctl', 'list-units'],
                      stdout=PIPE, universal_newlines=True)
    device_list = list_result.stdout.splitlines()
    # Filter out only swarm-device services
    device_list = [d.strip() for d in device_list if 'swarm-device' in d]
    # Extract service name
    device_list = [d.split()[0] for d in device_list]
    return device_list
# >>>

dobli's avatar
dobli committed
1222

1223
# ******************************
1224
# Docker client commands <<<
1225
# ******************************
Dobli's avatar
Dobli committed
1226
def resolve_service_nodes(service):
dobli's avatar
dobli committed
1227
    """Returnes nodes running a specified service
Dobli's avatar
Dobli committed
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259

    :service: name or id of a service
    :returns: list of nodes running the service
    """
    node_result = run(['docker', 'service', 'ps', service,
                       '--format', '{{.Node}}',
                       '-f', 'desired-state=running'],
                      universal_newlines=True,
                      stdout=PIPE)
    return node_result.stdout.splitlines()


def get_container_list(manager=None):
    """Return a list of containers running on a machine

    :manager: Docker machine to use for command, otherwise local
    :returns: list of containers
    """
    client = get_docker_client(manager)
    return [c.name for c in client.containers.list()]


def get_service_list(manager=None):
    """Return a list of services managed by a machine

    :manager: Docker machine to use for command, otherwise local
    :returns: list of services
    """
    client = get_docker_client(manager)
    return [s.name for s in client.services.list()]


1260
def assign_label_to_node(nodeid, label, value, manager=None):
1261
1262
1263
1264
1265
    """Assigns a label to a node (e.g. building)

    :nodeid: Id or name of the node
    :label: Label you want to add
    :value: The value to assign to the label
Dobli's avatar
Dobli committed
1266
    :manager: Docker machine to use for command, otherwise local
1267
    """
Dobli's avatar
Dobli committed
1268
    client = get_docker_client(manager)
1269
1270
1271
1272
1273

    node = client.nodes.get(nodeid)
    spec = node.attrs['Spec']
    spec['Labels'][label] = value
    node.update(spec)
1274
    logging.info(f'Assign label {label} with value {value} to {nodeid}')
1275
1276
1277
1278

    client.close()


1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
def run_command_in_service(service, command, building=None):
    """Runs a command in a service based on its name.
    When no matching container is found or the service name is ambigous
    an error will be displayed and the function exits

    :param service: Name of the service to execute command
    :param command: Command to execute
    :param building: Optional building, make service unambigous (Default: None)
    """

Dobli's avatar
Dobli committed
1289
    client = get_docker_client(building)
1290
1291
1292
1293
1294
1295
1296

    # Find containers matching name
    service_name_filter = {"name": service}
    containers = client.containers.list(filters=service_name_filter)

    # Ensure match is unambigous
    if (len(containers) > 1):
1297
        print(f'Found multiple containers matching service name {service}, '
1298
1299
              'ensure service is unambigous')
    elif (len(containers) < 1):
1300
        print(f'Found no matching container for service name {service}')
1301
1302
    else:
        service_container = containers[0]
1303
        print(f'Executing {command} in container {service_container.name}'
Dobli's avatar
Dobli committed
1304
              f'({service_container.id}) on building {building}\n')
dobli's avatar
dobli committed
1305
1306
        command_exec = service_container.exec_run(command)
        print(command_exec.output.decode())
1307
    client.close()
1308
1309


Dobli's avatar
Dobli committed
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
def get_docker_client(manager=None):
    """Returns docker client instance

    :manager: Optional machine to use, local otherwise
    :returns: Docker client instance
    """
    if manager:
        machine_env = get_machine_env(manager)
        client = docker.from_env(environment=machine_env)
    else:
        client = docker.from_env()
    return client
dobli's avatar
dobli committed
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343


def restore_building_backup(manager, building):
    client = get_docker_client(manager)
    # get backup services of the building
    services = client.services.list(filters={'label': f'backup={building}'})

    # scale down services (to prevent writes during restore)
    for s in services:
        s.scale(0)

    # Give services 10 seconds to shutdown
    print("Wait for services to shutdown...")
    sleep(10)

    # execute restore command in backup service
    run_command_in_service('backup', 'restore', manager)

    # reload and scale up services again
    for s in services:
        s.reload()
        s.scale(1)
1344
# >>>
dobli's avatar
dobli committed
1345
1346


1347
# ******************************
1348
# CLI base commands <<<
1349
# ******************************
1350
1351
1352
1353
1354
1355
1356
1357
def init_config_dirs_command(args):
    """Initialize config directories

    :args: parsed commandline arguments
    """
    base_dir = args.base_dir

    if base_dir is None:
1358
        base_dir = os.getcwd()
1359

Dobli's avatar
Dobli committed
1360
    # generate basic config folder
1361
1362
1363
    generate_config_folders(base_dir)


1364
1365
1366
1367
1368
1369
1370
1371
def assign_building_command(args):
    """Assigns the role of a building to a node

    :args: parsed commandline arguments
    """
    node = args.node
    building = args.building

1372
    print(f'Assign role of building {building} to node {node}')
1373
1374
1375
1376

    assign_label_to_node(node, 'building', building)


1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
def execute_command(args):
    """Top level function to manage command executions from CLI

    :args: parsed commandline arguments
    """
    service = args.service
    command = " ".join(str(x) for x in args.command)  # list to string
    building = args.building

    run_command_in_service(service, command, building)


def restore_command(args):
    """Top level function to manage command executions from CLI

    :args: parsed commandline arguments
    """
1394
1395
1396
1397
    building = args.building
    target = args.target

    if not check_machine_exists(target):
1398
        print(f'Machine with name {target} not found')
1399
1400
        return

1401
    print(f'Restoring building {building} on machine {target}')
1402
1403

    get_machine_env(target)
1404
1405


1406
1407
1408
def interactive_command(args):
    """Top level function to start the interactive mode

1409
    :args: parsed command line arguments
1410
    """
Dobli's avatar
Dobli committed
1411
    main_menu(args)
1412
1413


1414
# >>>
dobli's avatar
dobli committed
1415
1416


1417
# ******************************
1418
# Interactive menu entries <<<
1419
# ******************************
1420
def main_menu(args):
1421
1422
    """ Display main menu
    """
1423
1424
1425
1426
1427
1428
    # Base directory for configs
    base_dir = args.base_dir

    if base_dir is None:
        base_dir = os.getcwd()

Dobli's avatar
Dobli committed
1429
    # Main menu prompts selection contains function
1430
1431
    choice = qust.select('Public Building Manager - Main Menu',
                         choices=load_main_entires(base_dir), style=st).ask()
1432

Dobli's avatar
Dobli committed
1433
1434
    # Call funtion of menu entry
    choice(args)
1435
1436


Dobli's avatar
Dobli committed
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
def load_main_entires(base_dir):
    """Loads entries for main menu depending on available files

    :base_dir: directory of configuration files
    :returns: entries of main menu
    """
    custom_path = base_dir + '/' + CUSTOM_DIR

    entries = []
    if not os.path.exists(custom_path):
Dobli's avatar
Dobli committed
1447
1448
        entries.append({'name': 'Create initial structure',
                        'value': init_menu})
Dobli's avatar
Dobli committed
1449
    else:
Dobli's avatar
Dobli committed
1450
1451
1452
1453
        entries.append({'name': 'Manage Services',
                        'value': service_menu})
        entries.append({'name': 'Manage Users',
                        'value': user_menu})
1454
1455
        entries.append({'name': 'Manage Devices',
                        'value': device_menu})
dobli's avatar
dobli committed
1456
1457
        entries.append({'name': 'Manage Backups',
                        'value': backup_menu})
Dobli's avatar
Dobli committed
1458
1459
        entries.append({'name': 'Execute a command in a service container',
                        'value': exec_menu})
Dobli's avatar
Dobli committed
1460

Dobli's avatar
Dobli committed
1461
    entries.append({'name': 'Exit', 'value': sys.exit})
Dobli's avatar
Dobli committed
1462
1463
1464
1465

    return entries


Dobli's avatar
Dobli committed
1466
1467
1468
1469
1470
1471
def exit_menu(args):
    """Exits the programm
    """
    sys.exit()


Dobli's avatar
Dobli committed
1472
# *** Init Menu Entries ***
1473
def init_menu(args):
1474
    """Menu entry for initial setup and file generation
Dobli's avatar
Dobli committed
1475
1476

    :args: Passed commandline arguments
1477
    """
1478
1479
1480
1481
1482
1483
1484
    # Base directory for configs
    base_dir = args.base_dir

    if base_dir is None:
        base_dir = os.getcwd()

    # Prompts
1485
1486
1487
1488
    stack_name = qust.text('Choose a name for your setup', style=st).ask()
    hosts = qust.checkbox('What docker machines will be used?',
                          choices=generate_cb_choices(
                              get_machine_list()), style=st).ask()
1489
1490
1491
    # Ensure passwords match
    password_match = False
    while not password_match:
1492
1493
1494
1495
1496
        password = qust.password(
            'Choose a password for the ohadmin user:', style=st).ask()
        confirm = qust.password(
            'Repeat password for the ohadmin user:', style=st).ask()
        if password == confirm:
1497
            password_match = True
dobli's avatar
dobli committed
1498
        else:
1499
            print("Passwords did not match, try again")
1500

1501
1502
    # Initialize custom configuration dirs and templates
    generate_config_folders(base_dir)
1503
    generate_initial_compose(base_dir)
1504
    # Generate config files based on input
Dobli's avatar
Dobli committed
1505
    username = ADMIN_USER
dobli's avatar
dobli committed
1506
    generate_sftp_file(base_dir, username, password, ['backup_data/backup'])
dobli's avatar
dobli committed
1507
    generate_postgres_files(base_dir, username, password)
1508
1509
    generate_mosquitto_file(base_dir, username, password)
    generate_traefik_file(base_dir, username, password)
dobli's avatar
dobli committed
1510
    generate_volumerize_files(base_dir, hosts)
Dobli's avatar
Dobli committed
1511
    generate_filebrowser_file(base_dir, username, password)
1512
    generate_id_rsa_files(base_dir)
1513
1514
    generate_host_key_files(base_dir, hosts)

dobli's avatar
dobli committed
1515
    frames = []
1516
    for i, host in enumerate(hosts):
dobli's avatar
dobli committed
1517
1518
1519
1520
1521
1522
1523
        building, services = init_machine_menu(base_dir, host, i)
        frames.append({'host': host,
                       'building': building, 'services': services})

    # When frames is not empty generate frame config
    if frames:
        generate_pb_framr_file(base_dir, frames)
1524

1525
    # print(answers)
1526
    print(f"Configuration files for {stack_name} generated in {base_dir}")
1527
1528

    # Check if changes shall be applied to docker environment
1529
1530
    generate = qust.confirm(
        'Apply changes to docker environment?', default=True, style=st).ask()
1531

1532
1533
    if generate:
        generate_swarm(hosts)
1534
1535


1536
1537
1538
1539
1540
1541
def init_machine_menu(base_dir, host, increment):
    """Prompts to select server services

    :base_dir: Directory of config files
    :host: docker-machine host
    :increment: incrementing number to ensure ports are unique
dobli's avatar
dobli committed
1542
    :return: choosen building name and services
1543
1544
    """
    # Prompt for services
1545
1546
1547
    building = qust.text(f'Choose a name for building on server {host}',
                         default=f'{host}', style=st).ask()
    services = qust.checkbox(f'What services shall {host} provide?',
dobli's avatar
dobli committed
1548
                             choices=generate_cb_service_choices(checked=True),
1549
                             style=st).ask()
dobli's avatar
dobli committed
1550
    if Service.OPENHAB in services:
1551
        add_openhab_service(base_dir, host)
dobli's avatar
dobli committed
1552
    if Service.NODERED in services:
1553
        add_nodered_service(base_dir, host)
dobli's avatar
dobli committed
1554
    if Service.MQTT in services:
1555
        add_mqtt_service(base_dir, host, increment)
dobli's avatar
dobli committed
1556
    if Service.POSTGRES in services:
dobli's avatar
dobli committed
1557
        add_postgres_service(base_dir, host)
dobli's avatar
dobli committed
1558
1559
    if Service.BACKUP in services:
        add_volumerize_service(base_dir, host)
1560
1561
    if Service.FILES in services:
        add_file_service(base_dir, host)
dobli's avatar
dobli committed
1562
1563
    if Service.SFTP in services:
        add_sftp_service(base_dir, host, increment)
dobli's avatar
dobli committed
1564
    return building, services
1565
1566


Dobli's avatar
Dobli committed
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
# *** Exec Menu Entries ***
def exec_menu(args):
    """Menu entry for executing commands in services

    :args: Passed commandline arguments
    """
    machine = docker_client_prompt(" to execute command at")
    service_name = qust.select(
        'Which service container shall execute the command?',
        choices=get_container_list(machine), style=st).ask()
    command = qust.text('What command should be executed?', style=st).ask()

    run_command_in_service(service_name, command, machine)


# *** User Menu Entries ***
def user_menu(args):
    """Menu entry for user managment

    :args: Passed commandline arguments
    """
Dobli's avatar
Dobli committed
1588
1589
1590
1591
1592
1593
1594
    # Base directory for configs
    base_dir = args.base_dir

    if base_dir is None:
        base_dir = os.getcwd()

    # Ask for action
Dobli's avatar
Dobli committed
1595
    choice = qust.select("What do you want to do?", choices=[
1596
1597
        'Add a new user', 'Modify existing user', 'Exit'],
        style=st).ask()
Dobli's avatar
Dobli committed
1598
1599
    if "Add" in choice:
        new_user_menu(base_dir)
Dobli's avatar
Dobli committed
1600
1601
    elif "Modify" in choice:
        modify_user_menu(base_dir)
Dobli's avatar
Dobli committed
1602
1603


Dobli's avatar
Dobli committed
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
def new_user_menu(base_dir):
    """Menu entry for new users

    :base_dir: Directory of config files
    """
    current_users = get_users_from_files(base_dir)
    new_user = False
    while not new_user:
        username = qust.text("Choose a new username:", style=st).ask()
        if username not in current_users:
            new_user = True
        else:
            print(f"User with name {username} already exists, try again")

    # Ensure passwords match
    password_match = False
    while not password_match:
        password = qust.password(
            f'Choose a password for the user {username}:', style=st).ask()
        confirm = qust.password(
            f'Repeat password for the user {username}:', style=st).ask()
        if password == confirm:
            password_match = True
        else:
            print("Passwords did not match, try again")

    add_user_to_traefik_file(base_dir, username, password)


Dobli's avatar
Dobli committed
1633
def modify_user_menu(base_dir):
Dobli's avatar
Dobli committed
1634
    """Menu entry to remove users or change passwords
Dobli's avatar
Dobli committed
1635
1636
1637
1638

    :base_dir: Directory of config files
    """
    current_users = get_users_from_files(base_dir)
Dobli's avatar
Dobli committed
1639
1640
    user = qust.select("Choose user to modify:",
                       choices=current_users, style=st).ask()
Dobli's avatar
Dobli committed
1641

Dobli's avatar
Dobli committed
1642
1643
1644
1645
1646
1647
1648
1649
1650
    if user == 'ohadmin':
        choices = [{'name': 'Delete user',
                    'disabled': 'Disabled: cannot delete admin user'},
                   'Change password', 'Exit']
    else:
        choices = ['Delete user', 'Change password', 'Exit']

    action = qust.select(
        f"What should we do with {user}?", choices=choices, style=st).ask()
Dobli's avatar
Dobli committed
1651
1652

    if 'Delete' in action:
Dobli's avatar
Dobli committed
1653
1654
1655
1656
        is_sure = qust.confirm(
            f"Are you sure you want to delete user {user}?", style=st).ask()
        if is_sure:
            remove_user_from_traefik_file(base_dir, user)
Dobli's avatar
Dobli committed
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
    elif 'Change' in action:
        password_match = False
        while not password_match:
            password = qust.password(
                f'Choose a password for the user {user}:', style=st).ask()
            confirm = qust.password(
                f'Repeat password for the user {user}:', style=st).ask()
            if password == confirm:
                password_match = True
            else:
                print("Passwords did not match, try again")
Dobli's avatar
Dobli committed
1668
        add_user_to_traefik_file(base_dir, user, password)
Dobli's avatar
Dobli committed
1669
1670


Dobli's avatar
Dobli committed
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
# *** Service Menu Entries ***
def service_menu(args):
    """Menu entry for service managment

    :args: Passed commandline arguments
    """
    # Base directory for configs
    base_dir = args.base_dir

    if base_dir is None:
        base_dir = os.getcwd()

    # Ask for action
    choice = qust.select("What do you want to do?", choices=[
1685
1686
        'Modify existing services', 'Add additional service',
        'Exit'], style=st).ask()
Dobli's avatar
Dobli committed
1687
    if "Add" in choice:
1688
        service_add_menu(base_dir)
Dobli's avatar
Dobli committed
1689
1690
1691
1692
    elif "Modify" in choice:
        service_modify_menu(base_dir)


1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
def service_add_menu(base_dir):
    """Menu to add additional services

    :base_dir: Directory of config files
    """
    services = [s for s in Service if s.additional]
    service = qust.select(
        'What service do you want to add?', style=st,
        choices=generate_cb_service_choices(service_list=services)).ask()

    host = qust.select('Where should the service be located?',
                       choices=generate_cb_choices(
                           get_machine_list()), style=st).ask()
    identifier = qust.text(
        'Input an all lower case identifier:', style=st).ask()

    if service and host and identifier:
1710
1711
        if service == Service.POSTGRES:
            add_postgres_service(base_dir, host, postfix=identifier)
1712
1713


Dobli's avatar
Dobli committed
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
def service_modify_menu(base_dir):
    """Menu to modify services

    :base_dir: Directory of config files
    """
    services = get_current_services(base_dir)
    service = qust.select(
        'What service do you want to modify?', choices=services).ask()

    if service in ['proxy', 'landing']:
        choices = [{'name': 'Remove service',
                    'disabled': 'Disabled: cannot remove framework services'},
                   'Exit']
    else:
        choices = ['Remove service', 'Exit']

    action = qust.select(
        f"What should we do with {service}?", choices=choices, style=st).ask()

    if 'Remove' in action:
        delete_service(base_dir, service)


1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
# *** Device Menu Functions ***
def device_menu(args):
    """Menu to manage devices

    :args: Arguments form commandline
    """
    print("Adding device")
    # Base directory for configs
    base_dir = args.base_dir

    if base_dir is None:
        base_dir = os.getcwd()

    # Check if device scripts are installed
dobli's avatar
dobli committed
1751
    bin_path = '/usr/bin/enable-swarm-device'
1752
1753

    choices = ['Install device scripts']
dobli's avatar
dobli committed
1754
    if os.path.exists(bin_path):
1755
        choices.append('Link device to service')
dobli's avatar
dobli committed
1756
        choices.append('Unlink device')
1757
1758
1759
1760

    choices.append('Exit')

    # Ask for action
1761
1762
    choice = qust.select("What do you want to do? (root required)",
                         choices=choices, style=st).ask()
1763
    if "Install" in choice:
dobli's avatar
dobli committed
1764
        print("Installing device scripts (needs root)")
1765
1766
        device_install_menu(base_dir)
    elif "Link" in choice:
dobli's avatar
dobli committed
1767
        device_link_menu(base_dir)
dobli's avatar
dobli committed
1768
1769
    elif "Unlink" in choice:
        device_unlink_menu(base_dir)
1770
1771
1772
1773
1774
1775
1776


def device_install_menu(base_dir):
    """Install scripts to link devices

    :base_dir: Base directory of configuration files
    """
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
    machine = docker_client_prompt(" to install usb support")

    # Name of base dir on machines
    external_base_dir = os.path.basename(base_dir)

    # Check if files are available on targeted machine
    machine_dir = f"{external_base_dir}/install-usb-support.sh"
    print(machine_dir)
    if not check_file_on_machine(machine_dir, machine):
        print("Scripts missing on machine, will be copied")
        copy_files_to_machine(base_dir, machine)
    else:
        print("Scripts available on machine")

    execute_command_on_machine(f'sudo {machine_dir}', machine)
1792
1793


dobli's avatar
dobli committed
1794
1795
1796
1797
1798
def device_link_menu(base_dir):
    """Link device to a service

    :base_dir: Base directory of configuration files
    """
1799
    machine = docker_client_prompt(" to link device on")
dobli's avatar
dobli committed
1800
    device = qust.select("What device should be linked?",
1801
1802
1803
                         choices=USB_DEVICES, style=st).ask()

    # Start systemd service that ensures link (escapes of backslash needed)
dobli's avatar
dobli committed
1804
    link_cmd = f"sudo systemctl enable --now swarm-device@" + \
1805
1806
1807
        f"{device}\\\\\\\\x20openhab.service"

    # Needs enable to keep after reboot
dobli's avatar
dobli committed
1808
    execute_command_on_machine(link_cmd, machine)
1809
    print(f"Linked device {device} to openHAB service on machine {machine}")
dobli's avatar
dobli committed
1810
1811


dobli's avatar
dobli committed
1812
1813
1814
1815
1816
def device_unlink_menu(base_dir):
    """Unlink a device from a service

    :base_dir: Base directory of configuration files
    """
dobli's avatar
dobli committed
1817
    machine = docker_client_prompt(" to unlink device from")
dobli's avatar
dobli committed
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
    device = qust.select("What device should be unlinked?",
                         choices=USB_DEVICES, style=st).ask()

    # Stop systemd service that ensures link (escapes of backslash needed)
    link_cmd = f"sudo systemctl disable --now swarm-device@" + \
        f"{device}\\\\\\\\x20openhab.service"

    execute_command_on_machine(link_cmd, machine)
    print(f"Unlinked device {device} on machine {machine}")


dobli's avatar
dobli committed
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
# *** Backup Menu Entries ***
def backup_menu(args):
    """Menu entry for backup managment

    :args: Passed commandline arguments
    """
    # Base directory for configs
    base_dir = args.base_dir

    if base_dir is None:
        base_dir = os.getcwd()

    # Ask for action
    choice = qust.select("What do you want to do?", choices=[
        'Execute backup', 'Restore backup', 'Exit'],
        style=st).ask()
    if "Execute" in choice:
        execute_backup_menu(base_dir)
    elif "Restore" in choice:
        restore_backup_menu(base_dir)
        print("Restore")


def execute_backup_menu(base_dir):
    """Submenu for backup execution

    :base_dir: Base directory of configuration files
    """
    machine = docker_client_prompt(" to backup")

    full = qust.confirm("Execute full backup (otherwise partial)?",
                        default=False, style=st).ask()
    if full:
        run_command_in_service('backup', 'backupFull', machine)
        print("Full backup completed")
    else:
        run_command_in_service('backup', 'backup', machine)
        print("Partial backup completed")


def restore_backup_menu(base_dir):
    """Submenu for backup execution

    :base_dir: Base directory of configuration files
    """
    machine = docker_client_prompt(" to restore")

    confirm = qust.confirm(
        f'Restore services from last backup on machine {machine} '
        '(current data will be lost)?',
        default=False,
        style=st).ask()

    if confirm:
        restore_building_backup(machine, machine)
        print("Restore completed")
    else:
        print("Restore canceled")


Dobli's avatar
Dobli committed
1889
# *** Menu Helper Functions ***
1890
def generate_cb_choices(list, checked=False):
dobli's avatar
dobli committed
1891
1892
    """Generates checkbox entries for lists of strings

1893
1894
    :list: pyhton list that shall be converted
    :checked: if true, selections will be checked by default
dobli's avatar
dobli committed
1895
1896
    :returns: A list of dicts with name keys
    """
1897
    return [{'name': m, 'checked': checked} for m in list]
Dobli's avatar
Dobli committed
1898
1899


1900
def generate_cb_service_choices(checked=False, service_list=None):
dobli's avatar
dobli committed
1901
1902
1903
    """Generates checkbox entries for the sevice enum

    :checked: if true, selections will be checked by default
1904
    :service_list: optional list of services, use all if empty
dobli's avatar
dobli committed
1905
1906
    :returns: A list of dicts with name keys
    """
1907
    services = service_list if service_list is not None else Service
dobli's avatar
dobli committed
1908
    return [
1909
        {'name': s.fullname, 'value': s, 'checked': checked} for s in services
dobli's avatar
dobli committed
1910
1911
1912
    ]


Dobli's avatar
Dobli committed
1913
1914
1915
1916
1917
1918
def docker_client_prompt(message_details=''):
    """Show list of docker machines and return selection

    :manager: Optional machine to use, prompt otherwise
    :returns: Docker client instance
    """
1919
1920
1921
1922
    machine = qust.select(f'Choose manager machine{message_details}',
                          choices=get_machine_list(), style=st).ask()
    return machine
# >>>
dobli's avatar
dobli committed
1923

1924

1925
# ******************************
1926
# Script main (entry) <<<
1927
# ******************************
1928
1929
1930
if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser(
1931
        prog='building_manager',
1932
1933
        description='Generate and manage multi'
        'building configurations of openHAB with docker swarm')
1934
1935
1936
1937
    parser.add_argument(
        '--base_dir',
        '-d',
        help='Directory to creat config folders in, default is current dir')
1938
1939
    subparsers = parser.add_subparsers()

1940
1941
1942
1943
1944
1945
    # Interactive mode
    parser_interactive = subparsers.add_parser(
        'interactive',
        help='Starts the interactive mode of the building manager')
    parser_interactive.set_defaults(func=interactive_command)

1946
1947
1948
    # Restore command
    parser_restore = subparsers.add_parser('restore', help='Restore backups')
    parser_restore.add_argument(
1949
        'building', help='Name (label) of the building that shall be restored')
1950
1951
1952
1953
    parser_restore.add_argument(
        'target', help='Name of the machine to restore to')
    parser_restore.set_defaults(func=restore_command)

1954
1955
1956
1957
1958
1959
1960
1961
1962
    # Assign building command
    parser_assign_building = subparsers.add_parser(
        'assign_building', help='Assign the role of a building to a node')
    parser_assign_building.add_argument(
        'node', help='Name (or ID) of the node that gets the role assigned')
    parser_assign_building.add_argument(
        'building', help='Name of the building that will be assigned')
    parser_assign_building.set_defaults(func=assign_building_command)

1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
    # Execute command
    parser_exec = subparsers.add_parser(
        'exec', help='Execute commands in a service container')
    parser_exec.add_argument(
        'service', help='Name of the service that will run the command')
    parser_exec.add_argument(
        'command', help='Command to be executed', nargs=argparse.REMAINDER)
    parser_exec.add_argument(
        '--building',
        '-b',
        help='Building name (label) of the service if '
        'service location is ambiguous')
    parser_exec.set_defaults(func=execute_command)

1977
1978
1979
1980
1981
1982
1983
1984
1985
    # Config commands
    parser_config = subparsers.add_parser(
        'config', help='Manage configuration files')
    parser_config_subs = parser_config.add_subparsers()
    # - Config init
    parser_config_init = parser_config_subs.add_parser(
        'init', help='Initialize config file directories')
    parser_config_init.set_defaults(func=init_config_dirs_command)

1986
    # Parse arguments into args dict
1987
    args = parser.parse_args()
1988
1989
1990
1991
1992
1993

    # when no subcommand is defined show interactive menu
    try:
        args.func(args)
    except AttributeError:
        interactive_command(args)
1994
# >>>
dobli's avatar
dobli committed
1995
1996

# --- vim settings ---
1997
# vim:foldmethod=marker:foldlevel=0:foldmarker=<<<,>>>