RabbitMQ new connection refused due to SocketException - java

while trying to create a new connection to rabbitmq running on a different server, I got the following error:
java.io.IOException
at com.rabbitmq.client.impl.AMQChannel.wrap(AMQChannel.java:106)
at com.rabbitmq.client.impl.AMQChannel.wrap(AMQChannel.java:102)
at com.rabbitmq.client.impl.AMQChannel.exnWrappingRpc(AMQChannel.java:124)
at com.rabbitmq.client.impl.AMQConnection.start(AMQConnection.java:406)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:516)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:533)
Caused by: com.rabbitmq.client.ShutdownSignalException: connection error; reason: java.net.SocketException: Connection reset
at com.rabbitmq.utility.ValueOrException.getValue(ValueOrException.java:67)
at com.rabbitmq.utility.BlockingValueOrException.uninterruptibleGetValue(BlockingValueOrException.java:33)
at com.rabbitmq.client.impl.AMQChannel$BlockingRpcContinuation.getReply(AMQChannel.java:343)
at com.rabbitmq.client.impl.AMQChannel.privateRpc(AMQChannel.java:216)
at com.rabbitmq.client.impl.AMQChannel.exnWrappingRpc(AMQChannel.java:118)
Caused by: java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at java.io.BufferedInputStream.fill(Unknown Source)
at java.io.BufferedInputStream.read(Unknown Source)
at java.io.DataInputStream.readUnsignedByte(Unknown Source)
at com.rabbitmq.client.impl.Frame.readFrom(Frame.java:95)
at com.rabbitmq.client.impl.SocketFrameHandler.readFrame(SocketFrameHandler.java:131)
at com.rabbitmq.client.impl.AMQConnection$MainLoop.run(AMQConnection.java:533)
Steps taken :
rabbitmq is running on the server.
server is specified
default port is specified
lsof -i tcp:5672
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
beam.smp 3084 rabbitmq 15u IPv6 18611 0t0 TCP *:amqp (LISTEN)
rabbitmqctl list_connections
Listing connections ...
guest client_server 55765 running
...done.
netstat -tapnl | grep 5672
tcp 0 0 0.0.0.0:15672 0.0.0.0:* LISTEN 3084/beam.smp
tcp 0 0 0.0.0.0:55672 0.0.0.0:* LISTEN 3084/beam.smp
tcp 0 0 :::5672 :::* LISTEN 3084/beam.smp

One of the possible reasons is that user you are connecting with to RabbitMQ has no rights to access to virtual hosts.
You can check this using Management Plugin (Admin tab).

Do not specify the default port as you have mentioned in your steps.
If you have not created virtual host on the actual server, where you are trying to connect, Do create a virtual host and give it admin permision.
Set the virtual host on the factory before creating the new connection, like factory.setVirtualHost("VIRTUAL_HOST_NAME_ON_SERVER");
Make sure username on the server on which you are trying to connect is Admin and have access to the Virtual Host you just created.
Specify your username and password along with virtual host, while getting the connection.
Start your application in Debug Mode, and check if it now passes, factory.newConection();
This should make your things work.
Got the same exception, and it worked for me.
If it still does not work paste your code snippet.

Check the host and port value
In application.properties
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
See RabbitMQ site is running on port 15672 whereas in code using amqp protocol.

You can check if the SSL/TLS support is enabled. Then use the instruction useSslProtocol :
ConnectionFactory factory = new ConnectionFactory();
factory.useSslProtocol();

I got Unable to connect to AMQP server error when create a new connection. It was confirmed that it was a problem with the firewall. I solved it by command systemctl stop firewalld.

Related

"local port ... cannot be bound" when forwarding port using JSch in Java

