blob: 54ce6308e9b10882fd0aaa7828189a9999e8f153 [file] [log] [blame]
Alex0989ecf2022-03-29 13:43:21 -05001# Author: Alex Savatieiev (osavatieiev@mirantis.com; a.savex@gmail.com)
2# Copyright 2019-2022 Mirantis, Inc.
Alexe0c5b9e2019-04-23 18:51:23 -05003import ipaddress
4import json
Alex6b633ec2019-06-06 19:44:34 -05005from copy import deepcopy
Alexe0c5b9e2019-04-23 18:51:23 -05006
7from cfg_checker.common import logger_cli
8from cfg_checker.common.exception import InvalidReturnException
Alex1f90e7b2021-09-03 15:31:28 -05009from cfg_checker.common.exception import ConfigException
10from cfg_checker.common.exception import KubeException
Alexe0c5b9e2019-04-23 18:51:23 -050011from cfg_checker.modules.network.network_errors import NetworkErrors
Alex205546c2020-12-30 19:22:30 -060012from cfg_checker.nodes import SaltNodes, KubeNodes
Alexe0c5b9e2019-04-23 18:51:23 -050013
14# TODO: use templated approach
15# net interface structure should be the same
16_if_item = {
17 "name": "unnamed interface",
18 "mac": "",
19 "routes": {},
Alex6b633ec2019-06-06 19:44:34 -050020 "proto": "",
Alexe0c5b9e2019-04-23 18:51:23 -050021 "ip": [],
22 "parameters": {}
23}
24
25# collection of configurations
26_network_item = {
27 "runtime": {},
28 "config": {},
29 "reclass": {}
30}
31
32
33class NetworkMapper(object):
34 RECLASS = "reclass"
35 CONFIG = "config"
36 RUNTIME = "runtime"
37
Alexe9908f72020-05-19 16:04:53 -050038 def __init__(
39 self,
Alex9a4ad212020-10-01 18:04:25 -050040 config,
Alexe9908f72020-05-19 16:04:53 -050041 errors_class=None,
42 skip_list=None,
43 skip_list_file=None
44 ):
Alexe0c5b9e2019-04-23 18:51:23 -050045 logger_cli.info("# Initializing mapper")
Alex205546c2020-12-30 19:22:30 -060046 self.env_config = config
Alex6b633ec2019-06-06 19:44:34 -050047 # init networks and nodes
Alexe0c5b9e2019-04-23 18:51:23 -050048 self.networks = {}
Alex205546c2020-12-30 19:22:30 -060049 self.nodes = self.master.get_nodes(
Alexe9908f72020-05-19 16:04:53 -050050 skip_list=skip_list,
51 skip_list_file=skip_list_file
52 )
Alex205546c2020-12-30 19:22:30 -060053 self.cluster = self.master.get_info()
54 self.domain = self.master.domain
Alex6b633ec2019-06-06 19:44:34 -050055 # init and pre-populate interfaces
56 self.interfaces = {k: {} for k in self.nodes}
57 # Init errors class
Alexe0c5b9e2019-04-23 18:51:23 -050058 if errors_class:
59 self.errors = errors_class
60 else:
61 logger_cli.debug("... init error logs folder")
62 self.errors = NetworkErrors()
63
64 # adding net data to tree
65 def _add_data(self, _list, _n, _h, _d):
66 if _n not in _list:
67 _list[_n] = {}
68 _list[_n][_h] = [_d]
69 elif _h not in _list[_n]:
70 # there is no such host, just create it
71 _list[_n][_h] = [_d]
72 else:
73 # there is such host... this is an error
74 self.errors.add_error(
75 self.errors.NET_DUPLICATE_IF,
76 host=_h,
77 dup_if=_d['name']
78 )
79 _list[_n][_h].append(_d)
80
81 # TODO: refactor map creation. Build one map instead of two separate
82 def _map_network_for_host(self, host, if_class, net_list, data):
83 # filter networks for this IF IP
84 _nets = [n for n in net_list.keys() if if_class.ip in n]
85 _masks = [n.netmask for n in _nets]
86 if len(_nets) > 1:
87 # There a multiple network found for this IP, Error
88 self.errors.add_error(
89 self.errors.NET_SUBNET_INTERSECT,
90 host=host,
91 ip=str(if_class.exploded),
92 networks="; ".join([str(_n) for _n in _nets])
93 )
94 # check mask match
95 if len(_nets) > 0 and if_class.netmask not in _masks:
96 self.errors.add_error(
97 self.errors.NET_MASK_MISMATCH,
98 host=host,
99 if_name=data['name'],
100 if_cidr=if_class.exploded,
101 if_mapped_networks=", ".join([str(_n) for _n in _nets])
102 )
103
104 if len(_nets) < 1:
105 self._add_data(net_list, if_class.network, host, data)
106 else:
107 # add all data
108 for net in _nets:
109 self._add_data(net_list, net, host, data)
110
111 return net_list
112
113 def _map_reclass_networks(self):
114 # class uses nodes from self.nodes dict
115 _reclass = {}
116 # Get required pillars
Alex205546c2020-12-30 19:22:30 -0600117 self.master.get_specific_pillar_for_nodes("linux:network")
118 for node in self.master.nodes.keys():
Alexe0c5b9e2019-04-23 18:51:23 -0500119 # check if this node
Alex205546c2020-12-30 19:22:30 -0600120 if not self.master.is_node_available(node):
Alexe0c5b9e2019-04-23 18:51:23 -0500121 continue
122 # get the reclass value
Alex9a4ad212020-10-01 18:04:25 -0500123 _pillar = \
Alex205546c2020-12-30 19:22:30 -0600124 self.master.nodes[node]['pillars']['linux']['network']
Alexe0c5b9e2019-04-23 18:51:23 -0500125 # we should be ready if there is no interface in reclass for a node
Alex92e07ce2019-05-31 16:00:03 -0500126 # for example on APT node
Alexe0c5b9e2019-04-23 18:51:23 -0500127 if 'interface' in _pillar:
128 _pillar = _pillar['interface']
129 else:
130 logger_cli.info(
131 "... node '{}' skipped, no IF section in reclass".format(
132 node
133 )
134 )
135 continue
Alex92e07ce2019-05-31 16:00:03 -0500136
Alex6b633ec2019-06-06 19:44:34 -0500137 # build map based on IPs and save info too
Alex3bc95f62020-03-05 17:00:04 -0600138 for if_name, _dat in _pillar.items():
Alexb3dc8592019-06-11 13:20:36 -0500139 # get proper IF name
140 _if_name = if_name if 'name' not in _dat else _dat['name']
141 # place it
Alex6b633ec2019-06-06 19:44:34 -0500142 if _if_name not in self.interfaces[node]:
143 self.interfaces[node][_if_name] = deepcopy(_network_item)
Alexb3dc8592019-06-11 13:20:36 -0500144 self.interfaces[node][_if_name]['reclass'] = deepcopy(_dat)
Alex6b633ec2019-06-06 19:44:34 -0500145 # map network if any
Alexb3dc8592019-06-11 13:20:36 -0500146 if 'address' in _dat:
Alexe0c5b9e2019-04-23 18:51:23 -0500147 _if = ipaddress.IPv4Interface(
Alexb3dc8592019-06-11 13:20:36 -0500148 _dat['address'] + '/' + _dat['netmask']
Alexe0c5b9e2019-04-23 18:51:23 -0500149 )
Alexb3dc8592019-06-11 13:20:36 -0500150 _dat['name'] = _if_name
151 _dat['ifs'] = [_if]
Alexe0c5b9e2019-04-23 18:51:23 -0500152
153 _reclass = self._map_network_for_host(
154 node,
155 _if,
156 _reclass,
Alexb3dc8592019-06-11 13:20:36 -0500157 _dat
Alexe0c5b9e2019-04-23 18:51:23 -0500158 )
159
160 return _reclass
161
162 def _map_configured_networks(self):
163 # class uses nodes from self.nodes dict
164 _confs = {}
165
Alex92e07ce2019-05-31 16:00:03 -0500166 # TODO: parse /etc/network/interfaces
167
Alexe0c5b9e2019-04-23 18:51:23 -0500168 return _confs
169
Alex1f90e7b2021-09-03 15:31:28 -0500170 def _map_runtime_networks(self, result):
Alexe0c5b9e2019-04-23 18:51:23 -0500171 # class uses nodes from self.nodes dict
172 _runtime = {}
Alex205546c2020-12-30 19:22:30 -0600173 for key in self.master.nodes.keys():
Alexe0c5b9e2019-04-23 18:51:23 -0500174 # check if we are to work with this node
Alex205546c2020-12-30 19:22:30 -0600175 if not self.master.is_node_available(key):
Alexe0c5b9e2019-04-23 18:51:23 -0500176 continue
Alex205546c2020-12-30 19:22:30 -0600177 # due to much data to be passed from master,
Alexe0c5b9e2019-04-23 18:51:23 -0500178 # it is happening in order
Alex1f90e7b2021-09-03 15:31:28 -0500179 if key in result:
180 _text = result[key]
Alexe0c5b9e2019-04-23 18:51:23 -0500181 if '{' in _text and '}' in _text:
182 _text = _text[_text.find('{'):]
183 else:
184 raise InvalidReturnException(
185 "Non-json object returned: '{}'".format(
186 _text
187 )
188 )
189 _dict = json.loads(_text[_text.find('{'):])
Alex205546c2020-12-30 19:22:30 -0600190 self.master.nodes[key]['routes'] = _dict.pop("routes")
191 self.master.nodes[key]['networks'] = _dict
Alexe0c5b9e2019-04-23 18:51:23 -0500192 else:
Alex205546c2020-12-30 19:22:30 -0600193 self.master.nodes[key]['networks'] = {}
194 self.master.nodes[key]['routes'] = {}
Alexe0c5b9e2019-04-23 18:51:23 -0500195 logger_cli.debug("... {} has {} networks".format(
196 key,
Alex205546c2020-12-30 19:22:30 -0600197 len(self.master.nodes[key]['networks'].keys())
Alexe0c5b9e2019-04-23 18:51:23 -0500198 ))
199 logger_cli.info("-> done collecting networks data")
200
Alex3cdb1bd2021-09-10 15:51:11 -0500201 logger_cli.info("-> mapping runtime network IPs")
Alexe0c5b9e2019-04-23 18:51:23 -0500202 # match interfaces by IP subnets
Alex205546c2020-12-30 19:22:30 -0600203 for host, node_data in self.master.nodes.items():
204 if not self.master.is_node_available(host):
Alexe0c5b9e2019-04-23 18:51:23 -0500205 continue
206
Alex3bc95f62020-03-05 17:00:04 -0600207 for net_name, net_data in node_data['networks'].items():
Alexb3dc8592019-06-11 13:20:36 -0500208 # cut net name
209 _i = net_name.find('@')
210 _name = net_name if _i < 0 else net_name[:_i]
Alexe0c5b9e2019-04-23 18:51:23 -0500211 # get ips and calculate subnets
Alexb3dc8592019-06-11 13:20:36 -0500212 if _name in ['lo']:
Alexe0c5b9e2019-04-23 18:51:23 -0500213 # skip the localhost
214 continue
Alex6b633ec2019-06-06 19:44:34 -0500215 else:
216 # add collected data to interface storage
Alexb3dc8592019-06-11 13:20:36 -0500217 if _name not in self.interfaces[host]:
218 self.interfaces[host][_name] = \
Alex6b633ec2019-06-06 19:44:34 -0500219 deepcopy(_network_item)
Alexb3dc8592019-06-11 13:20:36 -0500220 self.interfaces[host][_name]['runtime'] = \
Alex6b633ec2019-06-06 19:44:34 -0500221 deepcopy(net_data)
222
Alexe0c5b9e2019-04-23 18:51:23 -0500223 # get data and make sure that wide mask goes first
224 _ip4s = sorted(
225 net_data['ipv4'],
226 key=lambda s: s[s.index('/'):]
227 )
228 for _ip_str in _ip4s:
229 # create interface class
230 _if = ipaddress.IPv4Interface(_ip_str)
231 # check if this is a VIP
232 # ...all those will have /32 mask
233 net_data['vip'] = None
234 if _if.network.prefixlen == 32:
235 net_data['vip'] = str(_if.exploded)
236 if 'name' not in net_data:
Alexb3dc8592019-06-11 13:20:36 -0500237 net_data['name'] = _name
Alexe0c5b9e2019-04-23 18:51:23 -0500238 if 'ifs' not in net_data:
239 net_data['ifs'] = [_if]
240 # map it
241 _runtime = self._map_network_for_host(
242 host,
243 _if,
244 _runtime,
245 net_data
246 )
247 else:
248 # data is already there, just add VIP
249 net_data['ifs'].append(_if)
250
Alex1839bbf2019-08-22 17:17:21 -0500251 def process_interface(lvl, interface, tree, res):
252 # get childs for each root
253 # tree row item (<if_name>, [<parents>], [<childs>])
254 if lvl not in tree:
255 # - no level - add it
256 tree[lvl] = {}
257 # there is such interface in this level?
258 if interface not in tree[lvl]:
259 # - IF not present
Alexf3dbe862019-10-07 15:17:04 -0500260 _n = ''
261 if interface not in res:
262 _n = 'unknown IF'
263 _p = None
264 _c = None
265 else:
266 # -- get parents, add
267 _p = res[interface]['lower']
268 # -- get childs, add
269 _c = res[interface]['upper']
270
Alex1839bbf2019-08-22 17:17:21 -0500271 # if None, put empty list
272 _p = _p if _p else []
Alex1839bbf2019-08-22 17:17:21 -0500273 # if None, put empty list
274 _c = _c if _c else []
275 tree[lvl].update({
276 interface: {
Alexf3dbe862019-10-07 15:17:04 -0500277 "note": _n,
Alex1839bbf2019-08-22 17:17:21 -0500278 "parents": _p,
279 "children": _c,
280 "size": len(_p) if len(_p) > len(_c) else len(_c)
281 }
282 })
283 for p_if in tree[lvl][interface]["parents"]:
284 # -- cycle: execute process for next parent, lvl-1
285 process_interface(lvl-1, p_if, tree, res)
286 for c_if in tree[lvl][interface]["children"]:
287 # -- cycle: execute process for next child, lvl+1
288 process_interface(lvl+1, c_if, tree, res)
289 else:
290 # - IF present - exit (been here already)
291 return
292
293 def _put(cNet, cIndex, _list):
Alexf3dbe862019-10-07 15:17:04 -0500294 _added = False
295 _actual_index = -1
296 # Check list len
297 _len = len(_list)
298 if cIndex >= _len:
299 # grow list to meet index
300 _list = _list + [''] * (cIndex - _len + 1)
301 _len = len(_list)
302
303 for _cI in range(cIndex, _len):
Alex1839bbf2019-08-22 17:17:21 -0500304 # add child per index
305 # if space is free
306 if not _list[_cI]:
307 _list[_cI] = cNet
Alexf3dbe862019-10-07 15:17:04 -0500308 _added = True
309 _actual_index = _cI
Alex1839bbf2019-08-22 17:17:21 -0500310 break
Alexf3dbe862019-10-07 15:17:04 -0500311 if not _added:
312 # grow list by one entry
313 _list = _list + [cNet]
314 _actual_index = len(_list) - 1
315 return _actual_index, _list
Alex1839bbf2019-08-22 17:17:21 -0500316
317 # build network hierachy
318 nr = node_data['networks']
319 # walk interface tree
320 for _ifname in node_data['networks']:
321 _tree = {}
322 _level = 0
323 process_interface(_level, _ifname, _tree, nr)
324 # save tree for node/if
325 node_data['networks'][_ifname]['tree'] = _tree
326
327 # debug, print built tree
328 # logger_cli.debug("# '{}'".format(_ifname))
Alex3bc95f62020-03-05 17:00:04 -0600329 lvls = list(_tree.keys())
Alex1839bbf2019-08-22 17:17:21 -0500330 lvls.sort()
331 n = len(lvls)
332 m = max([len(_tree[k].keys()) for k in _tree.keys()])
333 matrix = [["" for i in range(m)] for j in range(n)]
334 x = 0
335 while True:
336 _lv = lvls.pop(0)
337 # get all interfaces on this level
Alex3bc95f62020-03-05 17:00:04 -0600338 nets = iter(_tree[_lv].keys())
Alex1839bbf2019-08-22 17:17:21 -0500339 while True:
340 y = 0
341 # get next interface
Alex3bc95f62020-03-05 17:00:04 -0600342 try:
343 _net = next(nets)
344 except StopIteration:
345 break
Alex1839bbf2019-08-22 17:17:21 -0500346 # all nets
347 _a = [_net]
348 # put current interface if this is only one left
349 if not _tree[_lv][_net]['children']:
350 if _net not in matrix[x]:
Alexf3dbe862019-10-07 15:17:04 -0500351 _, matrix[x] = _put(
352 _net,
353 y,
354 matrix[x]
355 )
Alex1839bbf2019-08-22 17:17:21 -0500356 y += 1
357 else:
358 # get all nets with same child
359 for _c in _tree[_lv][_net]['children']:
360 for _o_net in nets:
361 if _c in _tree[_lv][_o_net]['children']:
362 _a.append(_o_net)
363 # flush collected nets
364 for idx in range(len(_a)):
365 if _a[idx] in matrix[x]:
366 # there is such interface on this level
367 # get index
368 _nI = matrix[x].index(_a[idx])
Alexf3dbe862019-10-07 15:17:04 -0500369 _, matrix[x+1] = _put(
370 _c,
371 _nI,
372 matrix[x+1]
373 )
Alex1839bbf2019-08-22 17:17:21 -0500374 else:
375 # there is no such interface
376 # add it
Alexf3dbe862019-10-07 15:17:04 -0500377 _t, matrix[x] = _put(
378 _a[idx],
379 0,
380 matrix[x]
381 )
382 # also, put child
383 _, matrix[x+1] = _put(
384 _c,
385 _t,
386 matrix[x+1]
387 )
Alex1839bbf2019-08-22 17:17:21 -0500388 # remove collected nets from processing
389 if _a[idx] in nets:
390 nets.remove(_a[idx])
391 y += len(_a)
392 if not nets:
393 x += 1
394 break
395 if not lvls:
396 break
397
398 lines = []
399 _columns = [len(max([i for i in li])) for li in matrix]
400 for idx_y in range(m):
401 line = ""
402 for idx_x in range(n):
Alex9b2c1d12020-03-19 09:32:35 -0500403 _len = _columns[idx_x] if _columns[idx_x] else 1
404 _fmt = "{" + ":{}".format(_len) + "} "
Alex1839bbf2019-08-22 17:17:21 -0500405 line += _fmt.format(matrix[idx_x][idx_y])
406 lines.append(line)
407 node_data['networks'][_ifname]['matrix'] = matrix
408 node_data['networks'][_ifname]['lines'] = lines
Alexe0c5b9e2019-04-23 18:51:23 -0500409 return _runtime
410
Alex1f90e7b2021-09-03 15:31:28 -0500411
412class SaltNetworkMapper(NetworkMapper):
413 def __init__(
414 self,
415 config,
416 errors_class=None,
417 skip_list=None,
418 skip_list_file=None
419 ):
420 self.master = SaltNodes(config)
421 super(SaltNetworkMapper, self).__init__(
422 config,
423 errors_class=errors_class,
424 skip_list=skip_list,
425 skip_list_file=skip_list_file
426 )
427
428 def get_script_output(self):
429 """
430 Get runtime networks by executing script on nodes
431 """
432 logger_cli.info("# Mapping node runtime network data")
433 self.master.prepare_script_on_active_nodes("ifs_data.py")
434 _result = self.master.execute_script_on_active_nodes(
435 "ifs_data.py",
436 args="json"
437 )
438
439 return _result
440
441 def map_networks(self):
Alex3cdb1bd2021-09-10 15:51:11 -0500442 logger_cli.info("-> Mapping reclass networks")
Alex1f90e7b2021-09-03 15:31:28 -0500443 self.map_network(self.RECLASS)
Alex3cdb1bd2021-09-10 15:51:11 -0500444 logger_cli.info("-> Mapping runtime networks")
Alex1f90e7b2021-09-03 15:31:28 -0500445 self.map_network(self.RUNTIME)
446
Alexe0c5b9e2019-04-23 18:51:23 -0500447 def map_network(self, source):
448 # maps target network using given source
449 _networks = None
450
451 if source == self.RECLASS:
452 _networks = self._map_reclass_networks()
453 elif source == self.CONFIG:
454 _networks = self._map_configured_networks()
455 elif source == self.RUNTIME:
Alex1f90e7b2021-09-03 15:31:28 -0500456 _r = self.get_script_output()
457 _networks = self._map_runtime_networks(_r)
Alexe0c5b9e2019-04-23 18:51:23 -0500458
459 self.networks[source] = _networks
460 return _networks
461
Alex3cdb1bd2021-09-10 15:51:11 -0500462 def create_map(self, skip_keywords=None):
Alex836fac82019-08-22 13:36:16 -0500463 """Create all needed elements for map output
Alexe0c5b9e2019-04-23 18:51:23 -0500464
465 :return: none
466 """
467 _runtime = self.networks[self.RUNTIME]
468 _reclass = self.networks[self.RECLASS]
Alex836fac82019-08-22 13:36:16 -0500469
470 # main networks, target vars
471 _map = {}
Alex6b633ec2019-06-06 19:44:34 -0500472 # No matter of proto, at least one IP will be present for the network
Alex836fac82019-08-22 13:36:16 -0500473 # we interested in, since we are to make sure that L3 level
474 # is configured according to reclass model
Alexe0c5b9e2019-04-23 18:51:23 -0500475 for network in _reclass:
476 # shortcuts
477 _net = str(network)
Alex836fac82019-08-22 13:36:16 -0500478 _map[_net] = {}
Alexe0c5b9e2019-04-23 18:51:23 -0500479 if network not in _runtime:
480 # reclass has network that not found in runtime
481 self.errors.add_error(
482 self.errors.NET_NO_RUNTIME_NETWORK,
483 reclass_net=str(network)
484 )
Alex1839bbf2019-08-22 17:17:21 -0500485 logger_cli.warn(
486 "WARN: {}: {}".format(
487 " No runtime network ", str(network)
488 )
489 )
Alexe0c5b9e2019-04-23 18:51:23 -0500490 continue
Alex6b633ec2019-06-06 19:44:34 -0500491 # hostnames
Alexe0c5b9e2019-04-23 18:51:23 -0500492 names = sorted(_runtime[network].keys())
493 for hostname in names:
Alex836fac82019-08-22 13:36:16 -0500494 _notes = []
Alex6b633ec2019-06-06 19:44:34 -0500495 node = hostname.split('.')[0]
Alex205546c2020-12-30 19:22:30 -0600496 if not self.master.is_node_available(hostname, log=False):
Alexe0c5b9e2019-04-23 18:51:23 -0500497 logger_cli.info(
Alex6b633ec2019-06-06 19:44:34 -0500498 " {0:8} {1}".format(node, "node not available")
Alexe0c5b9e2019-04-23 18:51:23 -0500499 )
500 # add non-responsive node erorr
501 self.errors.add_error(
502 self.errors.NET_NODE_NON_RESPONSIVE,
503 host=hostname
504 )
Alex836fac82019-08-22 13:36:16 -0500505 _notes.append(
506 self.errors.get_error_type_text(
507 self.errors.NET_NODE_NON_RESPONSIVE
508 )
509 )
Alexe0c5b9e2019-04-23 18:51:23 -0500510 continue
Alex6b633ec2019-06-06 19:44:34 -0500511 # lookup interface name on node using network CIDR
512 _if_name = _runtime[network][hostname][0]["name"]
Alex836fac82019-08-22 13:36:16 -0500513 _raw = self.interfaces[hostname][_if_name]['runtime']
Alex6b633ec2019-06-06 19:44:34 -0500514 # get proper reclass
515 _r = self.interfaces[hostname][_if_name]['reclass']
Alex6b633ec2019-06-06 19:44:34 -0500516 _if_name_suffix = ""
517 # get the proto value
Alex3b8e5432019-06-11 15:21:59 -0500518 if _r:
519 _if_rc = ""
520 else:
521 self.errors.add_error(
522 self.errors.NET_NODE_UNEXPECTED_IF,
523 host=hostname,
524 if_name=_if_name
525 )
Alex836fac82019-08-22 13:36:16 -0500526 _notes.append(
527 self.errors.get_error_type_text(
528 self.errors.NET_NODE_UNEXPECTED_IF
529 )
530 )
Alex3b8e5432019-06-11 15:21:59 -0500531 _if_rc = "*"
532
Alex6b633ec2019-06-06 19:44:34 -0500533 if "proto" in _r:
534 _proto = _r['proto']
Alexe0c5b9e2019-04-23 18:51:23 -0500535 else:
Alex6b633ec2019-06-06 19:44:34 -0500536 _proto = "-"
Alexe0c5b9e2019-04-23 18:51:23 -0500537
Alex6b633ec2019-06-06 19:44:34 -0500538 if "type" in _r:
539 _if_name_suffix += _r["type"]
540 if "use_interfaces" in _r:
541 _if_name_suffix += "->" + ",".join(_r["use_interfaces"])
542
543 if _if_name_suffix:
544 _if_name_suffix = "({})".format(_if_name_suffix)
545
Alex6b633ec2019-06-06 19:44:34 -0500546 # get gate and routes if proto is static
547 if _proto == 'static':
548 # get the gateway for current net
Alex205546c2020-12-30 19:22:30 -0600549 _routes = self.master.nodes[hostname]['routes']
Alex6b633ec2019-06-06 19:44:34 -0500550 _route = _routes[_net] if _net in _routes else None
Alex6b633ec2019-06-06 19:44:34 -0500551 # get the default gateway
552 if 'default' in _routes:
553 _d_gate = ipaddress.IPv4Address(
554 _routes['default']['gateway']
555 )
556 else:
557 _d_gate = None
Alexb3dc8592019-06-11 13:20:36 -0500558 _d_gate_str = str(_d_gate) if _d_gate else "No default!"
559 # match route with default
560 if not _route:
561 _gate = "?"
562 else:
563 _gate = _route['gateway'] if _route['gateway'] else "-"
Alex6b633ec2019-06-06 19:44:34 -0500564 else:
565 # in case of manual and dhcp, no check possible
566 _gate = "-"
567 _d_gate = "-"
Alex4067f002019-06-11 10:47:16 -0500568 _d_gate_str = "-"
Alex6b633ec2019-06-06 19:44:34 -0500569 # iterate through interfaces
Alexe0c5b9e2019-04-23 18:51:23 -0500570 _a = _runtime[network][hostname]
571 for _host in _a:
572 for _if in _host['ifs']:
Alexe0c5b9e2019-04-23 18:51:23 -0500573 _ip_str = str(_if.exploded)
Alexab232e42019-06-06 19:44:34 -0500574 _gate_error = ""
575 _up_error = ""
576 _mtu_error = ""
Alexe0c5b9e2019-04-23 18:51:23 -0500577
Alexb3dc8592019-06-11 13:20:36 -0500578 # Match gateway
Alexab232e42019-06-06 19:44:34 -0500579 if _proto == 'static':
Alexb3dc8592019-06-11 13:20:36 -0500580 # default reclass gate
Alex6b633ec2019-06-06 19:44:34 -0500581 _r_gate = "-"
582 if "gateway" in _r:
583 _r_gate = _r["gateway"]
Alexb3dc8592019-06-11 13:20:36 -0500584
Alexab232e42019-06-06 19:44:34 -0500585 # if values not match, put *
Alexb3dc8592019-06-11 13:20:36 -0500586 if _gate != _r_gate and _d_gate_str != _r_gate:
587 # if values not match, check if default match
Alex3b8e5432019-06-11 15:21:59 -0500588 self.errors.add_error(
589 self.errors.NET_UNEXPECTED_GATEWAY,
590 host=hostname,
591 if_name=_if_name,
592 ip=_ip_str,
593 gateway=_gate
594 )
Alex836fac82019-08-22 13:36:16 -0500595 _notes.append(
596 self.errors.get_error_type_text(
597 self.errors.NET_UNEXPECTED_GATEWAY
598 )
599 )
Alexab232e42019-06-06 19:44:34 -0500600 _gate_error = "*"
Alexe0c5b9e2019-04-23 18:51:23 -0500601
602 # IF status in reclass
Alex6b633ec2019-06-06 19:44:34 -0500603 _e = "enabled"
Alexab232e42019-06-06 19:44:34 -0500604 if _e not in _r:
Alex3b8e5432019-06-11 15:21:59 -0500605 self.errors.add_error(
606 self.errors.NET_NO_RC_IF_STATUS,
607 host=hostname,
608 if_name=_if_name
609 )
Alex836fac82019-08-22 13:36:16 -0500610 _notes.append(
611 self.errors.get_error_type_text(
612 self.errors.NET_NO_RC_IF_STATUS
613 )
614 )
Alexab232e42019-06-06 19:44:34 -0500615 _up_error = "*"
Alexe0c5b9e2019-04-23 18:51:23 -0500616
Alexe0c5b9e2019-04-23 18:51:23 -0500617 _rc_mtu = _r['mtu'] if 'mtu' in _r else None
Alexab232e42019-06-06 19:44:34 -0500618 _rc_mtu_s = ""
Alexe0c5b9e2019-04-23 18:51:23 -0500619 # check if this is a VIP address
620 # no checks needed if yes.
621 if _host['vip'] != _ip_str:
622 if _rc_mtu:
Alex3b8e5432019-06-11 15:21:59 -0500623 _rc_mtu_s = str(_rc_mtu)
Alexe0c5b9e2019-04-23 18:51:23 -0500624 # if there is an MTU value, match it
625 if _host['mtu'] != _rc_mtu_s:
626 self.errors.add_error(
627 self.errors.NET_MTU_MISMATCH,
628 host=hostname,
Alex6b633ec2019-06-06 19:44:34 -0500629 if_name=_if_name,
Alexe0c5b9e2019-04-23 18:51:23 -0500630 if_cidr=_ip_str,
631 reclass_mtu=_rc_mtu,
632 runtime_mtu=_host['mtu']
633 )
Alex836fac82019-08-22 13:36:16 -0500634 _notes.append(
635 self.errors.get_error_type_text(
636 self.errors.NET_MTU_MISMATCH
637 )
638 )
Alexb3dc8592019-06-11 13:20:36 -0500639 _rc_mtu_s = "/" + _rc_mtu_s
Alexab232e42019-06-06 19:44:34 -0500640 _mtu_error = "*"
641 else:
642 # empty the matched value
643 _rc_mtu_s = ""
Alex3b8e5432019-06-11 15:21:59 -0500644 elif _host['mtu'] != '1500' and \
645 _proto not in ["-", "dhcp"]:
Alexe0c5b9e2019-04-23 18:51:23 -0500646 # there is no MTU value in reclass
647 # and runtime value is not default
648 self.errors.add_error(
649 self.errors.NET_MTU_EMPTY,
650 host=hostname,
Alex6b633ec2019-06-06 19:44:34 -0500651 if_name=_if_name,
Alexe0c5b9e2019-04-23 18:51:23 -0500652 if_cidr=_ip_str,
653 if_mtu=_host['mtu']
654 )
Alex836fac82019-08-22 13:36:16 -0500655 _notes.append(
656 self.errors.get_error_type_text(
657 self.errors.NET_MTU_EMPTY
658 )
659 )
Alexab232e42019-06-06 19:44:34 -0500660 _mtu_error = "*"
Alexe0c5b9e2019-04-23 18:51:23 -0500661 else:
662 # this is a VIP
Alex6b633ec2019-06-06 19:44:34 -0500663 _if_name = " "*7
Alex6b633ec2019-06-06 19:44:34 -0500664 _if_name_suffix = ""
Alexe0c5b9e2019-04-23 18:51:23 -0500665 _ip_str += " VIP"
Alex836fac82019-08-22 13:36:16 -0500666 # Save all data
667 _values = {
668 "interface": _if_name,
669 "interface_error": _if_rc,
670 "interface_note": _if_name_suffix,
Alex1839bbf2019-08-22 17:17:21 -0500671 "interface_map": "\n".join(_host['lines']),
672 "interface_matrix": _host['matrix'],
Alex836fac82019-08-22 13:36:16 -0500673 "ip_address": _ip_str,
674 "address_type": _proto,
675 "rt_mtu": _host['mtu'],
676 "rc_mtu": _rc_mtu_s,
677 "mtu_error": _mtu_error,
678 "status": _host['state'],
679 "status_error": _up_error,
680 "subnet_gateway": _gate,
681 "subnet_gateway_error": _gate_error,
682 "default_gateway": _d_gate_str,
683 "raw_data": _raw,
684 "error_note": " and ".join(_notes)
685 }
686 if node in _map[_net]:
687 # add if to host
688 _map[_net][node].append(_values)
689 else:
690 _map[_net][node] = [_values]
691 _notes = []
692
693 # save map
694 self.map = _map
Alex836fac82019-08-22 13:36:16 -0500695 return
696
697 def print_map(self):
698 """
699 Create text report for CLI
700
701 :return: none
702 """
703 logger_cli.info("# Networks")
704 logger_cli.info(
705 " {0:8} {1:25} {2:25} {3:6} {4:10} {5:10} {6}/{7}".format(
706 "Host",
707 "IF",
708 "IP",
709 "Proto",
710 "MTU",
711 "State",
712 "Gate",
713 "Def.Gate"
714 )
715 )
716 for network in self.map.keys():
717 logger_cli.info("-> {}".format(network))
718 for hostname in self.map[network].keys():
719 node = hostname.split('.')[0]
720 _n = self.map[network][hostname]
721 for _i in _n:
722 # Host IF IP Proto MTU State Gate Def.Gate
723 _text = "{:7} {:17} {:25} {:6} {:10} " \
724 "{:10} {} / {}".format(
725 _i['interface'] + _i['interface_error'],
726 _i['interface_note'],
727 _i['ip_address'],
728 _i['address_type'],
729 _i['rt_mtu'] + _i['rc_mtu'] + _i['mtu_error'],
730 _i['status'] + _i['status_error'],
731 _i['subnet_gateway'] +
732 _i['subnet_gateway_error'],
733 _i['default_gateway']
Alexe0c5b9e2019-04-23 18:51:23 -0500734 )
Alexe0c5b9e2019-04-23 18:51:23 -0500735 logger_cli.info(
Alex836fac82019-08-22 13:36:16 -0500736 " {0:8} {1}".format(
737 node,
738 _text
739 )
Alexe0c5b9e2019-04-23 18:51:23 -0500740 )
Alex836fac82019-08-22 13:36:16 -0500741
742 # logger_cli.info("\n# Other networks")
743 # _other = [n for n in _runtime if n not in _reclass]
744 # for network in _other:
745 # logger_cli.info("-> {}".format(str(network)))
746 # names = sorted(_runtime[network].keys())
747
748 # for hostname in names:
749 # for _n in _runtime[network][hostname]:
750 # _ifs = [str(ifs.ip) for ifs in _n['ifs']]
751 # _text = "{:25} {:25} {:6} {:10} {}".format(
752 # _n['name'],
753 # ", ".join(_ifs),
754 # "-",
755 # _n['mtu'],
756 # _n['state']
757 # )
758 # logger_cli.info(
759 # " {0:8} {1}".format(hostname.split('.')[0], _text)
760 # )
761 # logger_cli.info("\n")
Alex1f90e7b2021-09-03 15:31:28 -0500762 return
Alex205546c2020-12-30 19:22:30 -0600763
764
765class KubeNetworkMapper(NetworkMapper):
766 def __init__(
767 self,
768 config,
769 errors_class=None,
770 skip_list=None,
771 skip_list_file=None
772 ):
773 self.master = KubeNodes(config)
Alex7b0ee9a2021-09-21 17:16:17 -0500774 self.daemonset = None
Alex205546c2020-12-30 19:22:30 -0600775 super(KubeNetworkMapper, self).__init__(
776 config,
777 errors_class=errors_class,
778 skip_list=skip_list,
779 skip_list_file=skip_list_file
780 )
Alex1f90e7b2021-09-03 15:31:28 -0500781
Alex7b0ee9a2021-09-21 17:16:17 -0500782 def get_daemonset(self):
783 if not self.daemonset:
784 _d = self.master.prepare_daemonset("daemonset_template.yaml")
785
786 # wait for daemonset, normally less than 60 sec for all
787 # but still, let us give it 10 second per pod
788 _timeout = self.master.nodes.__len__() * 10
789 if not self.master.wait_for_daemonset(_d, timeout=_timeout):
790 raise KubeException("Daemonset deployment fail")
791 self.daemonset = _d
792 return self.daemonset
793
Alexb2129542021-11-23 15:49:42 -0600794 def get_script_output(self, script, _args=None):
Alex1f90e7b2021-09-03 15:31:28 -0500795 """
796 Get runtime network by creating DaemonSet with Host network parameter
797 """
798 # prepare daemonset
799 logger_cli.info("-> Preparing daemonset to get node info")
Alex7b0ee9a2021-09-21 17:16:17 -0500800 _daemonset = self.get_daemonset()
Alex1f90e7b2021-09-03 15:31:28 -0500801 logger_cli.info("-> Running script on daemonset")
802 # exec script on all pods in daemonset
Alexb78191f2021-11-02 16:35:46 -0500803 _result = self.master.execute_cmd_on_daemon_set(
Alex1f90e7b2021-09-03 15:31:28 -0500804 _daemonset,
805 script,
Alexb2129542021-11-23 15:49:42 -0600806 _args=_args,
Alexb78191f2021-11-02 16:35:46 -0500807 is_script=True
Alex1f90e7b2021-09-03 15:31:28 -0500808 )
809
810 # delete daemonset
Alex7b0ee9a2021-09-21 17:16:17 -0500811 # TODO: handle daemonset delete properly
812 # self.master.delete_daemonset(_daemonset)
Alex1f90e7b2021-09-03 15:31:28 -0500813
814 return _result
815
816 def map_networks(self):
Alex3cdb1bd2021-09-10 15:51:11 -0500817 logger_cli.info("-> Mapping runtime networks")
Alex1f90e7b2021-09-03 15:31:28 -0500818 self.map_network(self.RUNTIME)
819
820 def map_network(self, source):
Alex7b0ee9a2021-09-21 17:16:17 -0500821 # if network type is mapped - just return it
822 if source in self.networks:
823 return self.networks[source]
Alex1f90e7b2021-09-03 15:31:28 -0500824 # maps target network using given source
825 _networks = None
Alex1f90e7b2021-09-03 15:31:28 -0500826 if source == self.RUNTIME:
827 logger_cli.info("# Mapping node runtime network data")
Alexb2129542021-11-23 15:49:42 -0600828 _r = self.get_script_output("ifs_data.py", _args="json")
Alex1f90e7b2021-09-03 15:31:28 -0500829 _networks = self._map_runtime_networks(_r)
830 else:
831 raise ConfigException(
832 "Network type not supported in 'Kube': '{}'".format(source)
833 )
834
835 self.networks[source] = _networks
836 return _networks
837
Alex3cdb1bd2021-09-10 15:51:11 -0500838 def create_map(self, skip_keywords=None):
Alex1f90e7b2021-09-03 15:31:28 -0500839 """Create all needed elements for map output
840
841 :return: none
842 """
Alex3cdb1bd2021-09-10 15:51:11 -0500843 # shortcut
Alex1f90e7b2021-09-03 15:31:28 -0500844 _runtime = self.networks[self.RUNTIME]
Alex3cdb1bd2021-09-10 15:51:11 -0500845 # networks to skip
846 _net_skip_list = []
Alex1f90e7b2021-09-03 15:31:28 -0500847 # main networks, target vars
848 _map = {}
849 # No matter of proto, at least one IP will be present for the network
850 # we interested in, since we are to make sure that L3 level
851 # is configured according to reclass model
852 for network in _runtime:
853 # shortcuts
854 _net = str(network)
855 _map[_net] = {}
856 # hostnames
857 names = sorted(_runtime[network].keys())
858 for hostname in names:
859 _notes = []
860 node = hostname.split('.')[0]
861 if not self.master.is_node_available(hostname, log=False):
862 logger_cli.info(
863 " {0:8} {1}".format(node, "node not available")
864 )
865 # add non-responsive node erorr
866 self.errors.add_error(
867 self.errors.NET_NODE_NON_RESPONSIVE,
868 host=hostname
869 )
870 _notes.append(
871 self.errors.get_error_type_text(
872 self.errors.NET_NODE_NON_RESPONSIVE
873 )
874 )
875 continue
876 # lookup interface name on node using network CIDR
877 _if_name = _runtime[network][hostname][0]["name"]
878 _raw = self.interfaces[hostname][_if_name]['runtime']
879 _if_name_suffix = ""
880 _a = _runtime[network][hostname]
881 for _host in _a:
882 for _if in _host['ifs']:
883 _ip_str = str(_if.exploded)
Alex3cdb1bd2021-09-10 15:51:11 -0500884 # Make sure we print VIP properly
885 if _host['vip'] == _ip_str:
886 _if_name = " "*7
887 _if_name_suffix = ""
888 _ip_str += " VIP"
Alex1f90e7b2021-09-03 15:31:28 -0500889
890 # Save all data
891 _values = {
892 "interface": _if_name,
893 "interface_note": _if_name_suffix,
894 "interface_map": "\n".join(_host['lines']),
895 "interface_matrix": _host['matrix'],
896 "ip_address": _ip_str,
897 "rt_mtu": _host['mtu'],
898 "status": _host['state'],
Alex3cdb1bd2021-09-10 15:51:11 -0500899 "type": _host['type'],
Alex1f90e7b2021-09-03 15:31:28 -0500900 "raw_data": _raw,
901 }
902 if node in _map[_net]:
903 # add if to host
904 _map[_net][node].append(_values)
905 else:
906 _map[_net][node] = [_values]
907 _notes = []
Alex3cdb1bd2021-09-10 15:51:11 -0500908 # process skips: if key substring found in interface name
909 # then skip the whole network.
910 if any([True for _w in skip_keywords if _w in _if_name]):
911 _net_skip_list.append(_net)
Alex1f90e7b2021-09-03 15:31:28 -0500912
Alex3cdb1bd2021-09-10 15:51:11 -0500913 # remove skipped networks from list
914 _net_skip_list = list(set(_net_skip_list))
915 for _net in _net_skip_list:
916 _map.pop(_net)
Alex1f90e7b2021-09-03 15:31:28 -0500917 # save map
918 self.map = _map
919 return
920
921 def print_map(self):
922 """
923 Create text report for CLI
924
925 :return: none
926 """
927 logger_cli.info("# Networks")
928 logger_cli.info(
Alex3cdb1bd2021-09-10 15:51:11 -0500929 " {0:47} {1:12} {2:25} {3:5} {4:4}".format(
Alex1f90e7b2021-09-03 15:31:28 -0500930 "Host",
931 "IF",
932 "IP",
933 "MTU",
934 "State"
935 )
936 )
937 for network in self.map.keys():
938 logger_cli.info("-> {}".format(network))
939 for hostname in self.map[network].keys():
940 node = hostname.split('.')[0]
941 _n = self.map[network][hostname]
942 for _i in _n:
943 # Host IF IP Proto MTU State Gate Def.Gate
Alex3cdb1bd2021-09-10 15:51:11 -0500944 _text = "{:10} {:2} {:25} {:5} {:4}".format(
Alex1f90e7b2021-09-03 15:31:28 -0500945 _i['interface'],
946 _i['interface_note'],
947 _i['ip_address'],
948 _i['rt_mtu'],
949 _i['status']
950 )
951 logger_cli.info(
Alex3cdb1bd2021-09-10 15:51:11 -0500952 " {0:47} {1}".format(
Alex1f90e7b2021-09-03 15:31:28 -0500953 node,
954 _text
955 )
956 )
957 return