blob: cb0d8269ba5c753c694d15e726227756bd98e3d1 [file] [log] [blame]
Jon Hall3b489db2015-10-05 14:38:37 -07001#!/usr/bin/env python
Jon Halle9b1fa32015-12-08 15:32:21 -08002"""
Jon Hall3b489db2015-10-05 14:38:37 -07003 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.
Jon Halle9b1fa32015-12-08 15:32:21 -08007"""
Jon Hall3b489db2015-10-05 14:38:37 -07008
9from os import environ
10from collections import deque, OrderedDict
11import re
12import json
13import sys
Jon Halle9b1fa32015-12-08 15:32:21 -080014import hashlib
Jon Hall3b489db2015-10-05 14:38:37 -070015
16convert = lambda text: int(text) if text.isdigit() else text.lower()
17alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]
18
19def 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
26def get_nodes(vars, port=9876):
Jon Hall37677302015-10-23 12:17:49 -070027 node = lambda k: { 'id': k, 'ip': k, 'port': port }
Jon Hall3b489db2015-10-05 14:38:37 -070028 return [ node(environ[v]) for v in vars ]
29
30def generate_permutations(nodes, k):
31 l = deque(nodes)
Jon Hall37677302015-10-23 12:17:49 -070032 perms = []
Jon Hall3b489db2015-10-05 14:38:37 -070033 for i in range(1, len(nodes)+1):
Jon Hall37677302015-10-23 12:17:49 -070034 part = {
35 'name': 'p%d' % i,
36 'members': list(l)[:k]
37 }
38 perms.append(part)
Jon Hall3b489db2015-10-05 14:38:37 -070039 l.rotate(-1)
Jon Hall37677302015-10-23 12:17:49 -070040 return perms
Jon Hall3b489db2015-10-05 14:38:37 -070041
42def generate_permutations2(nodes, k):
43 l = deque(nodes)
Jon Hall37677302015-10-23 12:17:49 -070044 perms = []
Jon Hall3b489db2015-10-05 14:38:37 -070045 for i in range(1, (len(nodes) + 1) / 2 + 1):
Jon Hall37677302015-10-23 12:17:49 -070046 part = {
47 'name': 'p%d' % i,
48 'members': list(l)[:k]
49 }
50 perms.append(part)
Jon Hall3b489db2015-10-05 14:38:37 -070051 l.rotate(-2)
Jon Hall37677302015-10-23 12:17:49 -070052 return perms
Jon Hall3b489db2015-10-05 14:38:37 -070053
54if __name__ == '__main__':
55 vars = get_OC_vars()
56 nodes = get_nodes(vars)
Jon Hall37677302015-10-23 12:17:49 -070057 partitions = generate_permutations2([v.get('id') for v in nodes], 3)
Jon Halle9b1fa32015-12-08 15:32:21 -080058 name = 0
59 for node in nodes:
60 name = name ^ hash(node['ip'])
Jon Hall3b489db2015-10-05 14:38:37 -070061 data = {
Jon Halle9b1fa32015-12-08 15:32:21 -080062 'name': name,
Jon Hall3b489db2015-10-05 14:38:37 -070063 'nodes': nodes,
64 'partitions': partitions
65 }
66 output = json.dumps(data, indent=4)
67
68 if len(sys.argv) == 2:
69 filename = sys.argv[1]
70 with open(filename, 'w') as f:
71 f.write(output)
72 else:
73 print output