blob: e557edac7132a43b4196fd6657129b088b70c2e6 [file] [log] [blame]
Bogdan45932c72018-11-06 15:28:00 +00001#!/usr/bin/env python
2"""
3usage: onos-gen-default-cluster [-h] [-s PARTITION_SIZE] [-n NUM_PARTITIONS]
4 [filename] [node_ip [node_ip ...]]
5
6Generate the partitions json file given a list of IPs or from the $OCC*
7environment variables.
8
9positional arguments:
10 filename File to write output to. If none is provided, output
11 is written to stdout.
12 node_ip IP Address(es) of the node(s) in the cluster. If no
13 IPs are given, will use the $OC* environment
14 variables. NOTE: these arguments are only processed
15 after the filename argument.
16
17optional arguments:
18 -h, --help show this help message and exit
19"""
20
21from os import environ
22import argparse
23import re
24import json
25
26convert = lambda text: int(text) if text.isdigit() else text.lower()
27alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]
28
29
30def get_vars_by_type(type):
31 vars = []
32 for var in environ:
33 if re.match(r"{}[0-9]+".format(type), var):
34 vars.append(var)
35 return sorted(vars, key=alphanum_key)
36
37
38def get_vars():
39 vars = get_vars_by_type('OCC')
40 if len(vars) == 0:
41 vars = get_vars_by_type('OC')
42 return vars
43
44
45def get_nodes(ips=None, default_port=9876):
46 node = lambda id, ip, port: {'id': id, 'ip': ip, 'port': port}
47 result = []
48 if not ips:
49 ips = [environ[v] for v in get_vars()]
50 i = 1
51 for ip_string in ips:
52 address_tuple = ip_string.split(":")
53 if len(address_tuple) == 3:
54 id = address_tuple[0]
55 ip = address_tuple[1]
56 port = int(address_tuple[2])
57 else:
58 i += 1
59 ip = ip_string
60 id = ip
61 port = default_port
62 result.append(node(id, ip, port))
63 return result
64
65
66if __name__ == '__main__':
67 parser = argparse.ArgumentParser(
68 description="Generate the partitions json file given a list of IPs or from environment variables.")
69
70 parser.add_argument(
71 'filename', metavar='filename', type=str, nargs='?',
72 help='File to write output to. If none is provided, output is written to stdout.')
73
74 parser.add_argument(
75 '--nodes', '-n', metavar='node_ip', type=str, nargs='+',
76 help='IP Address(es) of the storage nodes. If no IPs are given, ' +
77 'will use the $OCC* or $OC* environment variables. NOTE: these arguments' +
78 ' are only processed after the filename argument.')
79
80 args = parser.parse_args()
81 filename = args.filename
82 nodes = get_nodes(args.nodes)
83
84 data = {
85 'name': 'onos',
86 'controller': nodes
87 }
88 output = json.dumps(data, indent=4)
89
90 if filename:
91 with open(filename, 'w') as f:
92 f.write(output)
93 else:
94 print output