3 ##############################################################################
4 # Copyright (c) 2017 Politecnico di Torino and others.
6 # All rights reserved. This program and the accompanying materials
7 # are made available under the terms of the Apache License, Version 2.0
8 # which accompanies this distribution, and is available at
9 # http://www.apache.org/licenses/LICENSE-2.0
10 ##############################################################################
17 from pprint import pprint
19 #manages output easily (can either write to file or to stdout)
20 @contextlib.contextmanager
21 def smart_open(filename=None):
22 if filename and filename != '-':
23 fh = open(filename, 'w')
29 if fh is not sys.stdout:
32 def check_input_is_int(text):
34 data = raw_input(text)
38 print "Please enter a valid number!"
42 #parses a json file into a unicode dictionary
43 def parse_json_file(filename):
44 with open(filename) as json_file:
45 return json.load(json_file)
47 #returns an ascii dictionary from a unicode one
48 def convert_unicode_to_ascii(input):
49 if isinstance(input, dict):
50 return {convert_unicode_to_ascii(key): convert_unicode_to_ascii(value) for key, value in input.iteritems()}
51 elif isinstance(input, list):
52 return [convert_unicode_to_ascii(element) for element in input]
53 elif isinstance(input, unicode):
54 return input.encode('utf-8')
59 def parse_chains(chains_file):
60 chains_json = convert_unicode_to_ascii(parse_json_file(chains_file))
64 for chn in chains_json["chains"]:
66 chains[chn["id"]] = {}
67 #initiatlize the config dictionary for each node
68 for node in chn["nodes"]:
69 chains[chn["id"]][node["name"]] = {}
71 raise KeyError("Chains file is not valid!")
73 for chn in chains_json["chains"]:
75 #set chn values ---> chn(name, (field, value))
76 for node in chn["nodes"]:
77 for key, value in node.items():
78 #name key is redundant in map
80 chains[chn["id"]][node["name"]][key] = value
82 raise KeyError("Chains file is not valid!")
85 def check_chains_integrity(filename):
86 print "Checking input file..."
88 chains = convert_unicode_to_ascii(parse_json_file(filename))
89 print "File correctly parsed"
90 if isinstance(chains["chains"], list) == False:
91 print "Child of chains is not a list!"
93 for chain in chains["chains"]:
94 print "Chain found, checking its fields..."
95 print "Checking chain id field... "
98 print "Checking chain flowspace field... "
101 if isinstance(chain["nodes"], list) == False:
102 print "Chain #" + chain["id"] + " does not have a list of nodes!"
104 for node in chain["nodes"]:
105 print "Node found, checking its fields..."
106 print "Checking node name... "
109 print "Checking node functional_type field... "
110 node["functional_type"]
112 print "Checking node address field... "
115 except (KeyboardInterrupt, SystemExit):
118 print "One or more required fields are missing!"
120 print filename + " validated successfully!"
123 def check_config_integrity(filename):
124 print "Checking input file..."
126 config = convert_unicode_to_ascii(parse_json_file(filename))
128 print "File correctly parsed"
129 if isinstance(config["nodes"], list) == False:
130 print "Child of nodes is not a list!"
132 for node in config["nodes"]:
133 print "Node found, checking its fields..."
134 print "Checking id field... "
137 print "Checking description field... "
140 print "Checking configuration field... "
141 node["configuration"]
143 if isinstance(node["configuration"], list) == False:
144 print "Checking if node configuration is a list..."
145 print "Node with id " + node["id"] + " does not have a configuration list!"
147 for c in node["configuration"]:
148 print "Checking if node configuration element is a string or a dictionary..."
149 if (isinstance(c, str) == False and isinstance(c, dict) == False):
150 print "At least one element of node with id " + node["id"] + " has an invalid configuration (it is neither a string or a map)"
152 except (KeyboardInterrupt, SystemExit):
155 print "One or more required fields are missing!"
157 print filename + " validated successfully!"
160 def check_routing_integrity(filename):
161 print "Checking input file..."
163 routing = convert_unicode_to_ascii(parse_json_file(filename))
164 print "File correctly parsed"
165 if isinstance(routing["routing_table"], list) == False:
166 print "Child of routing_table is not a list!"
168 for node in routing["routing_table"]:
169 if isinstance(node, dict) == False:
170 print "Child of routing_table is not a map!"
172 for n, rt in node.items():
173 if isinstance(rt, list) == False:
174 print "Routing table of element " + n + " is not a list!"
177 if isinstance(entry, dict) == False:
178 print "Invalid entry for node " + n + " (not a map)!"
180 except (KeyboardInterrupt, SystemExit):
183 print "One or more required fields are missing!"
187 #prints every node for each input chain
188 def print_chains(chains):
189 for chain in chains["chains"]:
190 print "CHAIN #" + str(chain["id"])
191 for node in chain["nodes"]:
192 print "Name: " + str(node["name"])
193 print "Functional type: " + str(node["functional_type"])
194 print "Address: " + str(node["address"])
195 print "-----------------------------------"
198 #prints every node's configuration
199 def print_configuration(configuration):
200 print "NODES CONFIGURATION"
201 for node in configuration["nodes"]:
202 print "Name: " + str(node["id"])
203 print "Description: " + str(node["description"])
204 print "Configuration: "
205 pprint(node["configuration"])
206 print "-----------------------------------"
209 #print every node's routing table
210 def print_routing_table(routing):
212 for table in routing["routing_table"]:
213 for node,rt in table.items():
214 print "Name: " + str(node)
216 print "-----------------------------------"
219 #returns a list of tuple [(k1, v1), (k2, v2)] from a list of maps like [{k1 : v1},{k2 : v2}]
220 def formatted_list_from_list_of_maps(maps):
223 if isinstance(map, dict):
224 for k, v in map.items():
225 #l.append("(ctx." + str(k) + ", ctx." + str(v) + ")")
229 #l.append("ctx." + map)
233 def list_directories(dir):
234 #output = subprocess.call(["ls", "-d", "*/"])
235 output = subprocess.call(["find", dir, "-type", "d"])
238 #find = subprocess.Popen(["find", ".", "-type", "d"], stdout=subprocess.PIPE)
239 #output = subprocess.check_output(["sed", "-e", "s/[^-][^\/]*\// |/g", "-e", "s/|\([^ ]\)/|-\1/"], stdin=find.stdout)
242 # ps = subprocess.Popen(('ps', '-A'), stdout=subprocess.PIPE)
243 # output = subprocess.check_output(('grep', 'process_name'), stdin=ps.stdout)
248 output = subprocess.call(["find", dir, "-type", "f"])
251 def search_node_in_chains(n):
253 for chain in chains["chains"]:
254 for node in chain["nodes"]:
255 if node["name"] == n: