Search code examples
pythontimeoutdbus

Python dbus get_object set timeout


Code:

def get_user_totp_status (user_name = ''):
    key_name = 'tfaEnable'

    try:
        bus = dbus.SystemBus()
    except:
        print "connect dbus error!"
        sys.exit(1)

    infopipe_obj = bus.get_object("org.freedesktop.sssd.infopipe", "/org/freedesktop/sssd/infopipe")
    ifp = dbus.Interface(infopipe_obj,dbus_interface='org.freedesktop.sssd.infopipe')
    print "get user totp status from dbus error!"

    result = ifp.GetUserAttr(user_name, [key_name])
    user_totp_status = 'True'
    if result:
        for status in result[key_name]:
            user_totp_status = status

    return user_totp_status

===========
Error:
dbus.exceptions.DBusException: org.freedesktop.DBus.Error.TimedOut: Activation of org.freedesktop.sssd.infopipe timed out

========

If DBUS has problems, it will take a long time when "get_object". How do I set timeout to shorten the time?


Solution

  • Neither get_object nor start_service_by_name support a timeout. As a workaround you can directly use call_blocking before get_object like this:

    import dbus
    from _dbus_bindings import BUS_DAEMON_IFACE, BUS_DAEMON_NAME, BUS_DAEMON_PATH
    
    bus = dbus.SystemBus()
    
    timeout = 2
    flags = 0
    bus_name = "org.freedesktop.sssd.infopipe"
    
    try:
        bus.call_blocking(BUS_DAEMON_NAME, BUS_DAEMON_PATH,
                          BUS_DAEMON_IFACE,
                          'StartServiceByName',
                          'su', (bus_name, flags), timeout=timeout)
    
        infopipe_obj = bus.get_object("org.freedesktop.sssd.infopipe", "/org/freedesktop/sssd/infopipe")
    
    except dbus.exceptions.DBusException as e:
        print("The chosen bus is not available: %s", e)