Kafka SASL zookeeper authentication - authentication

I am facing the following error while enabling SASL on Zookeeper and broker authentication.
[2017-04-18 15:54:10,476] DEBUG Size of client SASL token: 0
(org.apache.zookeeper.server.ZooKeeperServer)
[2017-04-18 15:54:10,476] ERROR cnxn.saslServer is null: cnxn object did not initialize its saslServer properly. (org.apache.zookeeper.server. ZooKeeperServer)
[2017-04-18 15:54:10,478] ERROR SASL authentication failed using login context 'Client'. (org.apache.zookeeper.client.ZooKeeperSaslClient)
[2017-04-18 15:54:10,478] DEBUG Received event: WatchedEvent state:AuthFailed type:None path:null (org.I0Itec.zkclient.ZkClient)
[2017-04-18 15:54:10,478] INFO zookeeper state changed (AuthFailed) (org.I0Itec.zkclient.ZkClient)
[2017-04-18 15:54:10,478] DEBUG Leaving process event (org.I0Itec.zkclient.ZkClient)
[2017-04-18 15:54:10,478] DEBUG Closing ZkClient... (org.I0Itec.zkclient.ZkClient)
[2017-04-18 15:54:10,478] INFO Terminate ZkClient event thread. (org.I0Itec.zkclient.ZkEventThread)
[2017-04-18 15:54:10,478] DEBUG Closing ZooKeeper connected to localhost:2181 (org.I0Itec.zkclient.ZkConnection)
[2017-04-18 15:54:10,478] DEBUG Close called on already closed client (org.apache.zookeeper.ZooKeeper)
[2017-04-18 15:54:10,478] DEBUG Closing ZkClient...done (org.I0Itec.zkclient.ZkClient)
[2017-04-18 15:54:10,480] FATAL Fatal error during KafkaServer startup. Prepare to shutdown (kafka.server.KafkaServer)
org.I0Itec.zkclient.exception.ZkAuthFailedException: Authentication failure
at org.I0Itec.zkclient.ZkClient.waitForKeeperState(ZkClient.java:947)
at org.I0Itec.zkclient.ZkClient.waitUntilConnected(ZkClient.java:924)
at org.I0Itec.zkclient.ZkClient.connect(ZkClient.java:1231)
at org.I0Itec.zkclient.ZkClient.<init>(ZkClient.java:157)
at org.I0Itec.zkclient.ZkClient.<init>(ZkClient.java:131)
at kafka.utils.ZkUtils$.createZkClientAndConnection(ZkUtils.scala:79)
at kafka.utils.ZkUtils$.apply(ZkUtils.scala:61)
at kafka.server.KafkaServer.initZk(KafkaServer.scala:329)
at kafka.server.KafkaServer.startup(KafkaServer.scala:187)
at kafka.server.KafkaServerStartable.startup(KafkaServerStartable.scala:39)
at kafka.Kafka$.main(Kafka.scala:67)
at kafka.Kafka.main(Kafka.scala)
[2017-04-18 15:54:10,482] INFO shutting down (kafka.server.KafkaServer)
Following configuration is given in the JAAS file, which is passed as KAFKA_OPTS to take it as JVM parameter:-
KafkaServer {
org.apache.kafka.common.security.plain.PlainLoginModule required
username="admin"
password="admin-secret"
user_admin="admin-secret";
};
Client {
org.apache.kafka.common.security.plain.PlainLoginModule required
username="admin"
password="admin-secret";
};
kafka broker's server.properties has following extra fields set:-
zookeeper.set.acl=true
security.inter.broker.protocol=SASL_PLAINTEXT
sasl.mechanism.inter.broker.protocol=PLAIN
sasl.enabled.mechanisms=PLAIN
ssl.client.auth=required
ssl.endpoint.identification.algorithm=HTTPS
ssl.keystore.location=path
ssl.keystore.password=anything
ssl.key.password=anything
ssl.truststore.location=path
ssl.truststore.password=anything
Zookeeper properties are as follows:
authProvider.1=org.apache.zookeeper.server.auth.DigestAuthenticationProvider
jaasLoginRenew=3600000
requireClientAuthScheme=sasl

