~fo0bar/turku/turku-agent-encoding

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
#!/usr/bin/env python

# Turku backups - client agent
# Copyright 2015 Canonical Ltd.
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published by
# the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranties of MERCHANTABILITY,
# SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with
# this program.  If not, see <http://www.gnu.org/licenses/>.

from __future__ import print_function
import uuid
import string
import random
import json
import os
import copy
import subprocess
import sys
import platform
import time

CONFIG_D = '/etc/turku-agent/config.d'
SOURCES_D = '/etc/turku-agent/sources.d'
SOURCES_SECRETS_D = '/etc/turku-agent/sources_secrets.d'
SSH_PRIVATE_KEY = '/etc/turku-agent/id_rsa'
SSH_PUBLIC_KEY = '/etc/turku-agent/id_rsa.pub'
RSYNCD_CONF = '/etc/turku-agent/rsyncd.conf'
RSYNCD_SECRETS = '/etc/turku-agent/rsyncd.secrets'
VAR_DIR = '/var/lib/turku-agent'
RESTORE_DIR = '/var/backups/turku-agent/restore'


def json_dump_p(obj, f):
    """Calls json.dump with standard (pretty) formatting"""
    return json.dump(obj, f, sort_keys=True, indent=4, separators=(',', ': '))


def json_dumps_p(obj):
    """Calls json.dumps with standard (pretty) formatting"""
    return json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': '))


def dict_merge(s, m):
    """Recursively merge one dict into another."""
    if not isinstance(m, dict):
        return m
    out = copy.deepcopy(s)
    for k, v in m.items():
        if k in out and isinstance(out[k], dict):
            out[k] = dict_merge(out[k], v)
        else:
            out[k] = copy.deepcopy(v)
    return out


