hypfvieh/dbus-java

Cannot connect to DBUS

nihasmata opened this issue · 11 comments

I connect to a remote DBUS device and control the media player. For this, I wrote a test code as follows. Here, a DBUS connection is created every 10 seconds in an endless loop. Then it is checked whether the dbus connection exists and after 7 seconds the dbus connection is closed. The problem here is that when you connect to dbus for the first time, if the remote dbus is terminated and started again, the dbus connection is not established and it says No connection. Test code is below.

package com.yaltes.csvn.client.vsu;

import org.freedesktop.dbus.connections.impl.DBusConnection;
import org.freedesktop.dbus.connections.impl.DBusConnectionBuilder;
import org.freedesktop.dbus.exceptions.DBusException;

public class DBusTest {

    private DBusConnection dBusConnection;

    public static void main(String[] args) {
        new DBusTest().loopDBusConnection();
    }


    /**
     * Connect to DBUS in endless loop every 10 seconds
     */
    public void loopDBusConnection(){

        //Endless loop and try DBUS remote connection
        while(true) {

            Thread myThread = new Thread(() -> connectToDBus());
            myThread.start();

            try {
                Thread.sleep(10000); //Wait 10 seconds and then try new DBUS connection
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * Connect to DBUS
     */
    private void connectToDBus(){
        try {
            dBusConnection =  DBusConnectionBuilder.forAddress("tcp:host=10.0.5.141,port=2334").build();
            if(dBusConnection.isConnected()) {
                System.out.println("Connected to DBUS");
            }

            else {
                System.out.println("No connection to DBUS");
            }

            Thread.sleep(7000); // Wait 7 seconds then disconnect

            dBusConnection.disconnect();

            System.out.println("Disconnected from DBUS");

        } catch (DBusException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}

Output

Connected to DBUS
Disconnected from DBUS
No connection to DBUS
Disconnected from DBUS
No connection to DBUS
Disconnected from DBUS

The problem here is that when you connect to dbus for the first time, if the remote dbus is terminated and started again, the dbus connection is not established and it says No connection

Sounds like the remote end is not accepting connections. Are you able to connect to it using other utilities like 'dbus-send' or even telnet if you use TCP for connection?

For me it does not look like an issue of dbus-java. I tried your example with the EmbeddedDBusDaemon of dbus-java, just works as intended:

09:31:05.589 [Thread-0] INFO  o.f.d.c.transports.TransportBuilder - Using transport dbus-java-transport-tcp for address tcp:host=localhost,port=36827
Connected to DBUS
Disconnected from DBUS
09:31:15.407 [Thread-2] INFO  o.f.d.c.transports.TransportBuilder - Using transport dbus-java-transport-tcp for address tcp:host=localhost,port=36827
Connected to DBUS
Disconnected from DBUS
09:31:25.408 [Thread-4] INFO  o.f.d.c.transports.TransportBuilder - Using transport dbus-java-transport-tcp for address tcp:host=localhost,port=36827
Connected to DBUS
Disconnected from DBUS
09:31:35.409 [Thread-6] INFO  o.f.d.c.transports.TransportBuilder - Using transport dbus-java-transport-tcp for address tcp:host=localhost,port=36827
Connected to DBUS
Disconnected from DBUS
09:31:45.410 [Thread-8] INFO  o.f.d.c.transports.TransportBuilder - Using transport dbus-java-transport-tcp for address tcp:host=localhost,port=36827
Connected to DBUS
Disconnected from DBUS
09:31:55.411 [Thread-10] INFO  o.f.d.c.transports.TransportBuilder - Using transport dbus-java-transport-tcp for address tcp:host=localhost,port=36827
Connected to DBUS
Disconnected from DBUS

Yes, when i use the dbus-send there is no problem. Can i use EmbeddedDBusDaemon for my purpose ?

Please could you add the full source code with EmbeddedDBusDaemon ?

EmbeddedDBusDaemon is a Java implementation of the regular dbus daemon used on most modern Linux systems.
I don't think that this is a suitable replacement in your case because any media player (e.g. VLC) will automatically use the session bus of the executing user. That means the interfaces will be exposed to the default dbus daemon instead of the Java version. I would not recommend to replace the system wide default dbus daemon with the Java implementation (never tried that).
Example code can be found here

dbus-tcp.txt

My tcp configuration file added as attachment. If you change its extension as conf and then run with

dbus-daemon --config-file=/path/dbus-tcp.conf

you can simulate my case instead of EmbeddedDBusDaemon.

Thank you

I re-run the test with different setups.
First using dbus daemon of Ubuntu 23.10.1 running in a virtual machine, configured to provide access by TCP. To ensure it actually really connects to the bus, I request the introspection data of the Gnome DisplayManager running on the Ubuntu VM.
Works fine all the time.

Second test: using your provided config in a separate DBus instance - Wrote a small test app to export something to the second dbus instance and used your test-code to connect to the second DBus instance and call a method on the exported object retrieving a string. Also no issues:

12:08:45.942 [Thread-0] INFO  o.f.d.c.transports.TransportBuilder - Using transport dbus-java-transport-tcp for address tcp:host=localhost,port=2334
Connected to DBUS
You are connected to ws4711, connect number: 1
Disconnected from DBUS
12:08:55.760 [Thread-2] INFO  o.f.d.c.transports.TransportBuilder - Using transport dbus-java-transport-tcp for address tcp:host=localhost,port=2334
Connected to DBUS
You are connected to ws4711, connect number: 2
Disconnected from DBUS
12:09:05.761 [Thread-4] INFO  o.f.d.c.transports.TransportBuilder - Using transport dbus-java-transport-tcp for address tcp:host=localhost,port=2334
Connected to DBUS
You are connected to ws4711, connect number: 3
Disconnected from DBUS
12:09:15.761 [Thread-6] INFO  o.f.d.c.transports.TransportBuilder - Using transport dbus-java-transport-tcp for address tcp:host=localhost,port=2334
Connected to DBUS
You are connected to ws4711, connect number: 4

This was my sample apps code:

package com.github.hypfvieh.dbus.vmtest;

import org.freedesktop.dbus.connections.impl.DBusConnectionBuilder;
import org.freedesktop.dbus.interfaces.DBusInterface;

import java.time.LocalDateTime;

public class VMTestApp {
    public static void main(String[] args) {
        try (var con = DBusConnectionBuilder.forAddress("tcp:host=127.0.0.1,port=2334").build()) {
            QueryTestClz queryTestClz = new QueryTestClz();
            con.requestBusName(VMTestApp.class.getPackageName());
            con.exportObject(queryTestClz);
            while (true) {
                Thread.sleep(1000);
            }
        } catch (Exception _ex) {
            _ex.printStackTrace();
        }
    }
    
    public interface QueryTest extends DBusInterface {
        String doQueryTest();
    }
    
    public static class QueryTestClz implements QueryTest {

        private int callCounter = 0;
        
        @Override
        public String getObjectPath() {
            return "/vmtest";
        }

        @Override
        public String doQueryTest() {
            String str =  "You are connected to %s, connect number: %d".formatted(getHostName(), ++callCounter);
            System.out.println("[" + LocalDateTime.now() + "] " + str);
            return str;
        }
        
        static String getHostName() {
            try {
                return java.net.InetAddress.getLocalHost().getHostName();
            } catch (java.net.UnknownHostException _ex) {
                return "unknown host name";
            }
        }
    }
}

But i stop the dbus daemon after connection is established then my code try to reconnect and print "No connection to DBUS". After this line printed i run the dbus daemon again but no connection is established in client side so always print "No connection to DBUS". I didnt see no connection line in your side. Did you stop the dbus daemon when client code is running ?

This stopping of the daemon makes the difference. This is in deed a problem in dbus-java when using shared connections (which is the default).
When creating the second connection (the first reconnect attempt), dbus-java sees that there already is a connection and shared usage is enabled. Then it just returns that connection no matter if the underlying transport already disconnected.

I fixed that issue right now. Now when shared connections are enabled the transport status is checked before a existing connection will be re-used. If the transport is dead already, the connection object is dropped and a new one will be created.

Thank you for the quick response and fix. But how can i use this updated version ? Normally i use 4.3.1 version in my project which is developed in java 11. I think you updated the current one and it requires java 17, am i right ?

Correct it is only fixed in 5.0.0-SNAPSHOT. If you need to stick to Java 11, you may disable shared connections:
DBusConnectionBuilder.forAddress(busAddress).withShared(false).build()
This should work fine in your case. Sharing a connection is only useful if you have many connections to the same bus and if you are using unix sockets instead of TCP.

Thank you so much