I need to connect to MongoDB via SSH tunnel and the JSch port forwarding is throwing an error:
local port 127.0.0.1:27017 cannot be bound
I've to connect to MongoDB via SSH tunnel. I found the code here on stackoverflow and it solved my problem. But after few weeks, the same code stopped working. I'm unable to identify the reason for it. Also, using the same credentials that I'm using in Java code, I also tried to connect to the same via CMD using SSH -L command and it worked properly. I'm also able to connect to MongoDB to using same credentials from NoSQLBrowser. I have tried and searched for everything on google and the problem still remains unsolved. Below is the code for it -
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
JSch jsch = new JSch();
SSH_SESSION = null;
SSH_SESSION = jsch.getSession(SSH_USER, SSH_HOST, SSH_PORT);
SSH_SESSION.setPassword(SSH_PASSWORD);
SSH_SESSION.setConfig(config);
SSH_SESSION.connect();
SSH_SESSION.setPortForwardingL(27017, "localhost", 22);
MongoClient mongoClient = new MongoClient(LOCAL_HOST, LOCAL_PORT);
mongoClient.setReadPreference(ReadPreference.nearest());
MongoCursor<String> dbNames = mongoClient.listDatabaseNames().iterator();
while (dbNames.hasNext()) {
System.out.println(dbNames.next());```
I'm getting the following error on port forwarding line:-
com.jcraft.jsch.JSchException: PortForwardingL: local port 127.0.0.1:27017 cannot be bound.
at com.jcraft.jsch.PortWatcher.<init>(PortWatcher.java:158)
at com.jcraft.jsch.PortWatcher.addPort(PortWatcher.java:110)
at com.jcraft.jsch.Session.setPortForwardingL(Session.java:1847)
at com.jcraft.jsch.Session.setPortForwardingL(Session.java:1828)
at com.jcraft.jsch.Session.setPortForwardingL(Session.java:1809)
at com.jcraft.jsch.Session.setPortForwardingL(Session.java:1792)
at com.schenker.boot.bootdemo.controller.TestMongoAgain.main(TestMongoAgain.java:35)
Caused by: java.net.BindException: Address already in use: JVM_Bind
at java.net.DualStackPlainSocketImpl.bind0(Native Method)
at java.net.DualStackPlainSocketImpl.socketBind(Unknown Source)
at java.net.AbstractPlainSocketImpl.bind(Unknown Source)
at java.net.PlainSocketImpl.bind(Unknown Source)
at java.net.ServerSocket.bind(Unknown Source)
at java.net.ServerSocket.<init>(Unknown Source)
at com.jcraft.jsch.PortWatcher.<init>(PortWatcher.java:150)
... 6 more
com.jcraft.jsch.JSchException: PortForwardingL: local port 127.0.0.1:27017 is not registered.
at com.jcraft.jsch.PortWatcher.delPort(PortWatcher.java:118)
at com.jcraft.jsch.Session.delPortForwardingL(Session.java:1876)
at com.jcraft.jsch.Session.delPortForwardingL(Session.java:1865)
Also, a very strange thing that if instead of PortForwardingL if I use PortForwardingR, it doesn't throw any error but in the next line it gets connected to my local MongoDB. Can anyone please help me with this?
The port 27017 is probably used by some application/service running on your local machine – Probably your local Mongo DB.
Anyway, just pick any other port number. It can be anything.
Though if you use the port for internal use without your application only, you should not rely on a fixed port number. You never know when some other application blocks that port. Have JSch auto-pick a free port:
int forwardedPort = SSH_SESSION.setPortForwardingL(0, "localhost", 22);
MongoClient mongoClient = new MongoClient(LOCAL_HOST, forwardedPort);
Though in general, your code seems wrong. You forward the port to 22, while you probably should forward it to a remote Mongo DB port.
See a full working example (while it's for MySQL, for MongoDB it is the same, just with a different port):
Connect to remote MySQL database through SSH using Java
Obligatory warning: Do not use StrictHostKeyChecking=no to blindly accept all host keys. That is a security flaw. You lose a protection against MITM attacks.
For a correct (and secure) approach, see:
How to resolve Java UnknownHostKey, while using JSch SFTP library?

Problems when trying to attach to a process using jdb

I need to attach a jdb debug session to a java application that is being executed in a remote host, but I am unable to do it. I am working on linux, with openjdk 1.8.0_65, 64-Bit Server VM.
What I have tried
In order to enable the port listening, I have run the java application adding the following arguments to the command line:
-Xdebug -agentlib:jdwp=transport=dt_socket,address=127.0.0.1:8000,server=y,suspend=n
The following message is displayed in the console:
Listening for transport dt_socket at address: 8000
And the application starts running normally.
Then, from the remote host, I execute the following command:
> jdb -connect com.sun.jdi.SocketAttach:hostname=<remote_host>,port=8000
It fails, the output is:
java.net.ConnectException: Conexión rehusada
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
[...]
Fatal error:
Unable to attach to target VM.
What I have checked
In order to check that the port is actually open and I can connect to it from the remote host, I have performed the following operations:
Lets call the host that is executing the java app. hostA, and the one from which I wan to attach the jdb hostB, then:
Check that there is actually a socket listening on port 8000 in hostA
> netstat -tualpn | grep :8000
tcp 0 0 127.0.0.1:8000 0.0.0.0:* LISTEN 1399/<app_name>
In hostA, check that I can connect to the port 8000 (in other words, try to connect from the local host)
> nc -vz localhost 8000
nc: connect to localhost port 8000 (tcp) failed: Connection refused
Connection to localhost 8000 port [tcp/irdmi] succeeded!
With telnet, it seems that it can connect but the connection is closed as soon as it is stablished, maybe because the JVM is expecting some sort of request?
> telnet localhost 8000
Trying ::1...
telnet: connect to address ::1: Connection refused
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Connection closed by foreign host.
The java app. displays the following message when telnet connection is closed:
Debugger failed to attach: timeout during handshak
From hostB, check that I can connect to hostA, port 8000
> nc -vz hostA 8000
nc: connect to hostA port 8000 (tcp) failed: Connection refused
With telnet:
> telnet hostA 8000
Trying 172.17.10.127...
telnet: connect to address 172.17.10.127: Connection refused
So, I can't connect from hostA to hostB through the port 8000, although the JVM is listenning in the port 8000, in hostA.
Since the above fails, I have checked if the firewall is causing the connection refused. I have done it by using the nc command:
In hostA:
# First kill the java app (otherwise the port is busy), then:
> nc -l 8000
In hostB:
> nc -vz <hostA> 8000
Connection to hostA 8000 port [tcp/irdmi] succeeded!
As far as I understand, the above means that there is no firewall (or equivalent) blocking the port.
EDIT
Of course, I have tried to do jdb -attach but it fails even doing it from hostA.
I don't have enough points to comment. So I'm including this as an answer. It really isn't. BUT:
-Xdebug -agentlib:jdwp=transport=dt_socket,address=127.0.0.1:8000,serv=y,suspend=n
Isn't it supposed to be:
-Xdebug -agentlib:jdwp=transport=dt_socket,address=127.0.0.1:8000,server=y,suspend=n
??
[EDIT] You are probably already accounting for this - but also, if you are listening on 127.0.0.1, then it stands to reason that you won't connect from a remote computer. No doubt you are using an actual address, and just didn't include it here...
I have found the connection problem. In the command I use to launch the java application, I have changed the address parameter as following:
Before:
-Xdebug -agentlib:jdwp=transport=dt_socket,address=127.0.0.1:8000,server=y,suspend=n
After (see address):
-Xdebug -agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n

Connect to the MySQL server from another PC (from java application)

I realized an java application that connects to MySQL.
when i make my ip adress of my pc in the navigator of another pc in same local network ,I access to phpMyadmin and Wamp.
When i make 127.0.0.1 on the same pc (Wamp install) I connect to 127.0.0.1 from my java application and it works .
but the problem when I put my ip address in my java application either from my pc or from another pc in same local network , I can not manage to connect .
this is my file of configuration in the java application:
db.user=root
db.password=
db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://192.168.1.59:3306/testfournisseur
Is there a manipulation to do?
This is the errors appear when i connect to the database:
Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
Last packet sent to the server was 1 ms ago.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1074)
at com.mysql.jdbc.MysqlIO.readPacket(MysqlIO.java:666)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1069)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2031)
... 72 more
Caused by: java.io.EOFException: Can not read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpectedly lost.
at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:2431)
at com.mysql.jdbc.MysqlIO.readPacket(MysqlIO.java:590)
... 74 more
I'm unfamiliar with MySQL on Windows but the most common reason I see for being unable to connect is that the bind-address in my.cnf is set to 127.0.0.1, if you change this to 0.0.0.0 or another accessible address then it should work fine.
I also noticed you specify port 80 in your properties example, MySQL runs on 3306 by default so changing the port to that (or omitting it) may work.
Edit: Windows' built-in firewall may be blocking the connection so it's definitely worth checking out.

"java.io.EOFException: SSL peer shut down incorrectly" thrown when not using SSL

I am unable to connect VisualVM to a remote JVM. I have started the remote JVM with the following parameters:
java -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.local.only=false -Dcom.sun.management.jmxremote.port=9000 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false -Djava.rmi.server.hostname=[server ip] -Dlog4j.configurationFile=file:///home/ubuntu/servicesLog4j2.xml -jar /home/ubuntu/Program.jar &
Note the -Dcom.sun.management.jmxremote.ssl=false
I then start VisualVM and add a new JMX connection to the server. I specifically check the option:
Do not require SLL connection
When the connection fails, I can see the following error in the VisualVM log. I am unsure why SSL is involved if I have disabled SSL with a flag on the remote VM and specified not to require SSL in VisualVM. But it would appear this error is preventing the connection. What am I missing?
java.io.EOFException: SSL peer shut down incorrectly
at sun.security.ssl.InputRecord.read(InputRecord.java:505)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:954)
Caused: javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:973)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1343)
at sun.security.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl.java:728)
at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:123)
at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:82)
at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:140)
at java.io.DataOutputStream.flush(DataOutputStream.java:123)
at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:229)
Caused: java.rmi.ConnectIOException: error during JRMP connection establishment; nested exception is:
javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:304)
at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:202)
at sun.rmi.server.UnicastRef.newCall(UnicastRef.java:342)
at sun.rmi.registry.RegistryImpl_Stub.lookup(Unknown Source)
at com.sun.jndi.rmi.registry.RegistryContext.lookup(RegistryContext.java:118)
Caused: javax.naming.CommunicationException [Root exception is java.rmi.ConnectIOException: error during JRMP connection establishment; nested exception is:
javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake]
at com.sun.jndi.rmi.registry.RegistryContext.lookup(RegistryContext.java:122)
at com.sun.jndi.toolkit.url.GenericURLContext.lookup(GenericURLContext.java:205)
at javax.naming.InitialContext.lookup(InitialContext.java:417)
at javax.management.remote.rmi.RMIConnector.findRMIServerJNDI(RMIConnector.java:1929)
at javax.management.remote.rmi.RMIConnector.findRMIServer(RMIConnector.java:1896)
at javax.management.remote.rmi.RMIConnector.connect(RMIConnector.java:287)
Caused: java.io.IOException: Failed to retrieve RMIServer stub
at javax.management.remote.rmi.RMIConnector.connect(RMIConnector.java:369)
at com.sun.tools.visualvm.jmx.impl.JmxModelImpl$ProxyClient.tryConnect(JmxModelImpl.java:569)
[catch] at com.sun.tools.visualvm.jmx.impl.JmxModelImpl$ProxyClient.connect(JmxModelImpl.java:506)
at com.sun.tools.visualvm.jmx.impl.JmxModelImpl.connect(JmxModelImpl.java:234)
at com.sun.tools.visualvm.jmx.impl.JmxModelImpl.<init>(JmxModelImpl.java:223)
at com.sun.tools.visualvm.jmx.impl.JmxModelProvider.createModelFor(JmxModelProvider.java:60)
at com.sun.tools.visualvm.jmx.impl.JmxModelProvider.createModelFor(JmxModelProvider.java:41)
at com.sun.tools.visualvm.core.model.ModelFactory.getModel(ModelFactory.java:111)
at com.sun.tools.visualvm.tools.jmx.JmxModelFactory.getJmxModelFor(JmxModelFactory.java:69)
at com.sun.tools.visualvm.jmx.impl.JmxApplicationProvider.addJmxApplication(JmxApplicationProvider.java:295)
at com.sun.tools.visualvm.jmx.impl.JmxApplicationProvider.createJmxApplication(JmxApplicationProvider.java:200)
at com.sun.tools.visualvm.jmx.JmxApplicationsSupport.createJmxApplicationImpl(JmxApplicationsSupport.java:319)
at com.sun.tools.visualvm.jmx.JmxApplicationsSupport.createJmxApplicationInteractive(JmxApplicationsSupport.java:296)
at com.sun.tools.visualvm.jmx.impl.AddJMXConnectionAction$1.run(AddJMXConnectionAction.java:80)
at org.openide.util.RequestProcessor$Task.run(RequestProcessor.java:1423)
at org.openide.util.RequestProcessor$Processor.run(RequestProcessor.java:2033)
How I managed to solve this after some headaches:
If you have a firewall at the remote machine, you might have issues with the second random port (where remote objects are exported). Try to disable the firewall and if it works then you might have to do something like this. Tomcat have a listener to solve it: link
Make sure that the value under -Djava.rmi.server.hostname resolves to the host from your client location (that was my case)
And finally jconsole (at the JDK bin folder, the same than VisualVM) provides very useful information. Execute it from a console with the -debug option. With the debug option, Jconsole will pop up stacktraces explaining the real reason why your client can't connect. When you try to connect to nonSSL servers JConsole will initially fail and then it will ask you to connect "insecure", next you'll see the real reason, in my case it was looking for the object export port at the loopback IP 127.0.0.1 (because I wasn't using the -Djava.rmi.server.hostname option).
Hope it helps!

java RMI connection to server

I have a very simple rmi client / server application. I don't use the "rmiregistry" application though, I use this to create the server:
server = new RemoteServer();
registry = LocateRegistry.createRegistry(PORT);
registry.bind("RemoteServer", server);
The client part is:
registry = LocateRegistry.getRegistry(IPADDRESS, PORT);
remote = (IRemoteServer) registry.lookup("RemoteServer");
Here is the fascinating problem: The application works perfectly when both server and client are running in my (private) local network. As soon as I put the server on a public server, the application hangs for a minute, then gives me the following error:
java.rmi.ServerException: RemoteException occurred in server thread; nested exception is:
java.rmi.ConnectException: Connection refused to host: 192.168.x.y; nested exception is:
java.net.ConnectException: Connection timed out: connect
at sun.rmi.server.UnicastServerRef.dispatch(Unknown Source)
at sun.rmi.transport.Transport$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Unknown Source)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(Unknown Source)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(Unknown Source ... (the rest is truncated)
The key I think is that the client (running on my private network) cannot connect to myself (my address is 192.168.x.y where x.y is some other numbers, but the real error message shows my ip address listed there)
If I kill the rmi server on the public internet, then I instantly get a "connection refused to host: a.b.c.d") message, so I know that something at the server end is at least working.
Any suggestions?
EDIT: just to make this a little more clear: 192.168.x.y is the client address, a.b.c.d is the server address. The stacktrace shows the client cannot connect to the client.
Try running the server with this parameter for the virtual machine:
-Djava.rmi.server.hostname=hostname_of_the_server
192.168.* contains private IP addresses (as does 10.*). These will not be routed on the open internet. You need to make sure that you are using an public IP address for the server, and any firewalls (including NAT) are configured for access. You can do a quick check with telnet on the required port.
I would believe that the server tries to open a socket back to the client and it fails, and the exception is a bit unclear on its wording.
RMI is not very NAT-friendly, IIRC.

Categories