~wesmason/conn-check/configs-add-juju

« back to all changes in this revision

Viewing changes to conn_check_configs/juju/status.py

  • Committer: Wes Mason
  • Date: 2014-09-26 21:13:51 UTC
  • Revision ID: wesley.mason@canonical.com-20140926211351-83wjl383yqsub6bl
Add refactored juju status config generator

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#!/usr/bin/env python
 
2
 
 
3
import subprocess
 
4
import sys
 
5
import yaml
 
6
 
 
7
 
 
8
def get_checks(env):
 
9
    checks = []
 
10
    for name, service in env['services'].items():
 
11
        for unit_name, unit in service.get('units', {}).items():
 
12
            host = unit.get('public-address')
 
13
            if not host:
 
14
                continue
 
15
            for port_proto in unit.get('open-ports', []):
 
16
                port, proto = port_proto.split('/')
 
17
                if proto == 'tcp':
 
18
                    checks.append({
 
19
                        'type': proto,
 
20
                        'host': host,
 
21
                        'port': int(port),
 
22
                    })
 
23
    return checks
 
24
 
 
25
 
 
26
def main(args):
 
27
    parser = argparse.ArgumentParser()
 
28
    parser.add_argument('output_file')
 
29
    parser.add_argument('-s', '--use-stdin',
 
30
                        dest="stdin",
 
31
                        action="store_true",
 
32
                        default=False)
 
33
    opts = parser.parse_args(args)
 
34
 
 
35
    if opts.stdin:
 
36
        env = sys.stdin
 
37
    else:
 
38
        cmd = 'juju status --format=yaml'
 
39
        process = subprocess.Popen(cmd,
 
40
                                   stdout=subprocess.PIPE,
 
41
                                   stderr=subprocess.PIPE)
 
42
        env, err = process.communicate()
 
43
        err_code = process.returncode
 
44
 
 
45
        if err_code != 0:
 
46
            sys.stderr.write('Calling `{}` errored:'.format(cmd))
 
47
            sys.stderr.write(err)
 
48
            return err_code
 
49
 
 
50
    checks = get_checks(yaml.load(env))
 
51
 
 
52
    with open(opts.output_file, 'w') as f:
 
53
        yaml.dump(checks, f, default_flow_style=False)
 
54
 
 
55
    return 0
 
56
 
 
57
 
 
58
def run():
 
59
    sys.exit(main(sys.argv))
 
60
 
 
61
 
 
62
if __name__ == '__main__':
 
63
    run()