protected override void AfterStart(OpenedQueue queue)
 {
     base.AfterStart(queue);
     SendToQueue(primaryLoadBalancer, new QueryForAllKnownWorkersAndEndpoints());
     SendToQueue(primaryLoadBalancer, new QueryReadyForWorkQueueUri());
     StartTrackingHeartbeats();
 }
Exemplo n.º 2
0
 public bool TryMoveMessage(OpenedQueue queue, Message message, SubQueue subQueue, out string msgId)
 {
     using (var destinationQueue = queue.OpenSiblngQueue(subQueue, QueueAccessMode.Send))
     {
         Message receiveById;
         try
         {
             receiveById = queue.ReceiveById(message.Id);
         }
         catch (InvalidOperationException)
         {
             msgId = null;
             return(false);
         }
         receiveById.AppSpecific = 0;//reset flag
         destinationQueue.Send(receiveById);
         msgId = receiveById.Id;
         logger.DebugFormat("Moving messgage {0} from {1} to {2}, new id: {3}",
                            message.Id,
                            queue.RootUri,
                            destinationQueue.QueueUrl,
                            receiveById.Id);
         return(true);
     }
 }
Exemplo n.º 3
0
        protected override void HandlePeekedMessage(OpenedQueue queue, Message message)
        {
            foreach (var action in transportActions)
            {
                if (action.CanHandlePeekedMessage(message) == false)
                {
                    continue;
                }

                try
                {
                    if (action.HandlePeekedMessage(this, queue, message))
                    {
                        return;
                    }
                }
                catch (Exception e)
                {
                    logger.Error("Error when trying to execute action " + action + " on message " + message.Id + ". Message has been removed without handling!", e);
                    queue.ConsumeMessage(message.Id);
                }
            }

            if (consumeInTransaction)
            {
                ReceiveMessageInTransaction(queue, message.Id, MessageArrived, MessageProcessingCompleted, BeforeMessageTransactionCommit);
            }
            else
            {
                ReceiveMessage(queue, message.Id, MessageArrived, MessageProcessingCompleted);
            }
        }
Exemplo n.º 4
0
 protected override void BeforeStart(OpenedQueue queue)
 {
     foreach (var messageAction in transportActions)
     {
         messageAction.Init(this, queue);
     }
 }
Exemplo n.º 5
0
 protected override void BeforeStart(OpenedQueue queue)
 {
     foreach (var messageAction in transportActions)
     {
         messageAction.Init(this, queue);
     }
 }
Exemplo n.º 6
0
		protected override void BeforeStart(OpenedQueue queue)
		{
			try
			{
				queueStrategy.InitializeQueue(Endpoint, QueueType.LoadBalancer);
			}
			catch (Exception e)
			{
				throw new TransportException(
					"Could not open queue for load balancer: " + Endpoint + Environment.NewLine +
					"Queue path: " + MsmqUtil.GetQueuePath(Endpoint), e);
			}

			try
			{
				ReadUrisFromSubQueue(KnownWorkers, SubQueue.Workers);
			}
			catch (Exception e)
			{
				throw new InvalidOperationException("Could not read workers subqueue", e);
			}

			try
			{
				ReadUrisFromSubQueue(KnownEndpoints, SubQueue.Endpoints);
			}
			catch (Exception e)
			{
				throw new InvalidOperationException("Could not read endpoints subqueue", e);
			}

			RemoveAllReadyToWorkMessages();
		}
Exemplo n.º 7
0
        protected object[] DeserializeMessages(OpenedQueue messageQueue, Message transportMessage, Action <CurrentMessageInformation, Exception> messageSerializationException)
        {
            try
            {
                return(messageSerializer.Deserialize(transportMessage.BodyStream));
            }
            catch (Exception e)
            {
                try
                {
                    logger.Error("Error when serializing message", e);
                    if (messageSerializationException != null)
                    {
                        var information = new MsmqCurrentMessageInformation
                        {
                            MsmqMessage = transportMessage,
                            Queue       = messageQueue,
                            Message     = transportMessage,
                            Source      = messageQueue.RootUri,
                            MessageId   = transportMessage.GetMessageId(),
                            Headers     = transportMessage.Extension.DeserializeHeaders(),
                        };

                        messageSerializationException(information, e);
                    }
                }
                catch (Exception moduleEx)
                {
                    logger.Error("Error when notifying about serialization exception", moduleEx);
                }
                throw;
            }
        }