I found the issue by increasing the log level to DEBUG. Basically follow the steps below. I don't use SSL but you will integrate it without any issue.
Following are my configuration files:
server.properties
security.inter.broker.protocol=SASL_PLAINTEXT
sasl.mechanism.inter.broker.protocol=PLAIN
sasl.enabled.mechanisms=PLAIN
authorizer.class.name=kafka.security.auth.SimpleAclAuthorizer
allow.everyone.if.no.acl.found=true
auto.create.topics.enable=false
broker.id=0
listeners=SASL_PLAINTEXT://localhost:9092
advertised.listeners=SASL_PLAINTEXT://localhost:9092
num.network.threads=3
num.io.threads=8
socket.send.buffer.bytes=102400
socket.receive.buffer.bytes=102400
socket.request.max.bytes=104857600
advertised.host.name=localhost
num.partitions=1
num.recovery.threads.per.data.dir=1
log.flush.interval.messages=30000000
log.flush.interval.ms=1800000
log.retention.minutes=30
log.segment.bytes=1073741824
log.retention.check.interval.ms=300000
delete.topic.enable=true
zookeeper.connect=localhost:2181
zookeeper.connection.timeout.ms=6000
super.users=User:admin
zookeeper.properties
dataDir=/tmp/zookeeper
clientPort=2181
maxClientCnxns=0
authProvider.1=org.apache.zookeeper.server.auth.SASLAuthenticationProvider
requireClientAuthScheme=sasl
jaasLoginRenew=3600000
producer.properties
security.protocol=SASL_PLAINTEXT
sasl.mechanism=PLAIN
bootstrap.servers=localhost:9092
compression.type=none
consumer.properties
security.protocol=SASL_PLAINTEXT
sasl.mechanism=PLAIN
zookeeper.connect=localhost:2181
zookeeper.connection.timeout.ms=6000
group.id=test-consumer-group
Now are the most important files for making your server starting without any issue:
zookeeper_jaas.conf
Server {
org.apache.kafka.common.security.plain.PlainLoginModule required
username="admin"
password="admin-secret"
user_admin="admin-secret";
};
kafka_server_jaas.conf
KafkaServer {
org.apache.kafka.common.security.plain.PlainLoginModule required
username="admin"
password="admin-secret"
user_admin="admin-secret";
};
Client {
org.apache.kafka.common.security.plain.PlainLoginModule required
username="admin"
password="admin-secret";
};
After doing all these configuration, on a first terminal window:
Terminal 1 (start Zookeeper server)
From kafka root directory
$ export KAFKA_OPTS="-Djava.security.auth.login.config=/home/usename/Documents/kafka_2.11-0.10.1.0/config/zookeeper_jaas.conf"
$ bin/zookeeper-server-start.sh config/zookeeper.properties
Terminal 2 (start Kafka server)
From kafka root directory
$ export KAFKA_OPTS="-Djava.security.auth.login.config=/home/usename/Documents/kafka_2.11-0.10.1.0/config/kafka_server_jaas.conf"
$ bin/kafka-server-start.sh config/server.properties
[BEGIN UPDATE]
kafka_client_jaas.conf
KafkaClient {
org.apache.kafka.common.security.plain.PlainLoginModule required
username="admin"
password="admin-secret";
};
Terminal 3 (start Kafka consumer)
On a client terminal, export client jaas conf file and start consumer:
$ export KAFKA_OPTS="-Djava.security.auth.login.config=/home/username/Documents/kafka_2.11-0.10.1.0/kafka_client_jaas.conf"
$ ./bin/kafka-console-consumer.sh --new-consumer --zookeeper localhost:2181 --topic test-topic --from-beginning --consumer.config=config/consumer.properties --bootstrap-server=localhost:9092
Terminal 4 (start Kafka producer)
If you also want to produce, do this on another terminal window:
$ export KAFKA_OPTS="-Djava.security.auth.login.config=/home/username/Documents/kafka_2.11-0.10.1.0/kafka_client_jaas.conf"
$ ./bin/kafka-console-producer.sh --broker-list localhost:9092 --topic test-topic --producer.config=config/producer.properties
[END UPDATE]

