Exemplo n.º 1
0
        public void test_EnumerateQueues()
        {
            MQConnection con = null;

            try {
                con = connectToServer(address, null, null);

                addAllQueues(con);
                List <QueueData> qnames = new List <QueueData>();
                ErrorCode        ec     = con.EnumerateQueues(qnames);
                Assert.IsTrue(ec == ErrorCode.EC_NOERROR, "Couldn't enumerate queues");

                for (int x = 0; x < TEST_QUEUE.Length; x++)
                {
                    bool found = false;
                    for (int y = 0; y < qnames.Count; y++)
                    {
                        QueueData qd = qnames[y];
                        if (qd.Name.Equals(TEST_QUEUE[x]))
                        {
                            found = true;
                        }
                    }
                    Assert.IsTrue(found, "Queue not enumerated: " + TEST_QUEUE[0]);
                }
            } finally {
                if (con != null)
                {
                    con.Close();
                }
            }
        }
Exemplo n.º 2
0
        public void test_EnumerateUsers()
        {
            MQConnection con = null;

            try {
                con = connectToServer(address, null, null);

                addAllUsers(con);
                List <UserDescription> unames = new List <UserDescription>();
                ErrorCode ec = con.EnumerateUsers(unames);
                Assert.IsTrue(ec == ErrorCode.EC_NOERROR, "Couldn't enumerate users");

                for (int x = 0; x < TEST_USERS.Length; x++)
                {
                    bool found = false;
                    for (int y = 0; y < unames.Count; y++)
                    {
                        UserDescription ud = unames[y];
                        if (ud.Name.Equals(TEST_USERS[x]))
                        {
                            found = true;
                        }
                    }
                    Assert.IsTrue(found, "User not enumerated: " + TEST_USERS[0]);
                }
            } finally {
                if (con != null)
                {
                    con.Close();
                }
            }
        }
Exemplo n.º 3
0
        public void test_GroupPermissions()
        {
            MQConnection con = null;

            try {
                con = connectToServer(address, null, null);
                createNewGroup(con, TEST_GROUPS[0]);
                ErrorCode ec;
                for (int x = 7; x >= 0; x--)
                {
                    ec = con.GroupSetPermissions(TEST_GROUPS[0], (x & 0x04) != 0, (x & 0x2) != 0, (x & 0x1) != 0);
                    Assert.IsTrue(ec == ErrorCode.EC_NOERROR, "Failed to set permissions for: " + TEST_GROUPS[0]);
                    ActorPermissions actorPerms = new ActorPermissions();
                    ec = con.GroupGetPermissions(TEST_GROUPS[0], actorPerms);
                    Assert.IsTrue(ec == ErrorCode.EC_NOERROR, "Failed to retrive permissions for: " + TEST_GROUPS[0]);
                    Assert.IsTrue(actorPerms.ModifyQueues == ((x & 0x04) != 0), "Modify queues incorrectly set: " + x);
                    Assert.IsTrue(actorPerms.ModifyUsers == ((x & 0x02) != 0), "Modify users incorrectly set: " + x);
                    Assert.IsTrue(actorPerms.ModifyGroups == ((x & 0x01) != 0), "Modify groups incorrectly set: " + x);
                }
            } finally {
                if (con != null)
                {
                    con.Close();
                }
            }
        }
Exemplo n.º 4
0
        public void test_CreateTempQueue()
        {
            using (MQConnection con = connectToServer(address, null, null)) {
                String      queueName = String.Empty;
                QueueHandle qh        = new QueueHandle();

                // Try and create a temporary queue
                ErrorCode err = con.CreateTempQueue(out queueName, qh);
                Console.WriteLine("queueName:" + queueName);
                Assert.AreEqual(ErrorCode.EC_NOERROR, err, "Creating Queue");

                // Get permissions for that queue
                List <QueuePermissions> perms = new List <QueuePermissions>();
                con.QueueEnumeratePermissions(queueName, perms);
                for (int x = 0; x < perms.Count; ++x)
                {
                    QueuePermissions perm = perms[x];
                    Console.WriteLine(perm.EntityName + ":" + perm.Read + ":" + perm.Write + ":" + perm.Destroy + ":" + perm.ChangeSecurity);
                }
                Assert.IsTrue(perms.Count > 0);

                addAllUsers(con);

                // Try and write to that queue with another user.
                using (MQConnection con2 = connectToServer(simpleAddress, TEST_USERS[0], TEST_USERS[0])) {
                    QueueHandle qh2 = new QueueHandle();
                    ErrorCode   rc  = con2.OpenQueue(queueName, qh2);
                    Assert.IsTrue(rc == ErrorCode.EC_NOERROR, "Open Temp Queue rc:" + rc);
                    QueueMessage msg = new QueueMessage();
                    msg.Label = "Hello World";
                    Assert.IsTrue(ErrorCode.EC_NOERROR == con2.Enqueue(qh2, msg), "Enqueue to temp");
                    con2.CloseQueue(qh2);
                }
            }
        }
