blob: ba9a256f71fce99cad041bcd1b78aa167fda20d5 [file] [log] [blame]
Alexe0c5b9e2019-04-23 18:51:23 -05001import ipaddress
2import json
Alex6b633ec2019-06-06 19:44:34 -05003from copy import deepcopy
Alexe0c5b9e2019-04-23 18:51:23 -05004
5from cfg_checker.common import logger_cli
6from cfg_checker.common.exception import InvalidReturnException
7from cfg_checker.modules.network.network_errors import NetworkErrors
8from cfg_checker.nodes import salt_master
9
10# TODO: use templated approach
11# net interface structure should be the same
12_if_item = {
13 "name": "unnamed interface",
14 "mac": "",
15 "routes": {},
Alex6b633ec2019-06-06 19:44:34 -050016 "proto": "",
Alexe0c5b9e2019-04-23 18:51:23 -050017 "ip": [],
18 "parameters": {}
19}
20
21# collection of configurations
22_network_item = {
23 "runtime": {},
24 "config": {},
25 "reclass": {}
26}
27
28
29class NetworkMapper(object):
30 RECLASS = "reclass"
31 CONFIG = "config"
32 RUNTIME = "runtime"
33
34 def __init__(self, errors_class=None):
35 logger_cli.info("# Initializing mapper")
Alex6b633ec2019-06-06 19:44:34 -050036 # init networks and nodes
Alexe0c5b9e2019-04-23 18:51:23 -050037 self.networks = {}
38 self.nodes = salt_master.get_nodes()
Alex836fac82019-08-22 13:36:16 -050039 self.cluster = salt_master.get_info()
Alex6b633ec2019-06-06 19:44:34 -050040 # init and pre-populate interfaces
41 self.interfaces = {k: {} for k in self.nodes}
42 # Init errors class
Alexe0c5b9e2019-04-23 18:51:23 -050043 if errors_class:
44 self.errors = errors_class
45 else:
46 logger_cli.debug("... init error logs folder")
47 self.errors = NetworkErrors()
48
Alex836fac82019-08-22 13:36:16 -050049 def prepare_all_maps(self):
50 self.map_network(self.RECLASS)
51 self.map_network(self.RUNTIME)
52 self.map_network(self.CONFIG)
53
Alexe0c5b9e2019-04-23 18:51:23 -050054 # adding net data to tree
55 def _add_data(self, _list, _n, _h, _d):
56 if _n not in _list:
57 _list[_n] = {}
58 _list[_n][_h] = [_d]
59 elif _h not in _list[_n]:
60 # there is no such host, just create it
61 _list[_n][_h] = [_d]
62 else:
63 # there is such host... this is an error
64 self.errors.add_error(
65 self.errors.NET_DUPLICATE_IF,
66 host=_h,
67 dup_if=_d['name']
68 )
69 _list[_n][_h].append(_d)
70
71 # TODO: refactor map creation. Build one map instead of two separate
72 def _map_network_for_host(self, host, if_class, net_list, data):
73 # filter networks for this IF IP
74 _nets = [n for n in net_list.keys() if if_class.ip in n]
75 _masks = [n.netmask for n in _nets]
76 if len(_nets) > 1:
77 # There a multiple network found for this IP, Error
78 self.errors.add_error(
79 self.errors.NET_SUBNET_INTERSECT,
80 host=host,
81 ip=str(if_class.exploded),
82 networks="; ".join([str(_n) for _n in _nets])
83 )
84 # check mask match
85 if len(_nets) > 0 and if_class.netmask not in _masks:
86 self.errors.add_error(
87 self.errors.NET_MASK_MISMATCH,
88 host=host,
89 if_name=data['name'],
90 if_cidr=if_class.exploded,
91 if_mapped_networks=", ".join([str(_n) for _n in _nets])
92 )
93
94 if len(_nets) < 1:
95 self._add_data(net_list, if_class.network, host, data)
96 else:
97 # add all data
98 for net in _nets:
99 self._add_data(net_list, net, host, data)
100
101 return net_list
102
103 def _map_reclass_networks(self):
104 # class uses nodes from self.nodes dict
105 _reclass = {}
106 # Get required pillars
107 salt_master.get_specific_pillar_for_nodes("linux:network")
108 for node in salt_master.nodes.keys():
109 # check if this node
110 if not salt_master.is_node_available(node):
111 continue
112 # get the reclass value
113 _pillar = salt_master.nodes[node]['pillars']['linux']['network']
114 # we should be ready if there is no interface in reclass for a node
Alex92e07ce2019-05-31 16:00:03 -0500115 # for example on APT node
Alexe0c5b9e2019-04-23 18:51:23 -0500116 if 'interface' in _pillar:
117 _pillar = _pillar['interface']
118 else:
119 logger_cli.info(
120 "... node '{}' skipped, no IF section in reclass".format(
121 node
122 )
123 )
124 continue
Alex92e07ce2019-05-31 16:00:03 -0500125
Alex6b633ec2019-06-06 19:44:34 -0500126 # build map based on IPs and save info too
Alexb3dc8592019-06-11 13:20:36 -0500127 for if_name, _dat in _pillar.iteritems():
128 # get proper IF name
129 _if_name = if_name if 'name' not in _dat else _dat['name']
130 # place it
Alex6b633ec2019-06-06 19:44:34 -0500131 if _if_name not in self.interfaces[node]:
132 self.interfaces[node][_if_name] = deepcopy(_network_item)
Alexb3dc8592019-06-11 13:20:36 -0500133 self.interfaces[node][_if_name]['reclass'] = deepcopy(_dat)
Alex6b633ec2019-06-06 19:44:34 -0500134 # map network if any
Alexb3dc8592019-06-11 13:20:36 -0500135 if 'address' in _dat:
Alexe0c5b9e2019-04-23 18:51:23 -0500136 _if = ipaddress.IPv4Interface(
Alexb3dc8592019-06-11 13:20:36 -0500137 _dat['address'] + '/' + _dat['netmask']
Alexe0c5b9e2019-04-23 18:51:23 -0500138 )
Alexb3dc8592019-06-11 13:20:36 -0500139 _dat['name'] = _if_name
140 _dat['ifs'] = [_if]
Alexe0c5b9e2019-04-23 18:51:23 -0500141
142 _reclass = self._map_network_for_host(
143 node,
144 _if,
145 _reclass,
Alexb3dc8592019-06-11 13:20:36 -0500146 _dat
Alexe0c5b9e2019-04-23 18:51:23 -0500147 )
148
149 return _reclass
150
151 def _map_configured_networks(self):
152 # class uses nodes from self.nodes dict
153 _confs = {}
154
Alex92e07ce2019-05-31 16:00:03 -0500155 # TODO: parse /etc/network/interfaces
156
Alexe0c5b9e2019-04-23 18:51:23 -0500157 return _confs
158
159 def _map_runtime_networks(self):
160 # class uses nodes from self.nodes dict
161 _runtime = {}
162 logger_cli.info("# Mapping node runtime network data")
163 salt_master.prepare_script_on_active_nodes("ifs_data.py")
164 _result = salt_master.execute_script_on_active_nodes(
165 "ifs_data.py",
166 args=["json"]
167 )
168 for key in salt_master.nodes.keys():
169 # check if we are to work with this node
170 if not salt_master.is_node_available(key):
171 continue
172 # due to much data to be passed from salt_master,
173 # it is happening in order
174 if key in _result:
175 _text = _result[key]
176 if '{' in _text and '}' in _text:
177 _text = _text[_text.find('{'):]
178 else:
179 raise InvalidReturnException(
180 "Non-json object returned: '{}'".format(
181 _text
182 )
183 )
184 _dict = json.loads(_text[_text.find('{'):])
185 salt_master.nodes[key]['routes'] = _dict.pop("routes")
186 salt_master.nodes[key]['networks'] = _dict
187 else:
188 salt_master.nodes[key]['networks'] = {}
189 salt_master.nodes[key]['routes'] = {}
190 logger_cli.debug("... {} has {} networks".format(
191 key,
192 len(salt_master.nodes[key]['networks'].keys())
193 ))
194 logger_cli.info("-> done collecting networks data")
195
196 logger_cli.info("-> mapping IPs")
197 # match interfaces by IP subnets
198 for host, node_data in salt_master.nodes.iteritems():
199 if not salt_master.is_node_available(host):
200 continue
201
202 for net_name, net_data in node_data['networks'].iteritems():
Alexb3dc8592019-06-11 13:20:36 -0500203 # cut net name
204 _i = net_name.find('@')
205 _name = net_name if _i < 0 else net_name[:_i]
Alexe0c5b9e2019-04-23 18:51:23 -0500206 # get ips and calculate subnets
Alexb3dc8592019-06-11 13:20:36 -0500207 if _name in ['lo']:
Alexe0c5b9e2019-04-23 18:51:23 -0500208 # skip the localhost
209 continue
Alex6b633ec2019-06-06 19:44:34 -0500210 else:
211 # add collected data to interface storage
Alexb3dc8592019-06-11 13:20:36 -0500212 if _name not in self.interfaces[host]:
213 self.interfaces[host][_name] = \
Alex6b633ec2019-06-06 19:44:34 -0500214 deepcopy(_network_item)
Alexb3dc8592019-06-11 13:20:36 -0500215 self.interfaces[host][_name]['runtime'] = \
Alex6b633ec2019-06-06 19:44:34 -0500216 deepcopy(net_data)
217
Alexe0c5b9e2019-04-23 18:51:23 -0500218 # get data and make sure that wide mask goes first
219 _ip4s = sorted(
220 net_data['ipv4'],
221 key=lambda s: s[s.index('/'):]
222 )
223 for _ip_str in _ip4s:
224 # create interface class
225 _if = ipaddress.IPv4Interface(_ip_str)
226 # check if this is a VIP
227 # ...all those will have /32 mask
228 net_data['vip'] = None
229 if _if.network.prefixlen == 32:
230 net_data['vip'] = str(_if.exploded)
231 if 'name' not in net_data:
Alexb3dc8592019-06-11 13:20:36 -0500232 net_data['name'] = _name
Alexe0c5b9e2019-04-23 18:51:23 -0500233 if 'ifs' not in net_data:
234 net_data['ifs'] = [_if]
235 # map it
236 _runtime = self._map_network_for_host(
237 host,
238 _if,
239 _runtime,
240 net_data
241 )
242 else:
243 # data is already there, just add VIP
244 net_data['ifs'].append(_if)
245
246 return _runtime
247
248 def map_network(self, source):
249 # maps target network using given source
250 _networks = None
251
252 if source == self.RECLASS:
253 _networks = self._map_reclass_networks()
254 elif source == self.CONFIG:
255 _networks = self._map_configured_networks()
256 elif source == self.RUNTIME:
257 _networks = self._map_runtime_networks()
258
259 self.networks[source] = _networks
260 return _networks
261
Alex836fac82019-08-22 13:36:16 -0500262 def create_map(self):
263 """Create all needed elements for map output
Alexe0c5b9e2019-04-23 18:51:23 -0500264
265 :return: none
266 """
267 _runtime = self.networks[self.RUNTIME]
268 _reclass = self.networks[self.RECLASS]
Alex836fac82019-08-22 13:36:16 -0500269
270 # main networks, target vars
271 _map = {}
Alex6b633ec2019-06-06 19:44:34 -0500272 # No matter of proto, at least one IP will be present for the network
Alex836fac82019-08-22 13:36:16 -0500273 # we interested in, since we are to make sure that L3 level
274 # is configured according to reclass model
Alexe0c5b9e2019-04-23 18:51:23 -0500275 for network in _reclass:
276 # shortcuts
277 _net = str(network)
Alex836fac82019-08-22 13:36:16 -0500278 _map[_net] = {}
Alexe0c5b9e2019-04-23 18:51:23 -0500279 if network not in _runtime:
280 # reclass has network that not found in runtime
281 self.errors.add_error(
282 self.errors.NET_NO_RUNTIME_NETWORK,
283 reclass_net=str(network)
284 )
285 logger_cli.info(" {:-^50}".format(" No runtime network "))
286 continue
Alex6b633ec2019-06-06 19:44:34 -0500287 # hostnames
Alexe0c5b9e2019-04-23 18:51:23 -0500288 names = sorted(_runtime[network].keys())
289 for hostname in names:
Alex836fac82019-08-22 13:36:16 -0500290 _notes = []
Alex6b633ec2019-06-06 19:44:34 -0500291 node = hostname.split('.')[0]
Alexe0c5b9e2019-04-23 18:51:23 -0500292 if not salt_master.is_node_available(hostname, log=False):
293 logger_cli.info(
Alex6b633ec2019-06-06 19:44:34 -0500294 " {0:8} {1}".format(node, "node not available")
Alexe0c5b9e2019-04-23 18:51:23 -0500295 )
296 # add non-responsive node erorr
297 self.errors.add_error(
298 self.errors.NET_NODE_NON_RESPONSIVE,
299 host=hostname
300 )
Alex836fac82019-08-22 13:36:16 -0500301 _notes.append(
302 self.errors.get_error_type_text(
303 self.errors.NET_NODE_NON_RESPONSIVE
304 )
305 )
Alexe0c5b9e2019-04-23 18:51:23 -0500306 continue
Alex6b633ec2019-06-06 19:44:34 -0500307 # lookup interface name on node using network CIDR
308 _if_name = _runtime[network][hostname][0]["name"]
Alex836fac82019-08-22 13:36:16 -0500309 _raw = self.interfaces[hostname][_if_name]['runtime']
Alex6b633ec2019-06-06 19:44:34 -0500310 # get proper reclass
311 _r = self.interfaces[hostname][_if_name]['reclass']
Alex6b633ec2019-06-06 19:44:34 -0500312 _if_name_suffix = ""
313 # get the proto value
Alex3b8e5432019-06-11 15:21:59 -0500314 if _r:
315 _if_rc = ""
316 else:
317 self.errors.add_error(
318 self.errors.NET_NODE_UNEXPECTED_IF,
319 host=hostname,
320 if_name=_if_name
321 )
Alex836fac82019-08-22 13:36:16 -0500322 _notes.append(
323 self.errors.get_error_type_text(
324 self.errors.NET_NODE_UNEXPECTED_IF
325 )
326 )
Alex3b8e5432019-06-11 15:21:59 -0500327 _if_rc = "*"
328
Alex6b633ec2019-06-06 19:44:34 -0500329 if "proto" in _r:
330 _proto = _r['proto']
Alexe0c5b9e2019-04-23 18:51:23 -0500331 else:
Alex6b633ec2019-06-06 19:44:34 -0500332 _proto = "-"
Alexe0c5b9e2019-04-23 18:51:23 -0500333
Alex6b633ec2019-06-06 19:44:34 -0500334 if "type" in _r:
335 _if_name_suffix += _r["type"]
336 if "use_interfaces" in _r:
337 _if_name_suffix += "->" + ",".join(_r["use_interfaces"])
338
339 if _if_name_suffix:
340 _if_name_suffix = "({})".format(_if_name_suffix)
341
Alex6b633ec2019-06-06 19:44:34 -0500342 # get gate and routes if proto is static
343 if _proto == 'static':
344 # get the gateway for current net
345 _routes = salt_master.nodes[hostname]['routes']
346 _route = _routes[_net] if _net in _routes else None
Alex6b633ec2019-06-06 19:44:34 -0500347 # get the default gateway
348 if 'default' in _routes:
349 _d_gate = ipaddress.IPv4Address(
350 _routes['default']['gateway']
351 )
352 else:
353 _d_gate = None
Alexb3dc8592019-06-11 13:20:36 -0500354 _d_gate_str = str(_d_gate) if _d_gate else "No default!"
355 # match route with default
356 if not _route:
357 _gate = "?"
358 else:
359 _gate = _route['gateway'] if _route['gateway'] else "-"
Alex6b633ec2019-06-06 19:44:34 -0500360 else:
361 # in case of manual and dhcp, no check possible
362 _gate = "-"
363 _d_gate = "-"
Alex4067f002019-06-11 10:47:16 -0500364 _d_gate_str = "-"
Alex6b633ec2019-06-06 19:44:34 -0500365 # iterate through interfaces
Alexe0c5b9e2019-04-23 18:51:23 -0500366 _a = _runtime[network][hostname]
367 for _host in _a:
368 for _if in _host['ifs']:
Alexe0c5b9e2019-04-23 18:51:23 -0500369 _ip_str = str(_if.exploded)
Alexab232e42019-06-06 19:44:34 -0500370 _gate_error = ""
371 _up_error = ""
372 _mtu_error = ""
Alexe0c5b9e2019-04-23 18:51:23 -0500373
Alexb3dc8592019-06-11 13:20:36 -0500374 # Match gateway
Alexab232e42019-06-06 19:44:34 -0500375 if _proto == 'static':
Alexb3dc8592019-06-11 13:20:36 -0500376 # default reclass gate
Alex6b633ec2019-06-06 19:44:34 -0500377 _r_gate = "-"
378 if "gateway" in _r:
379 _r_gate = _r["gateway"]
Alexb3dc8592019-06-11 13:20:36 -0500380
Alexab232e42019-06-06 19:44:34 -0500381 # if values not match, put *
Alexb3dc8592019-06-11 13:20:36 -0500382 if _gate != _r_gate and _d_gate_str != _r_gate:
383 # if values not match, check if default match
Alex3b8e5432019-06-11 15:21:59 -0500384 self.errors.add_error(
385 self.errors.NET_UNEXPECTED_GATEWAY,
386 host=hostname,
387 if_name=_if_name,
388 ip=_ip_str,
389 gateway=_gate
390 )
Alex836fac82019-08-22 13:36:16 -0500391 _notes.append(
392 self.errors.get_error_type_text(
393 self.errors.NET_UNEXPECTED_GATEWAY
394 )
395 )
Alexab232e42019-06-06 19:44:34 -0500396 _gate_error = "*"
Alexe0c5b9e2019-04-23 18:51:23 -0500397
398 # IF status in reclass
Alex6b633ec2019-06-06 19:44:34 -0500399 _e = "enabled"
Alexab232e42019-06-06 19:44:34 -0500400 if _e not in _r:
Alex3b8e5432019-06-11 15:21:59 -0500401 self.errors.add_error(
402 self.errors.NET_NO_RC_IF_STATUS,
403 host=hostname,
404 if_name=_if_name
405 )
Alex836fac82019-08-22 13:36:16 -0500406 _notes.append(
407 self.errors.get_error_type_text(
408 self.errors.NET_NO_RC_IF_STATUS
409 )
410 )
Alexab232e42019-06-06 19:44:34 -0500411 _up_error = "*"
Alexe0c5b9e2019-04-23 18:51:23 -0500412
Alexe0c5b9e2019-04-23 18:51:23 -0500413 _rc_mtu = _r['mtu'] if 'mtu' in _r else None
Alexab232e42019-06-06 19:44:34 -0500414 _rc_mtu_s = ""
Alexe0c5b9e2019-04-23 18:51:23 -0500415 # check if this is a VIP address
416 # no checks needed if yes.
417 if _host['vip'] != _ip_str:
418 if _rc_mtu:
Alex3b8e5432019-06-11 15:21:59 -0500419 _rc_mtu_s = str(_rc_mtu)
Alexe0c5b9e2019-04-23 18:51:23 -0500420 # if there is an MTU value, match it
421 if _host['mtu'] != _rc_mtu_s:
422 self.errors.add_error(
423 self.errors.NET_MTU_MISMATCH,
424 host=hostname,
Alex6b633ec2019-06-06 19:44:34 -0500425 if_name=_if_name,
Alexe0c5b9e2019-04-23 18:51:23 -0500426 if_cidr=_ip_str,
427 reclass_mtu=_rc_mtu,
428 runtime_mtu=_host['mtu']
429 )
Alex836fac82019-08-22 13:36:16 -0500430 _notes.append(
431 self.errors.get_error_type_text(
432 self.errors.NET_MTU_MISMATCH
433 )
434 )
Alexb3dc8592019-06-11 13:20:36 -0500435 _rc_mtu_s = "/" + _rc_mtu_s
Alexab232e42019-06-06 19:44:34 -0500436 _mtu_error = "*"
437 else:
438 # empty the matched value
439 _rc_mtu_s = ""
Alex3b8e5432019-06-11 15:21:59 -0500440 elif _host['mtu'] != '1500' and \
441 _proto not in ["-", "dhcp"]:
Alexe0c5b9e2019-04-23 18:51:23 -0500442 # there is no MTU value in reclass
443 # and runtime value is not default
444 self.errors.add_error(
445 self.errors.NET_MTU_EMPTY,
446 host=hostname,
Alex6b633ec2019-06-06 19:44:34 -0500447 if_name=_if_name,
Alexe0c5b9e2019-04-23 18:51:23 -0500448 if_cidr=_ip_str,
449 if_mtu=_host['mtu']
450 )
Alex836fac82019-08-22 13:36:16 -0500451 _notes.append(
452 self.errors.get_error_type_text(
453 self.errors.NET_MTU_EMPTY
454 )
455 )
Alexab232e42019-06-06 19:44:34 -0500456 _mtu_error = "*"
Alexe0c5b9e2019-04-23 18:51:23 -0500457 else:
458 # this is a VIP
Alex6b633ec2019-06-06 19:44:34 -0500459 _if_name = " "*7
Alex6b633ec2019-06-06 19:44:34 -0500460 _if_name_suffix = ""
Alexe0c5b9e2019-04-23 18:51:23 -0500461 _ip_str += " VIP"
Alex836fac82019-08-22 13:36:16 -0500462 # Save all data
463 _values = {
464 "interface": _if_name,
465 "interface_error": _if_rc,
466 "interface_note": _if_name_suffix,
467 "ip_address": _ip_str,
468 "address_type": _proto,
469 "rt_mtu": _host['mtu'],
470 "rc_mtu": _rc_mtu_s,
471 "mtu_error": _mtu_error,
472 "status": _host['state'],
473 "status_error": _up_error,
474 "subnet_gateway": _gate,
475 "subnet_gateway_error": _gate_error,
476 "default_gateway": _d_gate_str,
477 "raw_data": _raw,
478 "error_note": " and ".join(_notes)
479 }
480 if node in _map[_net]:
481 # add if to host
482 _map[_net][node].append(_values)
483 else:
484 _map[_net][node] = [_values]
485 _notes = []
486
487 # save map
488 self.map = _map
489 # other runtime networks found
490 # docker, etc
491
492 return
493
494 def print_map(self):
495 """
496 Create text report for CLI
497
498 :return: none
499 """
500 logger_cli.info("# Networks")
501 logger_cli.info(
502 " {0:8} {1:25} {2:25} {3:6} {4:10} {5:10} {6}/{7}".format(
503 "Host",
504 "IF",
505 "IP",
506 "Proto",
507 "MTU",
508 "State",
509 "Gate",
510 "Def.Gate"
511 )
512 )
513 for network in self.map.keys():
514 logger_cli.info("-> {}".format(network))
515 for hostname in self.map[network].keys():
516 node = hostname.split('.')[0]
517 _n = self.map[network][hostname]
518 for _i in _n:
519 # Host IF IP Proto MTU State Gate Def.Gate
520 _text = "{:7} {:17} {:25} {:6} {:10} " \
521 "{:10} {} / {}".format(
522 _i['interface'] + _i['interface_error'],
523 _i['interface_note'],
524 _i['ip_address'],
525 _i['address_type'],
526 _i['rt_mtu'] + _i['rc_mtu'] + _i['mtu_error'],
527 _i['status'] + _i['status_error'],
528 _i['subnet_gateway'] +
529 _i['subnet_gateway_error'],
530 _i['default_gateway']
Alexe0c5b9e2019-04-23 18:51:23 -0500531 )
Alexe0c5b9e2019-04-23 18:51:23 -0500532 logger_cli.info(
Alex836fac82019-08-22 13:36:16 -0500533 " {0:8} {1}".format(
534 node,
535 _text
536 )
Alexe0c5b9e2019-04-23 18:51:23 -0500537 )
Alex836fac82019-08-22 13:36:16 -0500538
539 # logger_cli.info("\n# Other networks")
540 # _other = [n for n in _runtime if n not in _reclass]
541 # for network in _other:
542 # logger_cli.info("-> {}".format(str(network)))
543 # names = sorted(_runtime[network].keys())
544
545 # for hostname in names:
546 # for _n in _runtime[network][hostname]:
547 # _ifs = [str(ifs.ip) for ifs in _n['ifs']]
548 # _text = "{:25} {:25} {:6} {:10} {}".format(
549 # _n['name'],
550 # ", ".join(_ifs),
551 # "-",
552 # _n['mtu'],
553 # _n['state']
554 # )
555 # logger_cli.info(
556 # " {0:8} {1}".format(hostname.split('.')[0], _text)
557 # )
558 # logger_cli.info("\n")