You need to create a JAAS config file for Zookeeper and make it use it.
Create a file JAAS config file for Zookeeper with a content like this:
Server {
org.apache.zookeeper.server.auth.DigestLoginModule required
user_admin="admin-secret";
};
Where user (admin) and password (admin-secret) must match with username and password that you have in Client section of Kafka JAAS config file.
To make Zookeeper use the JAAS config file, pass the following JVM flag to Zookeeper pointing to the file created before.
-Djava.security.auth.login.config=/path/to/server/jaas/file.conf"
If you are using Zookeeper included with Kafka package you can launch Zookeeper like this, assuming that your Zookeeper JAAS config file is located in ./config/zookeeper_jaas.conf
EXTRA_ARGS=-Djava.security.auth.login.config=./config/zookeeper_jaas.conf ./bin/zookeeper-server-start.sh ./config/zookeeper.properties

Related

Failed to save Express session with ioredis in AWS Lambda and Elasticache global redis cluster

I've encountered an error when developing an AWS Elasticache global Redis cluster (with cluster mode enabled) to store user sessions for an AWS Lambda Node 16 Express app as the backend for a website. The main region is us-west-2 and a replica exists in us-east-1. There is no Redis AUTH or TLS encryption currently.
I need to be able to use a cluster mode enabled global Redis cache to ensure users can be connected to the site if one AWS region or AZ fails. I've so far been unable to find a solution to this.
Does anyone know a solution??
The lambda function returns an error when attempting to sign in:
ERROR Error: Connection is closed. at EventEmitter.sendCommand
(/opt/nodejs/node_modules/ioredis/built/cluster/index.js:343:28) at EventEmitter.get
(/opt/nodejs/node_modules/ioredis/built/utils/Commander.js:90:25) at RedisStore.get
(/opt/nodejs/node_modules/connect-redis/lib/connect-redis.js:33:19) at session
(/opt/nodejs/node_modules/express-session/index.js:485:11) at Layer.handle [as handle_request]
(/opt/nodejs/node_modules/express/lib/router/layer.js:95:5) at trim_prefix
(/opt/nodejs/node_modules/express/lib/router/index.js:317:13) at
/opt/nodejs/node_modules/express/lib/router/index.js:284:7 at Function.process_params
(/opt/nodejs/node_modules/express/lib/router/index.js:335:12) at next
(/opt/nodejs/node_modules/express/lib/router/index.js:275:10) at cookieParser
(/opt/nodejs/node_modules/cookie-parser/index.js:71:5)
ioredis enables me to use the primary endpoint for the main cluster in us-west-2 with the following code. (The endpoint and secret are utilized correctly in code, below are placeholders)
import session from 'express-session';
import connectRedis from 'connect-redis';
import Redis from 'ioredis';
// ...
const redisClient = new Redis.Cluster([
{
host: 'redisPrimaryEndpoint',
port: 6379,
},
]);
// ...
const RedisStore = connectRedis(session);
app.use(
session({
store: new RedisStore({ client: redisClient }),
secret: 'a secret',
resave: false,
saveUninitialized: true,
})
);

How to block creating/deleting kafka topic by unauthorized users?