Exemplo n.º 5
0
 public static bool Push(MQMessage message)
 {
     try
     {
         using (var channel = MQConnection.CreateModel())
         {
             channel.QueueDeclare(queue: MQQueueName,
                                  durable: true,
                                  exclusive: false,
                                  autoDelete: false,
                                  arguments: null);
             var properties = channel.CreateBasicProperties();
             properties.Persistent = true;
             //---------------------------------
             channel.BasicPublish(exchange: "",
                                  routingKey: MQQueueName,
                                  basicProperties: properties,
                                  body: message.ObjectToByteArray());
             //--------------------
             return(true);
         }
     }
     catch (Exception ex)
     {
         log.Error(ex);
         return(false);
     }
 }
Exemplo n.º 6
0
        public void test_EnumerateGroups()
        {
            MQConnection con = null;

            try {
                con = connectToServer(address, null, null);

                addAllGroups(con);
                List <string> gnames = new List <string>();
                ErrorCode     ec     = con.EnumerateGroups(gnames);
                Assert.IsTrue(ec == ErrorCode.EC_NOERROR, "Couldn't enumerate groups");

                for (int x = 0; x < TEST_GROUPS.Length; x++)
                {
                    bool found = false;
                    for (int y = 0; y < gnames.Count; y++)
                    {
                        string group = gnames[y];
                        if (group.Equals(TEST_GROUPS[x]))
                        {
                            found = true;
                        }
                    }
                    Assert.IsTrue(found, "Group not enumerated: " + TEST_GROUPS[0]);
                }
            } finally {
                if (con != null)
                {
                    con.Close();
                }
            }
        }
Exemplo n.º 7
0
 public RedisQueueRawServerListener(MQConnection connection, IMQueueRawServer server, bool responseServer) : base(connection, server, responseServer)
 {
     _name = server.Name;
     _messageHandlerDelegate = new Action <RedisChannel, RedisValue>(MessageHandler);
     _processDelegate        = new Func <RedisValue, Task>(ProcessingTaskAsync);
     _monitorDelegate        = new Func <Task>(MonitorProcess);
 }
