forked from NSO-developer/netsim-wrapper
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnetsim.py
More file actions
139 lines (114 loc) · 4.39 KB
/
Copy pathnetsim.py
File metadata and controls
139 lines (114 loc) · 4.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
from re import compile
from typing import Any
from logging import INFO
from .common.utils import Utils
class Netsim(Utils):
name = 'ncs-netsim'
command = ['ncs-netsim']
options = []
netsim_dir = 'netsim'
help = None
def __init__(self) -> None:
super(Netsim, self).__init__()
self.help()
self.options()
def ncs_netsim(self, cmd, print_result=True, throw_err=True) -> Any:
try:
output = self.run(cmd=self.command+cmd, error=throw_err)
if not output:
raise ValueError("something went wrong, try netsim-wrapper --help")
except ValueError as e:
if throw_err:
self.log.error(e)
self.exit
raise ValueError(e)
if print_result:
print(output.rsplit('\n'))
return output
def help(self):
if self.help:
return
try:
self.help = self.run(self.command + ['--help'])
except ValueError as e:
self.log.error(e)
self.exit
except FileNotFoundError as e:
self.log.error('ncs-netsim command not found. please source ncsrc file')
self.exit
def options(self):
if len(self.netsim_options):
return self.options
rgx_cmd = compile(r'^\s+([a-z-]+)')
rgx_opt = compile(r'^\s+\[(\S+)\s+\|\s+([a-z-]+).*?\]\s+([a-z]+)')
for line in self.help.split('\n'):
res = rgx_cmd.match(line)
if res:
self.options += list(res.groups())
res = rgx_opt.match(line)
if res:
self.options += list(res.groups())
self.options += ['cli', 'cli-c', 'cli-i', '--dir']
class Netsim(Utils):
name = 'ncs-netsim'
command = ['ncs-netsim']
netsim_options = []
netsim_dir = 'netsim'
_instance = None
_ncs_netsim_help = None
__stdout = subprocess.PIPE
__stderr = subprocess.PIPE
_split = '#######'
def __new__(cls, log_level=logging.INFO, log_format=None):
if cls._instance is None:
cls._instance = object.__new__(cls)
return cls._instance
def __init__(self, log_level=logging.INFO, log_format=None, *args, **kwargs):
Utils.__init__(self, log_level, log_format)
@property
def __netsim_devices_created_by(self):
self._netsim_devices_created_by = {}
data = self.run_ncs_netsim__command(['list'], print_output=False).split('\n')
result = list(filter(lambda x: 'netconf' in x, data))
for each in result:
each = each.split('/')
dev_name = each[-1].strip()
if dev_name == each[-2]:
self._netsim_devices_created_by[dev_name] = ['add-device', each[-2]]
else:
self._netsim_devices_created_by[dev_name] = ['add-to-network', each[-2]]
def _netsim_device_mapper(self, data):
_netsim_mapper = collections.OrderedDict()
for each_device in data:
device = each_device.split('=')
if len(device) > 1:
device = device[1].split('\n')[0]
_netsim_mapper[device] = self._netsim_device_keypair_mapper(device, each_device)
return _netsim_mapper
def _netsim_device_keypair_mapper(self, device, data):
_mapper = {}
for each_line in data.split('\n'):
if len(each_line.split('[')) > 1:
key = (each_line.split('[')[0]).strip(' ')
value = each_line.split('=')[1]
_mapper[key] = value
_mapper['created_by'] = self._netsim_devices_created_by.get(device)[0]
_mapper['parent'] = self._netsim_devices_created_by.get(device)[1]
return _mapper
def _dump_netsim_mapper(self, path, netsim_mapper):
fp = open(path, 'w')
fp.write('\n')
index = 0
for device_name, device_dict in netsim_mapper.items():
fp.write('## device {}\n'.format(device_name))
for key, value in device_dict.items():
if key in ['created_by', 'parent']:
continue
fp.write('{}[{}]={}\n'.format(key, index, value))
fp.write('#######\n\n')
index += 1
fp.close()
def read_netsim(self, path):
data = open(path).read().split(self._split)
self.__netsim_devices_created_by
return self._netsim_device_mapper(data)