· 6 years ago · May 23, 2019, 09:10 AM
1#!/usr/bin/python
2import re
3from typing import List, Any, Union
4
5import networkx as nx
6import psycopg2 as pg2
7import datetime
8import os
9
10
11device_dict = {}
12neighbouring_devices_list = []
13all_device_strings = []
14all_switch_pairs = []
15all_main_dev = []
16devices = []
17
18
19
20def get_basic_path():
21 directory_list = ['zzz', 'pliki']
22 for name in directory_list:
23 print(name)
24 file_names = []
25 os.chdir('/home/kkopowskadcl/switch_files/%s/' % name)
26 current_working_dir = os.getcwd()
27 print(current_working_dir)
28 for current_file in os.listdir(current_working_dir):
29 file_names.append(current_file)
30
31 for f in file_names:
32 print(f)
33 try:
34 f = open('%s/%s' % (current_working_dir, f), 'r')
35 file_text = f.read()
36 f.close()
37 except FileNotFoundError:
38 continue
39
40 main_dev = []
41 device_name_from_file = []
42 main_switch = re.compile(r'(\w+)(#)(sh)')
43 matches = main_switch.search(file_text)
44 main_dev.append(matches.group())
45 all_main_dev.append(matches.group())
46 device_name_from_file.append(matches.group())
47
48 # get final name for main device
49 device_name_from_file = [device_name_from_file[i][:-3] for i, z in enumerate(device_name_from_file)]
50 devices.extend(device_name_from_file)
51
52 neigh_dev = re.compile(r'(Device ID: )(\w+)')
53 match_neigh_dev = neigh_dev.findall(file_text)
54
55 local_port = re.compile(r'((Interface: )(\w+)(\d\/\d+),)')
56 match_local_port = local_port.findall(file_text)
57
58 remote_port = re.compile(r'(Port ID )(\(outgoing port\): )?(\w*)(\d\/\d+)')
59 match_remote_port = remote_port.findall(file_text)
60
61 neighbouring_devices_list = [(match_neigh_dev[i][1]) for i, match in enumerate(match_neigh_dev)]
62 switch_pairs = [(main_dev[0][:-3], dev) for dev in neighbouring_devices_list]
63 all_switch_pairs.extend(switch_pairs)
64
65 device_dict['Main device'] = main_dev[0][:-3]
66 device_dict['Local port'] = [x[3] for x in match_local_port]
67 device_dict['Remote port'] = [x[3] for x in match_remote_port]
68 device_dict['Neigh device'] = [x for x in neighbouring_devices_list]
69 assert len(device_dict['Neigh device']) == len(device_dict['Local port']) == len(
70 device_dict['Remote port']), 'Port=Neigh=Local assumption'
71
72 device_strings = []
73 neigh_device_nr = len(device_dict['Neigh device'])
74 for device in range(neigh_device_nr):
75 a = device_dict['Main device']
76 b = device_dict['Local port'][device]
77 c = device_dict['Remote port'][device]
78 d = device_dict['Neigh device'][device]
79 string = '{}|{}|{}|{}'.format(a, b, c, d)
80 device_strings.append(string)
81 all_device_strings.extend(device_strings)
82
83get_basic_path()
84
85print(all_switch_pairs)
86print(all_device_strings)
87#
88# # get all paths for all switches without data format
89# G = nx.DiGraph(all_switch_pairs)
90# all_paths = []
91# for root in G.nodes:
92# for leaf in G.nodes:
93# paths = nx.all_simple_paths(G, root, leaf)
94# all_paths.extend(paths)
95#
96# # get best switch path for one network
97# G = nx.Graph()
98# G.add_edges_from(all_switch_pairs)
99# labels = {node:node for node in G.nodes()}
100# nx.draw(G, with_labels=True)
101#
102# final_switch_track= []
103#
104# all_possible_tracks = (nx.shortest_path(G, source=all_switch_pairs[0][0]))
105# for track in all_possible_tracks.values():
106# final_switch_track = track[:]
107#
108# best_switch_path = []
109# best_switch_path.append(final_switch_track)
110#
111# ("""
112# ##################################################
113# G = nx.DiGraph(all_switch_pairs)
114# all_xxx = []
115# for root in G.nodes:
116# for leaf in G.nodes:
117# xxx = nx.all_shortest_paths(G, root, leaf)
118# all_xxx.extend(xxx)
119# print('all', all_xxx)
120# ##################################################
121# """)
122#
123# # get id number for database
124# id_number = [id_num for id_num, i in enumerate(all_paths)]
125#
126# # get device name for database
127# dev_name = [dev for dev in (all_paths[0][0])]
128# device_name = ''.join(dev_name)
129#
130# # concatenate all switch with ports (before format)
131# path_list_with_ports = []
132# for path in all_paths:
133# zipped_path = list(zip(path[:-1], path[1:]))
134# switch_relations = []
135# for nodes in zipped_path:
136# if nodes in all_switch_pairs:
137# switch_index = all_switch_pairs.index(nodes)
138# switch_relations.append(all_device_strings[switch_index])
139# result = ''.join(switch_relations).split('|')
140# path_list_with_ports.append(result)
141# print(len(path_list_with_ports))
142#
143# # concatenate the best switch path with ports (before format)
144# final_path = []
145# for switch in best_switch_path:
146# zipped_switch_list = list(zip(switch[:-1], switch[1:]))
147# list_of_dev_relations = []
148# for node in zipped_switch_list:
149# if node in all_switch_pairs:
150# node_index = all_switch_pairs.index(node)
151# list_of_dev_relations.append(all_device_strings[node_index])
152# joined_elements = ''.join(list_of_dev_relations).split('|')
153# final_path.append(joined_elements)
154# # format final path and path list with ports
155# def get_device_paths_for_user(path_list_with_ports):
156# best_path = []
157# devices_paths_for_user = []
158# for lst in path_list_with_ports:
159# device_name = lst[0][0]
160# inside_list = []
161# for item in lst:
162# if item.startswith(device_name):
163# half_len = int(len(item) / 2)
164# if item[half_len:] == item[:half_len]:
165# item = item[:half_len]
166# inside_list.append(item)
167# else:
168# inside_list.append(item)
169# else:
170# inside_list.append(item)
171# devices_paths_for_user.append(inside_list)
172# return devices_paths_for_user
173#
174# devices_paths_for_user = get_device_paths_for_user(path_list_with_ports)
175# best_path = get_device_paths_for_user(final_path)
176#
177# dev_index = [number for number, name in enumerate(devices)]
178# aaa = dict(zip(devices, dev_index))
179#
180# #slownik = {'Switch0': 0, 'Switch1': 1, 'Switch2': 2, 'Switch3': 3, 'Switch4': 4, 'Switch5': 5, 'Switch6': 6, 'Switch7': 7, 'Switch8': 8, 'Switch9': 9}
181# #for k, v in slownik.items():
182#
183# # index_for_system = []
184# # n = 0
185# # for item in devices_paths_for_user:
186# # damn_list = []
187# # for z in item:
188# # if z in devices:
189# # z = 'S' + str(n)
190# # damn_list.append(z)
191# # n += 1
192# # else:
193# # z = z
194# # damn_list.append(z)
195# # index_for_system.append(damn_list)
196# #
197# # print(index_for_system)
198# # final_index_for_system = ' '.join(index_for_system)
199# # print(final_index_for_system)
200#
201# list_of_all_paths_for_database = []
202# for item in devices_paths_for_user:
203# joined_paths = ' '.join(item)
204# list_of_all_paths_for_database.append(''.join(joined_paths).split(','))
205#
206# for path in best_path:
207# best_path_for_database = (' '.join(path))
208#
209# ("""
210# conn = pg2.connect(host='localhost', database='postgres', user='postgres', password='')
211# cur = conn.cursor()
212# cur.execute("CREATE TABLE IF NOT EXISTS active_paths (id SERIAL PRIMARY KEY, network_id VARCHAR(50), device_in_name VARCHAR(255) NOT NULL, device_out_name VARCHAR(255) NOT NULL,path VARCHAR(4000) NOT NULL, time_stamp TIMESTAMP NOT NULL);")
213# conn.commit()
214# conn.close()
215#
216#
217# conn = pg2.connect(host='localhost', database='postgres', user='postgres', password='')
218# cur = conn.cursor()
219# cur.execute("CREATE TABLE IF NOT EXISTS all_paths (id SERIAL PRIMARY KEY, network_id VARCHAR(50), device_in_name VARCHAR(255) NOT NULL, device_out_name VARCHAR(255) NOT NULL,path VARCHAR(4000) NOT NULL, time_stamp TIMESTAMP NOT NULL);")
220# conn.commit()
221# conn.close()
222#
223# conn = pg2.connect(host='localhost', database='postgres', user='postgres', password='')
224# cur = conn.cursor()
225# cur.execute("CREATE TABLE IF NOT EXISTS the_best_path (id SERIAL PRIMARY KEY, network_id VARCHAR(50), device_in_name VARCHAR(255) NOT NULL, device_out_name VARCHAR(255) NOT NULL,path VARCHAR(4000) NOT NULL, time_stamp TIMESTAMP NOT NULL);")
226# conn.commit()
227# conn.close()
228#
229# for path in range(len(list_of_all_paths_for_database)):
230#
231# time = datetime.datetime.now()
232# conn = pg2.connect(host='localhost', database='postgres', user='postgres', password='')
233# cur = conn.cursor()
234# cur.execute("INSERT INTO all_paths (device_in_name, device_out_name, path, time_stamp) VALUES( %s, %s, %s, %s);", ((str(all_paths[path][0])), str(all_paths[path][-1]), tuple(list_of_all_paths_for_database[path]), time))
235# conn.commit()
236# conn.close()
237#
238# for item in range(1):
239# time = datetime.datetime.now()
240# conn = pg2.connect(host='localhost', database='postgres', user='postgres', password='')
241# cur = conn.cursor()
242# cur.execute("INSERT INTO the_best_path (device_in_name, device_out_name, path, time_stamp) VALUES( %s, %s, %s, %s);", ((str(best_switch_path[item][0])), str(best_switch_path[item][-1]), best_path_for_database, time))
243# conn.commit()
244# conn.close()
245# """)
246#
247# # ("""
248# # CREATE TABLE IF NOT EXISTS all_paths (
249# # id VARCHAR(255) PRIMARY KEY NOT NULL,
250# # device_in_name VARCHAR(255) NOT NULL,
251# # device_out_name VARCHAR(255) NOT NULL,
252# # path VARCHAR(255) NOT NULL,
253# # time_stamp TIMESTAMP NOT NULL)""")
254# #
255# #
256# # ("""CREATE TABLE IF NOT EXISTS the_best_path (
257# # id VARCHAR(255) PRIMARY KEY NOT NULL,
258# # device_in_name VARCHAR(255) NOT NULL,
259# # device_out_name VARCHAR(255) NOT NULL,
260# # path VARCHAR(255) NOT NULL,
261# # time_stamp TIMESTAMP NOT NULL)""")