[plug] dbus-hooks
Brad Campbell
brad at wasp.net.au
Sun Apr 27 15:15:25 WST 2008
G'day all,
Having just braved the upgrade from Ubuntu 6.06LTS to 8.04LTS on my little laptop (which went very
smoothly considering all the things I've backported, modified or generally hacked over the last 18
months) I noticed that dbus-hooks by Cameron Patrick (that I've used extensively since I installed
it) was somewhat broken by the python-dbus api changes.
I dunno if anyone else uses it, but I'll attach my /usr/sbin/dbus-hooks for anyone that wants one
that works with the latest and greatest api.
The other change required in your config file is to replace the "." with "/" in your "system
service" sections and be sure to prefix a leading "/".. ie
system service=/org/freedesktop/NetworkManager,signal=DeviceNoLongerActive /home/brad/bin/network_down
I'm not sure if I got the changes "just so", but it's working perfectly here. Python-dbus
documentation is only slightly worse than reading the source having printed it, shredded it and then
tried to piece it back together with tweezers covered in gum.
Brad
--
"Human beings, who are almost unique in having the ability
to learn from the experience of others, are also remarkable
for their apparent disinclination to do so." -- Douglas Adams
-------------- next part --------------
#! /usr/bin/env python
# DBUS Hooks
# Copyright (c) 2006 Cameron Patrick.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
import dbus
import gobject
import sys
import os
if os.getuid() == 0:
DEFAULT_CFG_FILE = '/etc/dbus-hooks.conf'
else:
DEFAULT_CFG_FILE = os.environ['HOME'] + '/.dbus-hooks'
class ConfigError(Exception): pass
def spawn_receiver(cmd):
def handle(*args, **keywords):
msg = keywords["dbus_message"]
env = os.environ.copy()
env['DBUS_INTERFACE'] = msg.get_interface()
env['DBUS_PATH'] = msg.get_path()
env_list = [key+'='+val for key,val in env.iteritems()]
gobject.spawn_async([cmd,msg.get_member()]+map(str, args), env_list)
return handle
def die(msg):
sys.stderr.write(msg+'\n')
sys.exit(1)
def remove_after(s, c):
i = s.find(c)
if i < 0: return s
else: return s[0:c]
def parse_filter_str(msg):
if msg == '*': return {}
allowed_filters = { 'signal': 'signal_name',
'interface': 'dbus_interface',
'service': 'named_service',
'path': 'path' }
msgdict = {}
for p in msg.split(','):
try:
k, v = p.split('=')
except ValueError:
raise ConfigError('Filter expression '+repr(p)+' not of key=value format')
if k not in allowed_filters:
raise ConfigError('Unknown filter keyword '+repr(k))
msgdict[allowed_filters[k]] = v
return msgdict
def read_config(fn):
f = file(fn, 'r')
for line in f:
l = remove_after(line, '#').strip()
if len(l) == 0: continue
try:
bus, msg, prog = l.split()
except ValueError:
raise ConfigError("Bad config file line: " + l)
msgdict = parse_filter_str(msg)
yield (bus, msgdict, prog)
def maybe_get_bus(dict, val, bus):
try:
dict[val] = bus()
except dbus.DBusException:
pass
def main():
busses = {}
from dbus.mainloop.glib import DBusGMainLoop
DBusGMainLoop(set_as_default=True)
maybe_get_bus(busses, 'system', dbus.SystemBus)
maybe_get_bus(busses, 'session', dbus.SessionBus)
try:
_, cfg_file = sys.argv
except ValueError:
cfg_file = DEFAULT_CFG_FILE
try:
cfg = read_config(cfg_file)
for bus, msgdict, prog in cfg:
try:
b = busses[bus]
except KeyError:
die('Unknown bus '+repr(bus))
b.add_signal_receiver(spawn_receiver(prog),msgdict["signal_name"],None,None,msgdict["named_service"],message_keyword='dbus_message')
except ConfigError, e:
die(str(e))
loop = gobject.MainLoop()
loop.run()
if __name__ == '__main__': main()
More information about the plug
mailing list