I have setup Kafka and zookeeper authentication with SASL+ACL and Kafka to producer and consumer by SSL two way authentication including encryption.
By enabling SASL and ACL between Kafka and zookeeper it doesn't allow to login unauthorized Kafka broker to the zookeeper cluster. But still, topic creation and deletion can be done without any restrictions.
zookeeper.properties
dataDir=/x02/lsesv2-s/data/Zookeeper
clientPort=15300
tickTime=2000
initLimit=10
syncLimit=5
authProvider.1=org.apache.zookeeper.server.auth.SASLAuthenticationProvider
requireClientAuthScheme=sasl
jaasLoginRenew=3600000
quorum.auth.enableSasl=true
quorum.auth.learnerRequireSasl=true
quorum.auth.serverRequireSasl=true
quorum.auth.learner.loginContext=QuorumLearner
quorum.auth.server.loginContext=QuorumServer
server.1=172.25.33.12:15302:15301
server.2=172.25.33.13:15302:15301
server.3=172.25.33.11:15302:15301
zookeeper_jaas.conf
Server {
org.apache.zookeeper.server.auth.DigestLoginModule required
username="admin"
password="abc123"
user_admin="abc123";
};
QuorumServer {
org.apache.zookeeper.server.auth.DigestLoginModule required
user_admin="abc123";
};
QuorumLearner {
org.apache.zookeeper.server.auth.DigestLoginModule required
username="admin"
password="abc123";
};
Set ACL by below code
final CountDownLatch connectedSignal = new CountDownLatch(1);
String connect = "localhost:15300";
ZooKeeper zooKeeper = null;
try
{
String userName = "admin";
String password = "mit123";
zooKeeper = new ZooKeeper(connect, 5000, we ->
{
if (we.getState() == Watcher.Event.KeeperState.SyncConnected)
{
connectedSignal.countDown();
}
});
connectedSignal.await();
zooKeeper.addAuthInfo("digest", (userName + ":" + password).getBytes());
final String aclString = "auth:" + userName + ":" + password + ":" + "cdrwa" +
",sasl:" + userName + ":" + "cdrwa";
zooKeeper.setACL("/", parseACLs(aclString), -1);
} finally
{
if (zooKeeper != null)
{
zooKeeper.close();
}
}
Above code is working and below is the result after executing the code.
Welcome to ZooKeeper!
JLine support is disabled
WATCHER::
WatchedEvent state:SyncConnected type:None path:null
getAcl /
'sasl,'admin
: cdrwa
'digest,'admin:oiasY+rmnmmK9mec8kpnvv281HE=
: cdrwa
Instead of server.properties file I have overridden Kafka properties when it is started. *
Kafka properties
kafka/bin/kafka-server-start.sh /x02/lsesv2-s/current/kafka/config/server.properties
--override broker.id=1
--override zookeeper.connect=10g-flton-onl01:15300,10g-flton-onl02:15300,10g-flton-nor02:15300
--override num.network.threads=16
--override num.io.threads=16
--override socket.send.buffer.bytes=10240000
--override socket.receive.buffer.bytes=10240000
--override log.dirs=/x02/lsesv2-s/data/Kafka
--override offsets.topic.replication.factor=1
--override min.insync.replicas=1
--override inter.broker.listener.name=INTERNAL
--override listeners=INTERNAL://10g-flton-onl01:15307
--override advertised.listeners=INTERNAL://10g-flton-onl01:15307
--override listener.security.protocol.map=INTERNAL:SSL
--override security.protocol=SSL
--override ssl.client.auth=required
--override ssl.key.password=abc123
--override ssl.keystore.location=configs/MHV/kafka.server.keystore.jks
--override ssl.keystore.password=abc123
--override ssl.truststore.location=configs/MHV/kafka.server.truststore.jks
--override ssl.truststore.password=abc123
--override ssl.endpoint.identification.algorithm=
Kafka to producer/consumer authentication works fine and zookeeper to kafka authentication is also working fine. But still, topic creation and deletion can be done by unauthorized users too.
Topic creation
kafka/bin/kafka-topics.sh --create --zookeeper localhost:15300 --replication-factor 3 --partitions 8 --topic test
Topic deletion
kafka/bin/kafka-topics.sh --zookeeper localhost:15300 --delete --topic test
Note: I didn't set -Djava.security.auth.login.config=kafka_server_jaas.conf when creating or deleting topics. So this operation should be restricted. But actually, it doesn't.
Help me with topic creation and deletion for only authorized users.
It seems this is the required property from testing locally.
KAFKA_ZOOKEEPER_SET_ACL: "true"
For the Confluent images or maps directly too.
zookeeper.set.acl
Reference
Also as stated at Kafka 101 Confluent
the metadata stored in ZooKeeper is such that only brokers will be able to modify the corresponding znodes, but znodes are world readable. 
Because we configured ZooKeeper to require SASL authentication, we need to set the java.security.auth.login.config system property while starting the kafka-topics tool:
A code example and docker-compose file is shown here

When using the node driver, notarisation in flows hangs with a handshake failure

