blob: 8817ae2f747cfed4a4cc44aeb5cd4800f018123f [file] [log] [blame]
Brad Bishopeded8f32017-11-01 11:22:38 -04001# Contributors Listed Below - COPYRIGHT 2017
Brad Bishop63f59a72016-07-25 12:05:57 -04002# [+] International Business Machines Corp.
3#
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
14# implied. See the License for the specific language governing
15# permissions and limitations under the License.
16
17import dbus
18import dbus.service
19import dbus.exceptions
20import dbus.mainloop.glib
21import gobject
22import xml.etree.ElementTree as ET
23import obmc.utils.pathtree
Brad Bishop63f59a72016-07-25 12:05:57 -040024import obmc.mapper
25import obmc.dbuslib.bindings
26import obmc.dbuslib.enums
Brad Bishop99b8bc82017-07-29 21:39:52 -040027import sys
28import traceback
Brad Bishop63f59a72016-07-25 12:05:57 -040029
30
Brad Bishop2e0436c2016-09-19 18:02:19 -040031class MapperBusyException(dbus.exceptions.DBusException):
32 _dbus_error_name = 'org.freedesktop.DBus.Error.ObjectPathInUse'
33
34 def __init__(self):
35 super(MapperBusyException, self).__init__(
36 'busy processing bus traffic')
37
38
Brad Bishop63f59a72016-07-25 12:05:57 -040039class MapperNotFoundException(dbus.exceptions.DBusException):
40 _dbus_error_name = obmc.mapper.MAPPER_NOT_FOUND
41
42 def __init__(self, path):
43 super(MapperNotFoundException, self).__init__(
44 "path or object not found: %s" % path)
45
46
Brad Bishop520473f2016-09-19 21:46:36 -040047def find_dbus_interfaces(conn, service, path, callback, error_callback, **kw):
Brad Bishopbd8aa052016-09-19 09:30:06 -040048 iface_match = kw.pop('iface_match', bool)
Brad Bishop6a0320b2016-09-19 11:03:06 -040049 subtree_match = kw.pop('subtree_match', bool)
Brad Bishopbd8aa052016-09-19 09:30:06 -040050
Brad Bishop63f59a72016-07-25 12:05:57 -040051 class _FindInterfaces(object):
52 def __init__(self):
53 self.results = {}
Brad Bishop520473f2016-09-19 21:46:36 -040054 self.introspect_pending = []
55 self.gmo_pending = []
56 self.assoc_pending = []
Brad Bishop63f59a72016-07-25 12:05:57 -040057
58 @staticmethod
59 def _to_path(elements):
60 return '/' + '/'.join(elements)
61
62 @staticmethod
63 def _to_path_elements(path):
64 return filter(bool, path.split('/'))
65
66 def __call__(self, path):
Brad Bishop520473f2016-09-19 21:46:36 -040067 try:
68 self._find_interfaces(path)
69 except Exception, e:
70 error_callback(service, path, e)
Brad Bishop63f59a72016-07-25 12:05:57 -040071
72 @staticmethod
73 def _match(iface):
74 return iface == dbus.BUS_DAEMON_IFACE + '.ObjectManager' \
Brad Bishopbd8aa052016-09-19 09:30:06 -040075 or iface_match(iface)
Brad Bishop63f59a72016-07-25 12:05:57 -040076
Brad Bishop520473f2016-09-19 21:46:36 -040077 def check_done(self):
78 if any([
79 self.introspect_pending,
80 self.gmo_pending,
81 self.assoc_pending]):
82 return
83
84 callback(service, self.results)
85
86 def _assoc_callback(self, path, associations):
87 try:
88 iface = obmc.dbuslib.enums.OBMC_ASSOCIATIONS_IFACE
89 self.assoc_pending.remove(path)
Gunnar Mills296395c2017-09-06 13:56:43 -050090 self.results[path][iface]['associations'] = associations
Brad Bishop520473f2016-09-19 21:46:36 -040091 except Exception, e:
92 error_callback(service, path, e)
93 return None
94
95 self.check_done()
96
97 def _gmo_callback(self, path, objs):
98 try:
99 self.gmo_pending.remove(path)
100 for k, v in objs.iteritems():
101 self.results[k] = v
102 except Exception, e:
103 error_callback(service, path, e)
104 return None
105
106 self.check_done()
107
108 def _introspect_callback(self, path, data):
109 self.introspect_pending.remove(path)
110 if data is None:
111 self.check_done()
112 return
113
114 try:
115 path_elements = self._to_path_elements(path)
116 root = ET.fromstring(data)
117 ifaces = filter(
118 self._match,
119 [x.attrib.get('name') for x in root.findall('interface')])
120 ifaces = {x: {} for x in ifaces}
121 self.results[path] = ifaces
122
123 if obmc.dbuslib.enums.OBMC_ASSOCIATIONS_IFACE in ifaces:
124 obj = conn.get_object(service, path, introspect=False)
125 iface = dbus.Interface(obj, dbus.PROPERTIES_IFACE)
126 self.assoc_pending.append(path)
127 iface.Get.call_async(
128 obmc.dbuslib.enums.OBMC_ASSOCIATIONS_IFACE,
129 'associations',
130 reply_handler=lambda x: self._assoc_callback(
131 path, x),
132 error_handler=lambda e: error_callback(
133 service, path, e))
134
135 if dbus.BUS_DAEMON_IFACE + '.ObjectManager' in ifaces:
136 obj = conn.get_object(service, path, introspect=False)
137 iface = dbus.Interface(
138 obj, dbus.BUS_DAEMON_IFACE + '.ObjectManager')
139 self.gmo_pending.append(path)
140 iface.GetManagedObjects.call_async(
141 reply_handler=lambda x: self._gmo_callback(
142 path, x),
143 error_handler=lambda e: error_callback(
144 service, path, e))
145 else:
146 children = filter(
147 bool,
148 [x.attrib.get('name') for x in root.findall('node')])
149 children = [
150 self._to_path(
151 path_elements + self._to_path_elements(x))
152 for x in sorted(children)]
153 for child in filter(subtree_match, children):
154 if child not in self.results:
155 self._find_interfaces(child)
156 except Exception, e:
157 error_callback(service, path, e)
158 return None
159
160 self.check_done()
161
Brad Bishop63f59a72016-07-25 12:05:57 -0400162 def _find_interfaces(self, path):
163 path_elements = self._to_path_elements(path)
164 path = self._to_path(path_elements)
Brad Bishop520473f2016-09-19 21:46:36 -0400165 obj = conn.get_object(service, path, introspect=False)
166 iface = dbus.Interface(obj, dbus.INTROSPECTABLE_IFACE)
167 self.introspect_pending.append(path)
168 iface.Introspect.call_async(
169 reply_handler=lambda x: self._introspect_callback(path, x),
170 error_handler=lambda x: error_callback(service, path, x))
Brad Bishop63f59a72016-07-25 12:05:57 -0400171
172 return _FindInterfaces()(path)
173
174
175class Association(dbus.service.Object):
176 def __init__(self, bus, path, endpoints):
Brad Bishop70dd5952016-09-08 22:33:33 -0400177 super(Association, self).__init__(conn=bus, object_path=path)
Brad Bishop63f59a72016-07-25 12:05:57 -0400178 self.endpoints = endpoints
179
180 def __getattr__(self, name):
181 if name == 'properties':
182 return {
183 obmc.dbuslib.enums.OBMC_ASSOC_IFACE: {
184 'endpoints': self.endpoints}}
185 return super(Association, self).__getattr__(name)
186
187 def emit_signal(self, old):
188 if old != self.endpoints:
189 self.PropertiesChanged(
190 obmc.dbuslib.enums.OBMC_ASSOC_IFACE,
191 {'endpoints': self.endpoints}, ['endpoints'])
192
193 def append(self, endpoints):
194 old = self.endpoints
195 self.endpoints = list(set(endpoints).union(self.endpoints))
196 self.emit_signal(old)
197
198 def remove(self, endpoints):
199 old = self.endpoints
200 self.endpoints = list(set(self.endpoints).difference(endpoints))
201 self.emit_signal(old)
202
203 @dbus.service.method(dbus.PROPERTIES_IFACE, 'ss', 'as')
204 def Get(self, interface_name, property_name):
205 if property_name != 'endpoints':
206 raise dbus.exceptions.DBusException(name=DBUS_UNKNOWN_PROPERTY)
207 return self.GetAll(interface_name)[property_name]
208
209 @dbus.service.method(dbus.PROPERTIES_IFACE, 's', 'a{sas}')
210 def GetAll(self, interface_name):
211 if interface_name != obmc.dbuslib.enums.OBMC_ASSOC_IFACE:
212 raise dbus.exceptions.DBusException(DBUS_UNKNOWN_INTERFACE)
213 return {'endpoints': self.endpoints}
214
215 @dbus.service.signal(
216 dbus.PROPERTIES_IFACE, signature='sa{sas}as')
217 def PropertiesChanged(
218 self, interface_name, changed_properties, invalidated_properties):
219 pass
220
221
222class Manager(obmc.dbuslib.bindings.DbusObjectManager):
223 def __init__(self, bus, path):
Brad Bishop70dd5952016-09-08 22:33:33 -0400224 super(Manager, self).__init__(conn=bus, object_path=path)
Brad Bishop63f59a72016-07-25 12:05:57 -0400225
226
227class ObjectMapper(dbus.service.Object):
Brad Bishopcb2e1b32017-07-09 20:11:35 -0400228 def __init__(
229 self, bus, path, namespaces, interface_namespaces,
230 blacklist, interface_blacklist):
Brad Bishop63f59a72016-07-25 12:05:57 -0400231 super(ObjectMapper, self).__init__(bus, path)
232 self.cache = obmc.utils.pathtree.PathTree()
233 self.bus = bus
Brad Bishop63f59a72016-07-25 12:05:57 -0400234 self.service = None
235 self.index = {}
236 self.manager = Manager(bus, obmc.dbuslib.bindings.OBJ_PREFIX)
237 self.unique = bus.get_unique_name()
238 self.bus_map = {}
Brad Bishop2e0436c2016-09-19 18:02:19 -0400239 self.defer_signals = {}
Brad Bishop5d4890c2016-09-19 11:28:47 -0400240 self.bus_map[self.unique] = obmc.mapper.MAPPER_NAME
Brad Bishopcb2e1b32017-07-09 20:11:35 -0400241 self.namespaces = namespaces
242 self.interface_namespaces = interface_namespaces
243 self.blacklist = blacklist
244 self.blacklist.append(obmc.mapper.MAPPER_PATH)
245 self.interface_blacklist = interface_blacklist
Brad Bishop63f59a72016-07-25 12:05:57 -0400246
Brad Bishop5d4890c2016-09-19 11:28:47 -0400247 # add my object mananger instance
248 self.add_new_objmgr(obmc.dbuslib.bindings.OBJ_PREFIX, self.unique)
249
Brad Bishop63f59a72016-07-25 12:05:57 -0400250 self.bus.add_signal_receiver(
251 self.bus_handler,
252 dbus_interface=dbus.BUS_DAEMON_IFACE,
253 signal_name='NameOwnerChanged')
254 self.bus.add_signal_receiver(
255 self.interfaces_added_handler,
256 dbus_interface=dbus.BUS_DAEMON_IFACE + '.ObjectManager',
257 signal_name='InterfacesAdded',
258 sender_keyword='sender',
259 path_keyword='sender_path')
260 self.bus.add_signal_receiver(
261 self.interfaces_removed_handler,
262 dbus_interface=dbus.BUS_DAEMON_IFACE + '.ObjectManager',
263 signal_name='InterfacesRemoved',
264 sender_keyword='sender',
265 path_keyword='sender_path')
266 self.bus.add_signal_receiver(
267 self.properties_changed_handler,
268 dbus_interface=dbus.PROPERTIES_IFACE,
269 signal_name='PropertiesChanged',
270 path_keyword='path',
271 sender_keyword='sender')
272
Brad Bishop5d4890c2016-09-19 11:28:47 -0400273 print "ObjectMapper startup complete. Discovery in progress..."
274 self.discover()
Brad Bishop520473f2016-09-19 21:46:36 -0400275 gobject.idle_add(self.claim_name)
Brad Bishop5d4890c2016-09-19 11:28:47 -0400276
Brad Bishop520473f2016-09-19 21:46:36 -0400277 def claim_name(self):
278 if len(self.defer_signals):
279 return True
Brad Bishop5d4890c2016-09-19 11:28:47 -0400280 print "ObjectMapper discovery complete"
281 self.service = dbus.service.BusName(
282 obmc.mapper.MAPPER_NAME, self.bus)
Brad Bishop55b89cd2016-09-19 23:02:48 -0400283 self.manager.unmask_signals()
Brad Bishop520473f2016-09-19 21:46:36 -0400284 return False
Brad Bishop63f59a72016-07-25 12:05:57 -0400285
Brad Bishop2e0436c2016-09-19 18:02:19 -0400286 def discovery_callback(self, owner, items):
287 if owner in self.defer_signals:
288 self.add_items(owner, items)
289 pending = self.defer_signals[owner]
290 del self.defer_signals[owner]
291
292 for x in pending:
293 x()
Brad Bishop829181d2017-02-24 09:49:14 -0500294 self.IntrospectionComplete(owner)
Brad Bishop2e0436c2016-09-19 18:02:19 -0400295
296 def discovery_error(self, owner, path, e):
Brad Bishop99b8bc82017-07-29 21:39:52 -0400297 '''Log a message and remove all traces of the service
298 we were attempting to introspect.'''
299
Brad Bishop2e0436c2016-09-19 18:02:19 -0400300 if owner in self.defer_signals:
Brad Bishop99b8bc82017-07-29 21:39:52 -0400301 sys.stderr.write(
302 '{} discovery failure on {}\n'.format(
303 self.bus_map.get(owner, owner),
304 path))
305 traceback.print_exception(*sys.exc_info())
306 del self.defer_signals[owner]
307 del self.bus_map[owner]
Brad Bishop2e0436c2016-09-19 18:02:19 -0400308
Brad Bishop63f59a72016-07-25 12:05:57 -0400309 def cache_get(self, path):
310 cache_entry = self.cache.get(path, {})
311 if cache_entry is None:
312 # hide path elements without any interfaces
313 cache_entry = {}
314 return cache_entry
315
316 def add_new_objmgr(self, path, owner):
317 # We don't get a signal for the ObjectManager
318 # interface itself, so if we see a signal from
319 # make sure its in our cache, and add it if not.
320 cache_entry = self.cache_get(path)
321 old = self.interfaces_get(cache_entry, owner)
322 new = list(set(old).union([dbus.BUS_DAEMON_IFACE + '.ObjectManager']))
323 self.update_interfaces(path, owner, old, new)
324
Brad Bishop2e0436c2016-09-19 18:02:19 -0400325 def defer_signal(self, owner, callback):
326 self.defer_signals.setdefault(owner, []).append(callback)
327
Brad Bishop63f59a72016-07-25 12:05:57 -0400328 def interfaces_added_handler(self, path, iprops, **kw):
329 path = str(path)
330 owner = str(kw['sender'])
331 interfaces = self.get_signal_interfaces(owner, iprops.iterkeys())
Brad Bishop2e0436c2016-09-19 18:02:19 -0400332 if not interfaces:
333 return
334
335 if owner not in self.defer_signals:
Brad Bishop63f59a72016-07-25 12:05:57 -0400336 self.add_new_objmgr(str(kw['sender_path']), owner)
337 cache_entry = self.cache_get(path)
338 old = self.interfaces_get(cache_entry, owner)
339 new = list(set(interfaces).union(old))
Brad Bishopa6235962017-06-07 23:56:54 -0400340 new = {x: iprops.get(x, {}) for x in new}
Brad Bishop63f59a72016-07-25 12:05:57 -0400341 self.update_interfaces(path, owner, old, new)
Brad Bishop2e0436c2016-09-19 18:02:19 -0400342 else:
343 self.defer_signal(
344 owner,
345 lambda: self.interfaces_added_handler(
346 path, iprops, **kw))
Brad Bishop63f59a72016-07-25 12:05:57 -0400347
348 def interfaces_removed_handler(self, path, interfaces, **kw):
349 path = str(path)
350 owner = str(kw['sender'])
351 interfaces = self.get_signal_interfaces(owner, interfaces)
Brad Bishop2e0436c2016-09-19 18:02:19 -0400352 if not interfaces:
353 return
354
355 if owner not in self.defer_signals:
Brad Bishop63f59a72016-07-25 12:05:57 -0400356 self.add_new_objmgr(str(kw['sender_path']), owner)
357 cache_entry = self.cache_get(path)
358 old = self.interfaces_get(cache_entry, owner)
359 new = list(set(old).difference(interfaces))
360 self.update_interfaces(path, owner, old, new)
Brad Bishop2e0436c2016-09-19 18:02:19 -0400361 else:
362 self.defer_signal(
363 owner,
364 lambda: self.interfaces_removed_handler(
365 path, interfaces, **kw))
Brad Bishop63f59a72016-07-25 12:05:57 -0400366
367 def properties_changed_handler(self, interface, new, old, **kw):
368 owner = str(kw['sender'])
369 path = str(kw['path'])
370 interfaces = self.get_signal_interfaces(owner, [interface])
371 if not self.is_association(interfaces):
372 return
373 associations = new.get('associations', None)
374 if associations is None:
375 return
376
Brad Bishop2e0436c2016-09-19 18:02:19 -0400377 if owner not in self.defer_signals:
378 associations = [
379 (str(x), str(y), str(z)) for x, y, z in associations]
380 self.update_associations(
381 path, owner,
382 self.index_get_associations(path, [owner]),
383 associations)
384 else:
385 self.defer_signal(
386 owner,
387 lambda: self.properties_changed_handler(
388 interface, new, old, **kw))
Brad Bishop63f59a72016-07-25 12:05:57 -0400389
390 def process_new_owner(self, owned_name, owner):
391 # unique name
392 try:
393 return self.discover([(owned_name, owner)])
394 except dbus.exceptions.DBusException, e:
395 if obmc.dbuslib.enums.DBUS_UNKNOWN_SERVICE \
396 not in e.get_dbus_name():
397 raise
398
399 def process_old_owner(self, owned_name, owner):
400 if owner in self.bus_map:
401 del self.bus_map[owner]
402
403 for path, item in self.cache.dataitems():
404 old = self.interfaces_get(item, owner)
405 # remove all interfaces for this service
406 self.update_interfaces(
407 path, owner, old=old, new=[])
408
409 def bus_handler(self, owned_name, old, new):
410 valid = False
411 if not obmc.dbuslib.bindings.is_unique(owned_name):
412 valid = self.valid_signal(owned_name)
413
414 if valid and new:
415 self.process_new_owner(owned_name, new)
416 if valid and old:
Brad Bishop2e0436c2016-09-19 18:02:19 -0400417 # discard any unhandled signals
418 # or in progress discovery
419 if old in self.defer_signals:
420 del self.defer_signals[old]
421
Brad Bishop63f59a72016-07-25 12:05:57 -0400422 self.process_old_owner(owned_name, old)
423
424 def update_interfaces(self, path, owner, old, new):
425 # __xx -> intf list
426 # xx -> intf dict
427 if isinstance(old, dict):
428 __old = old.keys()
429 else:
430 __old = old
431 old = {x: {} for x in old}
432 if isinstance(new, dict):
433 __new = new.keys()
434 else:
435 __new = new
436 new = {x: {} for x in new}
437
438 cache_entry = self.cache.setdefault(path, {})
439 created = [] if self.has_interfaces(cache_entry) else [path]
440 added = list(set(__new).difference(__old))
441 removed = list(set(__old).difference(__new))
442 self.interfaces_append(cache_entry, owner, added)
443 self.interfaces_remove(cache_entry, owner, removed, path)
444 destroyed = [] if self.has_interfaces(cache_entry) else [path]
445
446 # react to anything that requires association updates
447 new_assoc = []
448 old_assoc = []
449 if self.is_association(added):
Brad Bishop926b35d2016-09-19 14:20:04 -0400450 iface = obmc.dbuslib.enums.OBMC_ASSOCIATIONS_IFACE
451 new_assoc = new[iface]['associations']
Brad Bishop63f59a72016-07-25 12:05:57 -0400452 if self.is_association(removed):
453 old_assoc = self.index_get_associations(path, [owner])
454 self.update_associations(
455 path, owner, old_assoc, new_assoc, created, destroyed)
456
457 def add_items(self, owner, bus_items):
458 for path, items in bus_items.iteritems():
459 self.update_interfaces(path, str(owner), old=[], new=items)
460
Brad Bishopcb2e1b32017-07-09 20:11:35 -0400461 def path_match(self, path):
462 match = False
463
464 if not any([x for x in self.blacklist if x in path]):
465 # not blacklisted
466
467 if any([x for x in self.namespaces if x in path]):
468 # a watched namespace contains the path
469 match = True
470 elif any([path for x in self.namespaces if path in x]):
471 # the path contains a watched namespace
472 match = True
473
474 return match
475
476 def interface_match(self, interface):
477 match = True
478
479 if any([x for x in self.interface_blacklist if x in interface]):
480 # not blacklisted
481 match = False
482 elif not any([x for x in self.interface_namespaces if x in interface]):
483 # the interface contains a watched interface namespace
484 match = False
485
486 return match
487
Brad Bishop63f59a72016-07-25 12:05:57 -0400488 def discover(self, owners=[]):
Brad Bishop062403d2017-07-29 22:43:40 -0400489 def get_owner(name):
490 try:
491 return (name, self.bus.get_name_owner(name))
492 except:
493 traceback.print_exception(*sys.exc_info())
494
Brad Bishop63f59a72016-07-25 12:05:57 -0400495 if not owners:
Brad Bishopd0b8e392016-09-19 11:24:45 -0400496 owned_names = filter(
497 lambda x: not obmc.dbuslib.bindings.is_unique(x),
498 self.bus.list_names())
Brad Bishop062403d2017-07-29 22:43:40 -0400499 owners = filter(bool, [get_owner(name) for name in owned_names])
Brad Bishop63f59a72016-07-25 12:05:57 -0400500 for owned_name, o in owners:
Brad Bishopaeac98b2017-07-29 22:56:48 -0400501 if not self.valid_signal(owned_name):
502 continue
Brad Bishop63f59a72016-07-25 12:05:57 -0400503 self.bus_map[o] = owned_name
Brad Bishop520473f2016-09-19 21:46:36 -0400504 self.defer_signals[o] = []
505 find_dbus_interfaces(
506 self.bus, o, '/',
507 self.discovery_callback,
508 self.discovery_error,
Brad Bishopcb2e1b32017-07-09 20:11:35 -0400509 subtree_match=self.path_match,
510 iface_match=self.interface_match)
Brad Bishop63f59a72016-07-25 12:05:57 -0400511
Brad Bishop63f59a72016-07-25 12:05:57 -0400512 def valid_signal(self, name):
Brad Bishop63f59a72016-07-25 12:05:57 -0400513 if obmc.dbuslib.bindings.is_unique(name):
514 name = self.bus_map.get(name)
515
Brad Bishopaeac98b2017-07-29 22:56:48 -0400516 return name is not None and name != obmc.mapper.MAPPER_NAME
Brad Bishop63f59a72016-07-25 12:05:57 -0400517
518 def get_signal_interfaces(self, owner, interfaces):
519 filtered = []
520 if self.valid_signal(owner):
Brad Bishopcb2e1b32017-07-09 20:11:35 -0400521 filtered = [str(x) for x in interfaces if self.interface_match(x)]
Brad Bishop63f59a72016-07-25 12:05:57 -0400522
523 return filtered
524
525 @staticmethod
526 def interfaces_get(item, owner, default=[]):
527 return item.get(owner, default)
528
529 @staticmethod
530 def interfaces_append(item, owner, append):
531 interfaces = item.setdefault(owner, [])
532 item[owner] = list(set(append).union(interfaces))
533
534 def interfaces_remove(self, item, owner, remove, path):
535 interfaces = item.get(owner, [])
536 item[owner] = list(set(interfaces).difference(remove))
537
538 if not item[owner]:
539 # remove the owner if there aren't any interfaces left
540 del item[owner]
541
542 if item:
543 # other owners remain
544 return
545
546 if self.cache.get_children(path):
547 # there are still references to this path
548 # from objects further down the tree.
549 # mark it for removal if that changes
550 self.cache.demote(path)
551 else:
552 # delete the entire path if everything is gone
553 del self.cache[path]
554
Brad Bishop1c33c222016-11-02 00:08:46 -0400555 @staticmethod
556 def filter_interfaces(item, ifaces):
557 if isinstance(item, dict):
558 # Called with a single object.
559 if not ifaces:
560 return item
561
562 # Remove interfaces from a service that
563 # aren't in a filter.
564 svc_map = lambda svc: (
565 svc[0],
566 list(set(ifaces).intersection(svc[1])))
567
568 # Remove services where no interfaces remain after mapping.
569 svc_filter = lambda svc: svc[1]
570
571 obj_map = lambda o: (
572 tuple(*filter(svc_filter, map(svc_map, [o]))))
573
574 return dict(filter(lambda x: x, map(obj_map, item.iteritems())))
575
576 # Called with a list of path/object tuples.
577 if not ifaces:
578 return dict(item)
579
580 obj_map = lambda x: (
581 x[0],
582 ObjectMapper.filter_interfaces(
583 x[1],
584 ifaces))
585
Brad Bishop94c92a92017-09-11 16:12:07 -0400586 return dict(filter(lambda x: x[1], map(obj_map, iter(item or []))))
Brad Bishop1c33c222016-11-02 00:08:46 -0400587
588 @dbus.service.method(obmc.mapper.MAPPER_IFACE, 'sas', 'a{sas}')
589 def GetObject(self, path, interfaces):
Brad Bishop63f59a72016-07-25 12:05:57 -0400590 o = self.cache_get(path)
591 if not o:
592 raise MapperNotFoundException(path)
Brad Bishop63f59a72016-07-25 12:05:57 -0400593
Brad Bishop1c33c222016-11-02 00:08:46 -0400594 return self.filter_interfaces(o, interfaces)
595
596 @dbus.service.method(obmc.mapper.MAPPER_IFACE, 'sias', 'as')
597 def GetSubTreePaths(self, path, depth, interfaces):
Brad Bishop63f59a72016-07-25 12:05:57 -0400598 try:
Brad Bishop24301972017-06-23 13:40:07 -0400599 return self.filter_interfaces(
600 self.cache.iteritems(path, depth),
601 interfaces)
Brad Bishop63f59a72016-07-25 12:05:57 -0400602 except KeyError:
603 raise MapperNotFoundException(path)
604
Brad Bishop1c33c222016-11-02 00:08:46 -0400605 @dbus.service.method(obmc.mapper.MAPPER_IFACE, 'sias', 'a{sa{sas}}')
606 def GetSubTree(self, path, depth, interfaces):
Brad Bishop63f59a72016-07-25 12:05:57 -0400607 try:
Brad Bishop1c33c222016-11-02 00:08:46 -0400608 return self.filter_interfaces(
609 self.cache.dataitems(path, depth),
610 interfaces)
Brad Bishop63f59a72016-07-25 12:05:57 -0400611 except KeyError:
612 raise MapperNotFoundException(path)
613
614 @staticmethod
615 def has_interfaces(item):
616 for owner in item.iterkeys():
617 if ObjectMapper.interfaces_get(item, owner):
618 return True
619 return False
620
621 @staticmethod
622 def is_association(interfaces):
623 return obmc.dbuslib.enums.OBMC_ASSOCIATIONS_IFACE in interfaces
624
625 def index_get(self, index, path, owners):
626 items = []
627 item = self.index.get(index, {})
628 item = item.get(path, {})
629 for o in owners:
630 items.extend(item.get(o, []))
631 return items
632
633 def index_append(self, index, path, owner, assoc):
634 item = self.index.setdefault(index, {})
635 item = item.setdefault(path, {})
636 item = item.setdefault(owner, [])
637 item.append(assoc)
638
639 def index_remove(self, index, path, owner, assoc):
640 index = self.index.get(index, {})
641 owners = index.get(path, {})
642 items = owners.get(owner, [])
643 if assoc in items:
644 items.remove(assoc)
645 if not items:
646 del owners[owner]
647 if not owners:
648 del index[path]
649
Brad Bishop63f59a72016-07-25 12:05:57 -0400650 def index_get_associations(self, path, owners=[], direction='forward'):
651 forward = 'forward' if direction == 'forward' else 'reverse'
652 reverse = 'reverse' if direction == 'forward' else 'forward'
653
654 associations = []
655 if not owners:
656 index = self.index.get(forward, {})
657 owners = index.get(path, {}).keys()
658
659 # f: forward
660 # r: reverse
661 for rassoc in self.index_get(forward, path, owners):
662 elements = rassoc.split('/')
663 rtype = ''.join(elements[-1:])
664 fendpoint = '/'.join(elements[:-1])
665 for fassoc in self.index_get(reverse, fendpoint, owners):
666 elements = fassoc.split('/')
667 ftype = ''.join(elements[-1:])
668 rendpoint = '/'.join(elements[:-1])
669 if rendpoint != path:
670 continue
671 associations.append((ftype, rtype, fendpoint))
672
673 return associations
674
675 def update_association(self, path, removed, added):
676 iface = obmc.dbuslib.enums.OBMC_ASSOC_IFACE
677 create = [] if self.manager.get(path, False) else [iface]
678
679 if added and create:
680 self.manager.add(
681 path, Association(self.bus, path, added))
682 elif added:
683 self.manager.get(path).append(added)
684
685 obj = self.manager.get(path, None)
686 if obj and removed:
687 obj.remove(removed)
688
689 if obj and not obj.endpoints:
690 self.manager.remove(path)
691
692 delete = [] if self.manager.get(path, False) else [iface]
693
694 if create != delete:
695 self.update_interfaces(
696 path, self.unique, delete, create)
697
698 def update_associations(
699 self, path, owner, old, new, created=[], destroyed=[]):
700 added = list(set(new).difference(old))
701 removed = list(set(old).difference(new))
702 for forward, reverse, endpoint in added:
703 # update the index
704 forward_path = str(path + '/' + forward)
705 reverse_path = str(endpoint + '/' + reverse)
706 self.index_append(
707 'forward', path, owner, reverse_path)
708 self.index_append(
709 'reverse', endpoint, owner, forward_path)
710
711 # create the association if the endpoint exists
712 if not self.cache_get(endpoint):
713 continue
714
715 self.update_association(forward_path, [], [endpoint])
716 self.update_association(reverse_path, [], [path])
717
718 for forward, reverse, endpoint in removed:
719 # update the index
720 forward_path = str(path + '/' + forward)
721 reverse_path = str(endpoint + '/' + reverse)
722 self.index_remove(
723 'forward', path, owner, reverse_path)
724 self.index_remove(
725 'reverse', endpoint, owner, forward_path)
726
727 # destroy the association if it exists
728 self.update_association(forward_path, [endpoint], [])
729 self.update_association(reverse_path, [path], [])
730
731 # If the associations interface endpoint comes
732 # or goes create or destroy the appropriate
733 # associations
734 for path in created:
735 for forward, reverse, endpoint in \
736 self.index_get_associations(path, direction='reverse'):
737 forward_path = str(path + '/' + forward)
738 reverse_path = str(endpoint + '/' + reverse)
739 self.update_association(forward_path, [], [endpoint])
740 self.update_association(reverse_path, [], [path])
741
742 for path in destroyed:
743 for forward, reverse, endpoint in \
744 self.index_get_associations(path, direction='reverse'):
745 forward_path = str(path + '/' + forward)
746 reverse_path = str(endpoint + '/' + reverse)
747 self.update_association(forward_path, [endpoint], [])
748 self.update_association(reverse_path, [path], [])
749
Brad Bishop1c33c222016-11-02 00:08:46 -0400750 @dbus.service.method(obmc.mapper.MAPPER_IFACE, 'sas', 'a{sa{sas}}')
751 def GetAncestors(self, path, interfaces):
Brad Bishop495ee092016-11-02 00:11:11 -0400752 if not self.cache_get(path):
753 raise MapperNotFoundException(path)
754
Brad Bishop63f59a72016-07-25 12:05:57 -0400755 elements = filter(bool, path.split('/'))
756 paths = []
757 objs = {}
758 while elements:
759 elements.pop()
760 paths.append('/' + '/'.join(elements))
761 if path != '/':
762 paths.append('/')
763
764 for path in paths:
765 obj = self.cache_get(path)
766 if not obj:
767 continue
768 objs[path] = obj
769
Brad Bishop1c33c222016-11-02 00:08:46 -0400770 return self.filter_interfaces(list(objs.iteritems()), interfaces)
Brad Bishop63f59a72016-07-25 12:05:57 -0400771
Brad Bishop829181d2017-02-24 09:49:14 -0500772 @dbus.service.signal(obmc.mapper.MAPPER_IFACE + '.Private', 's')
773 def IntrospectionComplete(self, name):
774 pass
775
Brad Bishop63f59a72016-07-25 12:05:57 -0400776
Brad Bishopcb2e1b32017-07-09 20:11:35 -0400777def server_main(
778 path_namespaces,
779 interface_namespaces,
780 blacklists,
781 interface_blacklists):
Brad Bishop63f59a72016-07-25 12:05:57 -0400782 dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
783 bus = dbus.SystemBus()
Brad Bishopcb2e1b32017-07-09 20:11:35 -0400784 o = ObjectMapper(
785 bus,
786 obmc.mapper.MAPPER_PATH,
787 path_namespaces,
788 interface_namespaces,
789 blacklists,
790 interface_blacklists)
Brad Bishop63f59a72016-07-25 12:05:57 -0400791 loop = gobject.MainLoop()
792
793 loop.run()