Exemplo n.º 8
0
        public static bool Consumer(Func <MQMessage, bool> excuteMessage)
        {
            try
            {
                using (var channel = MQConnection.CreateModel())
                {
                    channel.QueueDeclare(queue: MQQueueName,
                                         durable: true,
                                         exclusive: false,
                                         autoDelete: false,
                                         arguments: null);
                    channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false);

                    var consumer = new EventingBasicConsumer(channel);
                    consumer.Received += (ch, ea) =>
                    {
                        var body = ea.Body;
                        // ... process the message
                        MQMessage msg = ByteArrayToObject <MQMessage>(body);
                        if (excuteMessage(msg))
                        {
                            channel.BasicAck(ea.DeliveryTag, false);
                        }
                    };
                    String consumerTag = channel.BasicConsume(MQQueueName, false, consumer);
                    return(true);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
            return(false);
        }
Exemplo n.º 9
0
 public RequestReceivedEventArgs(string name, MQConnection sender, RequestMessage request, int messageLength, ISerializer senderSerializer, int cancellationBeforeClientResponseTimeoutInSec)
 {
     _senderSerializer = senderSerializer;
     Name          = name;
     Request       = request;
     Sender        = sender;
     MessageLength = messageLength;
     SendResponse  = request?.Header?.ResponseExpected ?? true;
     ProcessResponseTimeoutInSeconds = request?.Header?.ResponseTimeoutInSeconds ?? -1;
     Response = new ResponseMessage(request, null);
     if (ProcessResponseTimeoutInSeconds > 0)
     {
         _cancellationTokenSource = new CancellationTokenSource();
         ProcessResponseTimeoutCancellationToken = _cancellationTokenSource.Token;
         if (cancellationBeforeClientResponseTimeoutInSec > ProcessResponseTimeoutInSeconds)
         {
             Core.Log.Warning($"The cancellation time before client response timeout can't be greater than the ProcessResponseTimeout sent by the client. [CancellationBeforeClientResponseTimeout={cancellationBeforeClientResponseTimeoutInSec}, ProcessResponseTimeoutInSeconds={ProcessResponseTimeoutInSeconds}]");
             _cancellationTokenSource.CancelAfter(TimeSpan.FromSeconds(ProcessResponseTimeoutInSeconds));
         }
         else if (cancellationBeforeClientResponseTimeoutInSec < 0)
         {
             Core.Log.Warning($"The cancellation time before client response timeout can't be lower than 0.");
             _cancellationTokenSource.CancelAfter(TimeSpan.FromSeconds(ProcessResponseTimeoutInSeconds));
         }
         else
         {
             _cancellationTokenSource.CancelAfter(TimeSpan.FromSeconds(ProcessResponseTimeoutInSeconds - cancellationBeforeClientResponseTimeoutInSec));
         }
     }
     else
     {
         ProcessResponseTimeoutCancellationToken = CancellationToken.None;
     }
 }
Exemplo n.º 10
0
        SSLContext setupSSL()
        {
            // Setup the SSL Context using the JKS file created via gen_test_cert in the java/cert directory
            MQConnection con = connectToServer(address, "", "");

            ErrorCode ec = con.DeleteUser(user);

            Assert.IsTrue(ec == ErrorCode.EC_NOERROR || ec == ErrorCode.EC_DOESNOTEXIST, "Delete User");
            ec = con.CreateUser(user, password, description);
            Assert.IsTrue(ec == ErrorCode.EC_NOERROR, "Create User");
            Console.WriteLine("Adding Identity, user: "******" subject: " + subject);
            ec = con.AddUserIdentity(subject, issuer, user);
            Assert.IsTrue(ec == ErrorCode.EC_NOERROR, "AddUserIdentity");

            con.Close();

            SSLContext ctx = new SSLContext();

            ctx.ServerValidator     = new RemoteCertificateValidationCallback(SafmqSSLTest.ServerValidator);
            ctx.CertificateProvider = new LocalCertificateSelectionCallback(SafmqSSLTest.CertificateProvider);

            X509Certificate c = new X509Certificate(@"e:\blacksheep\safmq.trunk\safmq.net\safmq.net.test\sample.p12", "test");

            ctx.ClientCertificateList = new X509CertificateCollection();
            ctx.ClientCertificateList.Add(c);

            X509Certificate2 c2    = new X509Certificate2(@"e:\blacksheep\safmq.trunk\safmq.net\safmq.net.test\sample.p12", "test");
            X509Store        store = new X509Store(StoreName.My);

            store.Open(OpenFlags.ReadWrite);
            store.Add(c2);
            store.Close();

            return(ctx);
        }
Exemplo n.º 11
0
        public static MQMessage Pull()
        {
            //var factory = new ConnectionFactory() { HostName = MQHostName, UserName = MQUserName, Password = MQPassword };
            //using (var connection = factory.CreateConnection())

            try
            {
                using (var channel = MQConnection.CreateModel())
                {
                    channel.QueueDeclare(queue: MQQueueName,
                                         durable: true,
                                         exclusive: false,
                                         autoDelete: false,
                                         arguments: null);
                    //var properties = channel.CreateBasicProperties();
                    //properties.Persistent = true;
                    channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false);
                    BasicGetResult result = channel.BasicGet(MQQueueName, false);
                    if (result != null)
                    {
                        MQMessage model = ByteArrayToObject <MQMessage>(result.Body);
                        channel.BasicAck(result.DeliveryTag, false);
                        return(model);
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
            return(null);
        }
Exemplo n.º 12
0
        public void test_PasswordlessSignon()
        {
            ErrorCode ec;

            MQConnection con = connectToServer(address, "", "");

            ec = con.DeleteUser(user);
            Assert.IsTrue(ec == ErrorCode.EC_NOERROR || ec == ErrorCode.EC_DOESNOTEXIST, "Delete User");

            ec = con.CreateUser(user, password, description);
            Assert.IsTrue(ec == ErrorCode.EC_NOERROR, "Create User");

            ec = con.AddUserIdentity(subject, issuer, user);
            Assert.IsTrue(ec == ErrorCode.EC_NOERROR, "AddUserIdentity");

            List <X509Identity> ids = new List <X509Identity>();

            ec = con.EnumerateUserIdentities(user, ids);
            Assert.IsTrue(ec == ErrorCode.EC_NOERROR, "EnumerateUserIdentities");
            Assert.IsTrue(ids.Count > 0, "X.509 ID Count");
            // TODO: Check the results in the ids
            bool idFound = false;

            for (int x = 0; x < ids.Count; x++)
            {
                X509Identity id = ids[0];
                if (id.IssuerDN.Equals(issuer) && id.SubjectDN.Equals(subject))
                {
                    idFound = true;
                }
            }
            Assert.IsTrue(idFound, "Identity found in returned X.509 identities");
            con.Close();
        }
Exemplo n.º 13
0
        public MQChannel CreateChannel(string queue, string routeKey, string exchangeType)
        {
            MQConnection conn    = new MQConnection(this.UserName, this.Password, this.Host, this.Port, this.vHost, this.logger);
            MQChannel    channel = conn.CreateReceiveChannel(exchangeType, this.Exchange, queue, routeKey);

            return(channel);
        }
Exemplo n.º 14
0
 void addAllQueues(MQConnection con)
 {
     for (int x = 0; x < TEST_QUEUE.Length; x++)
     {
         createEmptyQueue(con, TEST_QUEUE[x]);
     }
 }
Exemplo n.º 15
0
 void addAllGroups(MQConnection con)
 {
     for (int x = 0; x < TEST_GROUPS.Length; x++)
     {
         createNewGroup(con, TEST_GROUPS[x]);
     }
 }
Exemplo n.º 16
0
 void addAllUsers(MQConnection con)
 {
     for (int x = 0; x < TEST_USERS.Length; x++)
     {
         createNewUser(con, TEST_USERS[x], TEST_DESC[x], TEST_PASSWD[x]);
     }
 }
Exemplo n.º 17
0
        /// <summary>
        /// 创建信道,添加一个信道到信道池
        /// </summary>
        /// <returns></returns>
        public bool NewChannel()
        {
            var q = ConnList.Where(o =>
            {
                return(o.ChannelCount < ConnecitonMaxChannelCount);
            });

            q = q.OrderBy(
                o => o.ChannelCount
                );
            var Conn = q.FirstOrDefault();


            if (Conn == null)
            {
                MQConnection newConn = new MQConnection(Serverconfg.Host, Serverconfg.Account, Serverconfg.Pass, Serverconfg.Port, Serverconfg.VirtualHost);

                ConnList.Add(newConn);

                Conn = newConn;
            }

            var Channel = Conn.CreateChannel();

            this.EnqueueFreeChannel(Channel);

            this.AllChannel.Add(Channel);

            return(true);
        }
Exemplo n.º 18
0
        public MQChannel CreateChannel(string queue, string routeKey, string exchangeType)
        {
            MQConnection     conn    = new MQConnection(this.Config, this.vHost);
            MQChannelManager cm      = new MQChannelManager(conn);
            MQChannel        channel = cm.CreateReceiveChannel(exchangeType, this.Exchange, queue, routeKey);

            return(channel);
        }
Exemplo n.º 19
0
        void createNewGroup(MQConnection con, string groupName)
        {
            ErrorCode ec = con.DeleteGroup(groupName);

            Assert.IsTrue((ec == ErrorCode.EC_NOERROR || ec == ErrorCode.EC_DOESNOTEXIST), "Failed to remove group prior to create: " + groupName);
            ec = con.CreateGroup(groupName);
            Assert.IsTrue(ec == ErrorCode.EC_NOERROR, "Failed to create group: " + groupName);
        }
Exemplo n.º 20
0
 public RawRequestReceivedEventArgs(string name, MQConnection sender, MultiArray <byte> request, Guid correlationId, int messageLength)
 {
     Name          = name;
     Request       = request;
     CorrelationId = correlationId;
     Sender        = sender;
     MessageLength = messageLength;
 }
Exemplo n.º 21
0
        /// <inheritdoc />
        /// <summary>
        /// Delete a message queue
        /// </summary>
        /// <param name="queue">Message Queue connection instance</param>
        /// <returns>true if the message queue was deleted; otherwise, false.</returns>
        public bool Delete(MQConnection queue)
        {
            var client = new NsqdHttpClient(queue.Route.Replace(":4150", ":4151"), TimeSpan.FromSeconds(60));

            client.DeleteChannel(queue.Name, queue.Name);
            client.DeleteTopic(queue.Name);
            return(true);
        }
Exemplo n.º 22
0
        void createNewUser(MQConnection con, string userName, string description, string password)
        {
            ErrorCode ec = con.DeleteUser(userName);

            Assert.IsTrue((ec == ErrorCode.EC_NOERROR || ec == ErrorCode.EC_DOESNOTEXIST), "Failed to remove user prior to create: " + userName);
            ec = con.CreateUser(userName, password, description);
            Assert.IsTrue(ec == ErrorCode.EC_NOERROR, "Failed to create user: " + userName);
        }
Exemplo n.º 23
0
        /// <inheritdoc />
        /// <summary>
        /// Delete a message queue
        /// </summary>
        /// <param name="queue">Message Queue connection instance</param>
        /// <returns>true if the message queue was deleted; otherwise, false.</returns>
        public bool Delete(MQConnection queue)
        {
            var rabbitQueue = new RabbitMQueue(queue);

            rabbitQueue.EnsureConnectionAsync(2000, 100).WaitAndResults();
            rabbitQueue.Channel.QueueDelete(queue.Name, false, false);
            rabbitQueue.Close();
            return(true);
        }
Exemplo n.º 24
0
 public RabbitMQueueServerListener(MQConnection connection, IMQueueServer server, bool responseServer) : base(connection, server, responseServer)
 {
     _messageType = responseServer ? typeof(ResponseMessage) : typeof(RequestMessage);
     _name        = server.Name;
     Core.Status.Attach(collection =>
     {
         collection.Add("Message Type", _messageType);
     });
 }
Exemplo n.º 25
0
        /// <inheritdoc />
        /// <summary>
        /// Delete a message queue
        /// </summary>
        /// <param name="queue">Message Queue connection instance</param>
        /// <returns>true if the message queue was deleted; otherwise, false.</returns>
        public bool Delete(MQConnection queue)
        {
            var rabbitQueue = new RabbitMQueue(queue);

            rabbitQueue.EnsureConnection();
            rabbitQueue.Channel.QueueDelete(queue.Name, false, false);
            rabbitQueue.Close();
            return(true);
        }
Exemplo n.º 26
0
 public RabbitMQueue(MQConnection queue)
 {
     Route               = queue.Route;
     Name                = queue.Name;
     Parameters          = queue.Parameters ?? new KeyValueCollection();
     ExchangeName        = Parameters[nameof(ExchangeName)];
     ExchangeType        = Parameters[nameof(ExchangeType)];
     Durable             = Parameters[nameof(Durable)].ParseTo(false);
     _internalConnection = InternalConnection;
 }
Exemplo n.º 27
0
 public NATSQueueServerListener(MQConnection connection, IMQueueServer server, bool responseServer) : base(connection, server, responseServer)
 {
     _factory     = new ConnectionFactory();
     _messageType = responseServer ? typeof(ResponseMessage) : typeof(RequestMessage);
     _name        = server.Name;
     Core.Status.Attach(collection =>
     {
         collection.Add(nameof(_messageType), _messageType);
     });
 }
Exemplo n.º 28
0
 /// <summary>
 /// Redis queue connection
 /// </summary>
 /// <param name="connection">Base connection</param>
 public RedisMQConnection(MQConnection connection)
 {
     if (string.IsNullOrEmpty(connection.Route))
     {
         throw new UriFormatException($"The route for the connection to {connection.Name} is null.");
     }
     Name       = connection.Name;
     Parameters = connection.Parameters;
     Route      = connection.Route;
 }
Exemplo n.º 29
0
        public static void ReceiveStatusMessage()
        {
            var model    = MQConnection.GetRabbitChannel(MessageQueues.Constants.Queries.StatusQuery);
            var consumer = new EventingBasicConsumer(model);

            consumer.Received += Status_Received;
            model.BasicConsume(MessageQueues.Constants.Queries.StatusQuery, true, consumer);

            Console.WriteLine("Start status processing...");
        }
Exemplo n.º 30
0
 public RabbitMQueue(MQConnection queue)
 {
     Route            = queue.Route;
     Name             = queue.Name;
     Parameters       = queue.Parameters ?? new KeyValueCollection();
     ExchangeName     = Parameters[nameof(ExchangeName)];
     ExchangeType     = Parameters[nameof(ExchangeType)];
     Durable          = Parameters[nameof(Durable)].ParseTo(true);
     _autoCloseAction = ActionDelegate.Create(Close).CreateBufferedAction(60000);
 }