blob: a6df2240b3533a6c45b11a3fcd6876cf39e458c6 [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)
Brad Bishop63f59a72016-07-25 12:05:57 -0400209 self.bus_map = {}
Brad Bishop2e0436c2016-09-19 18:02:19 -0400210 self.defer_signals = {}
Brad Bishopcb2e1b32017-07-09 20:11:35 -0400211 self.namespaces = namespaces
212 self.interface_namespaces = interface_namespaces
213 self.blacklist = blacklist
214 self.blacklist.append(obmc.mapper.MAPPER_PATH)
215 self.interface_blacklist = interface_blacklist
Brad Bishop63f59a72016-07-25 12:05:57 -0400216
Brad Bishop5d4890c2016-09-19 11:28:47 -0400217 # add my object mananger instance
Brad Bishop57255f62018-01-29 15:26:06 -0500218 self.add_new_objmgr(
219 obmc.dbuslib.bindings.OBJ_PREFIX, obmc.mapper.MAPPER_NAME)
Brad Bishop5d4890c2016-09-19 11:28:47 -0400220
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
Balaji B Rao84e331a2017-11-09 21:19:13 -0600245 print("ObjectMapper startup complete. Discovery in progress...")
Brad Bishop5d4890c2016-09-19 11:28:47 -0400246 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
Balaji B Rao84e331a2017-11-09 21:19:13 -0600252 print("ObjectMapper discovery complete")
Brad Bishop5d4890c2016-09-19 11:28:47 -0400253 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 Bishop7a790272017-12-14 21:25:24 -0500273
274 # Safe to add a reference to the traceback here,
275 # since it cannot contain the discovery_error frame.
276 exctype, value, tb = sys.exc_info()
Brad Bishop99b8bc82017-07-29 21:39:52 -0400277 sys.stderr.write(
Brad Bishop57255f62018-01-29 15:26:06 -0500278 '{} discovery failure on {}\n'.format(owner, path))
Brad Bishop7a790272017-12-14 21:25:24 -0500279 if tb:
280 traceback.print_exception(exctype, value, tb, file=sys.stderr)
281 else:
282 sys.stderr.write('{}: {}\n'.format(e.__class__.__name__, e))
283
Brad Bishop99b8bc82017-07-29 21:39:52 -0400284 del self.defer_signals[owner]
285 del self.bus_map[owner]
Brad Bishop2e0436c2016-09-19 18:02:19 -0400286
Brad Bishop63f59a72016-07-25 12:05:57 -0400287 def cache_get(self, path):
288 cache_entry = self.cache.get(path, {})
289 if cache_entry is None:
290 # hide path elements without any interfaces
291 cache_entry = {}
292 return cache_entry
293
294 def add_new_objmgr(self, path, owner):
295 # We don't get a signal for the ObjectManager
296 # interface itself, so if we see a signal from
297 # make sure its in our cache, and add it if not.
298 cache_entry = self.cache_get(path)
299 old = self.interfaces_get(cache_entry, owner)
300 new = list(set(old).union([dbus.BUS_DAEMON_IFACE + '.ObjectManager']))
301 self.update_interfaces(path, owner, old, new)
302
Brad Bishop2e0436c2016-09-19 18:02:19 -0400303 def defer_signal(self, owner, callback):
304 self.defer_signals.setdefault(owner, []).append(callback)
305
Brad Bishop63f59a72016-07-25 12:05:57 -0400306 def interfaces_added_handler(self, path, iprops, **kw):
307 path = str(path)
Brad Bishop57255f62018-01-29 15:26:06 -0500308 owner = self.bus_normalize(str(kw['sender']))
309 if not owner:
Brad Bishop787aa812018-01-28 23:42:03 -0500310 return
311 interfaces = self.filter_signal_interfaces(iter(iprops.keys()))
Brad Bishop2e0436c2016-09-19 18:02:19 -0400312 if not interfaces:
313 return
314
315 if owner not in self.defer_signals:
Brad Bishop63f59a72016-07-25 12:05:57 -0400316 self.add_new_objmgr(str(kw['sender_path']), owner)
317 cache_entry = self.cache_get(path)
318 old = self.interfaces_get(cache_entry, owner)
319 new = list(set(interfaces).union(old))
Brad Bishopa6235962017-06-07 23:56:54 -0400320 new = {x: iprops.get(x, {}) for x in new}
Brad Bishop63f59a72016-07-25 12:05:57 -0400321 self.update_interfaces(path, owner, old, new)
Brad Bishop2e0436c2016-09-19 18:02:19 -0400322 else:
323 self.defer_signal(
324 owner,
325 lambda: self.interfaces_added_handler(
326 path, iprops, **kw))
Brad Bishop63f59a72016-07-25 12:05:57 -0400327
328 def interfaces_removed_handler(self, path, interfaces, **kw):
329 path = str(path)
Brad Bishop57255f62018-01-29 15:26:06 -0500330 owner = self.bus_normalize(str(kw['sender']))
331 if not owner:
Brad Bishop787aa812018-01-28 23:42:03 -0500332 return
333 interfaces = self.filter_signal_interfaces(interfaces)
Brad Bishop2e0436c2016-09-19 18:02:19 -0400334 if not interfaces:
335 return
336
337 if owner not in self.defer_signals:
Brad Bishop63f59a72016-07-25 12:05:57 -0400338 self.add_new_objmgr(str(kw['sender_path']), owner)
339 cache_entry = self.cache_get(path)
340 old = self.interfaces_get(cache_entry, owner)
341 new = list(set(old).difference(interfaces))
342 self.update_interfaces(path, owner, old, new)
Brad Bishop2e0436c2016-09-19 18:02:19 -0400343 else:
344 self.defer_signal(
345 owner,
346 lambda: self.interfaces_removed_handler(
347 path, interfaces, **kw))
Brad Bishop63f59a72016-07-25 12:05:57 -0400348
349 def properties_changed_handler(self, interface, new, old, **kw):
Brad Bishop57255f62018-01-29 15:26:06 -0500350 owner = self.bus_normalize(str(kw['sender']))
Brad Bishop63f59a72016-07-25 12:05:57 -0400351 path = str(kw['path'])
Brad Bishop57255f62018-01-29 15:26:06 -0500352 if not owner:
Brad Bishop787aa812018-01-28 23:42:03 -0500353 return
354 interfaces = self.filter_signal_interfaces([interface])
Brad Bishop63f59a72016-07-25 12:05:57 -0400355 if not self.is_association(interfaces):
356 return
357 associations = new.get('associations', None)
358 if associations is None:
359 return
360
Brad Bishop2e0436c2016-09-19 18:02:19 -0400361 if owner not in self.defer_signals:
362 associations = [
363 (str(x), str(y), str(z)) for x, y, z in associations]
364 self.update_associations(
365 path, owner,
366 self.index_get_associations(path, [owner]),
367 associations)
368 else:
369 self.defer_signal(
370 owner,
371 lambda: self.properties_changed_handler(
372 interface, new, old, **kw))
Brad Bishop63f59a72016-07-25 12:05:57 -0400373
374 def process_new_owner(self, owned_name, owner):
375 # unique name
376 try:
377 return self.discover([(owned_name, owner)])
Balaji B Rao84e331a2017-11-09 21:19:13 -0600378 except dbus.exceptions.DBusException as e:
Brad Bishop63f59a72016-07-25 12:05:57 -0400379 if obmc.dbuslib.enums.DBUS_UNKNOWN_SERVICE \
380 not in e.get_dbus_name():
381 raise
382
383 def process_old_owner(self, owned_name, owner):
384 if owner in self.bus_map:
385 del self.bus_map[owner]
386
387 for path, item in self.cache.dataitems():
Brad Bishop57255f62018-01-29 15:26:06 -0500388 old = self.interfaces_get(item, owned_name)
Brad Bishop63f59a72016-07-25 12:05:57 -0400389 # remove all interfaces for this service
390 self.update_interfaces(
Brad Bishop57255f62018-01-29 15:26:06 -0500391 path, owned_name, old=old, new=[])
Brad Bishop63f59a72016-07-25 12:05:57 -0400392
393 def bus_handler(self, owned_name, old, new):
Brad Bishop45271cb2018-01-28 23:56:05 -0500394 if obmc.dbuslib.bindings.is_unique(owned_name) or \
395 owned_name == obmc.mapper.MAPPER_NAME:
396 return
Brad Bishop63f59a72016-07-25 12:05:57 -0400397
Brad Bishop45271cb2018-01-28 23:56:05 -0500398 if new:
Brad Bishop63f59a72016-07-25 12:05:57 -0400399 self.process_new_owner(owned_name, new)
Brad Bishop45271cb2018-01-28 23:56:05 -0500400 if old:
Brad Bishop2e0436c2016-09-19 18:02:19 -0400401 # discard any unhandled signals
402 # or in progress discovery
Brad Bishop57255f62018-01-29 15:26:06 -0500403 if owned_name in self.defer_signals:
404 del self.defer_signals[owned_name]
Brad Bishop2e0436c2016-09-19 18:02:19 -0400405
Brad Bishop63f59a72016-07-25 12:05:57 -0400406 self.process_old_owner(owned_name, old)
407
408 def update_interfaces(self, path, owner, old, new):
409 # __xx -> intf list
410 # xx -> intf dict
411 if isinstance(old, dict):
Balaji B Rao84e331a2017-11-09 21:19:13 -0600412 __old = list(old.keys())
Brad Bishop63f59a72016-07-25 12:05:57 -0400413 else:
414 __old = old
415 old = {x: {} for x in old}
416 if isinstance(new, dict):
Balaji B Rao84e331a2017-11-09 21:19:13 -0600417 __new = list(new.keys())
Brad Bishop63f59a72016-07-25 12:05:57 -0400418 else:
419 __new = new
420 new = {x: {} for x in new}
421
422 cache_entry = self.cache.setdefault(path, {})
423 created = [] if self.has_interfaces(cache_entry) else [path]
424 added = list(set(__new).difference(__old))
425 removed = list(set(__old).difference(__new))
426 self.interfaces_append(cache_entry, owner, added)
427 self.interfaces_remove(cache_entry, owner, removed, path)
428 destroyed = [] if self.has_interfaces(cache_entry) else [path]
429
430 # react to anything that requires association updates
431 new_assoc = []
432 old_assoc = []
433 if self.is_association(added):
Brad Bishop926b35d2016-09-19 14:20:04 -0400434 iface = obmc.dbuslib.enums.OBMC_ASSOCIATIONS_IFACE
435 new_assoc = new[iface]['associations']
Brad Bishop63f59a72016-07-25 12:05:57 -0400436 if self.is_association(removed):
437 old_assoc = self.index_get_associations(path, [owner])
438 self.update_associations(
439 path, owner, old_assoc, new_assoc, created, destroyed)
440
441 def add_items(self, owner, bus_items):
Balaji B Rao84e331a2017-11-09 21:19:13 -0600442 for path, items in bus_items.items():
Brad Bishop63f59a72016-07-25 12:05:57 -0400443 self.update_interfaces(path, str(owner), old=[], new=items)
444
Brad Bishopcb2e1b32017-07-09 20:11:35 -0400445 def path_match(self, path):
446 match = False
447
448 if not any([x for x in self.blacklist if x in path]):
449 # not blacklisted
450
451 if any([x for x in self.namespaces if x in path]):
452 # a watched namespace contains the path
453 match = True
454 elif any([path for x in self.namespaces if path in x]):
455 # the path contains a watched namespace
456 match = True
457
458 return match
459
460 def interface_match(self, interface):
461 match = True
462
463 if any([x for x in self.interface_blacklist if x in interface]):
464 # not blacklisted
465 match = False
466 elif not any([x for x in self.interface_namespaces if x in interface]):
467 # the interface contains a watched interface namespace
468 match = False
469
470 return match
471
Andrew Geissler140f4102018-02-19 08:31:05 -0800472 def discovery_error_retry(self, owner, path, e):
473 sys.stderr.write(
474 '{} discovery failure on {} - retry\n'.format(owner, path))
475 find_dbus_interfaces(self.bus, owner, '/',
476 self.discovery_callback,
477 self.discovery_error,
478 subtree_match=self.path_match,
479 iface_match=self.interface_match)
480
Brad Bishop63f59a72016-07-25 12:05:57 -0400481 def discover(self, owners=[]):
Brad Bishop062403d2017-07-29 22:43:40 -0400482 def get_owner(name):
483 try:
484 return (name, self.bus.get_name_owner(name))
Adriana Kobylaka1f24222018-01-10 16:09:07 -0600485 except Exception:
Brad Bishop062403d2017-07-29 22:43:40 -0400486 traceback.print_exception(*sys.exc_info())
487
Brad Bishop63f59a72016-07-25 12:05:57 -0400488 if not owners:
Brad Bishopcabc6382018-01-29 15:39:07 -0500489 owned_names = [
490 x for x in self.bus.list_names()
491 if not obmc.dbuslib.bindings.is_unique(x)]
492 owners = list(
493 filter(bool, [get_owner(name) for name in owned_names]))
Brad Bishop63f59a72016-07-25 12:05:57 -0400494 for owned_name, o in owners:
Brad Bishop5c5e13e2018-01-28 23:34:54 -0500495 if not self.bus_normalize(owned_name):
Brad Bishopaeac98b2017-07-29 22:56:48 -0400496 continue
Andrew Geissler12469242018-01-02 09:41:37 -0600497 self.bus_map[o] = owned_name
Brad Bishop57255f62018-01-29 15:26:06 -0500498 self.defer_signals[owned_name] = []
Brad Bishop520473f2016-09-19 21:46:36 -0400499 find_dbus_interfaces(
Brad Bishop57255f62018-01-29 15:26:06 -0500500 self.bus, owned_name, '/',
Brad Bishop520473f2016-09-19 21:46:36 -0400501 self.discovery_callback,
Andrew Geissler140f4102018-02-19 08:31:05 -0800502 self.discovery_error_retry,
Brad Bishopcb2e1b32017-07-09 20:11:35 -0400503 subtree_match=self.path_match,
504 iface_match=self.interface_match)
Brad Bishop63f59a72016-07-25 12:05:57 -0400505
Brad Bishop5c5e13e2018-01-28 23:34:54 -0500506 def bus_normalize(self, name):
507 '''
508 Normalize on well-known names and filter signals
509 originating from the mapper.
510 '''
511
Brad Bishop63f59a72016-07-25 12:05:57 -0400512 if obmc.dbuslib.bindings.is_unique(name):
513 name = self.bus_map.get(name)
514
Brad Bishop5c5e13e2018-01-28 23:34:54 -0500515 if name == obmc.mapper.MAPPER_NAME:
516 return None
517
518 return name
Brad Bishop63f59a72016-07-25 12:05:57 -0400519
Brad Bishop787aa812018-01-28 23:42:03 -0500520 def filter_signal_interfaces(self, interfaces):
521 return [str(x) for x in interfaces if self.interface_match(x)]
Brad Bishop63f59a72016-07-25 12:05:57 -0400522
523 @staticmethod
524 def interfaces_get(item, owner, default=[]):
525 return item.get(owner, default)
526
527 @staticmethod
528 def interfaces_append(item, owner, append):
529 interfaces = item.setdefault(owner, [])
530 item[owner] = list(set(append).union(interfaces))
531
532 def interfaces_remove(self, item, owner, remove, path):
533 interfaces = item.get(owner, [])
534 item[owner] = list(set(interfaces).difference(remove))
535
536 if not item[owner]:
537 # remove the owner if there aren't any interfaces left
538 del item[owner]
539
540 if item:
541 # other owners remain
542 return
543
544 if self.cache.get_children(path):
545 # there are still references to this path
546 # from objects further down the tree.
547 # mark it for removal if that changes
548 self.cache.demote(path)
549 else:
550 # delete the entire path if everything is gone
551 del self.cache[path]
552
Brad Bishop1c33c222016-11-02 00:08:46 -0400553 @staticmethod
554 def filter_interfaces(item, ifaces):
555 if isinstance(item, dict):
556 # Called with a single object.
557 if not ifaces:
558 return item
559
560 # Remove interfaces from a service that
561 # aren't in a filter.
Adriana Kobylak7f42ad22018-01-16 12:15:23 -0600562 svc_map = lambda svc: (
Brad Bishop1c33c222016-11-02 00:08:46 -0400563 svc[0],
564 list(set(ifaces).intersection(svc[1])))
565
566 # Remove services where no interfaces remain after mapping.
Adriana Kobylak7f42ad22018-01-16 12:15:23 -0600567 svc_filter = lambda svc: svc[1]
Brad Bishop1c33c222016-11-02 00:08:46 -0400568
Adriana Kobylak7f42ad22018-01-16 12:15:23 -0600569 obj_map = lambda o: (
Balaji B Rao84e331a2017-11-09 21:19:13 -0600570 tuple(*list(filter(svc_filter, list(map(svc_map, [o]))))))
Brad Bishop1c33c222016-11-02 00:08:46 -0400571
Balaji B Rao84e331a2017-11-09 21:19:13 -0600572 return dict([x for x in map(obj_map, iter(item.items())) if x])
Brad Bishop1c33c222016-11-02 00:08:46 -0400573
574 # Called with a list of path/object tuples.
575 if not ifaces:
576 return dict(item)
577
Adriana Kobylak7f42ad22018-01-16 12:15:23 -0600578 obj_map = lambda x: (
Brad Bishop1c33c222016-11-02 00:08:46 -0400579 x[0],
580 ObjectMapper.filter_interfaces(
581 x[1],
582 ifaces))
583
Balaji B Rao84e331a2017-11-09 21:19:13 -0600584 return dict([x for x in map(obj_map, iter(item or [])) if x[1]])
Brad Bishop1c33c222016-11-02 00:08:46 -0400585
586 @dbus.service.method(obmc.mapper.MAPPER_IFACE, 'sas', 'a{sas}')
587 def GetObject(self, path, interfaces):
Brad Bishop63f59a72016-07-25 12:05:57 -0400588 o = self.cache_get(path)
589 if not o:
590 raise MapperNotFoundException(path)
Brad Bishop63f59a72016-07-25 12:05:57 -0400591
Brad Bishop1c33c222016-11-02 00:08:46 -0400592 return self.filter_interfaces(o, interfaces)
593
594 @dbus.service.method(obmc.mapper.MAPPER_IFACE, 'sias', 'as')
595 def GetSubTreePaths(self, path, depth, interfaces):
Brad Bishop63f59a72016-07-25 12:05:57 -0400596 try:
Brad Bishop24301972017-06-23 13:40:07 -0400597 return self.filter_interfaces(
598 self.cache.iteritems(path, depth),
599 interfaces)
Brad Bishop63f59a72016-07-25 12:05:57 -0400600 except KeyError:
601 raise MapperNotFoundException(path)
602
Brad Bishop1c33c222016-11-02 00:08:46 -0400603 @dbus.service.method(obmc.mapper.MAPPER_IFACE, 'sias', 'a{sa{sas}}')
604 def GetSubTree(self, path, depth, interfaces):
Brad Bishop63f59a72016-07-25 12:05:57 -0400605 try:
Brad Bishop1c33c222016-11-02 00:08:46 -0400606 return self.filter_interfaces(
607 self.cache.dataitems(path, depth),
608 interfaces)
Brad Bishop63f59a72016-07-25 12:05:57 -0400609 except KeyError:
610 raise MapperNotFoundException(path)
611
612 @staticmethod
613 def has_interfaces(item):
Balaji B Rao84e331a2017-11-09 21:19:13 -0600614 for owner in item.keys():
Brad Bishop63f59a72016-07-25 12:05:57 -0400615 if ObjectMapper.interfaces_get(item, owner):
616 return True
617 return False
618
619 @staticmethod
620 def is_association(interfaces):
621 return obmc.dbuslib.enums.OBMC_ASSOCIATIONS_IFACE in interfaces
622
623 def index_get(self, index, path, owners):
624 items = []
625 item = self.index.get(index, {})
626 item = item.get(path, {})
627 for o in owners:
628 items.extend(item.get(o, []))
629 return items
630
631 def index_append(self, index, path, owner, assoc):
632 item = self.index.setdefault(index, {})
633 item = item.setdefault(path, {})
634 item = item.setdefault(owner, [])
635 item.append(assoc)
636
637 def index_remove(self, index, path, owner, assoc):
638 index = self.index.get(index, {})
639 owners = index.get(path, {})
640 items = owners.get(owner, [])
641 if assoc in items:
642 items.remove(assoc)
643 if not items:
644 del owners[owner]
645 if not owners:
646 del index[path]
647
Brad Bishop63f59a72016-07-25 12:05:57 -0400648 def index_get_associations(self, path, owners=[], direction='forward'):
649 forward = 'forward' if direction == 'forward' else 'reverse'
650 reverse = 'reverse' if direction == 'forward' else 'forward'
651
652 associations = []
653 if not owners:
654 index = self.index.get(forward, {})
Balaji B Rao84e331a2017-11-09 21:19:13 -0600655 owners = list(index.get(path, {}).keys())
Brad Bishop63f59a72016-07-25 12:05:57 -0400656
657 # f: forward
658 # r: reverse
659 for rassoc in self.index_get(forward, path, owners):
660 elements = rassoc.split('/')
661 rtype = ''.join(elements[-1:])
662 fendpoint = '/'.join(elements[:-1])
663 for fassoc in self.index_get(reverse, fendpoint, owners):
664 elements = fassoc.split('/')
665 ftype = ''.join(elements[-1:])
666 rendpoint = '/'.join(elements[:-1])
667 if rendpoint != path:
668 continue
669 associations.append((ftype, rtype, fendpoint))
670
671 return associations
672
673 def update_association(self, path, removed, added):
674 iface = obmc.dbuslib.enums.OBMC_ASSOC_IFACE
Brad Bishop8e1f4ab2017-11-02 20:44:17 -0400675 assoc = self.manager.get(path, None)
Brad Bishop63f59a72016-07-25 12:05:57 -0400676
Brad Bishopc33ae652017-11-02 22:23:09 -0400677 old_endpoints = assoc.Get(iface, 'endpoints') if assoc else []
Brad Bishop84041e32017-11-02 21:48:57 -0400678 new_endpoints = list(
679 set(old_endpoints).union(added).difference(removed))
680
681 if old_endpoints == new_endpoints:
682 return
683
684 create = [] if old_endpoints else [iface]
685 delete = [] if new_endpoints else [iface]
686
687 if create:
Brad Bishop63f59a72016-07-25 12:05:57 -0400688 self.manager.add(
Brad Bishop84041e32017-11-02 21:48:57 -0400689 path, Association(self.bus, path, new_endpoints))
690 elif delete:
Brad Bishop63f59a72016-07-25 12:05:57 -0400691 self.manager.remove(path)
Brad Bishop84041e32017-11-02 21:48:57 -0400692 else:
Brad Bishopc33ae652017-11-02 22:23:09 -0400693 assoc.Set(iface, 'endpoints', new_endpoints)
Brad Bishop63f59a72016-07-25 12:05:57 -0400694
695 if create != delete:
696 self.update_interfaces(
Brad Bishop57255f62018-01-29 15:26:06 -0500697 path, obmc.mapper.MAPPER_NAME, delete, create)
Brad Bishop63f59a72016-07-25 12:05:57 -0400698
699 def update_associations(
700 self, path, owner, old, new, created=[], destroyed=[]):
701 added = list(set(new).difference(old))
702 removed = list(set(old).difference(new))
703 for forward, reverse, endpoint in added:
Brad Bishopb15b6312017-11-01 16:34:13 -0400704 if not endpoint:
705 # skip associations without an endpoint
706 continue
707
Brad Bishop63f59a72016-07-25 12:05:57 -0400708 # update the index
709 forward_path = str(path + '/' + forward)
710 reverse_path = str(endpoint + '/' + reverse)
711 self.index_append(
712 'forward', path, owner, reverse_path)
713 self.index_append(
714 'reverse', endpoint, owner, forward_path)
715
716 # create the association if the endpoint exists
717 if not self.cache_get(endpoint):
718 continue
719
720 self.update_association(forward_path, [], [endpoint])
721 self.update_association(reverse_path, [], [path])
722
723 for forward, reverse, endpoint in removed:
724 # update the index
725 forward_path = str(path + '/' + forward)
726 reverse_path = str(endpoint + '/' + reverse)
727 self.index_remove(
728 'forward', path, owner, reverse_path)
729 self.index_remove(
730 'reverse', endpoint, owner, forward_path)
731
732 # destroy the association if it exists
733 self.update_association(forward_path, [endpoint], [])
734 self.update_association(reverse_path, [path], [])
735
736 # If the associations interface endpoint comes
737 # or goes create or destroy the appropriate
738 # associations
739 for path in created:
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
747 for path in destroyed:
748 for forward, reverse, endpoint in \
749 self.index_get_associations(path, direction='reverse'):
750 forward_path = str(path + '/' + forward)
751 reverse_path = str(endpoint + '/' + reverse)
752 self.update_association(forward_path, [endpoint], [])
753 self.update_association(reverse_path, [path], [])
754
Brad Bishop1c33c222016-11-02 00:08:46 -0400755 @dbus.service.method(obmc.mapper.MAPPER_IFACE, 'sas', 'a{sa{sas}}')
756 def GetAncestors(self, path, interfaces):
Brad Bishop495ee092016-11-02 00:11:11 -0400757 if not self.cache_get(path):
758 raise MapperNotFoundException(path)
759
Balaji B Rao84e331a2017-11-09 21:19:13 -0600760 elements = list(filter(bool, path.split('/')))
Brad Bishop63f59a72016-07-25 12:05:57 -0400761 paths = []
762 objs = {}
763 while elements:
764 elements.pop()
765 paths.append('/' + '/'.join(elements))
766 if path != '/':
767 paths.append('/')
768
769 for path in paths:
770 obj = self.cache_get(path)
771 if not obj:
772 continue
773 objs[path] = obj
774
Balaji B Rao84e331a2017-11-09 21:19:13 -0600775 return self.filter_interfaces(list(objs.items()), interfaces)
Brad Bishop63f59a72016-07-25 12:05:57 -0400776
Brad Bishop829181d2017-02-24 09:49:14 -0500777 @dbus.service.signal(obmc.mapper.MAPPER_IFACE + '.Private', 's')
778 def IntrospectionComplete(self, name):
779 pass
780
Brad Bishop63f59a72016-07-25 12:05:57 -0400781
Brad Bishopcb2e1b32017-07-09 20:11:35 -0400782def server_main(
783 path_namespaces,
784 interface_namespaces,
785 blacklists,
786 interface_blacklists):
Brad Bishop63f59a72016-07-25 12:05:57 -0400787 dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
788 bus = dbus.SystemBus()
Brad Bishopcb2e1b32017-07-09 20:11:35 -0400789 o = ObjectMapper(
790 bus,
791 obmc.mapper.MAPPER_PATH,
792 path_namespaces,
793 interface_namespaces,
794 blacklists,
795 interface_blacklists)
Brad Bishop63f59a72016-07-25 12:05:57 -0400796 loop = gobject.MainLoop()
797
798 loop.run()