Jon Hall | 69b2b98 | 2016-05-11 12:04:59 -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 [num_nodes] [-e] |
| 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_scaling(nodes, k, partitions=3, equal=False): |
| 37 | l = deque(nodes) |
| 38 | perms = [] |
| 39 | for i in range(1, partitions + 1): |
| 40 | if equal: |
| 41 | members = list(l) |
| 42 | else: |
| 43 | members = list(l)[:k] |
| 44 | |
| 45 | part = { |
| 46 | 'id': i, |
| 47 | 'members': members |
| 48 | } |
| 49 | perms.append(part) |
| 50 | l.rotate(-2) |
| 51 | return perms |
| 52 | |
| 53 | if __name__ == '__main__': |
| 54 | vars = get_OC_vars() |
| 55 | # NOTE: likely prone to errors |
| 56 | nodes = get_nodes(vars) |
| 57 | num = None |
| 58 | equal = False |
| 59 | if len(sys.argv) >= 3: |
| 60 | num = int(sys.argv[2]) |
| 61 | try: |
| 62 | equal = "-e" in sys.argv[3] |
| 63 | except: |
| 64 | equal = False |
| 65 | if num: |
| 66 | nodes = nodes[:num] |
| 67 | |
| 68 | base_partition = generate_base_partition([v.get('id') for v in nodes]) |
| 69 | extended_partitions = generate_extended_partitions_scaling([v.get('id') for v in nodes], |
| 70 | 3, equal=equal) |
| 71 | partitions = [] |
| 72 | partitions.append(base_partition) |
| 73 | partitions.extend(extended_partitions) |
| 74 | name = hash("HAScaling") |
| 75 | data = { |
| 76 | 'name': name, |
| 77 | 'nodes': nodes, |
| 78 | 'partitions': partitions |
| 79 | } |
| 80 | output = json.dumps(data, indent=4) |
| 81 | |
| 82 | if len(sys.argv) >= 2: |
| 83 | filename = sys.argv[1] |
| 84 | with open(filename, 'w') as f: |
| 85 | f.write(output) |
| 86 | else: |
| 87 | print output |