building_manager.py 37.9 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
5
import logging
6
import os
dobli's avatar
dobli committed
7
from hashlib import md5
8
from shutil import copy2
9
10
11
12
from subprocess import PIPE, run

import bcrypt
import docker
13
import questionary as qust
14
from ruamel.yaml import YAML
15
from prompt_toolkit.styles import Style
16
17
18
19

# Configure YAML
yaml = YAML()
yaml.indent(mapping=4, sequence=4, offset=2)
20
21
22

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

24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# 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 <<<
# ******************************

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

77
# Default Swarm port
dobli's avatar
dobli committed
78
SWARM_PORT = 2377
79
80
# UID for admin
UID = 9001
Dobli's avatar
Dobli committed
81
82
# Username for admin
ADMIN_USER = 'ohadmin'
dobli's avatar
dobli committed
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98


class Service(Enum):
    SFTP = ("SFTP", "sftp_X", False)
    OPENHAB = ("OpenHAB", "openhab_X", True, '/', 'dashboard')
    NODERED = ("Node-RED", "nodered_X", True, 'nodered', 'ballot')
    POSTGRES = ("Postgre SQL", "postgres_X", False)
    MQTT = ("Mosquitto MQTT Broker", "mqtt_X", False)

    def __init__(self, fullname, compose_entry, frontend,
                 prefix=None, icon=None):
        self.fullname = fullname
        self.compose_entry = compose_entry
        self.frontend = frontend
        self.prefix = prefix
        self.icon = icon
99
100
# >>>

101
102

# ******************************
103
# Compose file functions <<<
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
# ******************************
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}'
134
135
136
137
138
139
    # template
    template = get_service_template(base_dir, SERVICES['sftp'])
    # only label contraint is building
    template['deploy']['placement']['constraints'][0] = (
        f"{CONSTRAINTS['building']} == {hostname}")
    template['ports'] = [f'{2222 + number}:22']
140

141
    add_or_update_compose_service(compose_path, service_name, template)
142
143
144
145
146
147
148
149
150
151
152
153
154


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}'
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
    # template
    template = get_service_template(base_dir, SERVICES['openhab'])
    # 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')

    add_or_update_compose_service(compose_path, service_name, template)
174
175
176
177
178
179
180
181
182
183
184
185
186


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}'
187
188
189
190
191
192
193
194
195
    # template
    template = get_service_template(base_dir, SERVICES['nodered'])
    # 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
196
197
    template['deploy']['labels'].extend(
        generate_traefik_subdomain_labels(service_name, segment='sub'))
198

199
    add_or_update_compose_service(compose_path, service_name, template)
200
201
202
203
204
205
206
207
208
209
210
211
212
213


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}'
214
215
216
217
218
219
220
    # template
    template = get_service_template(base_dir, SERVICES['mqtt'])
    # 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']
221

222
    add_or_update_compose_service(compose_path, service_name, template)
223
224


dobli's avatar
dobli committed
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
def add_postgres_service(base_dir, hostname):
    """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
    """
    base_path = base_dir + '/' + CUSTOM_DIR
    # compose file
    compose_path = base_path + '/' + COMPOSE_NAME
    # service name
    service_name = f'postgres_{hostname}'
    # template
    template = get_service_template(base_dir, SERVICES['postgres'])
    # only label contraint is building
    template['deploy']['placement']['constraints'][0] = (
        f"{CONSTRAINTS['building']} == {hostname}")

    add_or_update_compose_service(compose_path, service_name, template)


245
# Helper functions
246
247
248
249
250
251
252
253
254
255
256
257
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]
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277


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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
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


297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
def generate_traefik_path_labels(url_path, segment=None, priority=2):
    """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
    :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}')
    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')
    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()
338
# >>>
dobli's avatar
dobli committed
339

340

341
# ******************************
342
# Config file functions <<<
343
# ******************************
344
def generate_config_folders(base_dir):
345
346
    """Generate folders for configuration files

347
    :base_dir: Path to add folders to