Whenever I try and test using the node driver, I find at the point of notarisation, my flows will hang.
After examining the node logs, it shows that the notary's message broker was unreachable:
[INFO ] 09:33:26,653 [nioEventLoopGroup-3-3] (AMQPClient.kt:91)
netty.AMQPClient.run - Retry connect {}
[INFO ] 09:33:26,657 [nioEventLoopGroup-3-4] (AMQPClient.kt:76)
netty.AMQPClient.operationComplete - Connected to localhost:10001 {}
[INFO ] 09:33:26,658 [nioEventLoopGroup-3-4]
(AMQPChannelHandler.kt:49) O=Notary Service, L=Zurich,
C=CH.channelActive - New client connection db926eb8 from
localhost/127.0.0.1:10001 to /127.0.0.1:63781 {}
[INFO ] 09:33:26,658
[nioEventLoopGroup-3-4] (AMQPClient.kt:86)
netty.AMQPClient.operationComplete - Disconnected from localhost:10001
{}
[ERROR] 09:33:26,658 [nioEventLoopGroup-3-4]
(AMQPChannelHandler.kt:98) O=Notary Service, L=Zurich,
C=CH.userEventTriggered - Handshake failure
SslHandshakeCompletionEvent(java.nio.channels.ClosedChannelException)
{}
[INFO ] 09:33:26,659 [nioEventLoopGroup-3-4]
(AMQPChannelHandler.kt:74) O=Notary Service, L=Zurich,
C=CH.channelInactive - Closed client connection db926eb8 from
localhost/127.0.0.1:10001 to /127.0.0.1:63781 {}
[INFO ] 09:33:26,659
[nioEventLoopGroup-3-4] (AMQPBridgeManager.kt:115)
peers.DLF1ZmHt1DXc9HbxzDNm6VHduUABBbNsp7Mh4DhoBs6ifd ->
localhost:10001:O=Notary Service, L=Zurich, C=CH.onSocketConnected -
Bridge Disconnected {}
While the notary logs display the following:
[INFO ] 13:24:21,735 [main] (ActiveMQServerImpl.java:540)
core.server.internalStart - AMQ221001: Apache ActiveMQ Artemis Message
Broker version 2.2.0 [localhost,
nodeID=7b3df3b8-98aa-11e8-83bd-ead493c8221e] {}
[DEBUG] 13:24:21,735 [main] (ArtemisRpcBroker.kt:51)
rpc.ArtemisRpcBroker.start - Artemis RPC broker is started. {}
[INFO ] 13:24:21,737 [main] (ArtemisMessagingClient.kt:28)
internal.ArtemisMessagingClient.start - Connecting to message broker:
localhost:10001 {}
[ERROR] 13:24:22,298 [main] (NettyConnector.java:713)
core.client.createConnection - AMQ214016: Failed to create netty
connection {} java.nio.channels.ClosedChannelException: null
at io.netty.handler.ssl.SslHandler.channelInactive(...)(Unknown Source) ~[netty-all-4.1.9.Final.jar:4.1.9.Final]
[DEBUG] 13:24:22,362 [main] (PersistentIdentityService.kt:137)
identity.PersistentIdentityService.verifyAndRegisterIdentity -
Registering identity O=Notary Service, L=Zurich, C=CH {}
[WARN ] 13:24:22,363 [main] (AppendOnlyPersistentMap.kt:79)
utilities.AppendOnlyPersistentMapBase.set - Double insert in
net.corda.node.utilities.AppendOnlyPersistentMap for entity class
class
net.corda.node.services.identity.PersistentIdentityService$PersistentIdentity
key 69ACAA32A0C7934D9454CB53EEA6CA6CCD8E4090B30C560A5A36EA10F3DC13E8,
not inserting the second time {}
[ERROR] 13:24:22,368 [main] (NodeStartup.kt:125) internal.Node.run -
Exception during node startup {}
org.apache.activemq.artemis.api.core.ActiveMQNotConnectedException:
AMQ119007: Cannot connect to server(s). Tried with all available
servers.
at org.apache.activemq.artemis.core.client.impl.ServerLocatorImpl.createSessionFactory(ServerLocatorImpl.java:787)
~[artemis-core-client-2.2.0.jar:2.2.0]
at net.corda.nodeapi.internal.ArtemisMessagingClient.start(ArtemisMessagingClient.kt:39)
~[corda-node-api-3.2-corda.jar:?]
at net.corda.nodeapi.internal.bridging.AMQPBridgeManager.start(AMQPBridgeManager.kt:195)
~[corda-node-api-3.2-corda.jar:?]
at net.corda.nodeapi.internal.bridging.BridgeControlListener.start(BridgeControlListener.kt:35)
~[corda-node-api-3.2-corda.jar:?]
at net.corda.node.internal.Node.startMessagingService(Node.kt:301) ~[corda-node-3.2-corda.jar:?]
How do I fix this?
IntelliJ Ultimate ships with the Yourkit profiler, which by default starts when IntelliJ starts and listens on port 100001 - the default port for the Notary in Driver.
You can locate the config for this using here and alter it to use a different port as per this
Your new config line will look something like this:
-agentlib:yjpagent=delay=10000,probe_disable=*,port=30000

