public async Task ProcessAsync(IDispatchTarget target, NamespacedName key, ReconcileData data, CancellationToken cancellationToken) { try { var message = new Message { MessageType = MessageType.Update, Key = $"{key.Namespace}:{key.Name}" }; var context = new YarpIngressContext(data.Ingress, data.ServiceList, data.EndpointsList); YarpParser.CovertFromKubernetesIngress(context); message.Cluster = context.Clusters; message.Routes = context.Routes; var bytes = JsonSerializer.SerializeToUtf8Bytes(message); _logger.LogInformation(JsonSerializer.Serialize(message)); await _dispatcher.SendAsync(target, bytes, cancellationToken).ConfigureAwait(false); } catch (Exception ex) { _logger.LogWarning(ex.Message); throw; } }
public void Detach(IDispatchTarget target) { _logger.LogDebug("Detaching {DispatchTarget}", target?.ToString()); lock (_targetsSync) { _targets = _targets.Remove(target); } }
public void Attach(IDispatchTarget target) { _logger.LogDebug("Attaching {DispatchTarget}", target?.ToString()); lock (_targetsSync) { _targets = _targets.Add(target); } _attached?.Invoke(target); }
/// <summary> /// Called each time a new connection arrives on the /api/dispatch endpoint. /// All of the currently-known Ingress names are queued up to be sent /// to the new target. /// </summary> /// <param name="target">The interface to target a connected client.</param> private void TargetAttached(IDispatchTarget target) { var keys = new List <NamespacedName>(); _cache.GetKeys(keys); foreach (var key in keys) { _queue.Add(new QueueItem(key, target)); } }
/// <summary> /// Called each time a new connection arrives on the /api/dispatch endpoint. /// All of the currently-known Ingress names are queued up to be sent /// to the new target. /// </summary> /// <param name="target">The interface to target a connected client.</param> private void TargetAttached(IDispatchTarget target) { var keys = new List <NamespacedName>(); _cache.GetKeys(keys); if (keys.Count > 0) { _queue.Add(new QueueItem("Target Attached", target)); } }
public void Detach(IDispatchTarget target) { #pragma warning disable CA1303 // Do not pass literals as localized parameters _logger.LogDebug("Detaching {DispatchTarget}", target?.ToString()); #pragma warning restore CA1303 // Do not pass literals as localized parameters lock (_targetsSync) { _targets = _targets.Remove(target); } }
private async Task <bool> SubscribeTopicAsyncInternal(Topic topic, BufferBlock <Message> messageQueue = null) { ITopic solTopic = ContextFactory.Instance.CreateTopic(topic.Name); FlowBindings.FlowBindingElement binding = null; if (messageQueue == null) { // Use default message block messageQueue = defaultAppMsgQueue; } bool newSubscription = flowBindings.AddBinding(topic, messageQueue, null, out binding); if (newSubscription && binding != null) { try { TaskCompletionSource <SessionEventArgs> tcs = new TaskCompletionSource <SessionEventArgs>(); IDispatchTarget dTarget = session.CreateDispatchTarget(solTopic, async(sender, msgEv) => await AcceptMessageEventAsync(msgEv, binding).ConfigureAwait(false)); binding.TopicDispatchTarget = dTarget; session.Subscribe(dTarget, SubscribeFlag.RequestConfirm, tcs); // Check subscription result var result = await tcs.Task.ConfigureAwait(false); if (result.Event == SessionEvent.SubscriptionOk) { return(true); } else { logger.LogError("Subscription error to topic: {0} responseCode {1} errorInfo: {2}", topic.Name, result.ResponseCode, result.Info); return(false); } } catch (Exception e) { binding.TopicDispatchTarget = null; flowBindings.RemoveBinding(topic, out binding); throw new MessagingException(e.Message, e); } } if (!newSubscription && binding != null) { // If existing subscription then ignore and return success return(true); } return(false); }
public async Task SendAsync(IDispatchTarget specificTarget, byte[] utf8Bytes, CancellationToken cancellationToken) { if (specificTarget != null) { await specificTarget.SendAsync(utf8Bytes, cancellationToken).ConfigureAwait(false); } else { foreach (var target in _targets) { await target.SendAsync(utf8Bytes, cancellationToken).ConfigureAwait(false); } } }
public async Task AttachAsync(IDispatchTarget target, CancellationToken cancellationToken) { #pragma warning disable CA1303 // Do not pass literals as localized parameters _logger.LogDebug("Attaching {DispatchTarget}", target?.ToString()); #pragma warning restore CA1303 // Do not pass literals as localized parameters lock (_targetsSync) { _targets = _targets.Add(target); } if (_lastMessage is not null) { await target.SendAsync(_lastMessage, cancellationToken).ConfigureAwait(false); } }
private async Task <bool> SubscribeTopicAsyncInternal(string topic) { // Ignore if we have already subscribed to the topic before if (topicSubscriptions.ContainsKey(topic)) { return(true); } try { var solTopic = ContextFactory.Instance.CreateTopic(topic); TaskCompletionSource <SessionEventArgs> tcs = new TaskCompletionSource <SessionEventArgs>(); IDispatchTarget dTarget = session.CreateDispatchTarget(solTopic, async(sender, msgEv) => await AcceptMessageEventAsync(msgEv).ConfigureAwait(false)); topicSubscriptions.Add(topic, dTarget); session.Subscribe(dTarget, SubscribeFlag.RequestConfirm, tcs); // Check subscription result var result = await tcs.Task.ConfigureAwait(false); if (result.Event == SessionEvent.SubscriptionOk) { return(true); } else { logger.Error("Subscription error to topic: {0} responseCode {1} errorInfo: {2}", topic, result.ResponseCode, result.Info); return(false); } } catch (Exception e) { throw new MessagingException(e.Message, e); } }
private void Attached(IDispatchTarget target) { _attached?.Invoke(target); }
public QueueItem(NamespacedName namespacedName, IDispatchTarget dispatchTarget) { NamespacedName = namespacedName; DispatchTarget = dispatchTarget; }
public QueueItem(string change, IDispatchTarget dispatchTarget) { Change = change; DispatchTarget = dispatchTarget; }
public override void SampleCall(string[] args) { // Resources used in this sample. IContext context = null; // The different Topics used in this sample. ITopic ASlashWildCard = ContextFactory.Instance.CreateTopic("a/>"); ITopic ASlashB = ContextFactory.Instance.CreateTopic("a/b"); ITopic CSlashD = ContextFactory.Instance.CreateTopic("c/d"); ITopic CSlashWildCard = ContextFactory.Instance.CreateTopic("c/>"); ITopic ASlashC = ContextFactory.Instance.CreateTopic("a/c"); ITopic CSlashE = ContextFactory.Instance.CreateTopic("c/e"); // Parse Arguments and initialize session properties. ArgParser cmdLineParser = new ArgParser(); if (!cmdLineParser.Parse(args)) { // Parse failed. PrintUsage(INVALID_ARGUMENTS_ERROR); return; } SessionProperties sessionProps = SampleUtils.NewSessionPropertiesFromConfig(cmdLineParser.Config); sessionProps.TopicDispatch = true; // This session property must be set to use topic dispatch capabilities try { InitContext(cmdLineParser.LogLevel); // Initialize the Context, connect the Session and assert capabilities. InitializeAndAssertCapabilities(ref context, ref this.session, sessionProps); // Add "a/>" Topic subscription to the Session. session.Subscribe(ASlashWildCard, true /*wait for confirm*/); // Create three dispatch targets. dispatch_1 = session.CreateDispatchTarget(ASlashB, HandleMessageEvent); session.Subscribe(dispatch_1, SubscribeFlag.LocalDispatchOnly, null); // local dispatch only dispatch_2 = session.CreateDispatchTarget(CSlashWildCard, HandleMessageEvent); session.Subscribe(dispatch_2, SubscribeFlag.WaitForConfirm, null); // subscribe to the appliance dispatch_3 = session.CreateDispatchTarget(CSlashD, HandleMessageEvent); session.Subscribe(dispatch_3, SubscribeFlag.LocalDispatchOnly, null); // local dispatch only // Publish to Topic a/c, and verify receipt only on the Session's message handler. IMessage msg = ContextFactory.Instance.CreateMessage(); msg.BinaryAttachment = Encoding.ASCII.GetBytes(SampleUtils.MSG_ATTACHMENTTEXT); msg.Destination = ASlashC; session.Send(msg); Console.WriteLine("\nPublished message to topic a/c"); Thread.Sleep(100); // Publish to Topic a/b, and verify receipt only on dispatch_1 message handler. msg.Destination = ASlashB; session.Send(msg); Console.WriteLine("\nPublished message to topic a/b"); Thread.Sleep(100); // Publish to Topic c/d, and verify receipt on both dispatch functions 2 and 3. msg.Destination = CSlashD; session.Send(msg); Console.WriteLine("\nPublished message to Topic c/d"); Thread.Sleep(100); // Publish on Topic c/e, and verify receipt on only dispatch function 2. msg.Destination = CSlashE; session.Send(msg); Console.WriteLine("\nPublished message to Topic c/e"); Thread.Sleep(100); // Wait for messages to be delivered. Thread.Sleep(Timeout); Console.WriteLine("\nDone"); } catch (Exception ex) { PrintException(ex); Console.WriteLine("Exiting"); } finally { if (session != null) { session.Unsubscribe(ContextFactory.Instance.CreateTopic(">"), true /*wait for confirm*/); } if (dispatch_1 != null) { session.Unsubscribe(dispatch_1, SubscribeFlag.LocalDispatchOnly, null); } if (dispatch_2 != null) { session.Unsubscribe(dispatch_2, SubscribeFlag.WaitForConfirm, null); } if (dispatch_3 != null) { session.Unsubscribe(dispatch_3, SubscribeFlag.LocalDispatchOnly, null); } if (session != null) { session.Dispose(); } if (context != null) { context.Dispose(); } // Must cleanup after. CleanupContext(); } }