def parse_args():
    import argparse

    parser = argparse.ArgumentParser(
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('--wait', '-w', type=float)
    return parser.parse_args()


def check_directories():
    for d in (CONFIG_D, SOURCES_D, VAR_DIR):
        if not os.path.isdir(d):
            os.makedirs(d)
    for d in (SOURCES_SECRETS_D,):
        if not os.path.isdir(d):
            os.makedirs(d)
            os.chmod(d, 0o700)
    for f in (SSH_PRIVATE_KEY, SSH_PUBLIC_KEY, RSYNCD_CONF, RSYNCD_SECRETS):
        d = os.path.dirname(f)
        if not os.path.isdir(d):
            os.makedirs(d)


def parse_config():
    api_config = {}
    built_config = {
        'machine': {},
        'sources': {}
    }

    root_config = {}

    # Merge in config.d/*.json to the root level
    config_files = [os.path.join(CONFIG_D, fn) for fn in os.listdir(CONFIG_D) if fn.endswith('.json') and os.path.isfile(os.path.join(CONFIG_D, fn)) and os.access(os.path.join(CONFIG_D, fn), os.R_OK)]
    config_files.sort()
    for file in config_files:
        with open(file) as f:
            j = json.load(f)
        root_config = dict_merge(root_config, j)

    # Validate the unit name
    if not 'unit_name' in root_config:
        root_config['unit_name'] = platform.node()
        # If this isn't in the on-disk config, don't write it; just
        # generate it every time

    # Validate the machine UUID/secret
    write_uuid_data = False
    if not 'machine_uuid' in root_config:
        root_config['machine_uuid'] = str(uuid.uuid4())
        write_uuid_data = True
    if not 'machine_secret' in root_config:
        root_config['machine_secret'] = ''.join(random.choice(string.ascii_letters + string.digits) for i in range(30))
        write_uuid_data = True
    # Write out the machine UUID/secret if needed
    if write_uuid_data:
        with open(os.path.join(CONFIG_D, '10-machine_uuid.json'), 'w') as f:
            os.chmod(os.path.join(CONFIG_D, '10-machine_uuid.json'), 0o600)
            json_dump_p({'machine_uuid': root_config['machine_uuid'], 'machine_secret': root_config['machine_secret']}, f)

    # Restoration configuration
    write_restore_data = False
    if not 'restore_path' in root_config:
        root_config['restore_path'] = RESTORE_DIR
        write_restore_data = True
    if not 'restore_module' in root_config:
        root_config['restore_module'] = 'turku-restore'
        write_restore_data = True
    if not 'restore_username' in root_config:
        root_config['restore_username'] = str(uuid.uuid4())
        write_restore_data = True
    if not 'restore_password' in root_config:
        root_config['restore_password'] = ''.join(random.choice(string.ascii_letters + string.digits) for i in range(30))
        write_restore_data = True
    if write_restore_data:
        with open(os.path.join(CONFIG_D, '10-restore.json'), 'w') as f:
            os.chmod(os.path.join(CONFIG_D, '10-restore.json'), 0o600)
            restore_out = {
                'restore_path': root_config['restore_path'],
                'restore_module': root_config['restore_module'],
                'restore_username': root_config['restore_username'],
                'restore_password': root_config['restore_password'],
            }
            json_dump_p(restore_out, f)
    if not os.path.isdir(root_config['restore_path']):
        os.makedirs(root_config['restore_path'])

    # Generate the SSH keypair if it doesn't exist
    if not os.path.isfile(SSH_PUBLIC_KEY):
        subprocess.check_call(['ssh-keygen', '-t', 'rsa', '-N', '', '-C', 'turku', '-f', SSH_PRIVATE_KEY])

    # Pull the SSH public key
    with open(SSH_PUBLIC_KEY) as f:
        root_config['ssh_public_key'] = f.read().rstrip()

    # Merge the following options into the api_config
    api_merge_map = (
        ('api_url', 'api_url'),
    )
    api_merge = {}
    for a, b in api_merge_map:
        if a in root_config:
            api_merge[b] = root_config[a]
    api_config = dict_merge(api_config, api_merge)

    # Merge the following options into the root
    root_merge_map = (
        ('api_auth', 'auth'),
    )
    root_merge = {}
    for a, b in root_merge_map:
        if a in root_config:
            root_merge[b] = root_config[a]
    built_config = dict_merge(built_config, root_merge)

    # Merge the following options into the machine section
    machine_merge_map = (
        ('machine_uuid', 'uuid'),
        ('machine_secret', 'secret'),
        ('environment_name', 'environment_name'),
        ('service_name', 'service_name'),
        ('unit_name', 'unit_name'),
        ('ssh_public_key', 'ssh_public_key'),
    )
    machine_merge = {}
    for a, b in machine_merge_map:
        if a in root_config:
            machine_merge[b] = root_config[a]
    built_config = dict_merge(built_config, {'machine': machine_merge})

    # Merge in sources.d/*.json to the sources dict
    sources_files = [os.path.join(SOURCES_D, fn) for fn in os.listdir(SOURCES_D) if fn.endswith('.json') and os.path.isfile(os.path.join(SOURCES_D, fn)) and os.access(os.path.join(SOURCES_D, fn), os.R_OK)]
    sources_files.sort()
    for file in sources_files:
        with open(file) as f:
            j = json.load(f)
        for s in j.keys():
            # Ignore incomplete source entries
            if not 'path' in j[s]:
                print('WARNING: Path not found for "%s", not using.' % s, file=sys.stderr)
                del j[s]
        built_config = dict_merge(built_config, {'sources': j})

    for s in built_config['sources']:
        # Check for missing usernames/passwords
        if not ('username' in built_config['sources'][s] or 'password' in built_config['sources'][s]):
            # If they're in sources_secrets.d, use them
            if os.path.isfile(os.path.join(SOURCES_SECRETS_D, s + '.json')):
                with open(os.path.join(SOURCES_SECRETS_D, s + '.json')) as f:
                    j = json.load(f)
                built_config = dict_merge(built_config, {'sources': {s: j}})
        # Check again and generate sources_secrets.d if still not found
        if not ('username' in built_config['sources'][s] or 'password' in built_config['sources'][s]):
            if not 'username' in built_config['sources'][s]:
                built_config['sources'][s]['username'] = str(uuid.uuid4())
            if not 'password' in built_config['sources'][s]:
                built_config['sources'][s]['password'] = ''.join(random.choice(string.ascii_letters + string.digits) for i in range(30))
            with open(os.path.join(SOURCES_SECRETS_D, s + '.json'), 'w') as f:
                json_dump_p({'username': built_config['sources'][s]['username'], 'password': built_config['sources'][s]['password']}, f)

    #print(json_dumps_p(built_config))

    built_config['restore'] = {
        'path': root_config['restore_path'],
        'module': root_config['restore_module'],
        'username': root_config['restore_username'],
        'password': root_config['restore_password'],
    }

    return((built_config, api_config))


def write_conf_files(built_config):
    # Build rsyncd.conf
    built_rsyncd_conf = 'address = 127.0.0.1\nport = 27873\nlog file = /dev/stdout\nuid = root\ngid = root\nlist = false\n\n'
    rsyncd_secrets = []
    rsyncd_secrets.append((built_config['restore']['username'], built_config['restore']['password']))
    built_rsyncd_conf += '[%s]\n    path = %s\n    auth users = %s\n    secrets file = %s\n    read only = false\n\n' % (built_config['restore']['module'], built_config['restore']['path'], built_config['restore']['username'], RSYNCD_SECRETS)
    for s in built_config['sources']:
        sd = built_config['sources'][s]
        rsyncd_secrets.append((sd['username'], sd['password']))
        built_rsyncd_conf += '[%s]\n    path = %s\n    auth users = %s\n    secrets file = %s\n    read only = true\n\n' % (s, sd['path'], sd['username'], RSYNCD_SECRETS)
    with open(RSYNCD_CONF, 'w') as f:
        f.write(built_rsyncd_conf)

    #print(built_rsyncd_conf)

    # Build rsyncd.secrets
    built_rsyncd_secrets = ''
    for (username, password) in rsyncd_secrets:
        built_rsyncd_secrets += username + ':' + password + '\n'
    with open(RSYNCD_SECRETS, 'w') as f:
        os.chmod(RSYNCD_SECRETS, 0o600)
        f.write(built_rsyncd_secrets)

    #print(built_rsyncd_secrets)


def restart_services():
    # Restart rsyncd
    if not subprocess.call(['service', 'turku-agent-rsyncd', 'restart']) == 0:
        subprocess.check_call(['service', 'turku-agent-rsyncd', 'start'])


def send_config(built_config, api_config):
    if not 'api_url' in api_config:
        return

    import httplib
    import urlparse

    # Send the completed config to the API server
    url = urlparse.urlparse(api_config['api_url'])
    if url.scheme == 'https':
        h = httplib.HTTPSConnection(url.netloc, timeout=5)
    else:
        h = httplib.HTTPConnection(url.netloc, timeout=5)
    dumped_json = json.dumps(built_config)
    h.putrequest('POST', '%s/update_config' % url.path)
    h.putheader('Content-Type', 'application/json')
    h.putheader('Content-Length', len(dumped_json))
    h.putheader('Accept', 'application/json')
    h.endheaders()
    h.send(dumped_json)

    # Read/validate the response
    res = h.getresponse()
    if not res.status == httplib.OK:
        return
    if not res.getheader('content-type') == 'application/json':
        return
    try:
        server_config = json.load(res)
    except ValueError:
        return

    # Write the response
    with open(os.path.join(VAR_DIR, 'server_config.json'), 'w') as f:
        os.chmod(os.path.join(VAR_DIR, 'server_config.json'), 0o600)
        json_dump_p(server_config, f)


def main(argv):
    args = parse_args()
    # Sleep a random amount of time if requested
    if args.wait:
        time.sleep(random.uniform(0, args.wait))

    check_directories()
    (built_config, api_config) = parse_config()
    write_conf_files(built_config)
    send_config(built_config, api_config)
    restart_services()


if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))