blob: 03400d60165f2493a75b4c14e4d0b26c18103532 [file] [log] [blame]
Brad Bishopeded8f32017-11-01 11:22:38 -04001# Contributors Listed Below - COPYRIGHT 2017
Brad Bishop63f59a72016-07-25 12:05:57 -04002# [+] International Business Machines Corp.
3#
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
14# implied. See the License for the specific language governing
15# permissions and limitations under the License.
16
17import dbus
18import dbus.service
19import dbus.exceptions
20import dbus.mainloop.glib
21import gobject
22import xml.etree.ElementTree as ET
23import obmc.utils.pathtree
Brad Bishop63f59a72016-07-25 12:05:57 -040024import obmc.mapper
25import obmc.dbuslib.bindings
26import obmc.dbuslib.enums
Brad Bishop99b8bc82017-07-29 21:39:52 -040027import sys
28import traceback
Brad Bishop63f59a72016-07-25 12:05:57 -040029
30
Brad Bishop2e0436c2016-09-19 18:02:19 -040031class MapperBusyException(dbus.exceptions.DBusException):
32 _dbus_error_name = 'org.freedesktop.DBus.Error.ObjectPathInUse'
33
34 def __init__(self):
35 super(MapperBusyException, self).__init__(
36 'busy processing bus traffic')
37
38
Brad Bishop63f59a72016-07-25 12:05:57 -040039class MapperNotFoundException(dbus.exceptions.DBusException):
40 _dbus_error_name = obmc.mapper.MAPPER_NOT_FOUND
41
42 def __init__(self, path):
43 super(MapperNotFoundException, self).__init__(
44 "path or object not found: %s" % path)
45
46
Brad Bishop520473f2016-09-19 21:46:36 -040047def find_dbus_interfaces(conn, service, path, callback, error_callback, **kw):
Brad Bishopbd8aa052016-09-19 09:30:06 -040048 iface_match = kw.pop('iface_match', bool)
Brad Bishop6a0320b2016-09-19 11:03:06 -040049 subtree_match = kw.pop('subtree_match', bool)
Brad Bishopbd8aa052016-09-19 09:30:06 -040050
Brad Bishop63f59a72016-07-25 12:05:57 -040051 class _FindInterfaces(object):
52 def __init__(self):
53 self.results = {}
Brad Bishop520473f2016-09-19 21:46:36 -040054 self.introspect_pending = []
55 self.gmo_pending = []
56 self.assoc_pending = []
Brad Bishop63f59a72016-07-25 12:05:57 -040057
58 @staticmethod
59 def _to_path(elements):
60 return '/' + '/'.join(elements)
61
62 @staticmethod
63 def _to_path_elements(path):
64 return filter(bool, path.split('/'))
65
66 def __call__(self, path):
Brad Bishop520473f2016-09-19 21:46:36 -040067 try:
68 self._find_interfaces(path)
69 except Exception, e:
70 error_callback(service, path, e)
Brad Bishop63f59a72016-07-25 12:05:57 -040071
72 @staticmethod
73 def _match(iface):
74 return iface == dbus.BUS_DAEMON_IFACE + '.ObjectManager' \
Brad Bishopbd8aa052016-09-19 09:30:06 -040075 or iface_match(iface)
Brad Bishop63f59a72016-07-25 12:05:57 -040076
Brad Bishop520473f2016-09-19 21:46:36 -040077 def check_done(self):
78 if any([
79 self.introspect_pending,
80 self.gmo_pending,
81 self.assoc_pending]):
82 return
83
84 callback(service, self.results)
85
86 def _assoc_callback(self, path, associations):
87 try:
88 iface = obmc.dbuslib.enums.OBMC_ASSOCIATIONS_IFACE
89 self.assoc_pending.remove(path)
Gunnar Mills296395c2017-09-06 13:56:43 -050090 self.results[path][iface]['associations'] = associations
Brad Bishop520473f2016-09-19 21:46:36 -040091 except Exception, e:
92 error_callback(service, path, e)
93 return None
94
95 self.check_done()
96
97 def _gmo_callback(self, path, objs):
98 try:
99 self.gmo_pending.remove(path)
100 for k, v in objs.iteritems():
101 self.results[k] = v
102 except Exception, e:
103 error_callback(service, path, e)
104 return None
105
106 self.check_done()
107
108 def _introspect_callback(self, path, data):
109 self.introspect_pending.remove(path)
110 if data is None:
111 self.check_done()
112 return
113
114 try:
115 path_elements = self._to_path_elements(path)
116 root = ET.fromstring(data)
117 ifaces = filter(
118 self._match,
119 [x.attrib.get('name') for x in root.findall('interface')])
120 ifaces = {x: {} for x in ifaces}
121 self.results[path] = ifaces
122
123 if obmc.dbuslib.enums.OBMC_ASSOCIATIONS_IFACE in ifaces:
124 obj = conn.get_object(service, path, introspect=False)
125 iface = dbus.Interface(obj, dbus.PROPERTIES_IFACE)
126 self.assoc_pending.append(path)
127 iface.Get.call_async(
128 obmc.dbuslib.enums.OBMC_ASSOCIATIONS_IFACE,
129 'associations',
130 reply_handler=lambda x: self._assoc_callback(
131 path, x),
132 error_handler=lambda e: error_callback(
133 service, path, e))
134
135 if dbus.BUS_DAEMON_IFACE + '.ObjectManager' in ifaces:
136 obj = conn.get_object(service, path, introspect=False)
137 iface = dbus.Interface(
138 obj, dbus.BUS_DAEMON_IFACE + '.ObjectManager')
139 self.gmo_pending.append(path)
140 iface.GetManagedObjects.call_async(
141 reply_handler=lambda x: self._gmo_callback(
142 path, x),
143 error_handler=lambda e: error_callback(
144 service, path, e))
145 else:
146 children = filter(
147 bool,
148 [x.attrib.get('name') for x in root.findall('node')])
149 children = [
150 self._to_path(
151 path_elements + self._to_path_elements(x))
152 for x in sorted(children)]
153 for child in filter(subtree_match, children):
154 if child not in self.results:
155 self._find_interfaces(child)
156 except Exception, e:
157 error_callback(service, path, e)
158 return None
159
160 self.check_done()
161
Brad Bishop63f59a72016-07-25 12:05:57 -0400162 def _find_interfaces(self, path):
163 path_elements = self._to_path_elements(path)
164 path = self._to_path(path_elements)
Brad Bishop520473f2016-09-19 21:46:36 -0400165 obj = conn.get_object(service, path, introspect=False)
166 iface = dbus.Interface(obj, dbus.INTROSPECTABLE_IFACE)
167 self.introspect_pending.append(path)
168 iface.Introspect.call_async(
169 reply_handler=lambda x: self._introspect_callback(path, x),
170 error_handler=lambda x: error_callback(service, path, x))
Brad Bishop63f59a72016-07-25 12:05:57 -0400171
172 return _FindInterfaces()(path)
173
174
175class Association(dbus.service.Object):
Brad Bishop734b2c32017-11-01 15:40:07 -0400176 """Implementation of org.openbmc.Association."""
177
Brad Bishopb9b3ed52017-11-01 21:40:31 -0400178 iface = obmc.dbuslib.enums.OBMC_ASSOC_IFACE
179
Brad Bishop63f59a72016-07-25 12:05:57 -0400180 def __init__(self, bus, path, endpoints):
Brad Bishop734b2c32017-11-01 15:40:07 -0400181 """Construct an Association.
182
183 Arguments:
184 bus -- The python-dbus connection to host the interface
185 path -- The D-Bus object path on which to implement the interface
186 endpoints -- A list of the initial association endpoints
187 """
Brad Bishop70dd5952016-09-08 22:33:33 -0400188 super(Association, self).__init__(conn=bus, object_path=path)
Brad Bishopb9b3ed52017-11-01 21:40:31 -0400189 self.properties = {self.iface: {'endpoints': endpoints}}
Brad Bishop63f59a72016-07-25 12:05:57 -0400190
191 def emit_signal(self, old):
Brad Bishopb9b3ed52017-11-01 21:40:31 -0400192 new = self.properties[self.iface]['endpoints']
193 if old != new:
Brad Bishop63f59a72016-07-25 12:05:57 -0400194 self.PropertiesChanged(
Brad Bishopb9b3ed52017-11-01 21:40:31 -0400195 self.iface, self.properties[self.iface], ['endpoints'])
Brad Bishop63f59a72016-07-25 12:05:57 -0400196
197 def append(self, endpoints):
198 old = self.endpoints
199 self.endpoints = list(set(endpoints).union(self.endpoints))
200 self.emit_signal(old)
201
202 def remove(self, endpoints):
203 old = self.endpoints
204 self.endpoints = list(set(self.endpoints).difference(endpoints))
205 self.emit_signal(old)
206
207 @dbus.service.method(dbus.PROPERTIES_IFACE, 'ss', 'as')
208 def Get(self, interface_name, property_name):
209 if property_name != 'endpoints':
210 raise dbus.exceptions.DBusException(name=DBUS_UNKNOWN_PROPERTY)
211 return self.GetAll(interface_name)[property_name]
212
213 @dbus.service.method(dbus.PROPERTIES_IFACE, 's', 'a{sas}')
214 def GetAll(self, interface_name):
215 if interface_name != obmc.dbuslib.enums.OBMC_ASSOC_IFACE:
216 raise dbus.exceptions.DBusException(DBUS_UNKNOWN_INTERFACE)
217 return {'endpoints': self.endpoints}
218
219 @dbus.service.signal(
220 dbus.PROPERTIES_IFACE, signature='sa{sas}as')
221 def PropertiesChanged(
222 self, interface_name, changed_properties, invalidated_properties):
223 pass
224
225
226class Manager(obmc.dbuslib.bindings.DbusObjectManager):
227 def __init__(self, bus, path):
Brad Bishop70dd5952016-09-08 22:33:33 -0400228 super(Manager, self).__init__(conn=bus, object_path=path)
Brad Bishop63f59a72016-07-25 12:05:57 -0400229
230
231class ObjectMapper(dbus.service.Object):
Brad Bishopcb2e1b32017-07-09 20:11:35 -0400232 def __init__(
233 self, bus, path, namespaces, interface_namespaces,
234 blacklist, interface_blacklist):
Brad Bishop63f59a72016-07-25 12:05:57 -0400235 super(ObjectMapper, self).__init__(bus, path)
236 self.cache = obmc.utils.pathtree.PathTree()
237 self.bus = bus
Brad Bishop63f59a72016-07-25 12:05:57 -0400238 self.service = None
239 self.index = {}
240 self.manager = Manager(bus, obmc.dbuslib.bindings.OBJ_PREFIX)
241 self.unique = bus.get_unique_name()
242 self.bus_map = {}
Brad Bishop2e0436c2016-09-19 18:02:19 -0400243 self.defer_signals = {}
Brad Bishop5d4890c2016-09-19 11:28:47 -0400244 self.bus_map[self.unique] = obmc.mapper.MAPPER_NAME
Brad Bishopcb2e1b32017-07-09 20:11:35 -0400245 self.namespaces = namespaces
246 self.interface_namespaces = interface_namespaces
247 self.blacklist = blacklist
248 self.blacklist.append(obmc.mapper.MAPPER_PATH)
249 self.interface_blacklist = interface_blacklist
Brad Bishop63f59a72016-07-25 12:05:57 -0400250
Brad Bishop5d4890c2016-09-19 11:28:47 -0400251 # add my object mananger instance
252 self.add_new_objmgr(obmc.dbuslib.bindings.OBJ_PREFIX, self.unique)
253
Brad Bishop63f59a72016-07-25 12:05:57 -0400254 self.bus.add_signal_receiver(
255 self.bus_handler,
256 dbus_interface=dbus.BUS_DAEMON_IFACE,
257 signal_name='NameOwnerChanged')
258 self.bus.add_signal_receiver(
259 self.interfaces_added_handler,
260 dbus_interface=dbus.BUS_DAEMON_IFACE + '.ObjectManager',
261 signal_name='InterfacesAdded',
262 sender_keyword='sender',
263 path_keyword='sender_path')
264 self.bus.add_signal_receiver(
265 self.interfaces_removed_handler,
266 dbus_interface=dbus.BUS_DAEMON_IFACE + '.ObjectManager',
267 signal_name='InterfacesRemoved',
268 sender_keyword='sender',
269 path_keyword='sender_path')
270 self.bus.add_signal_receiver(
271 self.properties_changed_handler,
272 dbus_interface=dbus.PROPERTIES_IFACE,
273 signal_name='PropertiesChanged',
Brad Bishopb270adc2017-11-14 23:32:59 -0500274 arg0=obmc.dbuslib.enums.OBMC_ASSOCIATIONS_IFACE,
Brad Bishop63f59a72016-07-25 12:05:57 -0400275 path_keyword='path',
276 sender_keyword='sender')
277
Brad Bishop5d4890c2016-09-19 11:28:47 -0400278 print "ObjectMapper startup complete. Discovery in progress..."
279 self.discover()
Brad Bishop520473f2016-09-19 21:46:36 -0400280 gobject.idle_add(self.claim_name)
Brad Bishop5d4890c2016-09-19 11:28:47 -0400281
Brad Bishop520473f2016-09-19 21:46:36 -0400282 def claim_name(self):
283 if len(self.defer_signals):
284 return True
Brad Bishop5d4890c2016-09-19 11:28:47 -0400285 print "ObjectMapper discovery complete"
286 self.service = dbus.service.BusName(
287 obmc.mapper.MAPPER_NAME, self.bus)
Brad Bishop55b89cd2016-09-19 23:02:48 -0400288 self.manager.unmask_signals()
Brad Bishop520473f2016-09-19 21:46:36 -0400289 return False
Brad Bishop63f59a72016-07-25 12:05:57 -0400290
Brad Bishop2e0436c2016-09-19 18:02:19 -0400291 def discovery_callback(self, owner, items):
292 if owner in self.defer_signals:
293 self.add_items(owner, items)
294 pending = self.defer_signals[owner]
295 del self.defer_signals[owner]
296
297 for x in pending:
298 x()
Brad Bishop829181d2017-02-24 09:49:14 -0500299 self.IntrospectionComplete(owner)
Brad Bishop2e0436c2016-09-19 18:02:19 -0400300
301 def discovery_error(self, owner, path, e):
Brad Bishop99b8bc82017-07-29 21:39:52 -0400302 '''Log a message and remove all traces of the service
303 we were attempting to introspect.'''
304
Brad Bishop2e0436c2016-09-19 18:02:19 -0400305 if owner in self.defer_signals:
Brad Bishop99b8bc82017-07-29 21:39:52 -0400306 sys.stderr.write(
307 '{} discovery failure on {}\n'.format(
308 self.bus_map.get(owner, owner),
309 path))
310 traceback.print_exception(*sys.exc_info())
311 del self.defer_signals[owner]
312 del self.bus_map[owner]
Brad Bishop2e0436c2016-09-19 18:02:19 -0400313
Brad Bishop63f59a72016-07-25 12:05:57 -0400314 def cache_get(self, path):
315 cache_entry = self.cache.get(path, {})
316 if cache_entry is None:
317 # hide path elements without any interfaces
318 cache_entry = {}
319 return cache_entry
320
321 def add_new_objmgr(self, path, owner):
322 # We don't get a signal for the ObjectManager
323 # interface itself, so if we see a signal from
324 # make sure its in our cache, and add it if not.
325 cache_entry = self.cache_get(path)
326 old = self.interfaces_get(cache_entry, owner)
327 new = list(set(old).union([dbus.BUS_DAEMON_IFACE + '.ObjectManager']))
328 self.update_interfaces(path, owner, old, new)
329
Brad Bishop2e0436c2016-09-19 18:02:19 -0400330 def defer_signal(self, owner, callback):
331 self.defer_signals.setdefault(owner, []).append(callback)
332
Brad Bishop63f59a72016-07-25 12:05:57 -0400333 def interfaces_added_handler(self, path, iprops, **kw):
334 path = str(path)
335 owner = str(kw['sender'])
336 interfaces = self.get_signal_interfaces(owner, iprops.iterkeys())
Brad Bishop2e0436c2016-09-19 18:02:19 -0400337 if not interfaces:
338 return
339
340 if owner not in self.defer_signals:
Brad Bishop63f59a72016-07-25 12:05:57 -0400341 self.add_new_objmgr(str(kw['sender_path']), owner)
342 cache_entry = self.cache_get(path)
343 old = self.interfaces_get(cache_entry, owner)
344 new = list(set(interfaces).union(old))
Brad Bishopa6235962017-06-07 23:56:54 -0400345 new = {x: iprops.get(x, {}) for x in new}
Brad Bishop63f59a72016-07-25 12:05:57 -0400346 self.update_interfaces(path, owner, old, new)
Brad Bishop2e0436c2016-09-19 18:02:19 -0400347 else:
348 self.defer_signal(
349 owner,
350 lambda: self.interfaces_added_handler(
351 path, iprops, **kw))
Brad Bishop63f59a72016-07-25 12:05:57 -0400352
353 def interfaces_removed_handler(self, path, interfaces, **kw):
354 path = str(path)
355 owner = str(kw['sender'])
356 interfaces = self.get_signal_interfaces(owner, interfaces)
Brad Bishop2e0436c2016-09-19 18:02:19 -0400357 if not interfaces:
358 return
359
360 if owner not in self.defer_signals:
Brad Bishop63f59a72016-07-25 12:05:57 -0400361 self.add_new_objmgr(str(kw['sender_path']), owner)
362 cache_entry = self.cache_get(path)
363 old = self.interfaces_get(cache_entry, owner)
364 new = list(set(old).difference(interfaces))
365 self.update_interfaces(path, owner, old, new)
Brad Bishop2e0436c2016-09-19 18:02:19 -0400366 else:
367 self.defer_signal(
368 owner,
369 lambda: self.interfaces_removed_handler(
370 path, interfaces, **kw))
Brad Bishop63f59a72016-07-25 12:05:57 -0400371
372 def properties_changed_handler(self, interface, new, old, **kw):
373 owner = str(kw['sender'])
374 path = str(kw['path'])
375 interfaces = self.get_signal_interfaces(owner, [interface])
376 if not self.is_association(interfaces):
377 return
378 associations = new.get('associations', None)
379 if associations is None:
380 return
381
Brad Bishop2e0436c2016-09-19 18:02:19 -0400382 if owner not in self.defer_signals:
383 associations = [
384 (str(x), str(y), str(z)) for x, y, z in associations]
385 self.update_associations(
386 path, owner,
387 self.index_get_associations(path, [owner]),
388 associations)
389 else:
390 self.defer_signal(
391 owner,
392 lambda: self.properties_changed_handler(
393 interface, new, old, **kw))
Brad Bishop63f59a72016-07-25 12:05:57 -0400394
395 def process_new_owner(self, owned_name, owner):
396 # unique name
397 try:
398 return self.discover([(owned_name, owner)])
399 except dbus.exceptions.DBusException, e:
400 if obmc.dbuslib.enums.DBUS_UNKNOWN_SERVICE \
401 not in e.get_dbus_name():
402 raise
403
404 def process_old_owner(self, owned_name, owner):
405 if owner in self.bus_map:
406 del self.bus_map[owner]
407
408 for path, item in self.cache.dataitems():
409 old = self.interfaces_get(item, owner)
410 # remove all interfaces for this service
411 self.update_interfaces(
412 path, owner, old=old, new=[])
413
414 def bus_handler(self, owned_name, old, new):
415 valid = False
416 if not obmc.dbuslib.bindings.is_unique(owned_name):
417 valid = self.valid_signal(owned_name)
418
419 if valid and new:
420 self.process_new_owner(owned_name, new)
421 if valid and old:
Brad Bishop2e0436c2016-09-19 18:02:19 -0400422 # discard any unhandled signals
423 # or in progress discovery
424 if old in self.defer_signals:
425 del self.defer_signals[old]
426
Brad Bishop63f59a72016-07-25 12:05:57 -0400427 self.process_old_owner(owned_name, old)
428
429 def update_interfaces(self, path, owner, old, new):
430 # __xx -> intf list
431 # xx -> intf dict
432 if isinstance(old, dict):
433 __old = old.keys()
434 else:
435 __old = old
436 old = {x: {} for x in old}
437 if isinstance(new, dict):
438 __new = new.keys()
439 else:
440 __new = new
441 new = {x: {} for x in new}
442
443 cache_entry = self.cache.setdefault(path, {})
444 created = [] if self.has_interfaces(cache_entry) else [path]
445 added = list(set(__new).difference(__old))
446 removed = list(set(__old).difference(__new))
447 self.interfaces_append(cache_entry, owner, added)
448 self.interfaces_remove(cache_entry, owner, removed, path)
449 destroyed = [] if self.has_interfaces(cache_entry) else [path]
450
451 # react to anything that requires association updates
452 new_assoc = []
453 old_assoc = []
454 if self.is_association(added):
Brad Bishop926b35d2016-09-19 14:20:04 -0400455 iface = obmc.dbuslib.enums.OBMC_ASSOCIATIONS_IFACE
456 new_assoc = new[iface]['associations']
Brad Bishop63f59a72016-07-25 12:05:57 -0400457 if self.is_association(removed):
458 old_assoc = self.index_get_associations(path, [owner])
459 self.update_associations(
460 path, owner, old_assoc, new_assoc, created, destroyed)
461
462 def add_items(self, owner, bus_items):
463 for path, items in bus_items.iteritems():
464 self.update_interfaces(path, str(owner), old=[], new=items)
465
Brad Bishopcb2e1b32017-07-09 20:11:35 -0400466 def path_match(self, path):
467 match = False
468
469 if not any([x for x in self.blacklist if x in path]):
470 # not blacklisted
471
472 if any([x for x in self.namespaces if x in path]):
473 # a watched namespace contains the path
474 match = True
475 elif any([path for x in self.namespaces if path in x]):
476 # the path contains a watched namespace
477 match = True
478
479 return match
480
481 def interface_match(self, interface):
482 match = True
483
484 if any([x for x in self.interface_blacklist if x in interface]):
485 # not blacklisted
486 match = False
487 elif not any([x for x in self.interface_namespaces if x in interface]):
488 # the interface contains a watched interface namespace
489 match = False
490
491 return match
492
Brad Bishop63f59a72016-07-25 12:05:57 -0400493 def discover(self, owners=[]):
Brad Bishop062403d2017-07-29 22:43:40 -0400494 def get_owner(name):
495 try:
496 return (name, self.bus.get_name_owner(name))
497 except:
498 traceback.print_exception(*sys.exc_info())
499
Brad Bishop63f59a72016-07-25 12:05:57 -0400500 if not owners:
Brad Bishopd0b8e392016-09-19 11:24:45 -0400501 owned_names = filter(
502 lambda x: not obmc.dbuslib.bindings.is_unique(x),
503 self.bus.list_names())
Brad Bishop062403d2017-07-29 22:43:40 -0400504 owners = filter(bool, [get_owner(name) for name in owned_names])
Brad Bishop63f59a72016-07-25 12:05:57 -0400505 for owned_name, o in owners:
Brad Bishopaeac98b2017-07-29 22:56:48 -0400506 if not self.valid_signal(owned_name):
507 continue
Brad Bishop63f59a72016-07-25 12:05:57 -0400508 self.bus_map[o] = owned_name
Brad Bishop520473f2016-09-19 21:46:36 -0400509 self.defer_signals[o] = []
510 find_dbus_interfaces(
511 self.bus, o, '/',
512 self.discovery_callback,
513 self.discovery_error,
Brad Bishopcb2e1b32017-07-09 20:11:35 -0400514 subtree_match=self.path_match,
515 iface_match=self.interface_match)
Brad Bishop63f59a72016-07-25 12:05:57 -0400516
Brad Bishop63f59a72016-07-25 12:05:57 -0400517 def valid_signal(self, name):
Brad Bishop63f59a72016-07-25 12:05:57 -0400518 if obmc.dbuslib.bindings.is_unique(name):
519 name = self.bus_map.get(name)
520
Brad Bishopaeac98b2017-07-29 22:56:48 -0400521 return name is not None and name != obmc.mapper.MAPPER_NAME
Brad Bishop63f59a72016-07-25 12:05:57 -0400522
523 def get_signal_interfaces(self, owner, interfaces):
524 filtered = []
525 if self.valid_signal(owner):
Brad Bishopcb2e1b32017-07-09 20:11:35 -0400526 filtered = [str(x) for x in interfaces if self.interface_match(x)]
Brad Bishop63f59a72016-07-25 12:05:57 -0400527
528 return filtered
529
530 @staticmethod
531 def interfaces_get(item, owner, default=[]):
532 return item.get(owner, default)
533
534 @staticmethod
535 def interfaces_append(item, owner, append):
536 interfaces = item.setdefault(owner, [])
537 item[owner] = list(set(append).union(interfaces))
538
539 def interfaces_remove(self, item, owner, remove, path):
540 interfaces = item.get(owner, [])
541 item[owner] = list(set(interfaces).difference(remove))
542
543 if not item[owner]:
544 # remove the owner if there aren't any interfaces left
545 del item[owner]
546
547 if item:
548 # other owners remain
549 return
550
551 if self.cache.get_children(path):
552 # there are still references to this path
553 # from objects further down the tree.
554 # mark it for removal if that changes
555 self.cache.demote(path)
556 else:
557 # delete the entire path if everything is gone
558 del self.cache[path]
559
Brad Bishop1c33c222016-11-02 00:08:46 -0400560 @staticmethod
561 def filter_interfaces(item, ifaces):
562 if isinstance(item, dict):
563 # Called with a single object.
564 if not ifaces:
565 return item
566
567 # Remove interfaces from a service that
568 # aren't in a filter.
569 svc_map = lambda svc: (
570 svc[0],
571 list(set(ifaces).intersection(svc[1])))
572
573 # Remove services where no interfaces remain after mapping.
574 svc_filter = lambda svc: svc[1]
575
576 obj_map = lambda o: (
577 tuple(*filter(svc_filter, map(svc_map, [o]))))
578
579 return dict(filter(lambda x: x, map(obj_map, item.iteritems())))
580
581 # Called with a list of path/object tuples.
582 if not ifaces:
583 return dict(item)
584
585 obj_map = lambda x: (
586 x[0],
587 ObjectMapper.filter_interfaces(
588 x[1],
589 ifaces))
590
Brad Bishop94c92a92017-09-11 16:12:07 -0400591 return dict(filter(lambda x: x[1], map(obj_map, iter(item or []))))
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):
621 for owner in item.iterkeys():
622 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, {})
662 owners = index.get(path, {}).keys()
663
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)
683 create = [] if assoc else [iface]
Brad Bishop63f59a72016-07-25 12:05:57 -0400684
685 if added and create:
686 self.manager.add(
687 path, Association(self.bus, path, added))
Brad Bishop8e1f4ab2017-11-02 20:44:17 -0400688 assoc = self.manager.get(path)
Brad Bishop63f59a72016-07-25 12:05:57 -0400689 elif added:
Brad Bishop8e1f4ab2017-11-02 20:44:17 -0400690 assoc.append(added)
Brad Bishop63f59a72016-07-25 12:05:57 -0400691
Brad Bishop8e1f4ab2017-11-02 20:44:17 -0400692 if assoc and removed:
693 assoc.remove(removed)
Brad Bishop63f59a72016-07-25 12:05:57 -0400694
Brad Bishop8e1f4ab2017-11-02 20:44:17 -0400695 delete = []
Brad Bishopb9b3ed52017-11-01 21:40:31 -0400696 endpoints = assoc.properties[iface]['endpoints']
697 if assoc and not endpoints:
Brad Bishop63f59a72016-07-25 12:05:57 -0400698 self.manager.remove(path)
Brad Bishop8e1f4ab2017-11-02 20:44:17 -0400699 delete = [iface]
Brad Bishop63f59a72016-07-25 12:05:57 -0400700
701 if create != delete:
702 self.update_interfaces(
703 path, self.unique, delete, create)
704
705 def update_associations(
706 self, path, owner, old, new, created=[], destroyed=[]):
707 added = list(set(new).difference(old))
708 removed = list(set(old).difference(new))
709 for forward, reverse, endpoint in added:
Brad Bishopb15b6312017-11-01 16:34:13 -0400710 if not endpoint:
711 # skip associations without an endpoint
712 continue
713
Brad Bishop63f59a72016-07-25 12:05:57 -0400714 # update the index
715 forward_path = str(path + '/' + forward)
716 reverse_path = str(endpoint + '/' + reverse)
717 self.index_append(
718 'forward', path, owner, reverse_path)
719 self.index_append(
720 'reverse', endpoint, owner, forward_path)
721
722 # create the association if the endpoint exists
723 if not self.cache_get(endpoint):
724 continue
725
726 self.update_association(forward_path, [], [endpoint])
727 self.update_association(reverse_path, [], [path])
728
729 for forward, reverse, endpoint in removed:
730 # update the index
731 forward_path = str(path + '/' + forward)
732 reverse_path = str(endpoint + '/' + reverse)
733 self.index_remove(
734 'forward', path, owner, reverse_path)
735 self.index_remove(
736 'reverse', endpoint, owner, forward_path)
737
738 # destroy the association if it exists
739 self.update_association(forward_path, [endpoint], [])
740 self.update_association(reverse_path, [path], [])
741
742 # If the associations interface endpoint comes
743 # or goes create or destroy the appropriate
744 # associations
745 for path in created:
746 for forward, reverse, endpoint in \
747 self.index_get_associations(path, direction='reverse'):
748 forward_path = str(path + '/' + forward)
749 reverse_path = str(endpoint + '/' + reverse)
750 self.update_association(forward_path, [], [endpoint])
751 self.update_association(reverse_path, [], [path])
752
753 for path in destroyed:
754 for forward, reverse, endpoint in \
755 self.index_get_associations(path, direction='reverse'):
756 forward_path = str(path + '/' + forward)
757 reverse_path = str(endpoint + '/' + reverse)
758 self.update_association(forward_path, [endpoint], [])
759 self.update_association(reverse_path, [path], [])
760
Brad Bishop1c33c222016-11-02 00:08:46 -0400761 @dbus.service.method(obmc.mapper.MAPPER_IFACE, 'sas', 'a{sa{sas}}')
762 def GetAncestors(self, path, interfaces):
Brad Bishop495ee092016-11-02 00:11:11 -0400763 if not self.cache_get(path):
764 raise MapperNotFoundException(path)
765
Brad Bishop63f59a72016-07-25 12:05:57 -0400766 elements = filter(bool, path.split('/'))
767 paths = []
768 objs = {}
769 while elements:
770 elements.pop()
771 paths.append('/' + '/'.join(elements))
772 if path != '/':
773 paths.append('/')
774
775 for path in paths:
776 obj = self.cache_get(path)
777 if not obj:
778 continue
779 objs[path] = obj
780
Brad Bishop1c33c222016-11-02 00:08:46 -0400781 return self.filter_interfaces(list(objs.iteritems()), interfaces)
Brad Bishop63f59a72016-07-25 12:05:57 -0400782
Brad Bishop829181d2017-02-24 09:49:14 -0500783 @dbus.service.signal(obmc.mapper.MAPPER_IFACE + '.Private', 's')
784 def IntrospectionComplete(self, name):
785 pass
786
Brad Bishop63f59a72016-07-25 12:05:57 -0400787
Brad Bishopcb2e1b32017-07-09 20:11:35 -0400788def server_main(
789 path_namespaces,
790 interface_namespaces,
791 blacklists,
792 interface_blacklists):
Brad Bishop63f59a72016-07-25 12:05:57 -0400793 dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
794 bus = dbus.SystemBus()
Brad Bishopcb2e1b32017-07-09 20:11:35 -0400795 o = ObjectMapper(
796 bus,
797 obmc.mapper.MAPPER_PATH,
798 path_namespaces,
799 interface_namespaces,
800 blacklists,
801 interface_blacklists)
Brad Bishop63f59a72016-07-25 12:05:57 -0400802 loop = gobject.MainLoop()
803
804 loop.run()