blob: 5da0807d3ef5a705a34d393b79dbf16f60d66e7c [file] [log] [blame]
Aaron Kruglikoveb0ae4e2015-11-10 19:16:16 -08001#!/usr/bin/env python
2"""
Brian O'Connor6e192432015-02-26 15:17:23 -08003 Generate the partitions json file from the $OC* environment variables
Aaron Kruglikoveb0ae4e2015-11-10 19:16:16 -08004
Brian O'Connor6e192432015-02-26 15:17:23 -08005 Usage: onos-gen-partitions [output file]
6 If output file is not provided, the json is written to stdout.
Aaron Kruglikoveb0ae4e2015-11-10 19:16:16 -08007"""
Brian O'Connor6e192432015-02-26 15:17:23 -08008
9from os import environ
10from collections import deque, OrderedDict
11import re
12import json
13import sys
Thomas Vachuskab56b9172015-11-24 11:24:23 -080014import hashlib
Brian O'Connor6e192432015-02-26 15:17:23 -080015
Aaron Kruglikoveb0ae4e2015-11-10 19:16:16 -080016convert = lambda text: int(text) if text.isdigit() else text.lower()
17alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]
Brian O'Connor6e192432015-02-26 15:17:23 -080018
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
Madan Jampani27b69c62015-05-15 15:49:02 -070026def get_nodes(vars, port=9876):
Madan Jampaniec1df022015-10-13 21:23:03 -070027 node = lambda k: { 'id': k, 'ip': k, 'port': port }
Brian O'Connor6e192432015-02-26 15:17:23 -080028 return [ node(environ[v]) for v in vars ]
29
30def generate_permutations(nodes, k):
31 l = deque(nodes)
Madan Jampaniec1df022015-10-13 21:23:03 -070032 perms = []
Brian O'Connor6e192432015-02-26 15:17:23 -080033 for i in range(1, len(nodes)+1):
Madan Jampaniec1df022015-10-13 21:23:03 -070034 part = {
35 'name': 'p%d' % i,
36 'members': list(l)[:k]
37 }
38 perms.append(part)
Brian O'Connor6e192432015-02-26 15:17:23 -080039 l.rotate(-1)
Madan Jampaniec1df022015-10-13 21:23:03 -070040 return perms
Brian O'Connor6e192432015-02-26 15:17:23 -080041
42if __name__ == '__main__':
43 vars = get_OC_vars()
44 nodes = get_nodes(vars)
Madan Jampaniec1df022015-10-13 21:23:03 -070045 partitions = generate_permutations([v.get('id') for v in nodes], 3)
Aaron Kruglikoveb0ae4e2015-11-10 19:16:16 -080046 name = 0
47 for node in nodes:
Thomas Vachuskab56b9172015-11-24 11:24:23 -080048 name = name ^ hash(node['ip'])
Madan Jampaniec1df022015-10-13 21:23:03 -070049 data = {
Aaron Kruglikoveb0ae4e2015-11-10 19:16:16 -080050 'name': name,
Brian O'Connor6e192432015-02-26 15:17:23 -080051 'nodes': nodes,
Aaron Kruglikoveb0ae4e2015-11-10 19:16:16 -080052 'partitions': partitions
Brian O'Connor6e192432015-02-26 15:17:23 -080053 }
54 output = json.dumps(data, indent=4)
55
56 if len(sys.argv) == 2:
57 filename = sys.argv[1]
58 with open(filename, 'w') as f:
59 f.write(output)
60 else:
61 print output