Failed to start broker after enabling Zookeeper Authentication

Started Zookeeper with the following properties ie zookeeper.properties
dataDir=/tmp/zookeepeeer
clientPort=2186
maxClientCnxns=0
auto.offset.reset=smallest
authProvider.1=org.apache.zookeeper.server.auth.DigestAuthenticationProvider
jaasLoginRenew=3600000
requireClientAuthScheme=sasl
zookeeper_jaas.conf
Server {
org.apache.kafka.common.security.plain.PlainLoginModule required
username="admin"
password="admin-secret"
user_admin="admin-secret";
};
Server.properties
group.initial.rebalance.delay.ms=0
authorizer.class.name=kafka.security.auth.SimpleAclAuthorizer
listeners=SASL_PLAINTEXT://localhost:9092
security.inter.broker.protocol= SASL_PLAINTEXT
sasl.mechanism.inter.broker.protocol=PLAIN
sasl.enabled.mechanisms=PLAIN
super.users=User:admin
zookeeper.set.acl=true
Kafka_server_jaaz.conf
KafkaServer {
org.apache.kafka.common.security.plain.PlainLoginModule required
username="admin"
password="admin-secret"
user_admin="admin-secret";
};
The error is as follows
java.lang.SecurityException: zookeeper.set.acl is true, but the verification of the JAAS login file failed.
I have tried the below solution but it again fails with the following error inspite of doing the changes
kafka_server_jaaz.conf
KafkaServer {
org.apache.kafka.common.security.plain.PlainLoginModule required
username="admin"
password="admin-secret"
user_admin="admin-secret";
};
Client {
org.apache.kafka.common.security.plain.PlainLoginModule required
username="admin"
password="admin-secret";
};
The server.properties is the same as above
But it fails with the following error:
[2018-02-23 10:16:04,459] ERROR Invalid ACL (kafka.utils.ZKCheckedEphemeral)
[2018-02-23 10:16:04,459] ERROR Invalid ACL (kafka.utils.ZKCheckedEphemeral)
[2018-02-23 10:16:04,460] FATAL [Kafka Server 0], Fatal error during KafkaServer
startup. Prepare to shutdown (kafka.server.KafkaServer)
org.I0Itec.zkclient.exception.ZkException:
org.apache.zookeeper.KeeperException$InvalidACLException: KeeperErrorCode = InvalidACL
In Kafka you also need to configure the SASL client which will be used when connecting to Zookeeper. This is done using the Client context in the Kafka JAAS config, e.g.
Client {
org.apache.kafka.common.security.plain.PlainLoginModule required
username="admin"
password="admin-secret";
};
If needed, the context name can be changed using the zookeeper.sasl.clientconfig system property.

Masstransit cannot access host machine RabbitMQ from a docker container

