blob: b73ed4a50168511984d4e7a481b3ca704c36ca47 [file] [log] [blame]
Jon Hall3b489db2015-10-05 14:38:37 -07001#!/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
9from os import environ
10from collections import deque, OrderedDict
11import re
12import json
13import sys
14
15convert = lambda text: int(text) if text.isdigit() else text.lower()
16alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]
17
18def 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
25def get_nodes(vars, port=9876):
Jon Hall37677302015-10-23 12:17:49 -070026 node = lambda k: { 'id': k, 'ip': k, 'port': port }
Jon Hall3b489db2015-10-05 14:38:37 -070027 return [ node(environ[v]) for v in vars ]
28
29def generate_permutations(nodes, k):
30 l = deque(nodes)
Jon Hall37677302015-10-23 12:17:49 -070031 perms = []
Jon Hall3b489db2015-10-05 14:38:37 -070032 for i in range(1, len(nodes)+1):
Jon Hall37677302015-10-23 12:17:49 -070033 part = {
34 'name': 'p%d' % i,
35 'members': list(l)[:k]
36 }
37 perms.append(part)
Jon Hall3b489db2015-10-05 14:38:37 -070038 l.rotate(-1)
Jon Hall37677302015-10-23 12:17:49 -070039 return perms
Jon Hall3b489db2015-10-05 14:38:37 -070040
41def generate_permutations2(nodes, k):
42 l = deque(nodes)
Jon Hall37677302015-10-23 12:17:49 -070043 perms = []
Jon Hall3b489db2015-10-05 14:38:37 -070044 for i in range(1, (len(nodes) + 1) / 2 + 1):
Jon Hall37677302015-10-23 12:17:49 -070045 part = {
46 'name': 'p%d' % i,
47 'members': list(l)[:k]
48 }
49 perms.append(part)
Jon Hall3b489db2015-10-05 14:38:37 -070050 l.rotate(-2)
Jon Hall37677302015-10-23 12:17:49 -070051 return perms
Jon Hall3b489db2015-10-05 14:38:37 -070052
53if __name__ == '__main__':
54 vars = get_OC_vars()
55 nodes = get_nodes(vars)
Jon Hall37677302015-10-23 12:17:49 -070056 partitions = generate_permutations2([v.get('id') for v in nodes], 3)
Jon Hall3b489db2015-10-05 14:38:37 -070057 data = {
Jon Hall37677302015-10-23 12:17:49 -070058 'name': 'default',
Jon Hall3b489db2015-10-05 14:38:37 -070059 'nodes': nodes,
60 'partitions': partitions
61 }
62 output = json.dumps(data, indent=4)
63
64 if len(sys.argv) == 2:
65 filename = sys.argv[1]
66 with open(filename, 'w') as f:
67 f.write(output)
68 else:
69 print output