Exemplo n.º 8
0
        public MsmqFlatQueueTestBase()
        {
            defaultTestBase = new MsmqTestBase();

            testQueueEndPoint = new Endpoint
            {
                Uri = new Uri("msmq://localhost/test_queue")
            };
            testQueuePath = MsmqUtil.GetQueuePath(testQueueEndPoint).QueuePath;

            transactionalTestQueueEndpoint = new Endpoint
            {
                Uri = new Uri("msmq://localhost/transactional_test_queue")
            };
            transactionalTestQueuePath = MsmqUtil.GetQueuePath(transactionalTestQueueEndpoint).QueuePath;

            subscriptionsEndpoint = new Endpoint
            {
                Uri = new Uri(testQueueEndPoint.Uri + "#" + subscriptions)
            };
            subscriptionQueuePath = MsmqUtil.GetQueuePath(subscriptionsEndpoint).QueuePath;

            SetupQueues();

            queue = MsmqUtil.GetQueuePath(testQueueEndPoint).Open();
            transactionalQueue = MsmqUtil.GetQueuePath(transactionalTestQueueEndpoint).Open();
            subscriptions = MsmqUtil.GetQueuePath(subscriptionsEndpoint).Open(QueueAccessMode.SendAndReceive,
                new XmlMessageFormatter(new[]
                {
                    typeof (string)
                }));
        }
Exemplo n.º 9
0
 /// <summary>
 /// Moves the message from the timeout queue to the main queue.
 /// </summary>
 /// <param name="queue">The queue.</param>
 /// <param name="messageId">The message id.</param>
 public void MoveTimeoutToMainQueue(OpenedQueue queue, string messageId)
 {
     using (var timeoutQueue = queue.OpenSubQueue(SubQueue.Timeout, QueueAccessMode.Receive))
     {
         var message = timeoutQueue.ReceiveById(messageId);
         message.AppSpecific = 0;//reset timeout flag
         queue.Send(message);
     }
 }
Exemplo n.º 10
0
 public void SendToErrorQueue(OpenedQueue queue, Message message)
 {
     using (var errQueue = new MessageQueue(GetErrorsQueuePath()))
     {
         // here we assume that the queue transactionalibilty is the same for the error sibling queue
         // and the main queue!
         errQueue.Send(message, queue.GetSingleTransactionType());
     }
 }
Exemplo n.º 11
0
 /// <summary>
 /// Moves the message from the timeout queue to the main queue.
 /// </summary>
 /// <param name="queue">The queue.</param>
 /// <param name="messageId">The message id.</param>
 public void MoveTimeoutToMainQueue(OpenedQueue queue, string messageId)
 {
     using (var timeoutQueue = queue.OpenSubQueue(SubQueue.Timeout, QueueAccessMode.Receive))
     {
         var message = timeoutQueue.ReceiveById(messageId);
         message.AppSpecific = 0;                //reset timeout flag
         queue.Send(message);
     }
 }
Exemplo n.º 12
0
 /// <summary>
 /// Moves the message from the timeout queue to the main queue.
 /// </summary>
 /// <param name="queue">The queue.</param>
 /// <param name="messageId">The message id.</param>
 public void MoveTimeoutToMainQueue(OpenedQueue queue, string messageId)
 {
     using (var destinationQueue = new MessageQueue(GetTimeoutQueuePath(), QueueAccessMode.Receive))
     {
         destinationQueue.MessageReadPropertyFilter.SetAll();
         var message = destinationQueue.ReceiveById(messageId);
         message.AppSpecific = 0;//reset timeout flag
         queue.Send(message);
     }
 }
Exemplo n.º 13
0
        private void ReceiveMessage(OpenedQueue queue, string messageId, Func <CurrentMessageInformation, bool> messageArrived, Action <CurrentMessageInformation, Exception> messageProcessingCompleted)
        {
            var message = queue.TryGetMessageFromQueue(messageId);

            if (message == null)
            {
                return;
            }

            ProcessMessage(message, queue, null, messageArrived, null, messageProcessingCompleted);
        }