348
    """
349
350
351
352
353
354
    base_path = base_dir + '/' + CUSTOM_DIR
    if not os.path.exists(base_dir):
        os.makedirs(base_dir)

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

355
    # generate empty config dirs
356
357
358
359
360
    for d in CONFIG_DIRS:
        new_dir = base_path + '/' + d
        if not os.path.exists(new_dir):
            os.makedirs(new_dir)

361
362
363
364
    # copy template configs
    for template_file in TEMPLATE_FILES:
        copy_template_config(base_dir, template_file)

365

366
367
368
369
370
371
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
372
373
374
375
376
    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)
377
378


379
380
381
382
383
384
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)

385
    :returns: a line as expected by mosquitto
386
387
388
389
390
391
    """
    password_hash = crypt.crypt(password, crypt.mksalt(crypt.METHOD_SHA512))
    line = f"{username}:{password_hash}"
    return line


392
393
394
395
def generate_sftp_user_line(username, password, directories=None):
    """Generates a line for a sftp user with a hashed password

    :username: username to use
396
    :password: password that will be hashed (SHA512)
397
398
    :directories: list of directories which the user should have

399
    :returns: a line as expected by sshd
400
401
402
    """
    # generate user line with hashed password
    password_hash = crypt.crypt(password, crypt.mksalt(crypt.METHOD_SHA512))
403
    line = f"{username}:{password_hash}:e:{UID}:{UID}"
404
405
406
407
408
409
410
411
    # 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


412
413
414
415
416
417
418
419
420
421
422
423
424
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
    """
    password_hash = bcrypt.hashpw(password.encode(), bcrypt.gensalt())
    line = f"{username}:{password_hash.decode()}"
    return line


dobli's avatar
dobli committed
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
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
    if service.prefix == "/":
        entry['url'] = f'http://{host}/'
        pass
    else:
        entry['url'] = f'/{service.prefix}_{host}'
    entry['icon'] = service.icon
    return entry


444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
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],
461
        universal_newlines=True)
462
463
464
465
    return mos_result.returncode == 0


def generate_sftp_file(base_dir, username, password, direcories=None):
466
    """Generates a sftp password file
467
468
469
470
471
472
473
474
475
476
477
478

    :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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
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)


495
496
497
498
499
500
501
502
503
504
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(
        ['ssh-keygen', '-t', 'rsa', '-b', '4096', '-f', id_path, '-N', ''],
505
        universal_newlines=True, stdout=PIPE)
506
507
508
509
510
511
512
513
514
515
516
    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'
517
518
    # host_names with sftp_ postfix
    sftp_hosts = [f'sftp_{host}' for host in hosts]
519
520
521

    # execute ssh-keygen
    id_result = run(['ssh-keygen', '-t', 'ed25519', '-f', key_path, '-N', ''],
522
                    universal_newlines=True, stdout=PIPE)
523
524
525
526
527
528
529
530

    # 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]
531
532
        # collect sftp hosts as comma separated string
        hosts_line = ','.join(h for h in sftp_hosts)
533
534
535
536
537
538
539
540
541
542
543
        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


544
545
546
547
548
549
550
551
552
553
554
555
556
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)


557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
def generate_volumerize_file(base_dir, hosts):
    """Generates config for volumerize backups

    :base_dir: path that contains custom config folder
    :hosts: names of backup hosts
    """
    configs = []

    for h in hosts:
        host_config = {
            'description': f'Backup Server on {h}',
            'url': f'sftp://ohadmin@sftp_{h}://home/ohadmin/backup_data/{h}'
        }
        configs.append(host_config)

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


dobli's avatar
dobli committed
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
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)


596
def create_or_replace_config_file(base_dir, config_path, content, json=False):
597
598
599
600
601
602
603
604
    """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:
605
606
607
608
609
        if json:
            import json
            json.dump(content, file, indent=2)
        else:
            file.write(content)
610
# >>>
dobli's avatar
dobli committed
611
612


613
# ******************************
614
# Docker machine functions <<<
615
# ******************************
616
617
618
619
620
621
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'],
622
623
                         universal_newlines=True,
                         stdout=PIPE)
624
625
626
627
628
629
630
    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
631
    :returns: True when machine is available
632
633
634
635
636
637
638
639
640
641
642
643
644
    """
    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],
