Stop installing librairies during tests
[parser.git] / verigraph / service / src / tests / j-verigraph-generator / utility.py
1 #!/usr/bin/python
2
3 ##############################################################################
4 # Copyright (c) 2017 Politecnico di Torino and others.
5 #
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 ##############################################################################
11
12 import json
13 import contextlib
14 import sys
15 import os
16 import subprocess
17 from pprint import pprint
18
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')
24     else:
25         fh = sys.stdout
26     try:
27         yield fh
28     finally:
29         if fh is not sys.stdout:
30             fh.close()
31
32 def check_input_is_int(text):
33     while True:
34         data = raw_input(text)
35         try:
36             int_value = int(data)
37         except ValueError:
38             print "Please enter a valid number!"
39             continue
40         return int_value
41
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)
46
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')
55     else:
56         return input
57
58 #parses a chains file
59 def parse_chains(chains_file):
60     chains_json = convert_unicode_to_ascii(parse_json_file(chains_file))
61
62     chains = {}
63
64     for chn in chains_json["chains"]:
65         try:
66             chains[chn["id"]] = {}
67             #initiatlize the config dictionary for each node
68             for node in chn["nodes"]:
69                 chains[chn["id"]][node["name"]] = {}
70         except:
71             raise KeyError("Chains file is not valid!")
72
73     for chn in chains_json["chains"]:
74         try:
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
79                     if key != "name":
80                         chains[chn["id"]][node["name"]][key] = value
81         except:
82             raise KeyError("Chains file is not valid!")
83     return chains
84
85 def check_chains_integrity(filename):
86     print "Checking input file..."
87     try:
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!"
92             return False
93         for chain in chains["chains"]:
94             print "Chain found, checking its fields..."
95             print "Checking chain id field... "
96             chain["id"]
97             print "OK!"
98             print "Checking chain flowspace field... "
99             chain["flowspace"]
100             print "OK!"
101             if isinstance(chain["nodes"], list) == False:
102                 print "Chain #" + chain["id"] + " does not have a list of nodes!"
103                 return False
104             for node in chain["nodes"]:
105                 print "Node found, checking its fields..."
106                 print "Checking node name... "
107                 node["name"]
108                 print "OK!"
109                 print "Checking node functional_type field... "
110                 node["functional_type"]
111                 print "OK!"
112                 print "Checking node address field... "
113                 node["address"]
114                 print "OK!"
115     except (KeyboardInterrupt, SystemExit):
116         raise
117     except:
118         print "One or more required fields are missing!"
119         return False
120     print filename + " validated successfully!"
121     return True
122
123 def check_config_integrity(filename):
124     print "Checking input file..."
125     try:
126         config = convert_unicode_to_ascii(parse_json_file(filename))
127         pprint(config)
128         print "File correctly parsed"
129         if isinstance(config["nodes"], list) == False:
130             print "Child of nodes is not a list!"
131             return False
132         for node in config["nodes"]:
133             print "Node found, checking its fields..."
134             print "Checking id field... "
135             node["id"]
136             print "OK!"
137             print "Checking description field... "
138             node["description"]
139             print "OK!"
140             print "Checking configuration field... "
141             node["configuration"]
142             print "OK!"
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!"
146                 return False
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)"
151                     return False
152     except (KeyboardInterrupt, SystemExit):
153         raise
154     except:
155         print "One or more required fields are missing!"
156         return False
157     print filename + " validated successfully!"
158     return True
159
160 def check_routing_integrity(filename):
161     print "Checking input file..."
162     try:
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!"
167             return False
168         for node in routing["routing_table"]:
169             if isinstance(node, dict) == False:
170                 print "Child of routing_table is not a map!"
171                 return False
172             for n, rt in node.items():
173                 if isinstance(rt, list) == False:
174                     print "Routing table of element " + n + " is not a list!"
175                     return False
176                 for entry in rt:
177                     if isinstance(entry, dict) == False:
178                         print "Invalid entry for node " + n + " (not a map)!"
179                         return False
180     except (KeyboardInterrupt, SystemExit):
181         raise
182     except:
183         print "One or more required fields are missing!"
184         return False
185     return True
186
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 "-----------------------------------"
196         print ""
197
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 "-----------------------------------"
207     print ""
208
209 #print every node's routing table
210 def print_routing_table(routing):
211     print "ROUTING"
212     for table in routing["routing_table"]:
213         for node,rt in table.items():
214             print "Name: " + str(node)
215             pprint(rt)
216             print "-----------------------------------"
217         print ""
218
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):
221     l = []
222     for map in maps:
223         if isinstance(map, dict):
224             for k, v in map.items():
225                 #l.append("(ctx." + str(k) + ", ctx." + str(v) + ")")
226                 l.append(str(k))
227                 l.append(str(v))
228         else:
229             #l.append("ctx." + map)
230             l.append(map)
231     return l
232
233 def list_directories(dir):
234     #output = subprocess.call(["ls", "-d", "*/"])
235     output = subprocess.call(["find", dir, "-type", "d"])
236
237     #TREE VERSION
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)
240     #find.wait()
241
242 #     ps = subprocess.Popen(('ps', '-A'), stdout=subprocess.PIPE)
243 #     output = subprocess.check_output(('grep', 'process_name'), stdin=ps.stdout)
244 #     ps.wait()
245     return output
246
247 def list_files(dir):
248     output = subprocess.call(["find", dir, "-type", "f"])
249     return output
250
251 def search_node_in_chains(n):
252     found = []
253     for chain in chains["chains"]:
254         for node in chain["nodes"]:
255             if node["name"] == n:
256                 found.append(node)
257     return found