Exemplo n.º 14
0
		public OpenedQueue Open(QueueAccessMode access, IMessageFormatter formatter)
		{
			var messageQueue = new MessageQueue(QueuePath, access);
			if (formatter != null)
				messageQueue.Formatter = formatter;
			var openedQueue = new OpenedQueue(this, messageQueue, QueueUri.ToString(),Transactional)
			{
				Formatter = formatter
			};
			if (SubQueue != null)
				return openedQueue.OpenSubQueue(SubQueue.Value, access);
			return openedQueue;
		}
Exemplo n.º 15
0
        public void Init(ITransport transport, IServiceBus bus)
        {
            var endpoint = endpointRouter.GetRoutedEndpoint(logQueue);
            var queueInfo = MsmqUtil.GetQueuePath(endpoint);
            queueInfo.Create();
            queue = queueInfo.Open(QueueAccessMode.Send);

            transport.MessageArrived += Transport_OnMessageArrived;
            transport.MessageProcessingFailure += Transport_OnMessageProcessingFailure;
            transport.MessageProcessingCompleted += Transport_OnMessageProcessingCompleted;
            transport.MessageSerializationException += Transport_OnMessageSerializationException;
            transport.MessageSent+=Transport_OnMessageSent;
        }
Exemplo n.º 16
0
        public void ReceiveMessageInTransaction(OpenedQueue queue, string messageId, Func <CurrentMessageInformation, bool> messageArrived, Action <CurrentMessageInformation, Exception> messageProcessingCompleted, Action <CurrentMessageInformation> beforeMessageTransactionCommit, Action <CurrentMessageInformation> beforeMessageTransactionRollback)
        {
            using (var tx = _transactionStrategy.Begin())
            {
                var message = queue.TryGetMessageFromQueue(messageId);

                if (message == null)
                {
                    return;// someone else got our message, better luck next time
                }
                ProcessMessage(message, queue, tx, messageArrived, beforeMessageTransactionCommit, beforeMessageTransactionRollback, messageProcessingCompleted);
            }
        }
Exemplo n.º 17
0
        private void ProcessMessage(
            Message message,
            OpenedQueue messageQueue,
            TransactionScope tx,
            Func <CurrentMessageInformation, bool> messageRecieved,
            Action <CurrentMessageInformation> beforeMessageTransactionCommit,
            Action <CurrentMessageInformation> beforeMessageTransactionRollback,
            Action <CurrentMessageInformation, Exception> messageCompleted)
        {
            Exception ex = null;

            currentMessageInformation = CreateMessageInformation(messageQueue, message, null, null);
            try
            {
                //deserialization errors do not count for module events
                object[] messages = DeserializeMessages(messageQueue, message, MessageSerializationException);
                try
                {
                    foreach (object msg in messages)
                    {
                        currentMessageInformation = CreateMessageInformation(messageQueue, message, messages, msg);

                        if (TransportUtil.ProcessSingleMessage(currentMessageInformation, messageRecieved) == false)
                        {
                            Discard(currentMessageInformation.Message);
                        }
                    }
                }
                catch (Exception e)
                {
                    ex = e;
                    logger.Error("Failed to process message", e);
                }
            }
            catch (Exception e)
            {
                ex = e;
                logger.Error("Failed to deserialize message", e);
            }
            finally
            {
                Action sendMessageBackToQueue = null;
                if (message != null && (messageQueue.IsTransactional == false || consumeInTransaction == false))
                {
                    sendMessageBackToQueue = () => messageQueue.Send(message);
                }
                var messageHandlingCompletion = new MessageHandlingCompletion(tx, sendMessageBackToQueue, ex, messageCompleted, beforeMessageTransactionCommit, beforeMessageTransactionRollback, logger, MessageProcessingFailure, currentMessageInformation);
                messageHandlingCompletion.HandleMessageCompletion();
                currentMessageInformation = null;
            }
        }
Exemplo n.º 18
0
 public bool TryMoveMessage(OpenedQueue queue, Message message, SubQueue subQueue, out string msgId)
 {
     try
     {
         queue.MoveToSubQueue(subQueue, message);
         msgId = message.Id;
         return true;
     }
     catch (TransportException)
     {
         msgId = null;
         return false;
     }
 }