645
646
                     universal_newlines=True,
                     stdout=PIPE)
647
648
649
650
651
652
653
654
655
656
657
658

    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
659
660
661
662
663
664
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],
665
666
                         universal_newlines=True,
                         stdout=PIPE)
667
    return machine_result.stdout.strip()
dobli's avatar
dobli committed
668
669
670
671
672
673


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
674
    :return: True if swarm init was successful
dobli's avatar
dobli committed
675
676
677
    """
    machine_ip = get_machine_ip(machine_name)
    init_command = 'docker swarm init --advertise-addr ' + machine_ip
678
    init_result = run(['docker-machine', 'ssh', machine_name, init_command],
679
                      universal_newlines=True)
680
    return init_result.returncode == 0
dobli's avatar
dobli committed
681
682
683
684
685
686
687


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
688
    :return: True if join to swarm was successful
dobli's avatar
dobli committed
689
690
691
    """
    token_command = 'docker swarm join-token manager -q'
    token_result = run(['docker-machine', 'ssh', leader_name, token_command],
692
693
                       universal_newlines=True,
                       stdout=PIPE)
694
    token = token_result.stdout.strip()
dobli's avatar
dobli committed
695
    leader_ip = get_machine_ip(leader_name)
696
    logging.info(f"Swarm leader with ip {leader_ip} uses token {token}")
dobli's avatar
dobli committed
697

698
699
700
    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],
701
                      universal_newlines=True)
dobli's avatar
dobli committed
702

703
    return join_result.returncode == 0
dobli's avatar
dobli committed
704
705


706
707
708
709
710
711
def generate_swarm(machines):
    """Generates a swarm, the first machine will be the initial leader

    :machines: list of machines in the swarm
    """
    leader = None
712
    for machine in machines:
713
714
715
716
717
718
        # 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')
719
720
                assign_label_to_node(leader, 'building',
                                     leader, manager=leader)
721
722
723
724
        else:
            print(f'Machine {machine} joins swarm of leader {leader}')
            if (join_swarm_machine(machine, leader)):
                print('Joining swarm successful\n')
725
726
                assign_label_to_node(machine, 'building',
                                     machine, manager=leader)
Dobli's avatar
Dobli committed
727
728


729
# >>>
dobli's avatar
dobli committed
730
731


732
# ******************************
733
# Docker client commands <<<
734
# ******************************
Dobli's avatar
Dobli committed
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
def resolve_service_nodes(service):
    """Returnes nodes running on a specified service

    :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()]


769
def assign_label_to_node(nodeid, label, value, manager=None):
770
771
772
773
774
    """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
775
    :manager: Docker machine to use for command, otherwise local
776
    """
Dobli's avatar
Dobli committed
777
    client = get_docker_client(manager)
778
779
780
781
782

    node = client.nodes.get(nodeid)
    spec = node.attrs['Spec']
    spec['Labels'][label] = value
    node.update(spec)
783
    logging.info(f'Assign label {label} with value {value} to {nodeid}')
784
785
786
787

    client.close()


788
789
790
791
792
793
794
795
796
797
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
798
    client = get_docker_client(building)
799
800
801
802
803
804
805

    # 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):
806
        print(f'Found multiple containers matching service name {service}, '
807
808
              'ensure service is unambigous')
    elif (len(containers) < 1):
809
        print(f'Found no matching container for service name {service}')
810
811
    else:
        service_container = containers[0]
812
        print(f'Executing {command} in container {service_container.name}'
Dobli's avatar
Dobli committed
813
              f'({service_container.id}) on building {building}\n')
dobli's avatar
dobli committed
814
815
        command_exec = service_container.exec_run(command)
        print(command_exec.output.decode())
816
    client.close()
817
818


Dobli's avatar
Dobli committed
819
820
821
822
823
824
825
826
827
828
829
830
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
831
# >>>
dobli's avatar
dobli committed
832
833


834
# ******************************
835
# CLI base commands <<<
836
# ******************************
837
838
839
840
841
842
843
844
def init_config_dirs_command(args):
    """Initialize config directories

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

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

