blob: e11f0fe8ce53e6ec65e44f5c1aee378622fa1329 [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):
Balaji B Rao84e331a2017-11-09 21:19:13 -060064 return list(filter(bool, path.split('/')))
Brad Bishop63f59a72016-07-25 12:05:57 -040065
66 def __call__(self, path):
Brad Bishop520473f2016-09-19 21:46:36 -040067 try:
68 self._find_interfaces(path)
Balaji B Rao84e331a2017-11-09 21:19:13 -060069 except Exception as e:
Brad Bishop520473f2016-09-19 21:46:36 -040070 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
Balaji B Rao84e331a2017-11-09 21:19:13 -060091 except Exception as e:
Brad Bishop520473f2016-09-19 21:46:36 -040092 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)
Balaji B Rao84e331a2017-11-09 21:19:13 -0600100 for k, v in objs.items():
Brad Bishop520473f2016-09-19 21:46:36 -0400101 self.results[k] = v
Balaji B Rao84e331a2017-11-09 21:19:13 -0600102 except Exception as e:
Brad Bishop520473f2016-09-19 21:46:36 -0400103 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)
Balaji B Rao84e331a2017-11-09 21:19:13 -0600117 ifaces = list(filter(
Brad Bishop520473f2016-09-19 21:46:36 -0400118 self._match,
Balaji B Rao84e331a2017-11-09 21:19:13 -0600119 [x.attrib.get('name') for x in root.findall('interface')]))
Brad Bishop520473f2016-09-19 21:46:36 -0400120 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:
Balaji B Rao84e331a2017-11-09 21:19:13 -0600146 children = list(filter(
Brad Bishop520473f2016-09-19 21:46:36 -0400147 bool,
Balaji B Rao84e331a2017-11-09 21:19:13 -0600148 [x.attrib.get('name') for x in root.findall('node')]))
Brad Bishop520473f2016-09-19 21:46:36 -0400149 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)
Balaji B Rao84e331a2017-11-09 21:19:13 -0600156 except Exception as e:
Brad Bishop520473f2016-09-19 21:46:36 -0400157 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 Bishopbcc06442018-01-29 14:54:51 -0500191 self.unmask_signals()
Brad Bishop63f59a72016-07-25 12:05:57 -0400192
Brad Bishop63f59a72016-07-25 12:05:57 -0400193
194class Manager(obmc.dbuslib.bindings.DbusObjectManager):
195 def __init__(self, bus, path):
Brad Bishop70dd5952016-09-08 22:33:33 -0400196 super(Manager, self).__init__(conn=bus, object_path=path)
Brad Bishop63f59a72016-07-25 12:05:57 -0400197
198
199class ObjectMapper(dbus.service.Object):
Brad Bishopcb2e1b32017-07-09 20:11:35 -0400200 def __init__(
201 self, bus, path, namespaces, interface_namespaces,
202 blacklist, interface_blacklist):
Brad Bishop63f59a72016-07-25 12:05:57 -0400203 super(ObjectMapper, self).__init__(bus, path)
204 self.cache = obmc.utils.pathtree.PathTree()
205 self.bus = bus
Brad Bishop63f59a72016-07-25 12:05:57 -0400206 self.service = None
207 self.index = {}
208 self.manager = Manager(bus, obmc.dbuslib.bindings.OBJ_PREFIX)
Andrew Geissler12469242018-01-02 09:41:37 -0600209 self.unique = bus.get_unique_name()
Brad Bishop63f59a72016-07-25 12:05:57 -0400210 self.bus_map = {}
Brad Bishop2e0436c2016-09-19 18:02:19 -0400211 self.defer_signals = {}
Andrew Geissler12469242018-01-02 09:41:37 -0600212 self.bus_map[self.unique] = obmc.mapper.MAPPER_NAME
Brad Bishopcb2e1b32017-07-09 20:11:35 -0400213 self.namespaces = namespaces
214 self.interface_namespaces = interface_namespaces
215 self.blacklist = blacklist
216 self.blacklist.append(obmc.mapper.MAPPER_PATH)
217 self.interface_blacklist = interface_blacklist
Brad Bishop63f59a72016-07-25 12:05:57 -0400218
Brad Bishop5d4890c2016-09-19 11:28:47 -0400219 # add my object mananger instance
Andrew Geissler12469242018-01-02 09:41:37 -0600220 self.add_new_objmgr(obmc.dbuslib.bindings.OBJ_PREFIX, self.unique)
Brad Bishop5d4890c2016-09-19 11:28:47 -0400221
Brad Bishop63f59a72016-07-25 12:05:57 -0400222 self.bus.add_signal_receiver(
223 self.bus_handler,
224 dbus_interface=dbus.BUS_DAEMON_IFACE,
225 signal_name='NameOwnerChanged')
226 self.bus.add_signal_receiver(
227 self.interfaces_added_handler,
228 dbus_interface=dbus.BUS_DAEMON_IFACE + '.ObjectManager',
229 signal_name='InterfacesAdded',
230 sender_keyword='sender',
231 path_keyword='sender_path')
232 self.bus.add_signal_receiver(
233 self.interfaces_removed_handler,
234 dbus_interface=dbus.BUS_DAEMON_IFACE + '.ObjectManager',
235 signal_name='InterfacesRemoved',
236 sender_keyword='sender',
237 path_keyword='sender_path')
238 self.bus.add_signal_receiver(
239 self.properties_changed_handler,
240 dbus_interface=dbus.PROPERTIES_IFACE,
241 signal_name='PropertiesChanged',
Brad Bishopb270adc2017-11-14 23:32:59 -0500242 arg0=obmc.dbuslib.enums.OBMC_ASSOCIATIONS_IFACE,
Brad Bishop63f59a72016-07-25 12:05:57 -0400243 path_keyword='path',
244 sender_keyword='sender')
245
Balaji B Rao84e331a2017-11-09 21:19:13 -0600246 print("ObjectMapper startup complete. Discovery in progress...")
Brad Bishop5d4890c2016-09-19 11:28:47 -0400247 self.discover()
Brad Bishop520473f2016-09-19 21:46:36 -0400248 gobject.idle_add(self.claim_name)
Brad Bishop5d4890c2016-09-19 11:28:47 -0400249
Brad Bishop520473f2016-09-19 21:46:36 -0400250 def claim_name(self):
251 if len(self.defer_signals):
252 return True
Balaji B Rao84e331a2017-11-09 21:19:13 -0600253 print("ObjectMapper discovery complete")
Brad Bishop5d4890c2016-09-19 11:28:47 -0400254 self.service = dbus.service.BusName(
255 obmc.mapper.MAPPER_NAME, self.bus)
Brad Bishop55b89cd2016-09-19 23:02:48 -0400256 self.manager.unmask_signals()
Brad Bishop520473f2016-09-19 21:46:36 -0400257 return False
Brad Bishop63f59a72016-07-25 12:05:57 -0400258
Brad Bishop2e0436c2016-09-19 18:02:19 -0400259 def discovery_callback(self, owner, items):
260 if owner in self.defer_signals:
261 self.add_items(owner, items)
262 pending = self.defer_signals[owner]
263 del self.defer_signals[owner]
264
265 for x in pending:
266 x()
Brad Bishop829181d2017-02-24 09:49:14 -0500267 self.IntrospectionComplete(owner)
Brad Bishop2e0436c2016-09-19 18:02:19 -0400268
269 def discovery_error(self, owner, path, e):
Brad Bishop99b8bc82017-07-29 21:39:52 -0400270 '''Log a message and remove all traces of the service
271 we were attempting to introspect.'''
272
Brad Bishop2e0436c2016-09-19 18:02:19 -0400273 if owner in self.defer_signals:
Brad Bishop7a790272017-12-14 21:25:24 -0500274
275 # Safe to add a reference to the traceback here,
276 # since it cannot contain the discovery_error frame.
277 exctype, value, tb = sys.exc_info()
Brad Bishop99b8bc82017-07-29 21:39:52 -0400278 sys.stderr.write(
279 '{} discovery failure on {}\n'.format(
280 self.bus_map.get(owner, owner),
281 path))
Brad Bishop7a790272017-12-14 21:25:24 -0500282 if tb:
283 traceback.print_exception(exctype, value, tb, file=sys.stderr)
284 else:
285 sys.stderr.write('{}: {}\n'.format(e.__class__.__name__, e))
286
Brad Bishop99b8bc82017-07-29 21:39:52 -0400287 del self.defer_signals[owner]
288 del self.bus_map[owner]
Brad Bishop2e0436c2016-09-19 18:02:19 -0400289
Brad Bishop63f59a72016-07-25 12:05:57 -0400290 def cache_get(self, path):
291 cache_entry = self.cache.get(path, {})
292 if cache_entry is None:
293 # hide path elements without any interfaces
294 cache_entry = {}
295 return cache_entry
296
297 def add_new_objmgr(self, path, owner):
298 # We don't get a signal for the ObjectManager
299 # interface itself, so if we see a signal from
300 # make sure its in our cache, and add it if not.
301 cache_entry = self.cache_get(path)
302 old = self.interfaces_get(cache_entry, owner)
303 new = list(set(old).union([dbus.BUS_DAEMON_IFACE + '.ObjectManager']))
304 self.update_interfaces(path, owner, old, new)
305
Brad Bishop2e0436c2016-09-19 18:02:19 -0400306 def defer_signal(self, owner, callback):
307 self.defer_signals.setdefault(owner, []).append(callback)
308
Brad Bishop63f59a72016-07-25 12:05:57 -0400309 def interfaces_added_handler(self, path, iprops, **kw):
310 path = str(path)
311 owner = str(kw['sender'])
Balaji B Rao84e331a2017-11-09 21:19:13 -0600312 interfaces = self.get_signal_interfaces(owner, iter(iprops.keys()))
Brad Bishop2e0436c2016-09-19 18:02:19 -0400313 if not interfaces:
314 return
315
316 if owner not in self.defer_signals:
Brad Bishop63f59a72016-07-25 12:05:57 -0400317 self.add_new_objmgr(str(kw['sender_path']), owner)
318 cache_entry = self.cache_get(path)
319 old = self.interfaces_get(cache_entry, owner)
320 new = list(set(interfaces).union(old))
Brad Bishopa6235962017-06-07 23:56:54 -0400321 new = {x: iprops.get(x, {}) for x in new}
Brad Bishop63f59a72016-07-25 12:05:57 -0400322 self.update_interfaces(path, owner, old, new)
Brad Bishop2e0436c2016-09-19 18:02:19 -0400323 else:
324 self.defer_signal(
325 owner,
326 lambda: self.interfaces_added_handler(
327 path, iprops, **kw))
Brad Bishop63f59a72016-07-25 12:05:57 -0400328
329 def interfaces_removed_handler(self, path, interfaces, **kw):
330 path = str(path)
331 owner = str(kw['sender'])
332 interfaces = self.get_signal_interfaces(owner, interfaces)
Brad Bishop2e0436c2016-09-19 18:02:19 -0400333 if not interfaces:
334 return
335
336 if owner not in self.defer_signals:
Brad Bishop63f59a72016-07-25 12:05:57 -0400337 self.add_new_objmgr(str(kw['sender_path']), owner)
338 cache_entry = self.cache_get(path)
339 old = self.interfaces_get(cache_entry, owner)
340 new = list(set(old).difference(interfaces))
341 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_removed_handler(
346 path, interfaces, **kw))
Brad Bishop63f59a72016-07-25 12:05:57 -0400347
348 def properties_changed_handler(self, interface, new, old, **kw):
349 owner = str(kw['sender'])
350 path = str(kw['path'])
351 interfaces = self.get_signal_interfaces(owner, [interface])
352 if not self.is_association(interfaces):
353 return
354 associations = new.get('associations', None)
355 if associations is None:
356 return
357
Brad Bishop2e0436c2016-09-19 18:02:19 -0400358 if owner not in self.defer_signals:
359 associations = [
360 (str(x), str(y), str(z)) for x, y, z in associations]
361 self.update_associations(
362 path, owner,
363 self.index_get_associations(path, [owner]),
364 associations)
365 else:
366 self.defer_signal(
367 owner,
368 lambda: self.properties_changed_handler(
369 interface, new, old, **kw))
Brad Bishop63f59a72016-07-25 12:05:57 -0400370
371 def process_new_owner(self, owned_name, owner):
372 # unique name
373 try:
374 return self.discover([(owned_name, owner)])
Balaji B Rao84e331a2017-11-09 21:19:13 -0600375 except dbus.exceptions.DBusException as e:
Brad Bishop63f59a72016-07-25 12:05:57 -0400376 if obmc.dbuslib.enums.DBUS_UNKNOWN_SERVICE \
377 not in e.get_dbus_name():
378 raise
379
380 def process_old_owner(self, owned_name, owner):
381 if owner in self.bus_map:
382 del self.bus_map[owner]
383
384 for path, item in self.cache.dataitems():
385 old = self.interfaces_get(item, owner)
386 # remove all interfaces for this service
387 self.update_interfaces(
388 path, owner, old=old, new=[])
389
390 def bus_handler(self, owned_name, old, new):
391 valid = False
392 if not obmc.dbuslib.bindings.is_unique(owned_name):
Brad Bishop5c5e13e2018-01-28 23:34:54 -0500393 valid = self.bus_normalize(owned_name)
Brad Bishop63f59a72016-07-25 12:05:57 -0400394
395 if valid and new:
396 self.process_new_owner(owned_name, new)
397 if valid and old:
Brad Bishop2e0436c2016-09-19 18:02:19 -0400398 # discard any unhandled signals
399 # or in progress discovery
400 if old in self.defer_signals:
401 del self.defer_signals[old]
402
Brad Bishop63f59a72016-07-25 12:05:57 -0400403 self.process_old_owner(owned_name, old)
404
405 def update_interfaces(self, path, owner, old, new):
406 # __xx -> intf list
407 # xx -> intf dict
408 if isinstance(old, dict):
Balaji B Rao84e331a2017-11-09 21:19:13 -0600409 __old = list(old.keys())
Brad Bishop63f59a72016-07-25 12:05:57 -0400410 else:
411 __old = old
412 old = {x: {} for x in old}
413 if isinstance(new, dict):
Balaji B Rao84e331a2017-11-09 21:19:13 -0600414 __new = list(new.keys())
Brad Bishop63f59a72016-07-25 12:05:57 -0400415 else:
416 __new = new
417 new = {x: {} for x in new}
418
419 cache_entry = self.cache.setdefault(path, {})
420 created = [] if self.has_interfaces(cache_entry) else [path]
421 added = list(set(__new).difference(__old))
422 removed = list(set(__old).difference(__new))
423 self.interfaces_append(cache_entry, owner, added)
424 self.interfaces_remove(cache_entry, owner, removed, path)
425 destroyed = [] if self.has_interfaces(cache_entry) else [path]
426
427 # react to anything that requires association updates
428 new_assoc = []
429 old_assoc = []
430 if self.is_association(added):
Brad Bishop926b35d2016-09-19 14:20:04 -0400431 iface = obmc.dbuslib.enums.OBMC_ASSOCIATIONS_IFACE
432 new_assoc = new[iface]['associations']
Brad Bishop63f59a72016-07-25 12:05:57 -0400433 if self.is_association(removed):
434 old_assoc = self.index_get_associations(path, [owner])
435 self.update_associations(
436 path, owner, old_assoc, new_assoc, created, destroyed)
437
438 def add_items(self, owner, bus_items):
Balaji B Rao84e331a2017-11-09 21:19:13 -0600439 for path, items in bus_items.items():
Brad Bishop63f59a72016-07-25 12:05:57 -0400440 self.update_interfaces(path, str(owner), old=[], new=items)
441
Brad Bishopcb2e1b32017-07-09 20:11:35 -0400442 def path_match(self, path):
443 match = False
444
445 if not any([x for x in self.blacklist if x in path]):
446 # not blacklisted
447
448 if any([x for x in self.namespaces if x in path]):
449 # a watched namespace contains the path
450 match = True
451 elif any([path for x in self.namespaces if path in x]):
452 # the path contains a watched namespace
453 match = True
454
455 return match
456
457 def interface_match(self, interface):
458 match = True
459
460 if any([x for x in self.interface_blacklist if x in interface]):
461 # not blacklisted
462 match = False
463 elif not any([x for x in self.interface_namespaces if x in interface]):
464 # the interface contains a watched interface namespace
465 match = False
466
467 return match
468
Brad Bishop63f59a72016-07-25 12:05:57 -0400469 def discover(self, owners=[]):
Brad Bishop062403d2017-07-29 22:43:40 -0400470 def get_owner(name):
471 try:
472 return (name, self.bus.get_name_owner(name))
Adriana Kobylaka1f24222018-01-10 16:09:07 -0600473 except Exception:
Brad Bishop062403d2017-07-29 22:43:40 -0400474 traceback.print_exception(*sys.exc_info())
475
Brad Bishop63f59a72016-07-25 12:05:57 -0400476 if not owners:
Brad Bishopcabc6382018-01-29 15:39:07 -0500477 owned_names = [
478 x for x in self.bus.list_names()
479 if not obmc.dbuslib.bindings.is_unique(x)]
480 owners = list(
481 filter(bool, [get_owner(name) for name in owned_names]))
Brad Bishop63f59a72016-07-25 12:05:57 -0400482 for owned_name, o in owners:
Brad Bishop5c5e13e2018-01-28 23:34:54 -0500483 if not self.bus_normalize(owned_name):
Brad Bishopaeac98b2017-07-29 22:56:48 -0400484 continue
Andrew Geissler12469242018-01-02 09:41:37 -0600485 self.bus_map[o] = owned_name
486 self.defer_signals[o] = []
Brad Bishop520473f2016-09-19 21:46:36 -0400487 find_dbus_interfaces(
Andrew Geissler12469242018-01-02 09:41:37 -0600488 self.bus, o, '/',
Brad Bishop520473f2016-09-19 21:46:36 -0400489 self.discovery_callback,
490 self.discovery_error,
Brad Bishopcb2e1b32017-07-09 20:11:35 -0400491 subtree_match=self.path_match,
492 iface_match=self.interface_match)
Brad Bishop63f59a72016-07-25 12:05:57 -0400493
Brad Bishop5c5e13e2018-01-28 23:34:54 -0500494 def bus_normalize(self, name):
495 '''
496 Normalize on well-known names and filter signals
497 originating from the mapper.
498 '''
499
Brad Bishop63f59a72016-07-25 12:05:57 -0400500 if obmc.dbuslib.bindings.is_unique(name):
501 name = self.bus_map.get(name)
502
Brad Bishop5c5e13e2018-01-28 23:34:54 -0500503 if name == obmc.mapper.MAPPER_NAME:
504 return None
505
506 return name
Brad Bishop63f59a72016-07-25 12:05:57 -0400507
508 def get_signal_interfaces(self, owner, interfaces):
509 filtered = []
Brad Bishop5c5e13e2018-01-28 23:34:54 -0500510 if self.bus_normalize(owner):
Brad Bishopcb2e1b32017-07-09 20:11:35 -0400511 filtered = [str(x) for x in interfaces if self.interface_match(x)]
Brad Bishop63f59a72016-07-25 12:05:57 -0400512
513 return filtered
514
515 @staticmethod
516 def interfaces_get(item, owner, default=[]):
517 return item.get(owner, default)
518
519 @staticmethod
520 def interfaces_append(item, owner, append):
521 interfaces = item.setdefault(owner, [])
522 item[owner] = list(set(append).union(interfaces))
523
524 def interfaces_remove(self, item, owner, remove, path):
525 interfaces = item.get(owner, [])
526 item[owner] = list(set(interfaces).difference(remove))
527
528 if not item[owner]:
529 # remove the owner if there aren't any interfaces left
530 del item[owner]
531
532 if item:
533 # other owners remain
534 return
535
536 if self.cache.get_children(path):
537 # there are still references to this path
538 # from objects further down the tree.
539 # mark it for removal if that changes
540 self.cache.demote(path)
541 else:
542 # delete the entire path if everything is gone
543 del self.cache[path]
544
Brad Bishop1c33c222016-11-02 00:08:46 -0400545 @staticmethod
546 def filter_interfaces(item, ifaces):
547 if isinstance(item, dict):
548 # Called with a single object.
549 if not ifaces:
550 return item
551
552 # Remove interfaces from a service that
553 # aren't in a filter.
Adriana Kobylak7f42ad22018-01-16 12:15:23 -0600554 svc_map = lambda svc: (
Brad Bishop1c33c222016-11-02 00:08:46 -0400555 svc[0],
556 list(set(ifaces).intersection(svc[1])))
557
558 # Remove services where no interfaces remain after mapping.
Adriana Kobylak7f42ad22018-01-16 12:15:23 -0600559 svc_filter = lambda svc: svc[1]
Brad Bishop1c33c222016-11-02 00:08:46 -0400560
Adriana Kobylak7f42ad22018-01-16 12:15:23 -0600561 obj_map = lambda o: (
Balaji B Rao84e331a2017-11-09 21:19:13 -0600562 tuple(*list(filter(svc_filter, list(map(svc_map, [o]))))))
Brad Bishop1c33c222016-11-02 00:08:46 -0400563
Balaji B Rao84e331a2017-11-09 21:19:13 -0600564 return dict([x for x in map(obj_map, iter(item.items())) if x])
Brad Bishop1c33c222016-11-02 00:08:46 -0400565
566 # Called with a list of path/object tuples.
567 if not ifaces:
568 return dict(item)
569
Adriana Kobylak7f42ad22018-01-16 12:15:23 -0600570 obj_map = lambda x: (
Brad Bishop1c33c222016-11-02 00:08:46 -0400571 x[0],
572 ObjectMapper.filter_interfaces(
573 x[1],
574 ifaces))
575
Balaji B Rao84e331a2017-11-09 21:19:13 -0600576 return dict([x for x in map(obj_map, iter(item or [])) if x[1]])
Brad Bishop1c33c222016-11-02 00:08:46 -0400577
578 @dbus.service.method(obmc.mapper.MAPPER_IFACE, 'sas', 'a{sas}')
579 def GetObject(self, path, interfaces):
Brad Bishop63f59a72016-07-25 12:05:57 -0400580 o = self.cache_get(path)
581 if not o:
582 raise MapperNotFoundException(path)
Brad Bishop63f59a72016-07-25 12:05:57 -0400583
Brad Bishop1c33c222016-11-02 00:08:46 -0400584 return self.filter_interfaces(o, interfaces)
585
586 @dbus.service.method(obmc.mapper.MAPPER_IFACE, 'sias', 'as')
587 def GetSubTreePaths(self, path, depth, interfaces):
Brad Bishop63f59a72016-07-25 12:05:57 -0400588 try:
Brad Bishop24301972017-06-23 13:40:07 -0400589 return self.filter_interfaces(
590 self.cache.iteritems(path, depth),
591 interfaces)
Brad Bishop63f59a72016-07-25 12:05:57 -0400592 except KeyError:
593 raise MapperNotFoundException(path)
594
Brad Bishop1c33c222016-11-02 00:08:46 -0400595 @dbus.service.method(obmc.mapper.MAPPER_IFACE, 'sias', 'a{sa{sas}}')
596 def GetSubTree(self, path, depth, interfaces):
Brad Bishop63f59a72016-07-25 12:05:57 -0400597 try:
Brad Bishop1c33c222016-11-02 00:08:46 -0400598 return self.filter_interfaces(
599 self.cache.dataitems(path, depth),
600 interfaces)
Brad Bishop63f59a72016-07-25 12:05:57 -0400601 except KeyError:
602 raise MapperNotFoundException(path)
603
604 @staticmethod
605 def has_interfaces(item):
Balaji B Rao84e331a2017-11-09 21:19:13 -0600606 for owner in item.keys():
Brad Bishop63f59a72016-07-25 12:05:57 -0400607 if ObjectMapper.interfaces_get(item, owner):
608 return True
609 return False
610
611 @staticmethod
612 def is_association(interfaces):
613 return obmc.dbuslib.enums.OBMC_ASSOCIATIONS_IFACE in interfaces
614
615 def index_get(self, index, path, owners):
616 items = []
617 item = self.index.get(index, {})
618 item = item.get(path, {})
619 for o in owners:
620 items.extend(item.get(o, []))
621 return items
622
623 def index_append(self, index, path, owner, assoc):
624 item = self.index.setdefault(index, {})
625 item = item.setdefault(path, {})
626 item = item.setdefault(owner, [])
627 item.append(assoc)
628
629 def index_remove(self, index, path, owner, assoc):
630 index = self.index.get(index, {})
631 owners = index.get(path, {})
632 items = owners.get(owner, [])
633 if assoc in items:
634 items.remove(assoc)
635 if not items:
636 del owners[owner]
637 if not owners:
638 del index[path]
639
Brad Bishop63f59a72016-07-25 12:05:57 -0400640 def index_get_associations(self, path, owners=[], direction='forward'):
641 forward = 'forward' if direction == 'forward' else 'reverse'
642 reverse = 'reverse' if direction == 'forward' else 'forward'
643
644 associations = []
645 if not owners:
646 index = self.index.get(forward, {})
Balaji B Rao84e331a2017-11-09 21:19:13 -0600647 owners = list(index.get(path, {}).keys())
Brad Bishop63f59a72016-07-25 12:05:57 -0400648
649 # f: forward
650 # r: reverse
651 for rassoc in self.index_get(forward, path, owners):
652 elements = rassoc.split('/')
653 rtype = ''.join(elements[-1:])
654 fendpoint = '/'.join(elements[:-1])
655 for fassoc in self.index_get(reverse, fendpoint, owners):
656 elements = fassoc.split('/')
657 ftype = ''.join(elements[-1:])
658 rendpoint = '/'.join(elements[:-1])
659 if rendpoint != path:
660 continue
661 associations.append((ftype, rtype, fendpoint))
662
663 return associations
664
665 def update_association(self, path, removed, added):
666 iface = obmc.dbuslib.enums.OBMC_ASSOC_IFACE
Brad Bishop8e1f4ab2017-11-02 20:44:17 -0400667 assoc = self.manager.get(path, None)
Brad Bishop63f59a72016-07-25 12:05:57 -0400668
Brad Bishopc33ae652017-11-02 22:23:09 -0400669 old_endpoints = assoc.Get(iface, 'endpoints') if assoc else []
Brad Bishop84041e32017-11-02 21:48:57 -0400670 new_endpoints = list(
671 set(old_endpoints).union(added).difference(removed))
672
673 if old_endpoints == new_endpoints:
674 return
675
676 create = [] if old_endpoints else [iface]
677 delete = [] if new_endpoints else [iface]
678
679 if create:
Brad Bishop63f59a72016-07-25 12:05:57 -0400680 self.manager.add(
Brad Bishop84041e32017-11-02 21:48:57 -0400681 path, Association(self.bus, path, new_endpoints))
682 elif delete:
Brad Bishop63f59a72016-07-25 12:05:57 -0400683 self.manager.remove(path)
Brad Bishop84041e32017-11-02 21:48:57 -0400684 else:
Brad Bishopc33ae652017-11-02 22:23:09 -0400685 assoc.Set(iface, 'endpoints', new_endpoints)
Brad Bishop63f59a72016-07-25 12:05:57 -0400686
687 if create != delete:
688 self.update_interfaces(
Andrew Geissler12469242018-01-02 09:41:37 -0600689 path, self.unique, delete, create)
Brad Bishop63f59a72016-07-25 12:05:57 -0400690
691 def update_associations(
692 self, path, owner, old, new, created=[], destroyed=[]):
693 added = list(set(new).difference(old))
694 removed = list(set(old).difference(new))
695 for forward, reverse, endpoint in added:
Brad Bishopb15b6312017-11-01 16:34:13 -0400696 if not endpoint:
697 # skip associations without an endpoint
698 continue
699
Brad Bishop63f59a72016-07-25 12:05:57 -0400700 # update the index
701 forward_path = str(path + '/' + forward)
702 reverse_path = str(endpoint + '/' + reverse)
703 self.index_append(
704 'forward', path, owner, reverse_path)
705 self.index_append(
706 'reverse', endpoint, owner, forward_path)
707
708 # create the association if the endpoint exists
709 if not self.cache_get(endpoint):
710 continue
711
712 self.update_association(forward_path, [], [endpoint])
713 self.update_association(reverse_path, [], [path])
714
715 for forward, reverse, endpoint in removed:
716 # update the index
717 forward_path = str(path + '/' + forward)
718 reverse_path = str(endpoint + '/' + reverse)
719 self.index_remove(
720 'forward', path, owner, reverse_path)
721 self.index_remove(
722 'reverse', endpoint, owner, forward_path)
723
724 # destroy the association if it exists
725 self.update_association(forward_path, [endpoint], [])
726 self.update_association(reverse_path, [path], [])
727
728 # If the associations interface endpoint comes
729 # or goes create or destroy the appropriate
730 # associations
731 for path in created:
732 for forward, reverse, endpoint in \
733 self.index_get_associations(path, direction='reverse'):
734 forward_path = str(path + '/' + forward)
735 reverse_path = str(endpoint + '/' + reverse)
736 self.update_association(forward_path, [], [endpoint])
737 self.update_association(reverse_path, [], [path])
738
739 for path in destroyed:
740 for forward, reverse, endpoint in \
741 self.index_get_associations(path, direction='reverse'):
742 forward_path = str(path + '/' + forward)
743 reverse_path = str(endpoint + '/' + reverse)
744 self.update_association(forward_path, [endpoint], [])
745 self.update_association(reverse_path, [path], [])
746
Brad Bishop1c33c222016-11-02 00:08:46 -0400747 @dbus.service.method(obmc.mapper.MAPPER_IFACE, 'sas', 'a{sa{sas}}')
748 def GetAncestors(self, path, interfaces):
Brad Bishop495ee092016-11-02 00:11:11 -0400749 if not self.cache_get(path):
750 raise MapperNotFoundException(path)
751
Balaji B Rao84e331a2017-11-09 21:19:13 -0600752 elements = list(filter(bool, path.split('/')))
Brad Bishop63f59a72016-07-25 12:05:57 -0400753 paths = []
754 objs = {}
755 while elements:
756 elements.pop()
757 paths.append('/' + '/'.join(elements))
758 if path != '/':
759 paths.append('/')
760
761 for path in paths:
762 obj = self.cache_get(path)
763 if not obj:
764 continue
765 objs[path] = obj
766
Balaji B Rao84e331a2017-11-09 21:19:13 -0600767 return self.filter_interfaces(list(objs.items()), interfaces)
Brad Bishop63f59a72016-07-25 12:05:57 -0400768
Brad Bishop829181d2017-02-24 09:49:14 -0500769 @dbus.service.signal(obmc.mapper.MAPPER_IFACE + '.Private', 's')
770 def IntrospectionComplete(self, name):
771 pass
772
Brad Bishop63f59a72016-07-25 12:05:57 -0400773
Brad Bishopcb2e1b32017-07-09 20:11:35 -0400774def server_main(
775 path_namespaces,
776 interface_namespaces,
777 blacklists,
778 interface_blacklists):
Brad Bishop63f59a72016-07-25 12:05:57 -0400779 dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
780 bus = dbus.SystemBus()
Brad Bishopcb2e1b32017-07-09 20:11:35 -0400781 o = ObjectMapper(
782 bus,
783 obmc.mapper.MAPPER_PATH,
784 path_namespaces,
785 interface_namespaces,
786 blacklists,
787 interface_blacklists)
Brad Bishop63f59a72016-07-25 12:05:57 -0400788 loop = gobject.MainLoop()
789
790 loop.run()