blob: 182cf2c31020fe79ccb77a1b8c0ffd52f5a8c332 [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
Brad Bishopc33ae652017-11-02 22:23:09 -0400175@obmc.dbuslib.bindings.add_interfaces([obmc.dbuslib.enums.OBMC_ASSOC_IFACE])
176class Association(obmc.dbuslib.bindings.DbusProperties):
Brad Bishop734b2c32017-11-01 15:40:07 -0400177 """Implementation of org.openbmc.Association."""
178
Brad Bishopb9b3ed52017-11-01 21:40:31 -0400179 iface = obmc.dbuslib.enums.OBMC_ASSOC_IFACE
180
Brad Bishop63f59a72016-07-25 12:05:57 -0400181 def __init__(self, bus, path, endpoints):
Brad Bishop734b2c32017-11-01 15:40:07 -0400182 """Construct an Association.
183
184 Arguments:
185 bus -- The python-dbus connection to host the interface
186 path -- The D-Bus object path on which to implement the interface
187 endpoints -- A list of the initial association endpoints
188 """
Brad Bishop70dd5952016-09-08 22:33:33 -0400189 super(Association, self).__init__(conn=bus, object_path=path)
Brad Bishopb9b3ed52017-11-01 21:40:31 -0400190 self.properties = {self.iface: {'endpoints': endpoints}}
Brad Bishop63f59a72016-07-25 12:05:57 -0400191
Brad Bishop63f59a72016-07-25 12:05:57 -0400192
193class Manager(obmc.dbuslib.bindings.DbusObjectManager):
194 def __init__(self, bus, path):
Brad Bishop70dd5952016-09-08 22:33:33 -0400195 super(Manager, self).__init__(conn=bus, object_path=path)
Brad Bishop63f59a72016-07-25 12:05:57 -0400196
197
198class ObjectMapper(dbus.service.Object):
Brad Bishopcb2e1b32017-07-09 20:11:35 -0400199 def __init__(
200 self, bus, path, namespaces, interface_namespaces,
201 blacklist, interface_blacklist):
Brad Bishop63f59a72016-07-25 12:05:57 -0400202 super(ObjectMapper, self).__init__(bus, path)
203 self.cache = obmc.utils.pathtree.PathTree()
204 self.bus = bus
Brad Bishop63f59a72016-07-25 12:05:57 -0400205 self.service = None
206 self.index = {}
207 self.manager = Manager(bus, obmc.dbuslib.bindings.OBJ_PREFIX)
208 self.unique = bus.get_unique_name()
209 self.bus_map = {}
Brad Bishop2e0436c2016-09-19 18:02:19 -0400210 self.defer_signals = {}
Brad Bishop5d4890c2016-09-19 11:28:47 -0400211 self.bus_map[self.unique] = obmc.mapper.MAPPER_NAME
Brad Bishopcb2e1b32017-07-09 20:11:35 -0400212 self.namespaces = namespaces
213 self.interface_namespaces = interface_namespaces
214 self.blacklist = blacklist
215 self.blacklist.append(obmc.mapper.MAPPER_PATH)
216 self.interface_blacklist = interface_blacklist
Brad Bishop63f59a72016-07-25 12:05:57 -0400217
Brad Bishop5d4890c2016-09-19 11:28:47 -0400218 # add my object mananger instance
219 self.add_new_objmgr(obmc.dbuslib.bindings.OBJ_PREFIX, self.unique)
220
Brad Bishop63f59a72016-07-25 12:05:57 -0400221 self.bus.add_signal_receiver(
222 self.bus_handler,
223 dbus_interface=dbus.BUS_DAEMON_IFACE,
224 signal_name='NameOwnerChanged')
225 self.bus.add_signal_receiver(
226 self.interfaces_added_handler,
227 dbus_interface=dbus.BUS_DAEMON_IFACE + '.ObjectManager',
228 signal_name='InterfacesAdded',
229 sender_keyword='sender',
230 path_keyword='sender_path')
231 self.bus.add_signal_receiver(
232 self.interfaces_removed_handler,
233 dbus_interface=dbus.BUS_DAEMON_IFACE + '.ObjectManager',
234 signal_name='InterfacesRemoved',
235 sender_keyword='sender',
236 path_keyword='sender_path')
237 self.bus.add_signal_receiver(
238 self.properties_changed_handler,
239 dbus_interface=dbus.PROPERTIES_IFACE,
240 signal_name='PropertiesChanged',
Brad Bishopb270adc2017-11-14 23:32:59 -0500241 arg0=obmc.dbuslib.enums.OBMC_ASSOCIATIONS_IFACE,
Brad Bishop63f59a72016-07-25 12:05:57 -0400242 path_keyword='path',
243 sender_keyword='sender')
244
Brad Bishop5d4890c2016-09-19 11:28:47 -0400245 print "ObjectMapper startup complete. Discovery in progress..."
246 self.discover()
Brad Bishop520473f2016-09-19 21:46:36 -0400247 gobject.idle_add(self.claim_name)
Brad Bishop5d4890c2016-09-19 11:28:47 -0400248
Brad Bishop520473f2016-09-19 21:46:36 -0400249 def claim_name(self):
250 if len(self.defer_signals):
251 return True
Brad Bishop5d4890c2016-09-19 11:28:47 -0400252 print "ObjectMapper discovery complete"
253 self.service = dbus.service.BusName(
254 obmc.mapper.MAPPER_NAME, self.bus)
Brad Bishop55b89cd2016-09-19 23:02:48 -0400255 self.manager.unmask_signals()
Brad Bishop520473f2016-09-19 21:46:36 -0400256 return False
Brad Bishop63f59a72016-07-25 12:05:57 -0400257
Brad Bishop2e0436c2016-09-19 18:02:19 -0400258 def discovery_callback(self, owner, items):
259 if owner in self.defer_signals:
260 self.add_items(owner, items)
261 pending = self.defer_signals[owner]
262 del self.defer_signals[owner]
263
264 for x in pending:
265 x()
Brad Bishop829181d2017-02-24 09:49:14 -0500266 self.IntrospectionComplete(owner)
Brad Bishop2e0436c2016-09-19 18:02:19 -0400267
268 def discovery_error(self, owner, path, e):
Brad Bishop99b8bc82017-07-29 21:39:52 -0400269 '''Log a message and remove all traces of the service
270 we were attempting to introspect.'''
271
Brad Bishop2e0436c2016-09-19 18:02:19 -0400272 if owner in self.defer_signals:
Brad Bishop99b8bc82017-07-29 21:39:52 -0400273 sys.stderr.write(
274 '{} discovery failure on {}\n'.format(
275 self.bus_map.get(owner, owner),
276 path))
277 traceback.print_exception(*sys.exc_info())
278 del self.defer_signals[owner]
279 del self.bus_map[owner]
Brad Bishop2e0436c2016-09-19 18:02:19 -0400280
Brad Bishop63f59a72016-07-25 12:05:57 -0400281 def cache_get(self, path):
282 cache_entry = self.cache.get(path, {})
283 if cache_entry is None:
284 # hide path elements without any interfaces
285 cache_entry = {}
286 return cache_entry
287
288 def add_new_objmgr(self, path, owner):
289 # We don't get a signal for the ObjectManager
290 # interface itself, so if we see a signal from
291 # make sure its in our cache, and add it if not.
292 cache_entry = self.cache_get(path)
293 old = self.interfaces_get(cache_entry, owner)
294 new = list(set(old).union([dbus.BUS_DAEMON_IFACE + '.ObjectManager']))
295 self.update_interfaces(path, owner, old, new)
296
Brad Bishop2e0436c2016-09-19 18:02:19 -0400297 def defer_signal(self, owner, callback):
298 self.defer_signals.setdefault(owner, []).append(callback)
299
Brad Bishop63f59a72016-07-25 12:05:57 -0400300 def interfaces_added_handler(self, path, iprops, **kw):
301 path = str(path)
302 owner = str(kw['sender'])
303 interfaces = self.get_signal_interfaces(owner, iprops.iterkeys())
Brad Bishop2e0436c2016-09-19 18:02:19 -0400304 if not interfaces:
305 return
306
307 if owner not in self.defer_signals:
Brad Bishop63f59a72016-07-25 12:05:57 -0400308 self.add_new_objmgr(str(kw['sender_path']), owner)
309 cache_entry = self.cache_get(path)
310 old = self.interfaces_get(cache_entry, owner)
311 new = list(set(interfaces).union(old))
Brad Bishopa6235962017-06-07 23:56:54 -0400312 new = {x: iprops.get(x, {}) for x in new}
Brad Bishop63f59a72016-07-25 12:05:57 -0400313 self.update_interfaces(path, owner, old, new)
Brad Bishop2e0436c2016-09-19 18:02:19 -0400314 else:
315 self.defer_signal(
316 owner,
317 lambda: self.interfaces_added_handler(
318 path, iprops, **kw))
Brad Bishop63f59a72016-07-25 12:05:57 -0400319
320 def interfaces_removed_handler(self, path, interfaces, **kw):
321 path = str(path)
322 owner = str(kw['sender'])
323 interfaces = self.get_signal_interfaces(owner, interfaces)
Brad Bishop2e0436c2016-09-19 18:02:19 -0400324 if not interfaces:
325 return
326
327 if owner not in self.defer_signals:
Brad Bishop63f59a72016-07-25 12:05:57 -0400328 self.add_new_objmgr(str(kw['sender_path']), owner)
329 cache_entry = self.cache_get(path)
330 old = self.interfaces_get(cache_entry, owner)
331 new = list(set(old).difference(interfaces))
332 self.update_interfaces(path, owner, old, new)
Brad Bishop2e0436c2016-09-19 18:02:19 -0400333 else:
334 self.defer_signal(
335 owner,
336 lambda: self.interfaces_removed_handler(
337 path, interfaces, **kw))
Brad Bishop63f59a72016-07-25 12:05:57 -0400338
339 def properties_changed_handler(self, interface, new, old, **kw):
340 owner = str(kw['sender'])
341 path = str(kw['path'])
342 interfaces = self.get_signal_interfaces(owner, [interface])
343 if not self.is_association(interfaces):
344 return
345 associations = new.get('associations', None)
346 if associations is None:
347 return
348
Brad Bishop2e0436c2016-09-19 18:02:19 -0400349 if owner not in self.defer_signals:
350 associations = [
351 (str(x), str(y), str(z)) for x, y, z in associations]
352 self.update_associations(
353 path, owner,
354 self.index_get_associations(path, [owner]),
355 associations)
356 else:
357 self.defer_signal(
358 owner,
359 lambda: self.properties_changed_handler(
360 interface, new, old, **kw))
Brad Bishop63f59a72016-07-25 12:05:57 -0400361
362 def process_new_owner(self, owned_name, owner):
363 # unique name
364 try:
365 return self.discover([(owned_name, owner)])
366 except dbus.exceptions.DBusException, e:
367 if obmc.dbuslib.enums.DBUS_UNKNOWN_SERVICE \
368 not in e.get_dbus_name():
369 raise
370
371 def process_old_owner(self, owned_name, owner):
372 if owner in self.bus_map:
373 del self.bus_map[owner]
374
375 for path, item in self.cache.dataitems():
376 old = self.interfaces_get(item, owner)
377 # remove all interfaces for this service
378 self.update_interfaces(
379 path, owner, old=old, new=[])
380
381 def bus_handler(self, owned_name, old, new):
382 valid = False
383 if not obmc.dbuslib.bindings.is_unique(owned_name):
384 valid = self.valid_signal(owned_name)
385
386 if valid and new:
387 self.process_new_owner(owned_name, new)
388 if valid and old:
Brad Bishop2e0436c2016-09-19 18:02:19 -0400389 # discard any unhandled signals
390 # or in progress discovery
391 if old in self.defer_signals:
392 del self.defer_signals[old]
393
Brad Bishop63f59a72016-07-25 12:05:57 -0400394 self.process_old_owner(owned_name, old)
395
396 def update_interfaces(self, path, owner, old, new):
397 # __xx -> intf list
398 # xx -> intf dict
399 if isinstance(old, dict):
400 __old = old.keys()
401 else:
402 __old = old
403 old = {x: {} for x in old}
404 if isinstance(new, dict):
405 __new = new.keys()
406 else:
407 __new = new
408 new = {x: {} for x in new}
409
410 cache_entry = self.cache.setdefault(path, {})
411 created = [] if self.has_interfaces(cache_entry) else [path]
412 added = list(set(__new).difference(__old))
413 removed = list(set(__old).difference(__new))
414 self.interfaces_append(cache_entry, owner, added)
415 self.interfaces_remove(cache_entry, owner, removed, path)
416 destroyed = [] if self.has_interfaces(cache_entry) else [path]
417
418 # react to anything that requires association updates
419 new_assoc = []
420 old_assoc = []
421 if self.is_association(added):
Brad Bishop926b35d2016-09-19 14:20:04 -0400422 iface = obmc.dbuslib.enums.OBMC_ASSOCIATIONS_IFACE
423 new_assoc = new[iface]['associations']
Brad Bishop63f59a72016-07-25 12:05:57 -0400424 if self.is_association(removed):
425 old_assoc = self.index_get_associations(path, [owner])
426 self.update_associations(
427 path, owner, old_assoc, new_assoc, created, destroyed)
428
429 def add_items(self, owner, bus_items):
430 for path, items in bus_items.iteritems():
431 self.update_interfaces(path, str(owner), old=[], new=items)
432
Brad Bishopcb2e1b32017-07-09 20:11:35 -0400433 def path_match(self, path):
434 match = False
435
436 if not any([x for x in self.blacklist if x in path]):
437 # not blacklisted
438
439 if any([x for x in self.namespaces if x in path]):
440 # a watched namespace contains the path
441 match = True
442 elif any([path for x in self.namespaces if path in x]):
443 # the path contains a watched namespace
444 match = True
445
446 return match
447
448 def interface_match(self, interface):
449 match = True
450
451 if any([x for x in self.interface_blacklist if x in interface]):
452 # not blacklisted
453 match = False
454 elif not any([x for x in self.interface_namespaces if x in interface]):
455 # the interface contains a watched interface namespace
456 match = False
457
458 return match
459
Brad Bishop63f59a72016-07-25 12:05:57 -0400460 def discover(self, owners=[]):
Brad Bishop062403d2017-07-29 22:43:40 -0400461 def get_owner(name):
462 try:
463 return (name, self.bus.get_name_owner(name))
464 except:
465 traceback.print_exception(*sys.exc_info())
466
Brad Bishop63f59a72016-07-25 12:05:57 -0400467 if not owners:
Brad Bishopd0b8e392016-09-19 11:24:45 -0400468 owned_names = filter(
469 lambda x: not obmc.dbuslib.bindings.is_unique(x),
470 self.bus.list_names())
Brad Bishop062403d2017-07-29 22:43:40 -0400471 owners = filter(bool, [get_owner(name) for name in owned_names])
Brad Bishop63f59a72016-07-25 12:05:57 -0400472 for owned_name, o in owners:
Brad Bishopaeac98b2017-07-29 22:56:48 -0400473 if not self.valid_signal(owned_name):
474 continue
Brad Bishop63f59a72016-07-25 12:05:57 -0400475 self.bus_map[o] = owned_name
Brad Bishop520473f2016-09-19 21:46:36 -0400476 self.defer_signals[o] = []
477 find_dbus_interfaces(
478 self.bus, o, '/',
479 self.discovery_callback,
480 self.discovery_error,
Brad Bishopcb2e1b32017-07-09 20:11:35 -0400481 subtree_match=self.path_match,
482 iface_match=self.interface_match)
Brad Bishop63f59a72016-07-25 12:05:57 -0400483
Brad Bishop63f59a72016-07-25 12:05:57 -0400484 def valid_signal(self, name):
Brad Bishop63f59a72016-07-25 12:05:57 -0400485 if obmc.dbuslib.bindings.is_unique(name):
486 name = self.bus_map.get(name)
487
Brad Bishopaeac98b2017-07-29 22:56:48 -0400488 return name is not None and name != obmc.mapper.MAPPER_NAME
Brad Bishop63f59a72016-07-25 12:05:57 -0400489
490 def get_signal_interfaces(self, owner, interfaces):
491 filtered = []
492 if self.valid_signal(owner):
Brad Bishopcb2e1b32017-07-09 20:11:35 -0400493 filtered = [str(x) for x in interfaces if self.interface_match(x)]
Brad Bishop63f59a72016-07-25 12:05:57 -0400494
495 return filtered
496
497 @staticmethod
498 def interfaces_get(item, owner, default=[]):
499 return item.get(owner, default)
500
501 @staticmethod
502 def interfaces_append(item, owner, append):
503 interfaces = item.setdefault(owner, [])
504 item[owner] = list(set(append).union(interfaces))
505
506 def interfaces_remove(self, item, owner, remove, path):
507 interfaces = item.get(owner, [])
508 item[owner] = list(set(interfaces).difference(remove))
509
510 if not item[owner]:
511 # remove the owner if there aren't any interfaces left
512 del item[owner]
513
514 if item:
515 # other owners remain
516 return
517
518 if self.cache.get_children(path):
519 # there are still references to this path
520 # from objects further down the tree.
521 # mark it for removal if that changes
522 self.cache.demote(path)
523 else:
524 # delete the entire path if everything is gone
525 del self.cache[path]
526
Brad Bishop1c33c222016-11-02 00:08:46 -0400527 @staticmethod
528 def filter_interfaces(item, ifaces):
529 if isinstance(item, dict):
530 # Called with a single object.
531 if not ifaces:
532 return item
533
534 # Remove interfaces from a service that
535 # aren't in a filter.
536 svc_map = lambda svc: (
537 svc[0],
538 list(set(ifaces).intersection(svc[1])))
539
540 # Remove services where no interfaces remain after mapping.
541 svc_filter = lambda svc: svc[1]
542
543 obj_map = lambda o: (
544 tuple(*filter(svc_filter, map(svc_map, [o]))))
545
546 return dict(filter(lambda x: x, map(obj_map, item.iteritems())))
547
548 # Called with a list of path/object tuples.
549 if not ifaces:
550 return dict(item)
551
552 obj_map = lambda x: (
553 x[0],
554 ObjectMapper.filter_interfaces(
555 x[1],
556 ifaces))
557
Brad Bishop94c92a92017-09-11 16:12:07 -0400558 return dict(filter(lambda x: x[1], map(obj_map, iter(item or []))))
Brad Bishop1c33c222016-11-02 00:08:46 -0400559
560 @dbus.service.method(obmc.mapper.MAPPER_IFACE, 'sas', 'a{sas}')
561 def GetObject(self, path, interfaces):
Brad Bishop63f59a72016-07-25 12:05:57 -0400562 o = self.cache_get(path)
563 if not o:
564 raise MapperNotFoundException(path)
Brad Bishop63f59a72016-07-25 12:05:57 -0400565
Brad Bishop1c33c222016-11-02 00:08:46 -0400566 return self.filter_interfaces(o, interfaces)
567
568 @dbus.service.method(obmc.mapper.MAPPER_IFACE, 'sias', 'as')
569 def GetSubTreePaths(self, path, depth, interfaces):
Brad Bishop63f59a72016-07-25 12:05:57 -0400570 try:
Brad Bishop24301972017-06-23 13:40:07 -0400571 return self.filter_interfaces(
572 self.cache.iteritems(path, depth),
573 interfaces)
Brad Bishop63f59a72016-07-25 12:05:57 -0400574 except KeyError:
575 raise MapperNotFoundException(path)
576
Brad Bishop1c33c222016-11-02 00:08:46 -0400577 @dbus.service.method(obmc.mapper.MAPPER_IFACE, 'sias', 'a{sa{sas}}')
578 def GetSubTree(self, path, depth, interfaces):
Brad Bishop63f59a72016-07-25 12:05:57 -0400579 try:
Brad Bishop1c33c222016-11-02 00:08:46 -0400580 return self.filter_interfaces(
581 self.cache.dataitems(path, depth),
582 interfaces)
Brad Bishop63f59a72016-07-25 12:05:57 -0400583 except KeyError:
584 raise MapperNotFoundException(path)
585
586 @staticmethod
587 def has_interfaces(item):
588 for owner in item.iterkeys():
589 if ObjectMapper.interfaces_get(item, owner):
590 return True
591 return False
592
593 @staticmethod
594 def is_association(interfaces):
595 return obmc.dbuslib.enums.OBMC_ASSOCIATIONS_IFACE in interfaces
596
597 def index_get(self, index, path, owners):
598 items = []
599 item = self.index.get(index, {})
600 item = item.get(path, {})
601 for o in owners:
602 items.extend(item.get(o, []))
603 return items
604
605 def index_append(self, index, path, owner, assoc):
606 item = self.index.setdefault(index, {})
607 item = item.setdefault(path, {})
608 item = item.setdefault(owner, [])
609 item.append(assoc)
610
611 def index_remove(self, index, path, owner, assoc):
612 index = self.index.get(index, {})
613 owners = index.get(path, {})
614 items = owners.get(owner, [])
615 if assoc in items:
616 items.remove(assoc)
617 if not items:
618 del owners[owner]
619 if not owners:
620 del index[path]
621
Brad Bishop63f59a72016-07-25 12:05:57 -0400622 def index_get_associations(self, path, owners=[], direction='forward'):
623 forward = 'forward' if direction == 'forward' else 'reverse'
624 reverse = 'reverse' if direction == 'forward' else 'forward'
625
626 associations = []
627 if not owners:
628 index = self.index.get(forward, {})
629 owners = index.get(path, {}).keys()
630
631 # f: forward
632 # r: reverse
633 for rassoc in self.index_get(forward, path, owners):
634 elements = rassoc.split('/')
635 rtype = ''.join(elements[-1:])
636 fendpoint = '/'.join(elements[:-1])
637 for fassoc in self.index_get(reverse, fendpoint, owners):
638 elements = fassoc.split('/')
639 ftype = ''.join(elements[-1:])
640 rendpoint = '/'.join(elements[:-1])
641 if rendpoint != path:
642 continue
643 associations.append((ftype, rtype, fendpoint))
644
645 return associations
646
647 def update_association(self, path, removed, added):
648 iface = obmc.dbuslib.enums.OBMC_ASSOC_IFACE
Brad Bishop8e1f4ab2017-11-02 20:44:17 -0400649 assoc = self.manager.get(path, None)
Brad Bishop63f59a72016-07-25 12:05:57 -0400650
Brad Bishopc33ae652017-11-02 22:23:09 -0400651 old_endpoints = assoc.Get(iface, 'endpoints') if assoc else []
Brad Bishop84041e32017-11-02 21:48:57 -0400652 new_endpoints = list(
653 set(old_endpoints).union(added).difference(removed))
654
655 if old_endpoints == new_endpoints:
656 return
657
658 create = [] if old_endpoints else [iface]
659 delete = [] if new_endpoints else [iface]
660
661 if create:
Brad Bishop63f59a72016-07-25 12:05:57 -0400662 self.manager.add(
Brad Bishop84041e32017-11-02 21:48:57 -0400663 path, Association(self.bus, path, new_endpoints))
664 elif delete:
Brad Bishop63f59a72016-07-25 12:05:57 -0400665 self.manager.remove(path)
Brad Bishop84041e32017-11-02 21:48:57 -0400666 else:
Brad Bishopc33ae652017-11-02 22:23:09 -0400667 assoc.Set(iface, 'endpoints', new_endpoints)
Brad Bishop63f59a72016-07-25 12:05:57 -0400668
669 if create != delete:
670 self.update_interfaces(
671 path, self.unique, delete, create)
672
673 def update_associations(
674 self, path, owner, old, new, created=[], destroyed=[]):
675 added = list(set(new).difference(old))
676 removed = list(set(old).difference(new))
677 for forward, reverse, endpoint in added:
Brad Bishopb15b6312017-11-01 16:34:13 -0400678 if not endpoint:
679 # skip associations without an endpoint
680 continue
681
Brad Bishop63f59a72016-07-25 12:05:57 -0400682 # update the index
683 forward_path = str(path + '/' + forward)
684 reverse_path = str(endpoint + '/' + reverse)
685 self.index_append(
686 'forward', path, owner, reverse_path)
687 self.index_append(
688 'reverse', endpoint, owner, forward_path)
689
690 # create the association if the endpoint exists
691 if not self.cache_get(endpoint):
692 continue
693
694 self.update_association(forward_path, [], [endpoint])
695 self.update_association(reverse_path, [], [path])
696
697 for forward, reverse, endpoint in removed:
698 # update the index
699 forward_path = str(path + '/' + forward)
700 reverse_path = str(endpoint + '/' + reverse)
701 self.index_remove(
702 'forward', path, owner, reverse_path)
703 self.index_remove(
704 'reverse', endpoint, owner, forward_path)
705
706 # destroy the association if it exists
707 self.update_association(forward_path, [endpoint], [])
708 self.update_association(reverse_path, [path], [])
709
710 # If the associations interface endpoint comes
711 # or goes create or destroy the appropriate
712 # associations
713 for path in created:
714 for forward, reverse, endpoint in \
715 self.index_get_associations(path, direction='reverse'):
716 forward_path = str(path + '/' + forward)
717 reverse_path = str(endpoint + '/' + reverse)
718 self.update_association(forward_path, [], [endpoint])
719 self.update_association(reverse_path, [], [path])
720
721 for path in destroyed:
722 for forward, reverse, endpoint in \
723 self.index_get_associations(path, direction='reverse'):
724 forward_path = str(path + '/' + forward)
725 reverse_path = str(endpoint + '/' + reverse)
726 self.update_association(forward_path, [endpoint], [])
727 self.update_association(reverse_path, [path], [])
728
Brad Bishop1c33c222016-11-02 00:08:46 -0400729 @dbus.service.method(obmc.mapper.MAPPER_IFACE, 'sas', 'a{sa{sas}}')
730 def GetAncestors(self, path, interfaces):
Brad Bishop495ee092016-11-02 00:11:11 -0400731 if not self.cache_get(path):
732 raise MapperNotFoundException(path)
733
Brad Bishop63f59a72016-07-25 12:05:57 -0400734 elements = filter(bool, path.split('/'))
735 paths = []
736 objs = {}
737 while elements:
738 elements.pop()
739 paths.append('/' + '/'.join(elements))
740 if path != '/':
741 paths.append('/')
742
743 for path in paths:
744 obj = self.cache_get(path)
745 if not obj:
746 continue
747 objs[path] = obj
748
Brad Bishop1c33c222016-11-02 00:08:46 -0400749 return self.filter_interfaces(list(objs.iteritems()), interfaces)
Brad Bishop63f59a72016-07-25 12:05:57 -0400750
Brad Bishop829181d2017-02-24 09:49:14 -0500751 @dbus.service.signal(obmc.mapper.MAPPER_IFACE + '.Private', 's')
752 def IntrospectionComplete(self, name):
753 pass
754
Brad Bishop63f59a72016-07-25 12:05:57 -0400755
Brad Bishopcb2e1b32017-07-09 20:11:35 -0400756def server_main(
757 path_namespaces,
758 interface_namespaces,
759 blacklists,
760 interface_blacklists):
Brad Bishop63f59a72016-07-25 12:05:57 -0400761 dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
762 bus = dbus.SystemBus()
Brad Bishopcb2e1b32017-07-09 20:11:35 -0400763 o = ObjectMapper(
764 bus,
765 obmc.mapper.MAPPER_PATH,
766 path_namespaces,
767 interface_namespaces,
768 blacklists,
769 interface_blacklists)
Brad Bishop63f59a72016-07-25 12:05:57 -0400770 loop = gobject.MainLoop()
771
772 loop.run()