Dobli's avatar
Dobli committed
847
    # generate basic config folder
848
849
850
    generate_config_folders(base_dir)


851
852
853
854
855
856
857
858
def assign_building_command(args):
    """Assigns the role of a building to a node

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

859
    print(f'Assign role of building {building} to node {node}')
860
861
862
863

    assign_label_to_node(node, 'building', building)


864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
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
    """
881
882
883
884
    building = args.building
    target = args.target

    if not check_machine_exists(target):
885
        print(f'Machine with name {target} not found')
886
887
        return

888
    print(f'Restoring building {building} on machine {target}')
889
890

    get_machine_env(target)
891
892


893
894
895
def interactive_command(args):
    """Top level function to start the interactive mode

896
    :args: parsed command line arguments
897
    """
Dobli's avatar
Dobli committed
898
    main_menu(args)
899
900


901
# >>>
dobli's avatar
dobli committed
902
903


904
# ******************************
905
# Interactive menu entries <<<
906
# ******************************
907
def main_menu(args):
908
909
    """ Display main menu
    """
910
911
912
913
914
915
916
    # Base directory for configs
    base_dir = args.base_dir

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

    # Main menu prompts
917
918
    choice = qust.select('Public Building Manager - Main Menu',
                         choices=load_main_entires(base_dir), style=st).ask()
919

Dobli's avatar
Dobli committed
920
    if 'Create' in choice:
921
        init_menu(args)
Dobli's avatar
Dobli committed
922
923
    elif 'Execute' in choice:
        exec_menu(args)
Dobli's avatar
Dobli committed
924
925
    elif 'User' in choice:
        user_menu(args)
926

927
    return choice
928
929


Dobli's avatar
Dobli committed
930
931
932
933
934
935
936
937
938
939
940
941
942
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):
        entries.append('Create initial structure')
    else:
        entries.append('Execute a command in a service container')
Dobli's avatar
Dobli committed
943
        entries.append('Manage Users')
Dobli's avatar
Dobli committed
944
945
946
947
948
949

    entries.append('Exit')

    return entries


Dobli's avatar
Dobli committed
950
# *** Init Menu Entries ***
951
def init_menu(args):
952
    """Menu entry for initial setup and file generation
Dobli's avatar
Dobli committed
953
954

    :args: Passed commandline arguments
955
    """
956
957
958
959
960
961
962
    # Base directory for configs
    base_dir = args.base_dir

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

    # Prompts
963
964
965
966
    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()
967
968
969
    # Ensure passwords match
    password_match = False
    while not password_match:
970
971
972
973
974
        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:
975
            password_match = True
dobli's avatar
dobli committed
976
        else:
977
            print("Passwords did not match, try again")
978

979
980
    # Initialize custom configuration dirs and templates
    generate_config_folders(base_dir)
981
    generate_initial_compose(base_dir)
982
    # Generate config files based on input
Dobli's avatar
Dobli committed
983
    username = ADMIN_USER
984
    generate_sftp_file(base_dir, username, password)
dobli's avatar
dobli committed
985
    generate_postgres_files(base_dir, username, password)
986
987
    generate_mosquitto_file(base_dir, username, password)
    generate_traefik_file(base_dir, username, password)
988
    generate_volumerize_file(base_dir, hosts)
989
    generate_id_rsa_files(base_dir)
990
991
    generate_host_key_files(base_dir, hosts)

dobli's avatar
dobli committed
992
    frames = []
993
    for i, host in enumerate(hosts):
dobli's avatar
dobli committed
994
995
996
997
998
999
1000
        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)
1001

1002
    # print(answers)
