Пример #1
0
        public void CancelSender(TheThing myBaseThingForLogging, CancellationToken?masterToken = null, bool triggerCancelOnly = false)
        {
            StopThingMatcher();
            SenderTaskInfo previousTaskInfo = null;

            if (pendingHistoryLoops.TryGetValue(cdeMID, out previousTaskInfo))
            {
                try
                {
                    if (!masterToken.HasValue)
                    {
                        masterToken = TheBaseAssets.MasterSwitchCancelationToken;
                    }
                    try
                    {
                        previousTaskInfo.cancelSource.Cancel();
                    }
                    catch { }
                    if (triggerCancelOnly)
                    {
                        return;
                    }
                    int       count       = 0;
                    const int timePerLoop = 1000;
                    const int timeout     = 1 * 60;
                    while (!masterToken.Value.IsCancellationRequested &&
                           previousTaskInfo.task.Status != TaskStatus.Canceled &&
                           previousTaskInfo.task.Status != TaskStatus.Faulted &&
                           previousTaskInfo.task.Status != TaskStatus.RanToCompletion &&
                           count < timeout
                           )
                    {
                        try
                        {
                            previousTaskInfo.task.Wait(timePerLoop, masterToken.Value);
                        }
                        catch (OperationCanceledException) { }
                        count++;
                        if (count >= timeout)
                        {
                            TheBaseAssets.MySYSLOG.WriteToLog(95275, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(myBaseThingForLogging.EngineName, "Connect", eMsgLevel.l2_Warning, $"Waiting on cancel previous send loop for {myBaseThingForLogging.FriendlyName} - {cdeMID}: timeout after {count * timePerLoop} ms. Retrying."));
                            count = 0;
                        }
                    }
                    if (count >= timeout)
                    {
                        TheBaseAssets.MySYSLOG.WriteToLog(95275, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(myBaseThingForLogging.EngineName, "Connect", eMsgLevel.l2_Warning, $"Unable to cancel previous send loop for {myBaseThingForLogging.FriendlyName} - {cdeMID}: timeout after {count * timePerLoop} ms"));
                    }
                    previousTaskInfo.cancelSource?.Dispose();
                    pendingHistoryLoops.RemoveNoCare(cdeMID);
                }
                catch (Exception e)
                {
                    TheBaseAssets.MySYSLOG.WriteToLog(95257, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(myBaseThingForLogging.EngineName, "Connect", eMsgLevel.l6_Debug, String.Format("Exception while cancelling previous send loop for thing {0}: {1}", cdeMID, TheCommonUtils.GetAggregateExceptionMessage(e))));
                }
            }
        }
Пример #2
0
        public override void Connect()
        {
            if (this.Connecting)
            {
                return;
            }
            try
            {
#if CDEPUBSUB
                ConnectPubSub();
#endif
                IsConnected             = true;
                MyBaseThing.StatusLevel = 1;
                TheBaseAssets.MySYSLOG.WriteToLog(180006, new TSM(MyBaseThing.EngineName, "Connect", eMsgLevel.l3_ImportantMessage, String.Format("Started Mesh Receiver {0}", this.GetBaseThing().FriendlyName)));
                MyBaseThing.LastMessage = DateTimeOffset.Now + ": Running";
            }
            catch (Exception e)
            {
                TheBaseAssets.MySYSLOG.WriteToLog(180007, new TSM(MyBaseThing.EngineName, "Connect", eMsgLevel.l1_Error, String.Format("Unable to start Mesh Receiver {0}. Exception: {1}", this.GetBaseThing().FriendlyName, TheCommonUtils.GetAggregateExceptionMessage(e))));
                MyBaseThing.LastMessage = DateTimeOffset.Now + ": Unable to connect - " + TheCommonUtils.GetAggregateExceptionMessage(e);
            }
            finally
            {
                this.Connecting = false;
            }
        }
Пример #3
0
        public override void Disconnect(bool bDrain)
        {
            try
            {
                this.Disconnecting = true;
                TheBaseAssets.MySYSLOG.WriteToLog(180008, new TSM(MyBaseThing.EngineName, "Disconnect", eMsgLevel.l6_Debug, String.Format("Closing Mesh Receiver for connection {0}", this.GetBaseThing().FriendlyName)));

#if CDEPUBSUB
                _pubsubCancellationTokenSource?.Cancel();
                _pubsubCancellationTokenSource = null;
#endif
                TheBaseAssets.MySYSLOG.WriteToLog(180009, new TSM(MyBaseThing.EngineName, "Disconnect", eMsgLevel.l3_ImportantMessage, String.Format("Stopped Mesh Receiver {0}", this.GetBaseThing().FriendlyName)));
                MyBaseThing.LastMessage = DateTimeOffset.Now + ": Stopped.";
                IsConnected             = false;
                MyBaseThing.StatusLevel = 0;
            }
            catch (Exception e)
            {
                TheBaseAssets.MySYSLOG.WriteToLog(180010, new TSM(MyBaseThing.EngineName, "Disconnect", eMsgLevel.l1_Error, String.Format("Unable to stop Mesh Receiver {0}. Exception: {1}", this.GetBaseThing().FriendlyName, TheCommonUtils.GetAggregateExceptionMessage(e))));
                MyBaseThing.LastMessage = DateTimeOffset.Now + ": Unable to stop - " + e.Message;
            }
            finally
            {
                this.Disconnecting = false;
            }
        }