Exemplo n.º 19
0
 public bool TryMoveMessage(OpenedQueue queue, Message message, SubQueue subQueue, out string msgId)
 {
     try
     {
         queue.MoveToSubQueue(subQueue, message);
         msgId = message.Id;
         return(true);
     }
     catch (TransportException)
     {
         msgId = null;
         return(false);
     }
 }
		private void HandleLoadBalancerMessage(OpenedQueue queue, Message message)
		{
			foreach (var msg in DeserializeMessages(queue, message, null))
			{
				var work = msg as ReadyToWork;
				if (work != null)
				{
					var copy = ReadyToWorkMessageArrived;
					if(copy != null)
					{
						copy(work);
					}
				}
			}
		}
Exemplo n.º 21
0
 private MsmqCurrentMessageInformation CreateMessageInformation(OpenedQueue queue, Message message, object[] messages, object msg)
 {
     return(new MsmqCurrentMessageInformation
     {
         MessageId = message.GetMessageId(),
         AllMessages = messages,
         Message = msg,
         Queue = queue,
         TransportMessageId = message.Id,
         Destination = Endpoint.Uri,
         Source = MsmqUtil.GetQueueUri(message.ResponseQueue),
         MsmqMessage = message,
         TransactionType = queue.GetTransactionType()
     });
 }
Exemplo n.º 22
0
        public void RaiseMessageSerializationException(OpenedQueue queue, Message msg, string errorMessage)
        {
            var copy = MessageSerializationException;

            if (copy == null)
            {
                return;
            }
            var messageInformation = new MsmqCurrentMessageInformation
            {
                MsmqMessage = msg,
                Queue       = queue,
                Message     = null,
                Source      = queue.RootUri,
                MessageId   = Guid.Empty
            };

            copy(messageInformation, new SerializationException(errorMessage));
        }
Exemplo n.º 23
0
        public void ReceiveMessageInTransaction(OpenedQueue queue, string messageId, Func <CurrentMessageInformation, bool> messageArrived, Action <CurrentMessageInformation, Exception> messageProcessingCompleted, Action <CurrentMessageInformation> beforeMessageTransactionCommit)
        {
            var transactionOptions = new TransactionOptions
            {
                IsolationLevel = queueIsolationLevel,
                Timeout        = TransportUtil.GetTransactionTimeout(),
            };

            using (var tx = new TransactionScope(TransactionScopeOption.Required, transactionOptions))
            {
                var message = queue.TryGetMessageFromQueue(messageId);

                if (message == null)
                {
                    return;// someone else got our message, better luck next time
                }
                ProcessMessage(message, queue, tx, messageArrived, beforeMessageTransactionCommit, messageProcessingCompleted);
            }
        }
Exemplo n.º 24
0
        public OpenedQueue Open(QueueAccessMode access, IMessageFormatter formatter)
        {
            var messageQueue = new MessageQueue(QueuePath, access);

            if (formatter != null)
            {
                messageQueue.Formatter = formatter;
            }
            var openedQueue = new OpenedQueue(this, messageQueue, QueueUri.ToString(), Transactional)
            {
                Formatter = formatter
            };

            if (SubQueue != null)
            {
                return(openedQueue.OpenSubQueue(SubQueue.Value, access));
            }
            return(openedQueue);
        }
Exemplo n.º 25
0
        /// <summary>
        /// Gets a listing of all timeout messages.
        /// </summary>
        /// <returns></returns>
        public IEnumerable<TimeoutInfo> GetTimeoutMessages(OpenedQueue queue)
        {
            using (var timeoutQueue = queue.OpenSiblngQueue(SubQueue.Timeout, QueueAccessMode.Receive))
            {
                var enumerator2 = timeoutQueue.GetMessageEnumerator2();
                while (enumerator2.MoveNext())
                {
                    var message = enumerator2.Current;
                    if (message == null)
                        continue;

                    yield return new TimeoutInfo
                                 	{
                                 		Id = message.Id,
                                 		Time = DateTime.FromBinary(BitConverter.ToInt64(message.Extension, 0))
                                 	};
                }
            }
        }
Exemplo n.º 26
0
 private void RemoveSubscriptionMessageFromQueue(OpenedQueue queue, string type, Uri uri)
 {
     subscriptionMessageIds.Write(writer =>
     {
         var key = new TypeAndUriKey
         {
             TypeName = type,
             Uri      = uri
         };
         IList <string> messageIds;
         if (writer.TryGetValue(key, out messageIds) == false)
         {
             return;
         }
         foreach (var msgId in messageIds)
         {
             queue.ConsumeMessage(msgId);
         }
         writer.Remove(key);
     });
 }
