blob: 5e51d6545b2ac7f451e8d2aaf5d5fc9ed3b97b2c [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
CamVan Nguyen2fd4b1f2018-03-05 12:19:46 -060021# TODO: openbmc/openbmc#2994 remove python 2 support
22try: # python 2
23 import gobject
24except ImportError: # python 3
25 from gi.repository import GObject as gobject
Brad Bishop63f59a72016-07-25 12:05:57 -040026import xml.etree.ElementTree as ET
27import obmc.utils.pathtree
Brad Bishop63f59a72016-07-25 12:05:57 -040028import obmc.mapper
29import obmc.dbuslib.bindings
30import obmc.dbuslib.enums
Brad Bishop99b8bc82017-07-29 21:39:52 -040031import sys
32import traceback
Brad Bishop63f59a72016-07-25 12:05:57 -040033
34
Brad Bishop2e0436c2016-09-19 18:02:19 -040035class MapperBusyException(dbus.exceptions.DBusException):
36 _dbus_error_name = 'org.freedesktop.DBus.Error.ObjectPathInUse'
37
38 def __init__(self):
39 super(MapperBusyException, self).__init__(
40 'busy processing bus traffic')
41
42
Brad Bishop63f59a72016-07-25 12:05:57 -040043class MapperNotFoundException(dbus.exceptions.DBusException):
44 _dbus_error_name = obmc.mapper.MAPPER_NOT_FOUND
45
46 def __init__(self, path):
47 super(MapperNotFoundException, self).__init__(
48 "path or object not found: %s" % path)
49
50
Brad Bishop520473f2016-09-19 21:46:36 -040051def find_dbus_interfaces(conn, service, path, callback, error_callback, **kw):
Brad Bishopbd8aa052016-09-19 09:30:06 -040052 iface_match = kw.pop('iface_match', bool)
Brad Bishop6a0320b2016-09-19 11:03:06 -040053 subtree_match = kw.pop('subtree_match', bool)
Brad Bishopbd8aa052016-09-19 09:30:06 -040054
Brad Bishop63f59a72016-07-25 12:05:57 -040055 class _FindInterfaces(object):
56 def __init__(self):
57 self.results = {}
Brad Bishop520473f2016-09-19 21:46:36 -040058 self.introspect_pending = []
59 self.gmo_pending = []
60 self.assoc_pending = []
Brad Bishop63f59a72016-07-25 12:05:57 -040061
62 @staticmethod
63 def _to_path(elements):
64 return '/' + '/'.join(elements)
65
66 @staticmethod
67 def _to_path_elements(path):
Balaji B Rao84e331a2017-11-09 21:19:13 -060068 return list(filter(bool, path.split('/')))
Brad Bishop63f59a72016-07-25 12:05:57 -040069
70 def __call__(self, path):
Brad Bishop520473f2016-09-19 21:46:36 -040071 try:
72 self._find_interfaces(path)
Balaji B Rao84e331a2017-11-09 21:19:13 -060073 except Exception as e:
Brad Bishop520473f2016-09-19 21:46:36 -040074 error_callback(service, path, e)
Brad Bishop63f59a72016-07-25 12:05:57 -040075
76 @staticmethod
77 def _match(iface):
78 return iface == dbus.BUS_DAEMON_IFACE + '.ObjectManager' \
Brad Bishopbd8aa052016-09-19 09:30:06 -040079 or iface_match(iface)
Brad Bishop63f59a72016-07-25 12:05:57 -040080
Brad Bishop520473f2016-09-19 21:46:36 -040081 def check_done(self):
82 if any([
83 self.introspect_pending,
84 self.gmo_pending,
85 self.assoc_pending]):
86 return
87
88 callback(service, self.results)
89
90 def _assoc_callback(self, path, associations):
91 try:
92 iface = obmc.dbuslib.enums.OBMC_ASSOCIATIONS_IFACE
93 self.assoc_pending.remove(path)
Gunnar Mills296395c2017-09-06 13:56:43 -050094 self.results[path][iface]['associations'] = associations
Balaji B Rao84e331a2017-11-09 21:19:13 -060095 except Exception as e:
Brad Bishop520473f2016-09-19 21:46:36 -040096 error_callback(service, path, e)
97 return None
98
99 self.check_done()
100
101 def _gmo_callback(self, path, objs):
102 try:
103 self.gmo_pending.remove(path)
CamVan Nguyen2fd4b1f2018-03-05 12:19:46 -0600104 for k, v in list(objs.items()):
Brad Bishopf9b24bf2018-04-02 16:46:32 -0400105 ifaces = {iface: properties for iface, properties in list(
106 filter(lambda x: iface_match(x[0]), v.items()))}
107 self.results[k] = ifaces
Balaji B Rao84e331a2017-11-09 21:19:13 -0600108 except Exception as e:
Brad Bishop520473f2016-09-19 21:46:36 -0400109 error_callback(service, path, e)
110 return None
111
112 self.check_done()
113
114 def _introspect_callback(self, path, data):
115 self.introspect_pending.remove(path)
116 if data is None:
117 self.check_done()
118 return
119
120 try:
121 path_elements = self._to_path_elements(path)
122 root = ET.fromstring(data)
Balaji B Rao84e331a2017-11-09 21:19:13 -0600123 ifaces = list(filter(
Brad Bishop520473f2016-09-19 21:46:36 -0400124 self._match,
Balaji B Rao84e331a2017-11-09 21:19:13 -0600125 [x.attrib.get('name') for x in root.findall('interface')]))
Brad Bishop520473f2016-09-19 21:46:36 -0400126 ifaces = {x: {} for x in ifaces}
127 self.results[path] = ifaces
128
129 if obmc.dbuslib.enums.OBMC_ASSOCIATIONS_IFACE in ifaces:
130 obj = conn.get_object(service, path, introspect=False)
131 iface = dbus.Interface(obj, dbus.PROPERTIES_IFACE)
132 self.assoc_pending.append(path)
133 iface.Get.call_async(
134 obmc.dbuslib.enums.OBMC_ASSOCIATIONS_IFACE,
135 'associations',
136 reply_handler=lambda x: self._assoc_callback(
137 path, x),
138 error_handler=lambda e: error_callback(
139 service, path, e))
140
141 if dbus.BUS_DAEMON_IFACE + '.ObjectManager' in ifaces:
142 obj = conn.get_object(service, path, introspect=False)
143 iface = dbus.Interface(
144 obj, dbus.BUS_DAEMON_IFACE + '.ObjectManager')
145 self.gmo_pending.append(path)
146 iface.GetManagedObjects.call_async(
147 reply_handler=lambda x: self._gmo_callback(
148 path, x),
149 error_handler=lambda e: error_callback(
150 service, path, e))
151 else:
Balaji B Rao84e331a2017-11-09 21:19:13 -0600152 children = list(filter(
Brad Bishop520473f2016-09-19 21:46:36 -0400153 bool,
Balaji B Rao84e331a2017-11-09 21:19:13 -0600154 [x.attrib.get('name') for x in root.findall('node')]))
Brad Bishop520473f2016-09-19 21:46:36 -0400155 children = [
156 self._to_path(
157 path_elements + self._to_path_elements(x))
158 for x in sorted(children)]
159 for child in filter(subtree_match, children):
160 if child not in self.results:
161 self._find_interfaces(child)
Balaji B Rao84e331a2017-11-09 21:19:13 -0600162 except Exception as e:
Brad Bishop520473f2016-09-19 21:46:36 -0400163 error_callback(service, path, e)
164 return None
165
166 self.check_done()
167
Brad Bishop63f59a72016-07-25 12:05:57 -0400168 def _find_interfaces(self, path):
169 path_elements = self._to_path_elements(path)
170 path = self._to_path(path_elements)
Brad Bishop520473f2016-09-19 21:46:36 -0400171 obj = conn.get_object(service, path, introspect=False)
172 iface = dbus.Interface(obj, dbus.INTROSPECTABLE_IFACE)
173 self.introspect_pending.append(path)
174 iface.Introspect.call_async(
175 reply_handler=lambda x: self._introspect_callback(path, x),
176 error_handler=lambda x: error_callback(service, path, x))
Brad Bishop63f59a72016-07-25 12:05:57 -0400177
178 return _FindInterfaces()(path)
179
180
Brad Bishopc33ae652017-11-02 22:23:09 -0400181@obmc.dbuslib.bindings.add_interfaces([obmc.dbuslib.enums.OBMC_ASSOC_IFACE])
182class Association(obmc.dbuslib.bindings.DbusProperties):
Brad Bishop734b2c32017-11-01 15:40:07 -0400183 """Implementation of org.openbmc.Association."""
184
Brad Bishopb9b3ed52017-11-01 21:40:31 -0400185 iface = obmc.dbuslib.enums.OBMC_ASSOC_IFACE
186
Brad Bishop63f59a72016-07-25 12:05:57 -0400187 def __init__(self, bus, path, endpoints):
Brad Bishop734b2c32017-11-01 15:40:07 -0400188 """Construct an Association.
189
190 Arguments:
191 bus -- The python-dbus connection to host the interface
192 path -- The D-Bus object path on which to implement the interface
193 endpoints -- A list of the initial association endpoints
194 """
Brad Bishop70dd5952016-09-08 22:33:33 -0400195 super(Association, self).__init__(conn=bus, object_path=path)
Brad Bishopb9b3ed52017-11-01 21:40:31 -0400196 self.properties = {self.iface: {'endpoints': endpoints}}
Brad Bishopbcc06442018-01-29 14:54:51 -0500197 self.unmask_signals()
Brad Bishop63f59a72016-07-25 12:05:57 -0400198
Brad Bishop63f59a72016-07-25 12:05:57 -0400199
200class Manager(obmc.dbuslib.bindings.DbusObjectManager):
201 def __init__(self, bus, path):
Brad Bishop70dd5952016-09-08 22:33:33 -0400202 super(Manager, self).__init__(conn=bus, object_path=path)
Brad Bishop63f59a72016-07-25 12:05:57 -0400203
204
205class ObjectMapper(dbus.service.Object):
Brad Bishopcb2e1b32017-07-09 20:11:35 -0400206 def __init__(
207 self, bus, path, namespaces, interface_namespaces,
208 blacklist, interface_blacklist):
Brad Bishop63f59a72016-07-25 12:05:57 -0400209 super(ObjectMapper, self).__init__(bus, path)
210 self.cache = obmc.utils.pathtree.PathTree()
211 self.bus = bus
Brad Bishop63f59a72016-07-25 12:05:57 -0400212 self.service = None
213 self.index = {}
214 self.manager = Manager(bus, obmc.dbuslib.bindings.OBJ_PREFIX)
Brad Bishop63f59a72016-07-25 12:05:57 -0400215 self.bus_map = {}
Brad Bishop2e0436c2016-09-19 18:02:19 -0400216 self.defer_signals = {}
Brad Bishopcb2e1b32017-07-09 20:11:35 -0400217 self.namespaces = namespaces
218 self.interface_namespaces = interface_namespaces
219 self.blacklist = blacklist
220 self.blacklist.append(obmc.mapper.MAPPER_PATH)
221 self.interface_blacklist = interface_blacklist
Brad Bishop63f59a72016-07-25 12:05:57 -0400222
Brad Bishop5d4890c2016-09-19 11:28:47 -0400223 # add my object mananger instance
Brad Bishop57255f62018-01-29 15:26:06 -0500224 self.add_new_objmgr(
225 obmc.dbuslib.bindings.OBJ_PREFIX, obmc.mapper.MAPPER_NAME)
Brad Bishop5d4890c2016-09-19 11:28:47 -0400226
Brad Bishop63f59a72016-07-25 12:05:57 -0400227 self.bus.add_signal_receiver(
228 self.bus_handler,
229 dbus_interface=dbus.BUS_DAEMON_IFACE,
230 signal_name='NameOwnerChanged')
231 self.bus.add_signal_receiver(
232 self.interfaces_added_handler,
233 dbus_interface=dbus.BUS_DAEMON_IFACE + '.ObjectManager',
234 signal_name='InterfacesAdded',
235 sender_keyword='sender',
236 path_keyword='sender_path')
237 self.bus.add_signal_receiver(
238 self.interfaces_removed_handler,
239 dbus_interface=dbus.BUS_DAEMON_IFACE + '.ObjectManager',
240 signal_name='InterfacesRemoved',
241 sender_keyword='sender',
242 path_keyword='sender_path')
243 self.bus.add_signal_receiver(
244 self.properties_changed_handler,
245 dbus_interface=dbus.PROPERTIES_IFACE,
246 signal_name='PropertiesChanged',
Brad Bishopb270adc2017-11-14 23:32:59 -0500247 arg0=obmc.dbuslib.enums.OBMC_ASSOCIATIONS_IFACE,
Brad Bishop63f59a72016-07-25 12:05:57 -0400248 path_keyword='path',
249 sender_keyword='sender')
250
Balaji B Rao84e331a2017-11-09 21:19:13 -0600251 print("ObjectMapper startup complete. Discovery in progress...")
Brad Bishop5d4890c2016-09-19 11:28:47 -0400252 self.discover()
Brad Bishop520473f2016-09-19 21:46:36 -0400253 gobject.idle_add(self.claim_name)
Brad Bishop5d4890c2016-09-19 11:28:47 -0400254
Brad Bishop520473f2016-09-19 21:46:36 -0400255 def claim_name(self):
256 if len(self.defer_signals):
257 return True
Balaji B Rao84e331a2017-11-09 21:19:13 -0600258 print("ObjectMapper discovery complete")
Brad Bishop5d4890c2016-09-19 11:28:47 -0400259 self.service = dbus.service.BusName(
260 obmc.mapper.MAPPER_NAME, self.bus)
Brad Bishop55b89cd2016-09-19 23:02:48 -0400261 self.manager.unmask_signals()
Brad Bishop520473f2016-09-19 21:46:36 -0400262 return False
Brad Bishop63f59a72016-07-25 12:05:57 -0400263
Brad Bishop2e0436c2016-09-19 18:02:19 -0400264 def discovery_callback(self, owner, items):
265 if owner in self.defer_signals:
266 self.add_items(owner, items)
267 pending = self.defer_signals[owner]
268 del self.defer_signals[owner]
269
270 for x in pending:
271 x()
Brad Bishop829181d2017-02-24 09:49:14 -0500272 self.IntrospectionComplete(owner)
Brad Bishop2e0436c2016-09-19 18:02:19 -0400273
274 def discovery_error(self, owner, path, e):
Brad Bishop99b8bc82017-07-29 21:39:52 -0400275 '''Log a message and remove all traces of the service
276 we were attempting to introspect.'''
277
Brad Bishop2e0436c2016-09-19 18:02:19 -0400278 if owner in self.defer_signals:
Brad Bishop7a790272017-12-14 21:25:24 -0500279
280 # Safe to add a reference to the traceback here,
281 # since it cannot contain the discovery_error frame.
282 exctype, value, tb = sys.exc_info()
Brad Bishop99b8bc82017-07-29 21:39:52 -0400283 sys.stderr.write(
Brad Bishop57255f62018-01-29 15:26:06 -0500284 '{} discovery failure on {}\n'.format(owner, path))
Brad Bishop7a790272017-12-14 21:25:24 -0500285 if tb:
286 traceback.print_exception(exctype, value, tb, file=sys.stderr)
287 else:
288 sys.stderr.write('{}: {}\n'.format(e.__class__.__name__, e))
289
Brad Bishop99b8bc82017-07-29 21:39:52 -0400290 del self.defer_signals[owner]
291 del self.bus_map[owner]
Brad Bishop2e0436c2016-09-19 18:02:19 -0400292
Brad Bishop63f59a72016-07-25 12:05:57 -0400293 def cache_get(self, path):
294 cache_entry = self.cache.get(path, {})
295 if cache_entry is None:
296 # hide path elements without any interfaces
297 cache_entry = {}
298 return cache_entry
299
300 def add_new_objmgr(self, path, owner):
301 # We don't get a signal for the ObjectManager
302 # interface itself, so if we see a signal from
303 # make sure its in our cache, and add it if not.
304 cache_entry = self.cache_get(path)
305 old = self.interfaces_get(cache_entry, owner)
306 new = list(set(old).union([dbus.BUS_DAEMON_IFACE + '.ObjectManager']))
307 self.update_interfaces(path, owner, old, new)
308
Brad Bishop2e0436c2016-09-19 18:02:19 -0400309 def defer_signal(self, owner, callback):
310 self.defer_signals.setdefault(owner, []).append(callback)
311
Brad Bishop63f59a72016-07-25 12:05:57 -0400312 def interfaces_added_handler(self, path, iprops, **kw):
313 path = str(path)
Brad Bishop57255f62018-01-29 15:26:06 -0500314 owner = self.bus_normalize(str(kw['sender']))
315 if not owner:
Brad Bishop787aa812018-01-28 23:42:03 -0500316 return
CamVan Nguyen2fd4b1f2018-03-05 12:19:46 -0600317 interfaces = self.filter_signal_interfaces(iter(list(iprops.keys())))
Brad Bishop2e0436c2016-09-19 18:02:19 -0400318 if not interfaces:
319 return
320
321 if owner not in self.defer_signals:
Brad Bishop63f59a72016-07-25 12:05:57 -0400322 self.add_new_objmgr(str(kw['sender_path']), owner)
323 cache_entry = self.cache_get(path)
324 old = self.interfaces_get(cache_entry, owner)
325 new = list(set(interfaces).union(old))
Brad Bishopa6235962017-06-07 23:56:54 -0400326 new = {x: iprops.get(x, {}) for x in new}
Brad Bishop63f59a72016-07-25 12:05:57 -0400327 self.update_interfaces(path, owner, old, new)
Brad Bishop2e0436c2016-09-19 18:02:19 -0400328 else:
329 self.defer_signal(
330 owner,
331 lambda: self.interfaces_added_handler(
332 path, iprops, **kw))
Brad Bishop63f59a72016-07-25 12:05:57 -0400333
334 def interfaces_removed_handler(self, path, interfaces, **kw):
335 path = str(path)
Brad Bishop57255f62018-01-29 15:26:06 -0500336 owner = self.bus_normalize(str(kw['sender']))
337 if not owner:
Brad Bishop787aa812018-01-28 23:42:03 -0500338 return
339 interfaces = self.filter_signal_interfaces(interfaces)
Brad Bishop2e0436c2016-09-19 18:02:19 -0400340 if not interfaces:
341 return
342
343 if owner not in self.defer_signals:
Brad Bishop63f59a72016-07-25 12:05:57 -0400344 self.add_new_objmgr(str(kw['sender_path']), owner)
345 cache_entry = self.cache_get(path)
346 old = self.interfaces_get(cache_entry, owner)
347 new = list(set(old).difference(interfaces))
348 self.update_interfaces(path, owner, old, new)
Brad Bishop2e0436c2016-09-19 18:02:19 -0400349 else:
350 self.defer_signal(
351 owner,
352 lambda: self.interfaces_removed_handler(
353 path, interfaces, **kw))
Brad Bishop63f59a72016-07-25 12:05:57 -0400354
355 def properties_changed_handler(self, interface, new, old, **kw):
Brad Bishop57255f62018-01-29 15:26:06 -0500356 owner = self.bus_normalize(str(kw['sender']))
Brad Bishop63f59a72016-07-25 12:05:57 -0400357 path = str(kw['path'])
Brad Bishop57255f62018-01-29 15:26:06 -0500358 if not owner:
Brad Bishop787aa812018-01-28 23:42:03 -0500359 return
360 interfaces = self.filter_signal_interfaces([interface])
Brad Bishop63f59a72016-07-25 12:05:57 -0400361 if not self.is_association(interfaces):
362 return
363 associations = new.get('associations', None)
364 if associations is None:
365 return
366
Brad Bishop2e0436c2016-09-19 18:02:19 -0400367 if owner not in self.defer_signals:
368 associations = [
369 (str(x), str(y), str(z)) for x, y, z in associations]
370 self.update_associations(
371 path, owner,
372 self.index_get_associations(path, [owner]),
373 associations)
374 else:
375 self.defer_signal(
376 owner,
377 lambda: self.properties_changed_handler(
378 interface, new, old, **kw))
Brad Bishop63f59a72016-07-25 12:05:57 -0400379
380 def process_new_owner(self, owned_name, owner):
381 # unique name
382 try:
383 return self.discover([(owned_name, owner)])
Balaji B Rao84e331a2017-11-09 21:19:13 -0600384 except dbus.exceptions.DBusException as e:
Brad Bishop63f59a72016-07-25 12:05:57 -0400385 if obmc.dbuslib.enums.DBUS_UNKNOWN_SERVICE \
386 not in e.get_dbus_name():
387 raise
388
389 def process_old_owner(self, owned_name, owner):
390 if owner in self.bus_map:
391 del self.bus_map[owner]
392
393 for path, item in self.cache.dataitems():
Brad Bishop57255f62018-01-29 15:26:06 -0500394 old = self.interfaces_get(item, owned_name)
Brad Bishop63f59a72016-07-25 12:05:57 -0400395 # remove all interfaces for this service
396 self.update_interfaces(
Brad Bishop57255f62018-01-29 15:26:06 -0500397 path, owned_name, old=old, new=[])
Brad Bishop63f59a72016-07-25 12:05:57 -0400398
399 def bus_handler(self, owned_name, old, new):
Brad Bishop45271cb2018-01-28 23:56:05 -0500400 if obmc.dbuslib.bindings.is_unique(owned_name) or \
401 owned_name == obmc.mapper.MAPPER_NAME:
402 return
Brad Bishop63f59a72016-07-25 12:05:57 -0400403
Brad Bishop45271cb2018-01-28 23:56:05 -0500404 if new:
Brad Bishop63f59a72016-07-25 12:05:57 -0400405 self.process_new_owner(owned_name, new)
Brad Bishop45271cb2018-01-28 23:56:05 -0500406 if old:
Brad Bishop2e0436c2016-09-19 18:02:19 -0400407 # discard any unhandled signals
408 # or in progress discovery
Brad Bishop57255f62018-01-29 15:26:06 -0500409 if owned_name in self.defer_signals:
410 del self.defer_signals[owned_name]
Brad Bishop2e0436c2016-09-19 18:02:19 -0400411
Brad Bishop63f59a72016-07-25 12:05:57 -0400412 self.process_old_owner(owned_name, old)
413
414 def update_interfaces(self, path, owner, old, new):
415 # __xx -> intf list
416 # xx -> intf dict
417 if isinstance(old, dict):
Balaji B Rao84e331a2017-11-09 21:19:13 -0600418 __old = list(old.keys())
Brad Bishop63f59a72016-07-25 12:05:57 -0400419 else:
420 __old = old
421 old = {x: {} for x in old}
422 if isinstance(new, dict):
Balaji B Rao84e331a2017-11-09 21:19:13 -0600423 __new = list(new.keys())
Brad Bishop63f59a72016-07-25 12:05:57 -0400424 else:
425 __new = new
426 new = {x: {} for x in new}
427
428 cache_entry = self.cache.setdefault(path, {})
429 created = [] if self.has_interfaces(cache_entry) else [path]
430 added = list(set(__new).difference(__old))
431 removed = list(set(__old).difference(__new))
432 self.interfaces_append(cache_entry, owner, added)
433 self.interfaces_remove(cache_entry, owner, removed, path)
434 destroyed = [] if self.has_interfaces(cache_entry) else [path]
435
436 # react to anything that requires association updates
437 new_assoc = []
438 old_assoc = []
439 if self.is_association(added):
Brad Bishop926b35d2016-09-19 14:20:04 -0400440 iface = obmc.dbuslib.enums.OBMC_ASSOCIATIONS_IFACE
441 new_assoc = new[iface]['associations']
Brad Bishop63f59a72016-07-25 12:05:57 -0400442 if self.is_association(removed):
443 old_assoc = self.index_get_associations(path, [owner])
444 self.update_associations(
445 path, owner, old_assoc, new_assoc, created, destroyed)
446
447 def add_items(self, owner, bus_items):
CamVan Nguyen2fd4b1f2018-03-05 12:19:46 -0600448 for path, items in list(bus_items.items()):
Brad Bishop63f59a72016-07-25 12:05:57 -0400449 self.update_interfaces(path, str(owner), old=[], new=items)
450
Brad Bishopcb2e1b32017-07-09 20:11:35 -0400451 def path_match(self, path):
452 match = False
453
454 if not any([x for x in self.blacklist if x in path]):
455 # not blacklisted
456
457 if any([x for x in self.namespaces if x in path]):
458 # a watched namespace contains the path
459 match = True
460 elif any([path for x in self.namespaces if path in x]):
461 # the path contains a watched namespace
462 match = True
463
464 return match
465
466 def interface_match(self, interface):
467 match = True
468
469 if any([x for x in self.interface_blacklist if x in interface]):
470 # not blacklisted
471 match = False
472 elif not any([x for x in self.interface_namespaces if x in interface]):
473 # the interface contains a watched interface namespace
474 match = False
475
476 return match
477
Andrew Geissler140f4102018-02-19 08:31:05 -0800478 def discovery_error_retry(self, owner, path, e):
479 sys.stderr.write(
480 '{} discovery failure on {} - retry\n'.format(owner, path))
481 find_dbus_interfaces(self.bus, owner, '/',
482 self.discovery_callback,
483 self.discovery_error,
484 subtree_match=self.path_match,
485 iface_match=self.interface_match)
486
Brad Bishop63f59a72016-07-25 12:05:57 -0400487 def discover(self, owners=[]):
Brad Bishop062403d2017-07-29 22:43:40 -0400488 def get_owner(name):
489 try:
490 return (name, self.bus.get_name_owner(name))
Adriana Kobylaka1f24222018-01-10 16:09:07 -0600491 except Exception:
Brad Bishop062403d2017-07-29 22:43:40 -0400492 traceback.print_exception(*sys.exc_info())
493
Brad Bishop63f59a72016-07-25 12:05:57 -0400494 if not owners:
Brad Bishopcabc6382018-01-29 15:39:07 -0500495 owned_names = [
496 x for x in self.bus.list_names()
497 if not obmc.dbuslib.bindings.is_unique(x)]
498 owners = list(
499 filter(bool, [get_owner(name) for name in owned_names]))
Brad Bishop63f59a72016-07-25 12:05:57 -0400500 for owned_name, o in owners:
Brad Bishop5c5e13e2018-01-28 23:34:54 -0500501 if not self.bus_normalize(owned_name):
Brad Bishopaeac98b2017-07-29 22:56:48 -0400502 continue
Andrew Geissler12469242018-01-02 09:41:37 -0600503 self.bus_map[o] = owned_name
Brad Bishop57255f62018-01-29 15:26:06 -0500504 self.defer_signals[owned_name] = []
Brad Bishop520473f2016-09-19 21:46:36 -0400505 find_dbus_interfaces(
Brad Bishop57255f62018-01-29 15:26:06 -0500506 self.bus, owned_name, '/',
Brad Bishop520473f2016-09-19 21:46:36 -0400507 self.discovery_callback,
Andrew Geissler140f4102018-02-19 08:31:05 -0800508 self.discovery_error_retry,
Brad Bishopcb2e1b32017-07-09 20:11:35 -0400509 subtree_match=self.path_match,
510 iface_match=self.interface_match)
Brad Bishop63f59a72016-07-25 12:05:57 -0400511
Brad Bishop5c5e13e2018-01-28 23:34:54 -0500512 def bus_normalize(self, name):
513 '''
514 Normalize on well-known names and filter signals
515 originating from the mapper.
516 '''
517
Brad Bishop63f59a72016-07-25 12:05:57 -0400518 if obmc.dbuslib.bindings.is_unique(name):
519 name = self.bus_map.get(name)
520
Brad Bishop5c5e13e2018-01-28 23:34:54 -0500521 if name == obmc.mapper.MAPPER_NAME:
522 return None
523
524 return name
Brad Bishop63f59a72016-07-25 12:05:57 -0400525
Brad Bishop787aa812018-01-28 23:42:03 -0500526 def filter_signal_interfaces(self, interfaces):
527 return [str(x) for x in interfaces if self.interface_match(x)]
Brad Bishop63f59a72016-07-25 12:05:57 -0400528
529 @staticmethod
530 def interfaces_get(item, owner, default=[]):
531 return item.get(owner, default)
532
533 @staticmethod
534 def interfaces_append(item, owner, append):
535 interfaces = item.setdefault(owner, [])
536 item[owner] = list(set(append).union(interfaces))
537
538 def interfaces_remove(self, item, owner, remove, path):
539 interfaces = item.get(owner, [])
540 item[owner] = list(set(interfaces).difference(remove))
541
542 if not item[owner]:
543 # remove the owner if there aren't any interfaces left
544 del item[owner]
545
546 if item:
547 # other owners remain
548 return
549
550 if self.cache.get_children(path):
551 # there are still references to this path
552 # from objects further down the tree.
553 # mark it for removal if that changes
554 self.cache.demote(path)
555 else:
556 # delete the entire path if everything is gone
557 del self.cache[path]
558
Brad Bishop1c33c222016-11-02 00:08:46 -0400559 @staticmethod
560 def filter_interfaces(item, ifaces):
561 if isinstance(item, dict):
562 # Called with a single object.
563 if not ifaces:
564 return item
565
566 # Remove interfaces from a service that
567 # aren't in a filter.
Adriana Kobylak7f42ad22018-01-16 12:15:23 -0600568 svc_map = lambda svc: (
Brad Bishop1c33c222016-11-02 00:08:46 -0400569 svc[0],
570 list(set(ifaces).intersection(svc[1])))
571
572 # Remove services where no interfaces remain after mapping.
Adriana Kobylak7f42ad22018-01-16 12:15:23 -0600573 svc_filter = lambda svc: svc[1]
Brad Bishop1c33c222016-11-02 00:08:46 -0400574
Adriana Kobylak7f42ad22018-01-16 12:15:23 -0600575 obj_map = lambda o: (
Balaji B Rao84e331a2017-11-09 21:19:13 -0600576 tuple(*list(filter(svc_filter, list(map(svc_map, [o]))))))
Brad Bishop1c33c222016-11-02 00:08:46 -0400577
CamVan Nguyen2fd4b1f2018-03-05 12:19:46 -0600578 return dict(
579 [x for x in map(obj_map, iter(list(item.items()))) if x])
Brad Bishop1c33c222016-11-02 00:08:46 -0400580
581 # Called with a list of path/object tuples.
582 if not ifaces:
583 return dict(item)
584
Adriana Kobylak7f42ad22018-01-16 12:15:23 -0600585 obj_map = lambda x: (
Brad Bishop1c33c222016-11-02 00:08:46 -0400586 x[0],
587 ObjectMapper.filter_interfaces(
588 x[1],
589 ifaces))
590
Balaji B Rao84e331a2017-11-09 21:19:13 -0600591 return dict([x for x in map(obj_map, iter(item or [])) if x[1]])
Brad Bishop1c33c222016-11-02 00:08:46 -0400592
593 @dbus.service.method(obmc.mapper.MAPPER_IFACE, 'sas', 'a{sas}')
594 def GetObject(self, path, interfaces):
Brad Bishop63f59a72016-07-25 12:05:57 -0400595 o = self.cache_get(path)
596 if not o:
597 raise MapperNotFoundException(path)
Brad Bishop63f59a72016-07-25 12:05:57 -0400598
Brad Bishop1c33c222016-11-02 00:08:46 -0400599 return self.filter_interfaces(o, interfaces)
600
601 @dbus.service.method(obmc.mapper.MAPPER_IFACE, 'sias', 'as')
602 def GetSubTreePaths(self, path, depth, interfaces):
Brad Bishop63f59a72016-07-25 12:05:57 -0400603 try:
Brad Bishop24301972017-06-23 13:40:07 -0400604 return self.filter_interfaces(
605 self.cache.iteritems(path, depth),
606 interfaces)
Brad Bishop63f59a72016-07-25 12:05:57 -0400607 except KeyError:
608 raise MapperNotFoundException(path)
609
Brad Bishop1c33c222016-11-02 00:08:46 -0400610 @dbus.service.method(obmc.mapper.MAPPER_IFACE, 'sias', 'a{sa{sas}}')
611 def GetSubTree(self, path, depth, interfaces):
Brad Bishop63f59a72016-07-25 12:05:57 -0400612 try:
Brad Bishop1c33c222016-11-02 00:08:46 -0400613 return self.filter_interfaces(
614 self.cache.dataitems(path, depth),
615 interfaces)
Brad Bishop63f59a72016-07-25 12:05:57 -0400616 except KeyError:
617 raise MapperNotFoundException(path)
618
619 @staticmethod
620 def has_interfaces(item):
CamVan Nguyen2fd4b1f2018-03-05 12:19:46 -0600621 for owner in list(item.keys()):
Brad Bishop63f59a72016-07-25 12:05:57 -0400622 if ObjectMapper.interfaces_get(item, owner):
623 return True
624 return False
625
626 @staticmethod
627 def is_association(interfaces):
628 return obmc.dbuslib.enums.OBMC_ASSOCIATIONS_IFACE in interfaces
629
630 def index_get(self, index, path, owners):
631 items = []
632 item = self.index.get(index, {})
633 item = item.get(path, {})
634 for o in owners:
635 items.extend(item.get(o, []))
636 return items
637
638 def index_append(self, index, path, owner, assoc):
639 item = self.index.setdefault(index, {})
640 item = item.setdefault(path, {})
641 item = item.setdefault(owner, [])
642 item.append(assoc)
643
644 def index_remove(self, index, path, owner, assoc):
645 index = self.index.get(index, {})
646 owners = index.get(path, {})
647 items = owners.get(owner, [])
648 if assoc in items:
649 items.remove(assoc)
650 if not items:
651 del owners[owner]
652 if not owners:
653 del index[path]
654
Brad Bishop63f59a72016-07-25 12:05:57 -0400655 def index_get_associations(self, path, owners=[], direction='forward'):
656 forward = 'forward' if direction == 'forward' else 'reverse'
657 reverse = 'reverse' if direction == 'forward' else 'forward'
658
659 associations = []
660 if not owners:
661 index = self.index.get(forward, {})
Balaji B Rao84e331a2017-11-09 21:19:13 -0600662 owners = list(index.get(path, {}).keys())
Brad Bishop63f59a72016-07-25 12:05:57 -0400663
664 # f: forward
665 # r: reverse
666 for rassoc in self.index_get(forward, path, owners):
667 elements = rassoc.split('/')
668 rtype = ''.join(elements[-1:])
669 fendpoint = '/'.join(elements[:-1])
670 for fassoc in self.index_get(reverse, fendpoint, owners):
671 elements = fassoc.split('/')
672 ftype = ''.join(elements[-1:])
673 rendpoint = '/'.join(elements[:-1])
674 if rendpoint != path:
675 continue
676 associations.append((ftype, rtype, fendpoint))
677
678 return associations
679
680 def update_association(self, path, removed, added):
681 iface = obmc.dbuslib.enums.OBMC_ASSOC_IFACE
Brad Bishop8e1f4ab2017-11-02 20:44:17 -0400682 assoc = self.manager.get(path, None)
Brad Bishop63f59a72016-07-25 12:05:57 -0400683
Brad Bishopc33ae652017-11-02 22:23:09 -0400684 old_endpoints = assoc.Get(iface, 'endpoints') if assoc else []
Brad Bishop84041e32017-11-02 21:48:57 -0400685 new_endpoints = list(
686 set(old_endpoints).union(added).difference(removed))
687
688 if old_endpoints == new_endpoints:
689 return
690
691 create = [] if old_endpoints else [iface]
692 delete = [] if new_endpoints else [iface]
693
694 if create:
Brad Bishop63f59a72016-07-25 12:05:57 -0400695 self.manager.add(
Brad Bishop84041e32017-11-02 21:48:57 -0400696 path, Association(self.bus, path, new_endpoints))
697 elif delete:
Brad Bishop63f59a72016-07-25 12:05:57 -0400698 self.manager.remove(path)
Brad Bishop84041e32017-11-02 21:48:57 -0400699 else:
Brad Bishopc33ae652017-11-02 22:23:09 -0400700 assoc.Set(iface, 'endpoints', new_endpoints)
Brad Bishop63f59a72016-07-25 12:05:57 -0400701
702 if create != delete:
703 self.update_interfaces(
Brad Bishop57255f62018-01-29 15:26:06 -0500704 path, obmc.mapper.MAPPER_NAME, delete, create)
Brad Bishop63f59a72016-07-25 12:05:57 -0400705
706 def update_associations(
707 self, path, owner, old, new, created=[], destroyed=[]):
708 added = list(set(new).difference(old))
709 removed = list(set(old).difference(new))
710 for forward, reverse, endpoint in added:
Brad Bishopb15b6312017-11-01 16:34:13 -0400711 if not endpoint:
712 # skip associations without an endpoint
713 continue
714
Brad Bishop63f59a72016-07-25 12:05:57 -0400715 # update the index
716 forward_path = str(path + '/' + forward)
717 reverse_path = str(endpoint + '/' + reverse)
718 self.index_append(
719 'forward', path, owner, reverse_path)
720 self.index_append(
721 'reverse', endpoint, owner, forward_path)
722
723 # create the association if the endpoint exists
724 if not self.cache_get(endpoint):
725 continue
726
727 self.update_association(forward_path, [], [endpoint])
728 self.update_association(reverse_path, [], [path])
729
730 for forward, reverse, endpoint in removed:
731 # update the index
732 forward_path = str(path + '/' + forward)
733 reverse_path = str(endpoint + '/' + reverse)
734 self.index_remove(
735 'forward', path, owner, reverse_path)
736 self.index_remove(
737 'reverse', endpoint, owner, forward_path)
738
739 # destroy the association if it exists
740 self.update_association(forward_path, [endpoint], [])
741 self.update_association(reverse_path, [path], [])
742
743 # If the associations interface endpoint comes
744 # or goes create or destroy the appropriate
745 # associations
746 for path in created:
747 for forward, reverse, endpoint in \
748 self.index_get_associations(path, direction='reverse'):
749 forward_path = str(path + '/' + forward)
750 reverse_path = str(endpoint + '/' + reverse)
751 self.update_association(forward_path, [], [endpoint])
752 self.update_association(reverse_path, [], [path])
753
754 for path in destroyed:
755 for forward, reverse, endpoint in \
756 self.index_get_associations(path, direction='reverse'):
757 forward_path = str(path + '/' + forward)
758 reverse_path = str(endpoint + '/' + reverse)
759 self.update_association(forward_path, [endpoint], [])
760 self.update_association(reverse_path, [path], [])
761
Brad Bishop1c33c222016-11-02 00:08:46 -0400762 @dbus.service.method(obmc.mapper.MAPPER_IFACE, 'sas', 'a{sa{sas}}')
763 def GetAncestors(self, path, interfaces):
Brad Bishop495ee092016-11-02 00:11:11 -0400764 if not self.cache_get(path):
765 raise MapperNotFoundException(path)
766
Balaji B Rao84e331a2017-11-09 21:19:13 -0600767 elements = list(filter(bool, path.split('/')))
Brad Bishop63f59a72016-07-25 12:05:57 -0400768 paths = []
769 objs = {}
770 while elements:
771 elements.pop()
772 paths.append('/' + '/'.join(elements))
773 if path != '/':
774 paths.append('/')
775
776 for path in paths:
777 obj = self.cache_get(path)
778 if not obj:
779 continue
780 objs[path] = obj
781
Balaji B Rao84e331a2017-11-09 21:19:13 -0600782 return self.filter_interfaces(list(objs.items()), interfaces)
Brad Bishop63f59a72016-07-25 12:05:57 -0400783
Brad Bishop829181d2017-02-24 09:49:14 -0500784 @dbus.service.signal(obmc.mapper.MAPPER_IFACE + '.Private', 's')
785 def IntrospectionComplete(self, name):
786 pass
787
Brad Bishop63f59a72016-07-25 12:05:57 -0400788
Brad Bishopcb2e1b32017-07-09 20:11:35 -0400789def server_main(
790 path_namespaces,
791 interface_namespaces,
792 blacklists,
793 interface_blacklists):
Brad Bishop63f59a72016-07-25 12:05:57 -0400794 dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
795 bus = dbus.SystemBus()
Brad Bishopcb2e1b32017-07-09 20:11:35 -0400796 o = ObjectMapper(
797 bus,
798 obmc.mapper.MAPPER_PATH,
799 path_namespaces,
800 interface_namespaces,
801 blacklists,
802 interface_blacklists)
Brad Bishop63f59a72016-07-25 12:05:57 -0400803 loop = gobject.MainLoop()
804
805 loop.run()