Brian O'Connor | 6e19243 | 2015-02-26 15:17:23 -0800 | [diff] [blame] | 1 | #!/usr/bin/env python |
| 2 | ''' |
| 3 | Generate the partitions json file from the $OC* environment variables |
| 4 | |
| 5 | Usage: onos-gen-partitions [output file] |
| 6 | If output file is not provided, the json is written to stdout. |
| 7 | ''' |
| 8 | |
| 9 | from os import environ |
| 10 | from collections import deque, OrderedDict |
| 11 | import re |
| 12 | import json |
| 13 | import sys |
| 14 | |
| 15 | convert = lambda text: int(text) if text.isdigit() else text.lower() |
| 16 | alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)] |
| 17 | |
| 18 | def get_OC_vars(): |
| 19 | vars = [] |
| 20 | for var in environ: |
| 21 | if re.match(r"OC[0-9]+", var): |
| 22 | vars.append(var) |
| 23 | return sorted(vars, key=alphanum_key) |
| 24 | |
Madan Jampani | 27b69c6 | 2015-05-15 15:49:02 -0700 | [diff] [blame] | 25 | def get_nodes(vars, port=9876): |
Madan Jampani | ec1df02 | 2015-10-13 21:23:03 -0700 | [diff] [blame^] | 26 | node = lambda k: { 'id': k, 'ip': k, 'port': port } |
Brian O'Connor | 6e19243 | 2015-02-26 15:17:23 -0800 | [diff] [blame] | 27 | return [ node(environ[v]) for v in vars ] |
| 28 | |
| 29 | def generate_permutations(nodes, k): |
| 30 | l = deque(nodes) |
Madan Jampani | ec1df02 | 2015-10-13 21:23:03 -0700 | [diff] [blame^] | 31 | perms = [] |
Brian O'Connor | 6e19243 | 2015-02-26 15:17:23 -0800 | [diff] [blame] | 32 | for i in range(1, len(nodes)+1): |
Madan Jampani | ec1df02 | 2015-10-13 21:23:03 -0700 | [diff] [blame^] | 33 | part = { |
| 34 | 'name': 'p%d' % i, |
| 35 | 'members': list(l)[:k] |
| 36 | } |
| 37 | perms.append(part) |
Brian O'Connor | 6e19243 | 2015-02-26 15:17:23 -0800 | [diff] [blame] | 38 | l.rotate(-1) |
Madan Jampani | ec1df02 | 2015-10-13 21:23:03 -0700 | [diff] [blame^] | 39 | return perms |
Brian O'Connor | 6e19243 | 2015-02-26 15:17:23 -0800 | [diff] [blame] | 40 | |
| 41 | if __name__ == '__main__': |
| 42 | vars = get_OC_vars() |
| 43 | nodes = get_nodes(vars) |
Madan Jampani | ec1df02 | 2015-10-13 21:23:03 -0700 | [diff] [blame^] | 44 | partitions = generate_permutations([v.get('id') for v in nodes], 3) |
| 45 | data = { |
| 46 | 'name': 'default', |
Brian O'Connor | 6e19243 | 2015-02-26 15:17:23 -0800 | [diff] [blame] | 47 | 'nodes': nodes, |
| 48 | 'partitions': partitions |
| 49 | } |
| 50 | output = json.dumps(data, indent=4) |
| 51 | |
| 52 | if len(sys.argv) == 2: |
| 53 | filename = sys.argv[1] |
| 54 | with open(filename, 'w') as f: |
| 55 | f.write(output) |
| 56 | else: |
| 57 | print output |