Debian Codegraph @

binding/python/team/core.py

raw
1 """
2 Copyright (C) 2011-2015 Jiri Pirko <[email protected]>
3
4 This library is free software; you can redistribute it and/or
5 modify it under the terms of the GNU Lesser General Public
6 License as published by the Free Software Foundation; either
7 version 2.1 of the License, or (at your option) any later version.
8
9 This library is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 Lesser General Public License for more details.
13
14 You should have received a copy of the GNU Lesser General Public
15 License along with this library; if not, write to the Free Software
16 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17 """
18
19 __author__ = """
20 [email protected] (Jiri Pirko)
21 """
22
23 import capi
24 import select
25 import struct
26
27 TEAM_ANY_CHANGE = capi.TEAM_ANY_CHANGE
28 TEAM_PORT_CHANGE = capi.TEAM_PORT_CHANGE
29 TEAM_OPTION_CHANGE = capi.TEAM_OPTION_CHANGE
30
31 class TeamError(Exception):
32 pass
33
34 class TeamLibError(TeamError):
35 def __init__(self, msg, err = 0):
36 self._msg = msg
37 self._err = err
38
39 def __str__(self):
40 msg = self._msg
41 if self._err:
42 msg += " Err=%d" % self._err
43 return msg
44
45 class TeamUnknownOptionTypeError(TeamError):
46 pass
47
48 class TeamNetDeviceIndexNameConverter(object):
49 """
50 Class does conversion between various network device identificators.
51 Note both functions have DeviceID as input parameter.
52 That can be either: interface index (int)
53 interface name (str)
54 TeamNetDevice (or inheritor) instance
55 """
56 def __init__(self, th):
57 self._th = th
58
59 def get_ifindex(self, dev_id):
60 """
61 Get interface index.
62 """
63 if isinstance(dev_id, int):
64 return dev_id
65 elif isinstance(dev_id, TeamNetDevice):
66 return dev_id.ifindex
67 elif isinstance(dev_id, str):
68 return capi.team_ifname2ifindex(self._th, dev_id)
69 raise TeamError("Cannot convert to interface index.")
70
71 def dev_ifname(self, dev_id):
72 """
73 Get interface name.
74 """
75 if isinstance(dev_id, str):
76 return dev_id
77 elif isinstance(dev_id, TeamNetDevice):
78 ifindex = dev_id.ifindex
79 elif isinstance(dev_id, int):
80 ifindex = dev_id
81 else:
82 raise TeamError("Cannot convert to interface name.")
83 return capi.team_ifindex2ifname(self._th, ifindex, 32)
84
85 class TeamNetDevice(object):
86 """
87 Class for manipulating generic network device.
88 """
89 def __init__(self, th, ifindex = 0):
90 self._th = th
91 self._conv = TeamNetDeviceIndexNameConverter(th)
92 self.ifindex = ifindex
93
94 def __str__(self):
95 return self.ifname
96
97 @property
98 def ifindex(self):
99 return self._ifindex
100
101 @ifindex.setter
102 def ifindex(self, ifindex):
103 self._ifindex = ifindex
104 self.ifname = self._conv.dev_ifname(ifindex)
105
106 def get_hwaddr(self):
107 err, hwaddr = capi.team_hwaddr_get(self._th, self.ifindex, 6)
108 if err:
109 raise TeamLibError("Failed to get hardware address", err)
110 return ":".join(map(lambda x: "%02X" % x, struct.unpack('BBBBBB', hwaddr)))
111
112 def set_hwaddr(self, hwaddr_str):
113 pack = struct.pack('BBBBBB', *map(lambda x : int(x, 16), hwaddr_str.split(":")))
114 err = capi.team_hwaddr_set(self._th, self.ifindex, pack)
115 if err:
116 raise TeamLibError("Failed to set hardware address", err)
117
118 class TeamPort(TeamNetDevice):
119 """
120 Class stores port data and serves for port modification.
121 """
122 def update(self, lib_port):
123 """
124 Update option by give library structure.
125 """
126 self.speed = capi.team_get_port_speed(lib_port)
127 self.duplex = capi.team_get_port_duplex(lib_port)
128 self.changed = capi.team_is_port_changed(lib_port)
129 self.linkup = capi.team_is_port_link_up(lib_port)
130 self.removed = capi.team_is_port_removed(lib_port)
131
132 class TeamPortListIterator(object):
133 """
134 Iterator class for TeamPortList class for iterating over all listed ports.
135 """
136 def __init__(self, ports):
137 self._ports = ports
138 self._cursor = 0
139
140 def __iter__(self):
141 iter
142
143 def next(self):
144 """ Get next item in dict """
145 if self._cursor == len(self._ports):
146 raise StopIteration
147 else:
148 key = self._ports.keys()[self._cursor]
149 self._cursor += 1
150 return self._ports[key]
151
152 class TeamPortList(object):
153 """
154 Class contains list of ports present on team. Dictionary is used
155 internaly since port interface index is unique.
156 """
157 def __init__(self, th):
158 self._th = th
159 self._conv = TeamNetDeviceIndexNameConverter(th)
160 self._ports = {}
161 self.update()
162
163 def __len__(self):
164 return len(self._ports)
165
166 def __iter__(self):
167 return TeamPortListIterator(self._ports)
168
169 def get_port(self, port_dev_id):
170 """
171 Get port instance identified by DeviceID.
172 """
173 return self._ports[self._conv.get_ifindex(port_dev_id)]
174
175 def update(self):
176 """
177 Fetch fresh data from library and adjust update dictionary and port
178 instances by it.
179 """
180 lib_port_ifindex_list = []
181 lib_port = capi.team_get_next_port(self._th, None)
182 while lib_port:
183 ifindex = capi.team_get_port_ifindex(lib_port)
184 lib_port_ifindex_list.append(ifindex)
185 try:
186 port = self.get_port(ifindex)
187 except KeyError:
188 port = TeamPort(self._th, ifindex)
189 self._ports[ifindex] = port
190 port.update(lib_port)
191 lib_port = capi.team_get_next_port(self._th, lib_port)
192
193 for ifindex in self._ports.keys():
194 if not ifindex in lib_port_ifindex_list:
195 del self._ports[ifindex]
196
197 class TeamOption(object):
198 """
199 Class stores option data and serves for value modification.
200 """
201 def __init__(self, th, name):
202 self._th = th
203 self.name = name
204
205 def _get_option_value(self, lib_option):
206 opt_type = capi.team_get_option_type(lib_option)
207 if opt_type == capi.TEAM_OPTION_TYPE_U32:
208 return capi.team_get_option_value_u32(lib_option)
209 elif opt_type == capi.TEAM_OPTION_TYPE_STRING:
210 return capi.team_get_option_value_string(lib_option)
211 else:
212 raise TeamUnknownOptionTypeError()
213
214 def update(self, lib_option):
215 """
216 Update option by give library structure.
217 """
218 self.value = self._get_option_value(lib_option)
219 self.changed = capi.team_is_option_changed(lib_option)
220
221 def set_value(self, value):
222 """
223 Set option value.
224 """
225 if isinstance(value, int):
226 err = capi.team_set_option_value_by_name_u32(self._th, self.name,
227 value)
228 elif isinstance(value, str):
229 err = capi.team_set_option_value_by_name_string(self._th,
230 self.name,
231 value)
232 else:
233 raise TeamUnknownOptionTypeError()
234 if err:
235 raise TeamLibError("Failed to set option", err)
236
237 class TeamOptionListIterator(object):
238 """
239 Iterator class for TeamOptionList class for iterating over all options.
240 """
241 def __init__(self, options):
242 self._options = options
243 self._cursor = 0
244
245 def __iter__(self):
246 iter
247
248 def next(self):
249 """ Get next item in dict """
250 if self._cursor == len(self._options):
251 raise StopIteration
252 else:
253 key = self._options.keys()[self._cursor]
254 self._cursor += 1
255 return self._options[key]
256
257 class TeamOptionList(object):
258 """
259 Class contains list of options present on team. Dictionary is used
260 internaly since option name is unique.
261 """
262 def __init__(self, th):
263 self._th = th
264 self._options = {}
265 self.update()
266
267 def __len__(self):
268 return len(self._options)
269
270 def __iter__(self):
271 return TeamOptionListIterator(self._options)
272
273 def get_option(self, opt_name):
274 """
275 Get option instance identified by name.
276 """
277 return self._options[opt_name]
278
279 def update(self):
280 """
281 Fetch fresh data from library and adjust update dictionary and option
282 instances by it.
283 """
284 lib_option_name_list = []
285 lib_option = capi.team_get_next_option(self._th, None)
286 while lib_option:
287 opt_name = capi.team_get_option_name(lib_option)
288 lib_option_name_list.append(opt_name)
289 try:
290 option = self.get_option(opt_name)
291 except KeyError:
292 option = TeamOption(self._th, opt_name)
293 self._options[opt_name] = option
294 try:
295 option.update(lib_option)
296 except TeamUnknownOptionTypeError:
297 del self._options[opt_name]
298 lib_option = capi.team_get_next_option(self._th, lib_option)
299
300 for opt_name in self._options.keys():
301 if not opt_name in lib_option_name_list:
302 del self._options[opt_name]
303
304 class TeamChangeHandler(object):
305 def __init__(self, func, func_priv, type_mask):
306 self._func = func
307 self._func_priv = func_priv
308 self._type_mask = type_mask
309
310 def call(self, curr_type_mask):
311 if self._type_mask & curr_type_mask:
312 return self._func(self._func_priv)
313 else:
314 return 0
315
316 class TeamChangeHandlerList(object):
317 def __init__(self):
318 self._list = []
319
320 def add(self, handler):
321 if handler in self._list:
322 raise TeamError("Failed to register change handler. Handler is already registered.")
323 self._list.append(handler)
324
325 def remove(self, handler):
326 if not handler in self._list:
327 raise TeamError("Failed to unregister change handler. Handler is not registered.")
328 self._list.remove(handler)
329
330 def call(self, type_mask):
331 for handler in self._list:
332 ret = handler.call(type_mask)
333 if ret != 0:
334 return ret
335
336
337 class Team(TeamNetDevice):
338 """
339 Class representing one team device instance.
340 Paramaters passed to constructor allows:
341 create == True ... Create new team device if it does not already exist.
342 recreate == True ... Same as create but in case device exists already,
343 it's removed first.
344 destroy == True ... Remove team device in close function.
345 """
346 def __init__(self, teamdev, create = False, recreate = False, destroy = False):
347 th = capi.team_alloc()
348 if not th:
349 raise TeamLibError("Failed to allocate team handle.")
350
351 super(Team, self).__init__(th)
352
353 if isinstance(teamdev, str):
354 err = 0
355 if recreate:
356 err = capi.team_recreate(th, teamdev)
357 elif create:
358 err = capi.team_create(th, teamdev)
359 if err:
360 raise TeamLibError("Failed to create team.", err)
361
362 ifindex = self._conv.get_ifindex(teamdev) if teamdev else 0
363 err = capi.team_init(th, ifindex)
364 if err:
365 raise TeamLibError("Failed to init team.", err)
366
367 self.ifindex = ifindex
368 self._destroy = destroy
369 self._change_handler_list = TeamChangeHandlerList()
370 self._port_list = TeamPortList(th)
371 self._option_list = TeamOptionList(th)
372
373 self._change_handler = capi.team_change_handler(self._change_handler_func,
374 TEAM_ANY_CHANGE)
375 capi.py_team_change_handler_register(self._th, self._change_handler, None)
376
377
378 def close(self):
379 """
380 Do class cleanup
381 """
382 if self._destroy:
383 err = capi.team_destroy(self._th)
384 if err:
385 raise TeamLibError("Failed to destroy team.", err)
386
387 capi.py_team_change_handler_unregister(self._th,
388 self._change_handler, None)
389 capi.team_free(self._th)
390
391 def kill_loop(self):
392 self._kill_loop = True
393
394 def loop_forever(self):
395 self._kill_loop = False
396 fd = capi.team_get_event_fd(self._th)
397 while True:
398 try:
399 ret = select.select([fd], [], [])
400 if fd in ret[0]:
401 capi.team_handle_events(self._th)
402 except KeyboardInterrupt:
403 return
404 except select.error as e:
405 if e[0] == 4:
406 if self._kill_loop:
407 return
408 except:
409 raise
410
411 def check_events(self):
412 capi.team_check_events(self._th)
413
414 def _change_handler_func(self, func_priv, type_mask):
415 if type_mask & TEAM_PORT_CHANGE:
416 self._port_list.update()
417 if type_mask & TEAM_OPTION_CHANGE:
418 self._option_list.update()
419 self._change_handler_list.call(type_mask)
420
421 def change_handler_register(self, change_handler):
422 self._change_handler_list.add(change_handler)
423
424 def change_handler_unregister(self, change_handler):
425 self._change_handler_list.remove(change_handler)
426
427 def get_mode_name(self):
428 err, name = capi.team_get_mode_name(self._th)
429 if err:
430 raise TeamLibError("Failed to get mode name.", err)
431 return name
432
433 def set_mode_name(self, name):
434 err = capi.team_set_mode_name(self._th, name)
435 if err:
436 raise TeamLibError("Failed to set mode name.", err)
437
438 def get_active_port(self):
439 err, port_ifindex = capi.team_get_active_port(self._th)
440 if err:
441 raise TeamLibError("Failed to get active port.", err)
442 return self.get_port(port_ifindex)
443
444 def set_active_port(self, dev_port_id):
445 err = capi.team_set_active_port(self._th,
446 self._conv.get_ifindex(dev_port_id))
447 if err:
448 raise TeamLibError("Failed to set active port.", err)
449
450 def port_list(self):
451 return self._port_list
452
453 def get_port(self, port_dev_id):
454 return self._port_list.get_port(port_dev_id)
455
456 def port_add(self, port_dev_id):
457 err = capi.team_port_add(self._th,
458 self._conv.get_ifindex(port_dev_id))
459 if err:
460 raise TeamLibError("Failed to add port.", err)
461
462 def port_remove(self, port_dev_id):
463 err = capi.team_port_remove(self._th,
464 self._conv.get_ifindex(port_dev_id))
465 if err:
466 raise TeamLibError("Failed to remove port.", err)
467
468 def option_list(self):
469 return self._option_list
470
471 def get_option(self, opt_name):
472 return self._option_list.get_option(opt_name)