Exemplo n.º 27
0
        /// <summary>
        /// Gets a listing of all timeout messages.
        /// </summary>
        /// <returns></returns>
        public IEnumerable <TimeoutInfo> GetTimeoutMessages(OpenedQueue queue)
        {
            using (var timeoutQueue = queue.OpenSiblngQueue(SubQueue.Timeout, QueueAccessMode.Receive))
            {
                var enumerator2 = timeoutQueue.GetMessageEnumerator2();
                while (enumerator2.MoveNext())
                {
                    var message = enumerator2.Current;
                    if (message == null || message.Extension.Length < 16)
                    {
                        continue;
                    }

                    yield return(new TimeoutInfo
                    {
                        Id = message.Id,
                        Time = DateTime.FromBinary(BitConverter.ToInt64(message.Extension, 16))
                    });
                }
            }
        }
		protected override void HandlePeekedMessage(OpenedQueue queue, Message message)
		{
			try
			{
				using (var tx = new TransactionScope(TransactionScopeOption.Required, TransportUtil.GetTransactionTimeout()))
				{
					message = queue.TryGetMessageFromQueue(message.Id);
					if (message == null)
						return;

					if ((MessageType) message.AppSpecific == MessageType.LoadBalancerMessageMarker)
					{
						HandleLoadBalancerMessage(queue, message);
					}
				tx.Complete();
				}
			}
			catch (Exception e)
			{
				logger.Error("Fail to process load balanced message properly", e);
			}
		}
Exemplo n.º 29
0
 private bool?TryPeek(OpenedQueue queue, out Message message)
 {
     try
     {
         message = queue.Peek(TimeOutForPeek);
     }
     catch (MessageQueueException e)
     {
         message = null;
         if (e.MessageQueueErrorCode != MessageQueueErrorCode.IOTimeout)
         {
             logger.Error("Could not peek message from queue", e);
             return(false);
         }
         return(null); // nothing found
     }
     catch (Exception e)
     {
         message = null;
         logger.Error("Could not peek message from queue", e);
         return(false);
     }
     return(true);
 }
