protected override void AfterStart(OpenedQueue queue)
 {
     base.AfterStart(queue);
     SendToQueue(primaryLoadBalancer, new QueryForAllKnownWorkersAndEndpoints());
     SendToQueue(primaryLoadBalancer, new QueryReadyForWorkQueueUri());
     StartTrackingHeartbeats();
 }
Пример #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);
     }
 }
Пример #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);
            }
        }
Пример #4
0
 protected override void BeforeStart(OpenedQueue queue)
 {
     foreach (var messageAction in transportActions)
     {
         messageAction.Init(this, queue);
     }
 }
Пример #5
0
 protected override void BeforeStart(OpenedQueue queue)
 {
     foreach (var messageAction in transportActions)
     {
         messageAction.Init(this, queue);
     }
 }
Пример #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();
		}
Пример #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;
            }
        }
Пример #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)
                }));
        }
Пример #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);
     }
 }
Пример #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());
     }
 }
Пример #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);
     }
 }
Пример #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);
     }
 }
Пример #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);
        }
Пример #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;
		}
Пример #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;
        }
Пример #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);
            }
        }
Пример #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;
            }
        }
Пример #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;
     }
 }
Пример #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);
					}
				}
			}
		}
Пример #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()
     });
 }
Пример #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));
        }
Пример #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);
            }
        }
Пример #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);
        }
Пример #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))
                                 	};
                }
            }
        }
Пример #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);
     });
 }
Пример #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);
			}
		}
Пример #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);
 }
Пример #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();
		}
Пример #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;
                }
        }
Пример #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);
            }
        }
Пример #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()
     };
 }
Пример #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);
        }
Пример #35
0
 public OpenedQueue(OpenedQueue parent, MessageQueue queue, string url)
     : this(parent.info, queue, url, parent.transactional)
 {
     this.parent = parent;
 }
Пример #36
0
 protected virtual void BeforeStart(OpenedQueue queue)
 {
 }
Пример #37
0
 protected virtual void BeforeStart(OpenedQueue queue)
 {
 }
Пример #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);
		}
Пример #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);
				}
			}
		}
Пример #40
0
 public void SendToErrorQueue(OpenedQueue queue, Message message)
 {
     queue.Send(message);
 }
Пример #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);
			}
		}
Пример #42
0
 protected abstract void HandlePeekedMessage(OpenedQueue queue, Message message);
Пример #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);
		}
Пример #44
0
 protected virtual void AfterStart(OpenedQueue queue)
 {
 }
Пример #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);
			}
		}
Пример #46
0
 public OpenedQueue OpenSubQueue(OpenedQueue queue, SubQueue subQueue, QueueAccessMode accessMode)
 {
     return(queue.OpenSubQueue(subQueue, accessMode));
 }
Пример #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);
      });
 }
Пример #49
0
 protected virtual void AfterStart(OpenedQueue queue)
 {
 }
Пример #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));
 }
Пример #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;
            }
        }
Пример #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);
            }
        }
Пример #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;
 }
Пример #54
0
 protected abstract void HandlePeekedMessage(OpenedQueue queue, Message message);