A R Karthick | f2f4ca6 | 2016-08-17 10:34:08 -0700 | [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] [node_ip ...] |
| 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(ips=None, port=9876): |
| 27 | node = lambda k: { 'id': k, 'ip': k, 'port': port } |
| 28 | if not ips: |
| 29 | ips = [ environ[v] for v in get_OC_vars() ] |
| 30 | return [ node(v) for v in ips ] |
| 31 | |
| 32 | def generate_partitions(nodes, k): |
| 33 | l = deque(nodes) |
| 34 | perms = [] |
| 35 | for i in range(1, len(nodes)+1): |
| 36 | part = { |
| 37 | 'id': i, |
| 38 | 'members': list(l)[:k] |
| 39 | } |
| 40 | perms.append(part) |
| 41 | l.rotate(-1) |
| 42 | return perms |
| 43 | |
| 44 | if __name__ == '__main__': |
| 45 | nodes = get_nodes(sys.argv[2:]) |
| 46 | partitions = generate_partitions([v.get('id') for v in nodes], 3) |
| 47 | m = hashlib.sha256() |
| 48 | for node in nodes: |
| 49 | m.update(node['ip']) |
| 50 | name = int(m.hexdigest()[:8], base=16) # 32-bit int based on SHA256 digest |
| 51 | data = { |
| 52 | 'name': name, |
| 53 | 'nodes': nodes, |
| 54 | 'partitions': partitions |
| 55 | } |
| 56 | output = json.dumps(data, indent=4) |
| 57 | |
| 58 | if len(sys.argv) >= 2 and sys.argv[1] != '-': |
| 59 | filename = sys.argv[1] |
| 60 | with open(filename, 'w') as f: |
| 61 | f.write(output) |
| 62 | else: |
| 63 | print output |