1003
    print(f"Configuration files for {stack_name} generated in {base_dir}")
1004
1005

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

1009
1010
    if generate:
        generate_swarm(hosts)
1011
1012


1013
1014
1015
1016
1017
1018
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
1019
    :return: choosen building name and services
1020
1021
    """
    # Prompt for services
1022
1023
1024
    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
1025
                             choices=generate_cb_service_choices(checked=True),
1026
                             style=st).ask()
dobli's avatar
dobli committed
1027
    if Service.SFTP in services:
1028
        add_sftp_service(base_dir, host, increment)
dobli's avatar
dobli committed
1029
    if Service.OPENHAB in services:
1030
        add_openhab_service(base_dir, host)
dobli's avatar
dobli committed
1031
    if Service.NODERED in services:
1032
        add_nodered_service(base_dir, host)
dobli's avatar
dobli committed
1033
    if Service.MQTT in services:
1034
        add_mqtt_service(base_dir, host, increment)
dobli's avatar
dobli committed
1035
    if Service.POSTGRES in services:
dobli's avatar
dobli committed
1036
        add_postgres_service(base_dir, host)
dobli's avatar
dobli committed
1037
    return building, services
1038
1039


Dobli's avatar
Dobli committed
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
# *** 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
    """
    choice = qust.select("What do you want to do?", choices=[
                         'Add a new user', 'Remove existing user'],
                         style=st).ask()
    print(choice)


Dobli's avatar
Dobli committed
1067
# *** Menu Helper Functions ***
1068
def generate_cb_choices(list, checked=False):
dobli's avatar
dobli committed
1069
1070
    """Generates checkbox entries for lists of strings

1071
1072
    :list: pyhton list that shall be converted
    :checked: if true, selections will be checked by default
dobli's avatar
dobli committed
1073
1074
    :returns: A list of dicts with name keys
    """
1075
    return [{'name': m, 'checked': checked} for m in list]
Dobli's avatar
Dobli committed
1076
1077


dobli's avatar
dobli committed
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
def generate_cb_service_choices(checked=False):
    """Generates checkbox entries for the sevice enum

    :checked: if true, selections will be checked by default
    :returns: A list of dicts with name keys
    """
    return [
        {'name': s.fullname, 'value': s, 'checked': checked} for s in Service
    ]


Dobli's avatar
Dobli committed
1089
1090
1091
1092
1093
1094
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
    """
1095
1096
1097
1098
    machine = qust.select(f'Choose manager machine{message_details}',
                          choices=get_machine_list(), style=st).ask()
    return machine
# >>>
dobli's avatar
dobli committed
1099

1100

1101
# ******************************
1102
# Script main (entry) <<<
1103
# ******************************
1104
1105
1106
if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser(
1107
        prog='building_manager',
1108
1109
        description='Generate and manage multi'
        'building configurations of openHAB with docker swarm')
1110
1111
1112
1113
    parser.add_argument(
        '--base_dir',
        '-d',
        help='Directory to creat config folders in, default is current dir')
1114
1115
    subparsers = parser.add_subparsers()

1116
1117
1118
1119
1120
1121
    # Interactive mode
    parser_interactive = subparsers.add_parser(
        'interactive',
        help='Starts the interactive mode of the building manager')
    parser_interactive.set_defaults(func=interactive_command)

1122
1123
1124
    # Restore command
    parser_restore = subparsers.add_parser('restore', help='Restore backups')
    parser_restore.add_argument(
1125
        'building', help='Name (label) of the building that shall be restored')
1126
1127
1128
1129
    parser_restore.add_argument(
        'target', help='Name of the machine to restore to')
    parser_restore.set_defaults(func=restore_command)

1130
1131
1132
1133
1134
1135
1136
1137
1138
    # 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)

1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
    # 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)

1153
1154
1155
1156
1157
1158
1159
1160
1161
    # 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)

1162
    # Parse arguments into args dict
1163
    args = parser.parse_args()
1164
1165
1166
1167
1168
1169

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

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