I created a simple .net core console application with docker support. Following
Masstransit code fails to connect to RabbitMQ instance on host machine. But similar implementation using RabitMq.Client is able to connect to host machine RabbitMQ instance.
Masstransit throws
MassTransit.RabbitMqTransport.RabbitMqConnectionException: Connect
failed: ctas#192.168.0.9:5672/ --->
RabbitMQ.Client.Exceptions.BrokerUnreachableException:
host machine ip : 192.168.0.9
using Masstransit
string rabbitMqUri = "rabbitmq://192.168.0.9/";
string userName = "ctas";
string password = "ctas#123";
string assetServiceQueue = "hello";
var bus = Bus.Factory.CreateUsingRabbitMq(cfg =>
{
var host = cfg.Host(new Uri(rabbitMqUri), hst =>
{
hst.Username(userName);
hst.Password(password);
});
cfg.ReceiveEndpoint(host,
assetServiceQueue, e =>
{
e.Consumer<AddNewAssetReceivedConsumer>();
});
});
bus.Start();
Console.WriteLine("Service Running.... Press enter to exit");
Console.ReadLine();
bus.Stop();
Using RabbitMQ Client
public static void Main()
{
var factory = new ConnectionFactory();
factory.UserName = "ctas";
factory.Password = "ctas#123";
factory.VirtualHost = "watcherindustry";
factory.HostName = "192.168.0.9";
using (var connection = factory.CreateConnection())
using (var channel = connection.CreateModel())
{
channel.QueueDeclare(queue: "hello",
durable: false,
exclusive: false,
autoDelete: false,
arguments: null);
var consumer = new EventingBasicConsumer(channel);
consumer.Received += (model, ea) =>
{
var body = ea.Body;
var message = Encoding.UTF8.GetString(body);
Console.WriteLine(" [x] Received {0}", message);
};
channel.BasicConsume(queue: "hello",
autoAck: true,
consumer: consumer);
Console.WriteLine(" Press [enter] to exit.");
Console.ReadLine();
}
}
Docker file
FROM microsoft/dotnet:1.1-runtime
ARG source
WORKDIR /app
COPY ${source:-obj/Docker/publish} .
ENTRYPOINT ["dotnet", "TestClient.dll"]
I created an example, and was able to connect my host, using the preview package from masstransit.
Start rabbitmq in docker and expose ports on the host
docker run -d -p 5672:5672 -p 15672:15672 --hostname my-rabbit --name some-rabbit rabbitmq:3-management
Build and run console app.
docker build -t dotnetapp .
docker run -d -e RABBITMQ_URI=rabbitmq://guest:guest#172.17.0.2:5672 --name some-dotnetapp dotnetapp
To verify your receiving messages run
docker logs some-dotnetapp --follow
you should see the following output
Application is starting...
Connecting to rabbitmq://guest:guest#172.17.0.2:5672
Received: Hello, World [08/12/2017 04:35:53]
Received: Hello, World [08/12/2017 04:35:58]
Received: Hello, World [08/12/2017 04:36:03]
Received: Hello, World [08/12/2017 04:36:08]
Received: Hello, World [08/12/2017 04:36:13]
...
Notes:
172.17.0.2 was my-rabbit container ip address but you can replace it with your machine ip address
http://localhost:15672 is the rabbitmq management console log in with guest as username and password.
Lastly portainer.io is a very useful application to visually view you local docker environment.
Thanks for the response. I managed to resolve this issue. My findings are as follows.
to connect to a rabbitmq instance on another docker container, they have to be moved/connected to the same network. To do this
create a newtork
docker network create -d bridge my_bridge
connect both app and rabbitmq containers to same network
docker network connect my_bridge <container name>
For masstransit uri use rabbitmq container IP on that network or container name
To connect rabbitmq instance of host machine from a app on docker container.
masstransit uri should include machine name( I tried IP, that did not work)
Try using virtual host in MassTransit configuration too, not sure why you decided to omit it.
var host = cfg.Host("192.168.0.9", "watcherindustry", hst =>
{
hst.Username(userName);
hst.Password(password);
});
Look at Alexey Zimarev comment to your question, if your rabbit runs on a container then it should be on your docker-compese file and then use that entry in your endpoint definition to connect to rabbit because docker creates an internal network on which you are agnostic from source code...
rabbitmq:
container_name: "rabbitmq-yournode01"
hostname: rabbit
image: rabbitmq:3.6.6-management
environment:
- RABBITMQ_DEFAULT_USER=yourusergoeshere
- RABBITMQ_DEFAULT_PASS=yourpasswordgoeshere
- RABBITMQ_DEFAULT_VHOST=vhost
volumes:
- rabbit-volume:/var/lib/rabbitmq
ports:
- "5672:5672"
- "15672:15672"
In your app settings you should have something lie:
"ConnectionString": "host=rabbitmq:5672;virtualHost=vhost;username=yourusergoeshere;password=yourpasswordgoeshere;timeout=0;prefetchcount=1",
And if you'd use EasyNEtQ you could do:
_bus = RabbitHutch.CreateBus(_connectionString); // The one above
I hope it helps,
Juan