building_manager.py 13.3 KB
Newer Older
1
2
#!/usr/bin/env python
import docker
3
import logging
4
import os
5

6
from shutil import copy2
7
from subprocess import run
8
from PyInquirer import prompt
9
10
11

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

13
# Directories for config generation
14
15
CUSTOM_DIR = 'custom_configs'
TEMPLATE_DIR = 'template_configs'
Dobli's avatar
Dobli committed
16
17
18
19
CONFIG_DIRS = ['mosquitto', 'nodered', 'ssh', 'traefik', 'volumerize']
TEMPLATE_FILES = [
    'mosquitto/mosquitto.conf', 'nodered/nodered_package.json',
    'nodered/nodered_settings.js', 'ssh/sshd_config', 'traefik/traefik.toml'
20
]
21

22
# Default Swarm port
dobli's avatar
dobli committed
23
24
SWARM_PORT = 2377

25

26
# ******************************
dobli's avatar
dobli committed
27
# Config file functions {{{
28
# ******************************
29
def generate_config_folders(base_dir):
30
31
    """Generate folders for configuration files

32
    :base_dir: Path to add folders to
33
    """
34
35
36
37
38
39
    base_path = base_dir + '/' + CUSTOM_DIR
    if not os.path.exists(base_dir):
        os.makedirs(base_dir)

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

40
41
42
43
44
45
    for d in CONFIG_DIRS:
        new_dir = base_path + '/' + d
        if not os.path.exists(new_dir):
            os.makedirs(new_dir)


46
47
48
49
50
51
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
52
53
54
55
56
    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)
57
58


59
60
61
62
63
64
65
66
67
68
69
70
71
72
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)
    :returns: a line as expected by mosquitto

    """
    import crypt
    password_hash = crypt.crypt(password, crypt.mksalt(crypt.METHOD_SHA512))
    line = f"{username}:{password_hash}"
    return line


dobli's avatar
dobli committed
73
74
75
# }}}


76
# ******************************
dobli's avatar
dobli committed
77
# Docker machine functions {{{
78
# ******************************
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
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'],
                         text=True,
                         capture_output=True)
    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
94
    :returns: True when machine is available
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
    """
    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],
                     text=True,
                     capture_output=True)

    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
122
123
124
125
126
127
128
129
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],
                         text=True,
                         capture_output=True)
130
    return machine_result.stdout.strip()
dobli's avatar
dobli committed
131
132
133
134
135
136


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
137
    :return: True if swarm init was successful
dobli's avatar
dobli committed
138
139
140
    """
    machine_ip = get_machine_ip(machine_name)
    init_command = 'docker swarm init --advertise-addr ' + machine_ip
141
142
143
144
    init_result = run(['docker-machine', 'ssh', machine_name, init_command],
                      text=True,
                      capture_output=True)
    return init_result.returncode == 0
dobli's avatar
dobli committed
145
146
147
148
149
150
151


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
152
    :return: True if join to swarm was successful
dobli's avatar
dobli committed
153
154
155
156
157
    """
    token_command = 'docker swarm join-token manager -q'
    token_result = run(['docker-machine', 'ssh', leader_name, token_command],
                       text=True,
                       capture_output=True)
158
    token = token_result.stdout.strip()
dobli's avatar
dobli committed
159
    leader_ip = get_machine_ip(leader_name)
160
    logging.info(f"Swarm leader with ip {leader_ip} uses token {token}")
dobli's avatar
dobli committed
161

162
163
164
    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],
dobli's avatar
dobli committed
165
166
167
                      text=True,
                      capture_output=True)

168
    return join_result.returncode == 0
dobli's avatar
dobli committed
169
170


dobli's avatar
dobli committed
171
172
173
# }}}


174
# ******************************
dobli's avatar
dobli committed
175
# Docker client commands {{{
176
# ******************************
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
def assign_label_to_node(nodeid, label, value):
    """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
    """
    client = docker.from_env()

    node = client.nodes.get(nodeid)
    spec = node.attrs['Spec']
    spec['Labels'][label] = value
    node.update(spec)

    client.close()


194
195
196
197
198
199
200
201
202
203
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)
    """

204
205
206
207
208
    if building:
        building_env = get_machine_env(building)
        client = docker.from_env(environment=building_env)
    else:
        client = docker.from_env()
209
210
211
212
213
214
215

    # 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):
216
        print(f'Found multiple containers matching service name {service}, '
217
218
              'ensure service is unambigous')
    elif (len(containers) < 1):
219
        print(f'Found no matching container for service name {service}')
220
221
    else:
        service_container = containers[0]
222
223
        print(f'Executing {command} in container {service_container.name}'
              f'({service_container.id}) on building {building}')
224
        print(service_container.exec_run(command))
225
    client.close()
226
227


dobli's avatar
dobli committed
228
229
230
# }}}


231
# ******************************
dobli's avatar
dobli committed
232
# CLI base commands {{{
233
# ******************************
234
235
236
237
238
239
240
241
def init_config_dirs_command(args):
    """Initialize config directories

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

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

