Jon Hall | 6e70975 | 2016-02-01 13:38:46 -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 | import hashlib |
| 15 | |
| 16 | convert = lambda text: int(text) if text.isdigit() else text.lower() |
| 17 | alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)] |
| 18 | |
| 19 | def get_OC_vars(): |
| 20 | vars = [] |
| 21 | for var in environ: |
| 22 | if re.match(r"OC[0-9]+", var): |
| 23 | vars.append(var) |
| 24 | return sorted(vars, key=alphanum_key) |
| 25 | |
| 26 | def get_nodes(vars, port=9876): |
| 27 | node = lambda k: { 'id': k, 'ip': k, 'port': port } |
| 28 | return [ node(environ[v]) for v in vars ] |
| 29 | |
| 30 | def generate_base_partition(nodes): |
| 31 | return { |
| 32 | 'id': 0, |
| 33 | 'members': nodes |
| 34 | } |
| 35 | |
| 36 | def generate_extended_partitions(nodes, k): |
| 37 | l = deque(nodes) |
| 38 | perms = [] |
| 39 | for i in range(1, len(nodes)+1): |
| 40 | part = { |
| 41 | 'id': i, |
| 42 | 'members': list(l)[:k] |
| 43 | } |
| 44 | perms.append(part) |
| 45 | l.rotate(-1) |
| 46 | return perms |
| 47 | |
| 48 | def generate_extended_partitions_HA(nodes, k): |
| 49 | l = deque(nodes) |
| 50 | perms = [] |
| 51 | for i in range(1, (len(nodes) + 1) / 2 + 1): |
| 52 | part = { |
| 53 | 'id': i, |
| 54 | 'members': list(l)[:k] |
| 55 | } |
| 56 | perms.append(part) |
| 57 | l.rotate(-2) |
| 58 | return perms |
| 59 | |
| 60 | if __name__ == '__main__': |
| 61 | vars = get_OC_vars() |
| 62 | nodes = get_nodes(vars) |
| 63 | base_partition = generate_base_partition([v.get('id') for v in nodes]) |
| 64 | extended_partitions = generate_extended_partitions_HA([v.get('id') for v in nodes], 3) |
| 65 | partitions = [] |
| 66 | partitions.append(base_partition) |
| 67 | partitions.extend(extended_partitions) |
| 68 | name = 0 |
| 69 | for node in nodes: |
| 70 | name = name ^ hash(node['ip']) |
| 71 | data = { |
| 72 | 'name': name, |
| 73 | 'nodes': nodes, |
| 74 | 'partitions': partitions |
| 75 | } |
| 76 | output = json.dumps(data, indent=4) |
| 77 | |
| 78 | if len(sys.argv) == 2: |
| 79 | filename = sys.argv[1] |
| 80 | with open(filename, 'w') as f: |
| 81 | f.write(output) |
| 82 | else: |
| 83 | print output |