Пример #4
0
        internal override bool Connect(TheQueuedSender pSender)
        {
            if (pSender == null /*|| pSender.MyTargetNodeChannel==null*/)
            {
                return(false);
            }
            if (pSender.IsConnected)
            {
                return(true);
            }

            IsClient = true;
            if (MyQSender == null)
            {
                MyQSender = pSender;
            }

            var _MyTargetNodeChannel = pSender?.MyTargetNodeChannel;
            Uri TargetUri            = TheCommonUtils.CUri(_MyTargetNodeChannel?.TargetUrl, true);

            if (TargetUri == null)
            {
                TheBaseAssets.MySYSLOG.WriteToLog(4365, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("WSProcessor", "Invalid Target URL", eMsgLevel.l1_Error, $"{_MyTargetNodeChannel?.ToString()}"));
                return(false);
            }
            OwnerNodeID = _MyTargetNodeChannel.cdeMID;
            string TargetUriPath = TargetUri.AbsolutePath;
            Uri    tTarget       = new Uri(TargetUri, TheBaseAssets.MyScopeManager.GetISBPath(TargetUriPath, TheCommonUtils.GetOriginST(_MyTargetNodeChannel), _MyTargetNodeChannel.SenderType, 1, Guid.Empty, true));

            tTarget = tTarget.SetWSInfo(tTarget.Port, "");

            string connectFailureReason = "";

            try
            {
                IsActive       = true;
                CloseFired     = false;
                ConnectSuccess = false;
                ClientWebSocket wsClientSocket = new ClientWebSocket();
                websocket = wsClientSocket;
                if (!string.IsNullOrEmpty(TheBaseAssets.MyServiceHostInfo.ProxyUrl))
                {
                    try
                    {
                        System.Net.NetworkCredential tNet = null;
                        if (!string.IsNullOrEmpty(TheBaseAssets.MyServiceHostInfo.ProxyUID))
                        {
                            tNet = new System.Net.NetworkCredential(TheBaseAssets.MyServiceHostInfo.ProxyUID, TheBaseAssets.MyServiceHostInfo.ProxyPWD);
                        }
                        if (wsClientSocket.Options != null)
                        {
                            wsClientSocket.Options.Proxy = new System.Net.WebProxy(TheBaseAssets.MyServiceHostInfo.ProxyUrl, true, null, tNet);
                            TheBaseAssets.MySYSLOG.WriteToLog(4365, TSM.L(eDEBUG_LEVELS.VERBOSE) ? null : new TSM("WSProcessor", $"Web Proxy set: {TheBaseAssets.MyServiceHostInfo.ProxyUrl} UID: {!string.IsNullOrEmpty(TheBaseAssets.MyServiceHostInfo.ProxyUID)} PWD: {!string.IsNullOrEmpty(TheBaseAssets.MyServiceHostInfo.ProxyPWD)}", eMsgLevel.l4_Message));
                        }
                    }
                    catch (Exception e)
                    {
                        TheBaseAssets.MySYSLOG.WriteToLog(4365, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("WSProcessor", "Error setting Proxy credentials:", eMsgLevel.l1_Error, e.ToString()));
                    }
                }
                if (!string.IsNullOrEmpty(_MyTargetNodeChannel?.ClientCertificateThumb))
                {
                    try
                    {
                        X509Certificate2Collection cert = TheCertificates.GetClientCertificatesByThumbprint(_MyTargetNodeChannel?.ClientCertificateThumb);
                        if (cert?.Count < 1)
                        {
                            TheBaseAssets.MySYSLOG.WriteToLog(4365, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("WSProcessor", $"Error setting Client Certificate - Requested Cert with Thumbprint {_MyTargetNodeChannel?.ClientCertificateThumb} not found", eMsgLevel.l1_Error));
                            return(false);
                        }
                        wsClientSocket.Options.ClientCertificates = cert;
                    }
                    catch (Exception certex)
                    {
                        TheBaseAssets.MySYSLOG.WriteToLog(4365, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("WSProcessor", "Error setting Client Certificate", eMsgLevel.l1_Error, certex.ToString()));
                        return(false);
                    }
                }
                Task myTask = wsClientSocket.ConnectAsync(tTarget, CancellationToken.None);
                myTask.Wait(TheBaseAssets.MyServiceHostInfo.TO.WsTimeOut * 12);
                if (myTask.IsCompleted)
                {
                    // CODE REVIEW MH: ProcessWS synchronously can run for quite a bit until the first await. Should we start this as a new task?
                    ConnectSuccess = true;
                    var taskNoWait = ProcessWS(); //Sets Connecting and Connected when ready
                }
                else
                {
                    TheBaseAssets.MySYSLOG.WriteToLog(4365, new TSM("WSProcessor", $"WSClient Connect Request timed out Task:{myTask.Status}", eMsgLevel.l2_Warning));
                    connectFailureReason += "Connect Request Timeout";
                }
            }
            catch (Exception e)
            {
                TheBaseAssets.MySYSLOG.WriteToLog(4365, TSM.L(eDEBUG_LEVELS.VERBOSE) ? null : new TSM("WSProcessor", "ClientConnect Request Failed:", eMsgLevel.l1_Error, e.ToString()));
                connectFailureReason += TheCommonUtils.GetAggregateExceptionMessage(e, false);
            }
            if (ConnectSuccess) //This prevents double shutdown as the eventconnecte with ConnectSuccess=false will cause a shutdown again
            {
                eventConnected?.Invoke(this, ConnectSuccess, $"1602:{connectFailureReason}");
            }
            else
            {
                Shutdown(true, $"1603:WSConnect was not successful ({connectFailureReason})");
            }
            return(ConnectSuccess);
        }