Dobli's avatar
Dobli committed
244
    # generate basic config folder
245
246
    generate_config_folders(base_dir)

Dobli's avatar
Dobli committed
247
248
249
250
    # copy template configs
    for template_file in TEMPLATE_FILES:
        copy_template_config(base_dir, template_file)

251

252
253
254
255
256
257
258
259
def assign_building_command(args):
    """Assigns the role of a building to a node

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

260
    print(f'Assign role of building {building} to node {node}')
261
262
263
264

    assign_label_to_node(node, 'building', building)


265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
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
    """
282
283
284
285
    building = args.building
    target = args.target

    if not check_machine_exists(target):
286
        print(f'Machine with name {target} not found')
287
288
        return

289
    print(f'Restoring building {building} on machine {target}')
290
291

    get_machine_env(target)
292
293


294
295
296
297
298
299
300
301
def interactive_command(args):
    """Top level function to start the interactive mode

    :args: command line arguments
    """
    print(main_menu())


dobli's avatar
dobli committed
302
303
304
# }}}


305
# ******************************
dobli's avatar
dobli committed
306
# Interactive menu entries {{{
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
# ******************************
def main_menu():
    """ Display main menu
    """
    questions = [{
        'type':
        'list',
        'name':
        'main',
        'message':
        'Public Building Manager - Main Menu',
        'choices': ['Create initial structure', 'Execute command', 'Exit']
    }]
    answers = prompt(questions)

    if 'Create' in answers['main']:
        init_menu()

    return answers


def init_menu():
    """Menu entry for initial setup and file generation
    """
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
    questions = [{
        'type': 'input',
        'name': 'stack_name',
        'message': 'Choose a name for your setup'
    },
                 {
                     'type': 'checkbox',
                     'name': 'machines',
                     'message': 'What docker machines will be used?',
                     'choices': generate_checkbox_choices(get_machine_list())
                 },
                 {
                     'type': 'input',
                     'name': 'username',
                     'message': 'Choose a username for the initial user'
                 },
                 {
                     'type': 'password',
                     'name': 'password',
                     'message': 'Choose a password for the initial user'
                 }]
352
353
    answers = prompt(questions)

dobli's avatar
dobli committed
354
355
356
357
358
359
    leader = None

    for machine in answers['machines']:
        # init swarm with first machine
        if leader is None:
            leader = machine
360
            print(f'Create initial swarm with leader {leader}')
361
362
            if init_swarm_machine(leader):
                print('Swarm init successful\n')
dobli's avatar
dobli committed
363
        else:
364
365
366
            print(f'Machine {machine} joins swarm of leader {leader}')
            if (join_swarm_machine(machine, leader)):
                print('Joining swarm successful\n')
367
368
369
370

    user_line = generate_mosquitto_user_line(answers['username'],
                                             answers['password'])
    print(user_line)
371
372
373
    print(answers)


dobli's avatar
dobli committed
374
375
376
377
378
379
380
381
def generate_checkbox_choices(list):
    """Generates checkbox entries for lists of strings

    :returns: A list of dicts with name keys
    """
    return [{'name': m} for m in list]


dobli's avatar
dobli committed
382
383
# }}}

384
# ******************************
dobli's avatar
dobli committed
385
# Script main (entry) {{{
386
# ******************************
387
388
389
390
391
392
393
394
if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser(
        prog='building_manger',
        description='Generate and manage multi'
        'building configurations of openHAB with docker swarm')
    subparsers = parser.add_subparsers()

395
396
397
398
399
400
    # Interactive mode
    parser_interactive = subparsers.add_parser(
        'interactive',
        help='Starts the interactive mode of the building manager')
    parser_interactive.set_defaults(func=interactive_command)

401
402
403
    # Restore command
    parser_restore = subparsers.add_parser('restore', help='Restore backups')
    parser_restore.add_argument(
404
        'building', help='Name (label) of the building that shall be restored')
405
406
407
408
    parser_restore.add_argument(
        'target', help='Name of the machine to restore to')
    parser_restore.set_defaults(func=restore_command)

409
410
411
412
413
414
415
416
417
    # 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)

418
419
420
421
422
423
424
425
426
427
428
429
430
431
    # 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)

432
433
434
435
436
437
438
439
440
441
442
443
444
    # 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.add_argument(
        '--base_dir',
        '-d',
        help='Directory to creat config folders in, default is current dir')
    parser_config_init.set_defaults(func=init_config_dirs_command)

445
446
    args = parser.parse_args()
    args.func(args)
dobli's avatar
dobli committed
447
448
449
450
# }}}

# --- vim settings ---
# vim:foldmethod=marker:foldlevel=0