Exemplo n.º 30
0
		protected override void AfterStart(OpenedQueue queue)
		{
			if (_readyForWorkListener != null)
			{
				_readyForWorkListener.ReadyToWorkMessageArrived += readyForWorkMessage => HandleReadyForWork(queue, readyForWorkMessage);
				_readyForWorkListener.Start();
			}
			
			if (secondaryLoadBalancer != null)
			{
				foreach (var queueUri in KnownEndpoints.GetValues())
				{
					logger.InfoFormat("Notifying {0} that primary load balancer {1} is taking over from secondary",
						queueUri,
						Endpoint.Uri
						);
					SendToQueue(queueUri, new Reroute
					{
						NewEndPoint = Endpoint.Uri,
						OriginalEndPoint = Endpoint.Uri
					});
				}

				SendHeartBeatToSecondaryServer(null);
				heartBeatTimer.Change(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
				Reroute reroute;
				if (_readyForWorkListener != null)
					reroute = new Reroute
					{
						NewEndPoint = _readyForWorkListener.Endpoint.Uri,
						OriginalEndPoint = _readyForWorkListener.Endpoint.Uri
					};
				else
					reroute = new Reroute
					{
						NewEndPoint = Endpoint.Uri,
						OriginalEndPoint = Endpoint.Uri
					};

				SendToAllWorkers(
					GenerateMsmqMessageFromMessageBatch(reroute),
					"Rerouting {1} back to {0}"
					);
			}

			if (ShouldNotifyWorkersLoaderIsReadyToAcceptWorkOnStartup)
				NotifyWorkersThatLoaderIsReadyToAcceptWork();
		}
Exemplo n.º 31
0
        private void ProcessMessage(
            Message message,
            OpenedQueue messageQueue,
            TransactionScope tx,
            Func<CurrentMessageInformation, bool> messageRecieved,
            Action<CurrentMessageInformation, Exception> messageCompleted)
        {
            Exception ex = null;
                currentMessageInformation = CreateMessageInformation(messageQueue, message, null, null);
                try
                {
                    //deserialization errors do not count for module events
                    object[] messages = DeserializeMessages(messageQueue, message, MessageSerializationException);
                    try
                    {
                        foreach (object msg in messages)
                        {
                            currentMessageInformation = CreateMessageInformation(messageQueue, message, messages, msg);

                            if (TransportUtil.ProcessSingleMessage(currentMessageInformation, messageRecieved) == false)
                                Discard(currentMessageInformation.Message);
                        }
                    }
                    catch (Exception e)
                    {
                        ex = e;
                        logger.Error("Failed to process message", e);
                    }
                }
                catch (Exception e)
                {
                    ex = e;
                    logger.Error("Failed to deserialize message", e);
                }
                finally
                {
                    HandleMessageCompletion(message, tx, messageQueue, ex, messageCompleted);
                    currentMessageInformation = null;
                }
        }
Exemplo n.º 32
0
        private void HandleMessageCompletion(
            Message message,
            TransactionScope tx,
            OpenedQueue messageQueue,
            Exception exception,
            Action<CurrentMessageInformation, Exception> messageCompleted)
        {
            if (exception == null)
            {
                try
                {
                    if (tx != null)
                    {
                        tx.Complete();
                        tx.Dispose();
                    }
                    try
                    {
                        if (messageCompleted != null)
                            messageCompleted(currentMessageInformation, exception);
                    }
                    catch (Exception e)
                    {
                        logger.Error("An error occured when raising the MessageCompleted event, the error will NOT affect the message processing", e);
                    }
                    return;
                }
                catch (Exception e)
                {
                    logger.Warn("Failed to complete transaction, moving to error mode", e);
                    exception = e;
                }
            }
            if (message == null)
                return;

            try
            {
                if (messageCompleted != null)
                    messageCompleted(currentMessageInformation, exception);
            }
            catch (Exception e)
            {
                logger.Error("An error occured when raising the MessageCompleted event, the error will NOT affect the message processing", e);
            }

            try
            {
                var copy = MessageProcessingFailure;
                if (copy != null)
                    copy(currentMessageInformation, exception);
            }
            catch (Exception moduleException)
            {
                logger.Error("Module failed to process message failure: " + exception.Message,
                                             moduleException);
            }

            if (messageQueue.IsTransactional == false)// put the item back in the queue
            {
                messageQueue.Send(message);
            }
        }
Exemplo n.º 33
0
 private MsmqCurrentMessageInformation CreateMessageInformation(OpenedQueue queue,Message message, object[] messages, object msg)
 {
     return new MsmqCurrentMessageInformation
     {
         MessageId = message.GetMessageId(),
         AllMessages = messages,
         Message = msg,
         Queue = queue,
         TransportMessageId = message.Id,
         Destination = Endpoint.Uri,
         Source = MsmqUtil.GetQueueUri(message.ResponseQueue),
         MsmqMessage = message,
         TransactionType = queue.GetTransactionType()
     };
 }
Exemplo n.º 34
0
        protected override void HandlePeekedMessage(OpenedQueue queue,Message message)
        {
            foreach (var action in transportActions)
            {
                if(action.CanHandlePeekedMessage(message)==false)
                    continue;

                try
                {
                    if (action.HandlePeekedMessage(this, queue, message))
                        return;
                }
                catch (Exception e)
                {
                    logger.Error("Error when trying to execute action " + action + " on message " + message.Id + ". Message has been removed without handling!", e);
                    queue.ConsumeMessage(message.Id);
                }
            }
            ReceiveMessageInTransaction(queue, message.Id, MessageArrived, MessageProcessingCompleted);
        }
Exemplo n.º 35
0
 public OpenedQueue(OpenedQueue parent, MessageQueue queue, string url)
     : this(parent.info, queue, url, parent.transactional)
 {
     this.parent = parent;
 }
Exemplo n.º 36
0
 protected virtual void BeforeStart(OpenedQueue queue)
 {
 }
Exemplo n.º 37
0
 protected virtual void BeforeStart(OpenedQueue queue)
 {
 }
Exemplo n.º 38
0
		private void HandleReadyForWork(OpenedQueue queue, ReadyToWork work)
		{
			logger.DebugFormat("{0} is ready to work", work.Endpoint);
			var needToAddToQueue = KnownWorkers.Add(work.Endpoint);

			if (needToAddToQueue)
				AddWorkerToQueue(queue, work);

			readyForWork.Enqueue(work.Endpoint);
		}
Exemplo n.º 39
0
		private void HandleStandardMessage(OpenedQueue queue, Message message)
		{
			var worker = readyForWork.Dequeue();

			if (worker == null) // handle message later
			{
				queue.Send(message);

                continuousDeliveryFailures++;

                if (continuousDeliveryFailures >= 100)
                {
                    System.Threading.Thread.Sleep(1000);
                    continuousDeliveryFailures = 0;
                }
			}
			else
			{
                continuousDeliveryFailures = 0;
				var workerEndpoint = endpointRouter.GetRoutedEndpoint(worker);
				using (var workerQueue = MsmqUtil.GetQueuePath(workerEndpoint).Open(QueueAccessMode.Send))
				{
					logger.DebugFormat("Dispatching message '{0}' to {1}", message.Id, workerEndpoint.Uri);
					workerQueue.Send(message);
				}
			}
		}
Exemplo n.º 40
0
 public void SendToErrorQueue(OpenedQueue queue, Message message)
 {
     queue.Send(message);
 }
Exemplo n.º 41
0
		protected override void HandlePeekedMessage(OpenedQueue queue, Message message)
		{
			try
			{
				using (var tx = new TransactionScope(TransactionScopeOption.Required, TransportUtil.GetTransactionTimeout()))
				{
					message = queue.TryGetMessageFromQueue(message.Id);
					if (message == null)
						return;

					PersistEndpoint(queue, message);

					switch ((MessageType)message.AppSpecific)
					{
						case MessageType.ShutDownMessageMarker:
							//silently cnsume the message
							break;
						case MessageType.LoadBalancerMessageMarker:
							HandleLoadBalancerMessage(queue, message);
							break;
						case MessageType.AdministrativeMessageMarker:
							SendToAllWorkers(message, "Dispatching administrative message from {0} to load balancer {1}");
							break;
						default:
							HandleStandardMessage(queue, message);
							break;
					}
					tx.Complete();
				}
			}
			catch (Exception e)
			{
				logger.Error("Fail to process load balanced message properly", e);
			}
		}
Exemplo n.º 42
0
 protected abstract void HandlePeekedMessage(OpenedQueue queue, Message message);
Exemplo n.º 43
0
		private void PersistEndpoint(OpenedQueue queue, Message message)
		{
			var queueUri = MsmqUtil.GetQueueUri(message.ResponseQueue);
			if (queueUri == null)
				return;
			bool needToPersist = knownEndpoints.Add(queueUri);
			if (needToPersist == false)
				return;

			logger.InfoFormat("Adding new endpoint: {0}", queueUri);
			var persistedEndPoint = new Message
			{
				Formatter = new XmlMessageFormatter(new[] { typeof(string) }),
				Body = queueUri.ToString(),
				Label = ("Known end point: " + queueUri).EnsureLabelLength()
			};
			queue.Send(persistedEndPoint.SetSubQueueToSendTo(SubQueue.Endpoints));

			SendToQueue(secondaryLoadBalancer, new NewEndpointPersisted
			{
				PersistedEndpoint = queueUri
			});
			Raise(SentNewEndpointPersisted);
		}
Exemplo n.º 44
0
 protected virtual void AfterStart(OpenedQueue queue)
 {
 }
Exemplo n.º 45
0
		private void HandleLoadBalancerMessage(OpenedQueue queue, Message message)
		{
			foreach (var msg in DeserializeMessages(queue, message, null))
			{

				var query = msg as QueryForAllKnownWorkersAndEndpoints;
				if (query != null)
				{
					SendKnownWorkersAndKnownEndpoints(message.ResponseQueue);
					continue;
				}
				var queryReadyForWorkQueueUri = msg as QueryReadyForWorkQueueUri;
				if (queryReadyForWorkQueueUri != null)
				{
					SendReadyForWorkQueueUri(message.ResponseQueue);
					continue;
				}
				var work = msg as ReadyToWork;
				if (work != null)
				{
					HandleReadyForWork(queue, work);
				}

				HandleLoadBalancerMessages(msg);
			}
		}
Exemplo n.º 46
0
 public OpenedQueue OpenSubQueue(OpenedQueue queue, SubQueue subQueue, QueueAccessMode accessMode)
 {
     return(queue.OpenSubQueue(subQueue, accessMode));
 }
Exemplo n.º 47
0
		private void AddWorkerToQueue(OpenedQueue queue, ReadyToWork work)
		{
			var persistedWorker = new Message
			{
				Formatter = new XmlMessageFormatter(new[] { typeof(string) }),
				Body = work.Endpoint.ToString(),
				Label = ("Known worker: " + work.Endpoint).EnsureLabelLength()
			};
			logger.InfoFormat("New worker: {0}", work.Endpoint);
			queue.Send(persistedWorker.SetSubQueueToSendTo(SubQueue.Workers));

			SendToQueue(secondaryLoadBalancer, new NewWorkerPersisted
			{
				Endpoint = work.Endpoint
			});
			Raise(SentNewWorkerPersisted);
		}
 private void RemoveSubscriptionMessageFromQueue(OpenedQueue queue, string type, Uri uri)
 {
     subscriptionMessageIds.Write(writer =>
     {
          var key = new TypeAndUriKey
          {
              TypeName = type,
              Uri = uri
          };
          IList<string> messageIds;
          if (writer.TryGetValue(key, out messageIds) == false)
              return;
          foreach (var msgId in messageIds)
          {
              queue.ConsumeMessage(msgId);
          }
          writer.Remove(key);
      });
 }
Exemplo n.º 49
0
 protected virtual void AfterStart(OpenedQueue queue)
 {
 }
Exemplo n.º 50
0
 public void RaiseMessageSerializationException(OpenedQueue queue, Message msg, string errorMessage)
 {
     var copy = MessageSerializationException;
     if (copy == null)
         return;
     var messageInformation = new MsmqCurrentMessageInformation
     {
         MsmqMessage = msg,
         Queue = queue,
         Message = null,
         Source = queue.RootUri,
         MessageId = Guid.Empty
     };
     copy(messageInformation, new SerializationException(errorMessage));
 }
Exemplo n.º 51
0
        protected object[] DeserializeMessages(OpenedQueue messageQueue, Message transportMessage, Action<CurrentMessageInformation, Exception> messageSerializationException)
        {
            try
            {
                return messageSerializer.Deserialize(transportMessage.BodyStream);
            }
            catch (Exception e)
            {
                try
                {
                    logger.Error("Error when serializing message", e);
                    if (messageSerializationException != null)
                    {
                        var information = new MsmqCurrentMessageInformation
                        {
                            MsmqMessage = transportMessage,
                            Queue = messageQueue,
                            Message = transportMessage,
                            Source = messageQueue.RootUri,
                            MessageId = transportMessage.GetMessageId(),
                            Headers = transportMessage.Extension.DeserializeHeaders(),
                        };

                        messageSerializationException(information, e);
                    }
                }
                catch (Exception moduleEx)
                {
                    logger.Error("Error when notifying about serialization exception", moduleEx);
                }
                throw;
            }
        }
Exemplo n.º 52
0
        public void ReceiveMessageInTransaction(OpenedQueue queue, string messageId, Func<CurrentMessageInformation, bool> messageArrived, Action<CurrentMessageInformation, Exception> messageProcessingCompleted)
        {
            var transactionOptions = new TransactionOptions
            {
                IsolationLevel = queueIsolationLevel,
                Timeout = TransportUtil.GetTransactionTimeout(),
            };
            using (var tx = new TransactionScope(TransactionScopeOption.Required, transactionOptions))
            {
                var message = queue.TryGetMessageFromQueue(messageId);

                if (message == null)
                    return;// someone else got our message, better luck next time

                ProcessMessage(message, queue, tx, messageArrived, messageProcessingCompleted);
            }
        }
Exemplo n.º 53
0
 private bool? TryPeek(OpenedQueue queue, out Message message)
 {
     try
     {
         message = queue.Peek(TimeOutForPeek);
     }
     catch (MessageQueueException e)
     {
         message = null;
         if (e.MessageQueueErrorCode != MessageQueueErrorCode.IOTimeout)
         {
             logger.Error("Could not peek message from queue", e);
             return false;
         }
         return null; // nothing found
     }
     catch (Exception e)
     {
         message = null;
         logger.Error("Could not peek message from queue", e);
         return false;
     }
     return true;
 }
Exemplo n.º 54
0
 protected abstract void HandlePeekedMessage(OpenedQueue queue, Message message);