예제 #1
0
        private bool WriteLogToFile(TheEventLogData pLogItem, bool WaitForLock)
        {
            if (pLogItem == null || string.IsNullOrEmpty(pLogItem.EventCategory))
            {
                return(false);
            }
            if (mWriteToConsole)
            {
                Console.WriteLine($"{pLogItem.EventCategory} : {TheCommonUtils.GetDateTimeString(pLogItem.EventTime, -1)} : {pLogItem.EventName} : {pLogItem.EventString}");
            }
            if (string.IsNullOrEmpty(mLogFilePath) && string.IsNullOrEmpty(TheThing.GetSafePropertyString(MyBaseThing, "LogFilePath")))
            {
                return(false);
            }

            if (EachCategoryInOwnFile)
            {
                //TODO: Tune with array of EventCategory Log file names
                //MyCurLog = mLogFilePath + string.Format("\\{1}_{0:yyyMMdd_HHmmss}.txt", DateTime.Now,pLogItem.EventCategory);
                //MyCurLog = TheCommonUtils.cdeFixupFileName(MyCurLog);
                //TheCommonUtils.CreateDirectories(MyCurLog);
            }
            if (EachDayInOwnFile && mLogFileDate.Day != DateTimeOffset.Now.Day)
            {
                LogFilePath = MyCurLog = TheCommonUtils.cdeFixupFileName(mLogFilePath + string.Format("\\LOG_{0:yyyMMdd_HHmmss}.txt", DateTime.Now));
                LogFileDate = mLogFileDate = DateTimeOffset.Now;
            }
            // ReSharper disable once EmptyEmbeddedStatement
            if (WaitForLock)
            {
                while (TheCommonUtils.cdeIsLocked(writeLock))
                {
                    TheCommonUtils.SleepOneEye(50, 50);
                }
            }
            if (!TheCommonUtils.cdeIsLocked(writeLock))
            {
                lock (writeLock)
                {
                    var bLogFileExists = System.IO.File.Exists(MyCurLog);
                    if (mMaxLogFileSize > 0 && bLogFileExists)
                    {
                        try
                        {
                            System.IO.FileInfo f2 = new System.IO.FileInfo(MyCurLog);
                            if (f2.Length > mMaxLogFileSize * (1024 * 1024))
                            {
                                MyCurLog    = LogFilePath = TheCommonUtils.cdeFixupFileName(mLogFilePath + string.Format("\\LOG_{0:yyyMMdd_HHmmss}.txt", DateTime.Now));
                                LogFileDate = mLogFileDate = DateTimeOffset.Now;
                            }
                        }
                        catch
                        {
                            //ignored
                        }
                        bLogFileExists = System.IO.File.Exists(MyCurLog);
                    }
                    try
                    {
                        using (System.IO.StreamWriter fs = new System.IO.StreamWriter(MyCurLog, bLogFileExists))
                        {
                            if (EachCategoryInOwnFile)
                            {
                                fs.WriteLine($"{pLogItem.EventTime} : {TheCommonUtils.GetDateTimeString(pLogItem.EventTime, -1)} : {pLogItem.EventString}");
                            }
                            else
                            {
                                fs.WriteLine($"{pLogItem.EventCategory} : {TheCommonUtils.GetDateTimeString(pLogItem.EventTime,-1)} : {pLogItem.EventName} : {pLogItem.EventString}");
                            }
                        }
                    }
                    catch
                    {
                        //ignored
                    }
                }
            }
            return(true);
        }
예제 #2
0
        private void onPrometheusHttpRequest(TheRequestData tRequest)
        {
            try
            {
                tRequest.AllowStatePush = false; //No need to track state
                if (HoldOffOnSenderLoop && (DateTimeOffset.Now - _lastPollTime) > maxMetricSampleRate)
                {
                    // Using polling: generate all metrics now
                    GenerateMetrics();
                    _lastPollTime = DateTimeOffset.Now;
                }

                using (var outputStream = new MemoryStream())
                {
                    try
                    {
                        _registry.CollectAndExportAsTextAsync(outputStream, TheBaseAssets.MasterSwitchCancelationToken).Wait();
                    }
                    catch (ScrapeFailedException ex)
                    {
                        tRequest.StatusCode = 500;
                        EventsSentErrorCountSinceStart++;

                        if (!string.IsNullOrWhiteSpace(ex.Message))
                        {
                            tRequest.ResponseBuffer = Encoding.UTF8.GetBytes(ex.Message);
                        }

                        return;
                    }

                    if (tRequest.Header.TryGetValue("Accept", out var acceptHeader))
                    {
                        var acceptHeaders = acceptHeader?.Split(',');
                        var contentType   = "text/plain";
                        tRequest.ResponseMimeType = contentType;

                        tRequest.StatusCode = 200;

                        tRequest.ResponseBuffer = outputStream.ToArray();
                        EventsSentSinceStart++;
                        TheThing.SetSafePropertyNumber(MyBaseThing, "QValue", EventsSentSinceStart);
                        LastSendTime = DateTimeOffset.Now;
                        TheThing.SetSafePropertyString(MyBaseThing, "StateSensorUnit", TheCommonUtils.GetDateTimeString(LastSendTime, -1));
                    }
                    else
                    {
                        tRequest.StatusCode     = 406;
                        tRequest.ResponseBuffer = Encoding.UTF8.GetBytes("No accept header");
                        EventsSentErrorCountSinceStart++;
                        return;
                    }
                }
            }
            catch (Exception ex) when(!(ex is OperationCanceledException))
            {
                EventsSentErrorCountSinceStart++;
                TheBaseAssets.MySYSLOG.WriteToLog(95307, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(strPrometheusExporter, $"Error in metric server: {this.MyBaseThing?.Address}", eMsgLevel.l3_ImportantMessage, ex.ToString()));
                try
                {
                    tRequest.StatusCode = 500;
                }
                catch
                {
                    // Might be too late in request processing to set response code, so just ignore.
                }
            }
        }
 public override string ToString()
 {
     return($"ORG:{TheCommonUtils.GetDeviceIDML(ORG)},TH:{TopicHash}, FID:{FID}, OUT:{IsOutgoing}, TIM:{TheCommonUtils.GetDateTimeString(SentTime, -1)}, ENG:{Engine}");
 }
        public string GetSessionLog()
        {
            string retString = $"<div class=\"cdeInfoBlock\" style=\"clear:both; max-width:1570px; width:initial; \"><div class=\"cdeInfoBlockHeader cdeInfoBlockHeaderText\" id=\"sessionLog\">Session Log: ({MySessionStates.Count}) ";

            retString += $"<a download =\"SessionLog_{TheCommonUtils.GetMyNodeName()}.csv\" href=\"#\" class=\'cdeExportLink\' onclick=\"return ExcellentExport.csv(this, 'sessionLogTable');\">(Export as CSV)</a></div>";
            List <string> tSessions = MySessionStates.TheKeys;
            string        tFont;
            int           count = 0;

            foreach (string tKey in tSessions)
            {
                if (count == 0)
                {
                    retString += $"<table class=\"cdeHilite\" style=\"width:95%; margin-left:1%;\" id=\"sessionLogTable\"><tr>";
                    retString += $"<th style=\"background-color:rgba(90,90,90, 0.25);font-size:x-small;min-width:175px; width:300px;\">SEID</th>";
                    retString += $"<th style=\"background-color:rgba(90,90,90, 0.25);font-size:x-small;min-width:80px; width:80px;\">DID</th>";
                    retString += $"<th style=\"background-color:rgba(90,90,90, 0.25);font-size:x-small;min-width:80px; width:150px;\">Last Access</th>";
                    retString += $"<th style=\"background-color:rgba(90,90,90, 0.25);font-size:x-small;min-width:80px; width:150px;\">End</th>";
                    retString += $"<th style=\"background-color:rgba(90,90,90, 0.25);font-size:x-small;width:100px;\">Browser</th>";
                    retString += $"<th style=\"background-color:rgba(90,90,90, 0.25);font-size:x-small;width:200px;\">Current Url</th>";
                    retString += $"<th style=\"background-color:rgba(90,90,90, 0.25);font-size:x-small;width:300px\">Remote Address</th>";
                    retString += $"<th style=\"background-color:rgba(90,90,90, 0.25);font-size:x-small;min-width:80px; width:80px;\">CID</th>";
                    retString += $"<th style=\"background-color:rgba(90,90,90, 0.25);font-size:x-small;min-width:80px; width:80px;\">SID</th>";
                    retString += $"<th style=\"background-color:rgba(90,90,90, 0.25);font-size:x-small;width:400px;\">User Agent</th>";
                    retString += "</tr>";
                }
                count++;
                TheSessionState tSession = MySessionStates.MyMirrorCache.MyRecords[tKey];
                if (tSession.MyDevice == Guid.Empty)
                {
                    tFont = " style='color:lightgray'";
                }
                else
                {
                    tFont = "";
                }
                retString += $"<tr {tFont}>";
                retString += $"<td class=\"cdeClip cdeLogEntry\" style=\"text-align:left;\">{tSession.cdeMID}</td>";
                retString += $"<td class=\"cdeClip cdeLogEntry\" style=\"text-align:left;\">{TheCommonUtils.GetDeviceIDML(tSession.MyDevice)}</td>";
                retString += $"<td class=\"cdeClip cdeLogEntry\" style=\"text-align:center;\">{TheCommonUtils.GetDateTimeString(tSession.LastAccess,-1)}</td>";
                retString += $"<td class=\"cdeClip cdeLogEntry\" style=\"text-align:center;\">{TheCommonUtils.GetDateTimeString(tSession.EndTime,-1)}</td>";
                retString += $"<td class=\"cdeClip cdeLogEntry\" style=\"text-align:left;\">{tSession.Browser} {tSession.BrowserDesc}</td>";
                retString += $"<td class=\"cdeClip cdeLogEntry\" style=\"max-width:200px; width: 200px;\"><div class=\"cdeClip\" style=\"max-height:100px; overflow-y:auto;\">{tSession.CurrentURL}</div></td>";
                retString += $"<td class=\"cdeClip cdeLogEntry\" style=\"text-align:left;\">{tSession.RemoteAddress}</td>";
                retString += $"<td class=\"cdeClip cdeLogEntry\" style=\"text-align:left;\">{(tSession.CID==Guid.Empty?"Not Set":tSession.CID.ToString().Substring(0,4))}</td>";
                retString += $"<td class=\"cdeClip cdeLogEntry\" style=\"text-align:left;\">{(string.IsNullOrEmpty(tSession.SScopeID) ? "Not Set" : cdeStatus.GetSScopeHashML(tSession.SScopeID))}</td>";
                retString += $"<td class=\"cdeClip cdeLogEntry\" style=\"max-width:400px; width: 400px;\"><div class=\"cdeClip\" style=\"max-height:100px; overflow-y:auto;\">{tSession.UserAgent}</div></td>";
                retString += "</tr>";
            }
            if (count > 0)
            {
                retString += "</table></div>";
                return(retString);
            }
            return("");
        }
 internal void RemoveSession(TheSessionState SessionState)
 {
     if (SessionState == null)
     {
         return;
     }
     SessionState.HasExpired = true;
     SessionState.EndTime    = DateTimeOffset.Now;
     SessionState.ARApp      = Guid.Empty;
     TheBaseAssets.MySYSLOG.WriteToLog(1234, TSM.L(eDEBUG_LEVELS.VERBOSE) ? null : new TSM("SSM", $"Session killed at {TheCommonUtils.GetDateTimeString(DateTimeOffset.Now)} for RemoteAdr: {TheCommonUtils.GetDeviceIDML(SessionState.MyDevice)}", eMsgLevel.l3_ImportantMessage));
     TheCommonUtils.cdeRunAsync("RemoveSession", true, (o) => MySessionStates.RemoveAnItem(SessionState, null)); //Do not block the main thread...take your time HasExpired is set :)
 }
예제 #6
0
        internal static TheNodeInfoHeader GetInfoHeaderJSON()
        {
            var tHead = new TheNodeInfoHeader {
                CloudRoutes    = new List <TheServiceRouteInfo>(),
                NodeID         = TheBaseAssets.MyServiceHostInfo.MyDeviceInfo.DeviceID,
                NodeName       = TheBaseAssets.MyServiceHostInfo.NodeName,
                BuildVersion   = TheBaseAssets.BuildVersion,
                CurrentVersion = TheBaseAssets.CurrentVersionInfo,
                ScopeHash      = TheBaseAssets.MyScopeManager.IsScopingEnabled ? TheBaseAssets.MyScopeManager.ScopeID.Substring(0, 4).ToUpper() : "unscoped",
                OSInfo         = TheBaseAssets.MyServiceHostInfo.OSInfo
            };
            var CNs = TheQueuedSenderRegistry.GetCloudNodes(true);

            if (CNs.Count > 0)
            {
                foreach (var tQ in CNs)
                {
                    var tInfo = new TheServiceRouteInfo
                    {
                        Url            = tQ.MyTargetNodeChannel.TargetUrl,
                        IsConnected    = tQ.IsConnected,
                        IsConnecting   = tQ.IsConnecting,
                        LastError      = tQ.GetLastError(),
                        ErrorCode      = tQ.GetLastErrorCode(),
                        LastHB         = (tQ.GetLastHeartBeat() == DateTimeOffset.MinValue ? "not yet" : $"{TheCommonUtils.GetDateTimeString(tQ.GetLastHeartBeat(), -1)}"),
                        ConnectedSince = (tQ.MyLastConnectTime == DateTimeOffset.MinValue ? "not yet" : $"{TheCommonUtils.GetDateTimeString(tQ.MyLastConnectTime, -1)}"),
                        IsAlive        = tQ.IsAlive,
                        UsesWS         = tQ.HasWebSockets()
                    };
                    tInfo.Status = $"{tInfo.Url} (Connected: {(tInfo.IsConnected ? "Yes, all is good" : (tInfo.IsConnecting ? "Not, yet - trying to connect" : "No, and not yet trying to connect again!"))}{(!string.IsNullOrEmpty(tInfo.LastError) ? $" Last Error: {tInfo.LastError}" : "")})";
                    tHead.CloudRoutes.Add(tInfo);
                }
            }
            return(tHead);
        }
예제 #7
0
        internal static string InfoHeader(bool IsSmall)
        {
            //string ret = $"<h3>{TheBaseAssets.MyServiceHostInfo.MyAppPresenter}</h3><h1>{TheBaseAssets.MyServiceHostInfo.ApplicationTitle} V{TheBaseAssets.MyServiceHostInfo.CurrentVersion}</h1><h3>Hosted at: {TheBaseAssets.LocalHostQSender.MyTargetNodeChannel}<br/>NodeName: {TheBaseAssets.MyServiceHostInfo.NodeName}</br>AppName:{TheBaseAssets.MyServiceHostInfo.ApplicationName}<br/>lcd: {TheBaseAssets.MyServiceHostInfo.BaseDirectory}</br>CDE:V{TheBaseAssets.CurrentVersionInfo} Drop: {TheBaseAssets.BuildVersion}</br>Started:{TheCommonUtils.GetDateTimeString(TheBaseAssets.MyServiceHostInfo.cdeCTIM, -1)}";
            string ret2 = $"<h3>{TheBaseAssets.MyServiceHostInfo.MyAppPresenter}</h3>"; //<div id=\"mainBox\" style=\"width-fixed:90%;display:flex; flex-flow: column wrap\">

            ret2 += $"<h1 id=\"title\">{TheBaseAssets.MyServiceHostInfo.ApplicationTitle} V{TheBaseAssets.MyServiceHostInfo.CurrentVersion}</h1>";
            if (TheBaseAssets.MyServiceHostInfo.ShowMarkupInLog)
            {
                ret2 += $"<script>var cdeCSOn; function cdeColorSpan(pContent, pColor) {{ var x = document.getElementsByClassName(\"cdeRSHash\");var i;for (i = 0; i < x.length; i++){{ if (!pContent) {{ if (!cdeCSOn) x[i].style.backgroundColor = \"transparent\"; }} else {{ if (pContent.innerText==x[i].innerText && !cdeCSOn) x[i].style.backgroundColor = pColor; }}}}}}</script>";
            }
            ret2 += $"<div class=\"cdeInfoBlock\" style=\"width:750px;\"><div class=\"cdeInfoBlockHeader cdeInfoBlockHeaderText\" id=\"nodeInfo\">Node Info</div><table style=\"margin-left:2%\">";
            ret2 += $"<tr><th scope=\"rowgroup;\" style=\"background-color:rgba(90,90,90, 0.15); padding:3px; text-align:right; min-width:200px;\">Hosted at:</th><td style=\"border-bottom:1px solid rgba(90, 90, 90, 0.25);padding:3px;text-align:left \">{TheBaseAssets.LocalHostQSender.MyTargetNodeChannel.ToMLString(true)}</td></tr>";
            ret2 += $"<tr><th scope=\"rowgroup;\" style=\"background-color:rgba(90,90,90, 0.15); padding:3px; text-align:right\">Node ID:</th><td style=\"border-bottom:1px solid rgba(90, 90, 90, 0.25);padding:3px;text-align:left \">{TheCommonUtils.GetDeviceIDML(TheBaseAssets.MyServiceHostInfo.MyDeviceInfo.DeviceID)}</td><tr>";
            ret2 += $"<tr><th scope=\"rowgroup;\" style=\"background-color:rgba(90,90,90, 0.15); padding:3px; text-align:right\">Node Name:</th><td style=\"border-bottom:1px solid rgba(90, 90, 90, 0.25);padding:3px;text-align:left \">{TheBaseAssets.MyServiceHostInfo.NodeName}</td><tr>";
            ret2 += $"<tr><th scope=\"rowgroup;\" style=\"background-color:rgba(90,90,90, 0.15); padding:3px; text-align:right\">Station Name:</th><td style=\"border-bottom:1px solid rgba(90, 90, 90, 0.25);padding:3px;text-align:left \">{TheBaseAssets.MyServiceHostInfo.MyStationName}</td><tr>";
            ret2 += $"<tr><th scope=\"rowgroup;\" style=\"background-color:rgba(90,90,90, 0.15); padding:3px; text-align:right\">Application Name:</th><td style=\"border-bottom:1px solid rgba(90, 90, 90, 0.25);padding:3px;text-align:left \">{TheBaseAssets.MyServiceHostInfo.ApplicationName}</td><tr>";
            ret2 += $"<tr><th scope=\"rowgroup;\" style=\"background-color:rgba(90,90,90, 0.15); padding:3px; text-align:right\">OS Info:</th><td style=\"border-bottom:1px solid rgba(90, 90, 90, 0.25);padding:3px;text-align:left;word-wrap: break-word;max-width:540px \">{TheBaseAssets.MyServiceHostInfo.OSInfo}</td><tr>";
            ret2 += $"<tr><th scope=\"rowgroup;\" style=\"background-color:rgba(90,90,90, 0.15); padding:3px; text-align:right\">Local Dir:</th><td style=\"border-bottom:1px solid rgba(90, 90, 90, 0.25);padding:3px;text-align:left \">{TheBaseAssets.MyServiceHostInfo.BaseDirectory}</td><tr>";
            ret2 += $"<tr><th scope=\"rowgroup;\" style=\"background-color:rgba(90,90,90, 0.15); padding:3px; text-align:right\">CDE Info:</th><td style=\"border-bottom:1px solid rgba(90, 90, 90, 0.25);padding:3px;text-align:left \">{TheBaseAssets.CurrentVersionInfo}</td><tr>";
            ret2 += $"<tr><th scope=\"rowgroup;\" style=\"background-color:rgba(90,90,90, 0.15); padding:3px; text-align:right\">CDE Drop:</th><td style=\"border-bottom:1px solid rgba(90, 90, 90, 0.25);padding:3px;text-align:left \">V{TheBaseAssets.BuildVersion}</td><tr>";
            ret2 += $"<tr><th scope=\"rowgroup;\" style=\"background-color:rgba(90,90,90, 0.15); padding:3px; text-align:right\">CDE Crypto:</th><td style=\"border-bottom:1px solid rgba(90, 90, 90, 0.25);padding:3px;text-align:left \">{TheBaseAssets.MySecrets.CryptoVersion()}</td><tr>";
            ret2 += $"<tr><th scope=\"rowgroup;\" style=\"background-color:rgba(90,90,90, 0.15); padding:3px; text-align:right\">Unique Meshes Connected:</th><td style=\"border-bottom:1px solid rgba(90, 90, 90, 0.25);padding:3px;text-align:left \">{TheQueuedSenderRegistry.GetUniqueMeshCount()}</td><tr>";
            string tScope = "";

            if (TheBaseAssets.MyScopeManager.IsScopingEnabled)
            {
                tScope = GetScopeHashML(TheBaseAssets.MyScopeManager.GetScopeHash(null));
            }
            ret2 += $"<tr><th scope=\"rowgroup;\" style=\"background-color:rgba(90,90,90, 0.15); padding:3px; text-align:right\">Local Node-Scope:</th><td style=\"border-bottom:1px solid rgba(90, 90, 90, 0.25);padding:3px;text-align:left \">{(TheBaseAssets.MyScopeManager.IsScopingEnabled ? $"A local Scope is set. Hash: {tScope}" : "Scoping is disabled")}</td><tr>";
            ret2 += $"<tr><th scope=\"rowgroup;\" style=\"background-color:rgba(90,90,90, 0.15); padding:3px; text-align:right\">Client Cert Thumbprint:</th><td style=\"border-bottom:1px solid rgba(90, 90, 90, 0.25);padding:3px;text-align:left \">{(TheBaseAssets.MyServiceHostInfo.ClientCertificateThumb?.Length > 3 ? $"{TheBaseAssets.MyServiceHostInfo.ClientCertificateThumb.Substring(0, 4)}" : $"No client certificate specified")}</td><tr>";
            ret2 += $"<tr><th scope=\"rowgroup;\" style=\"background-color:rgba(90,90,90, 0.15); padding:3px; text-align:right\">Node Started at:</th><td style=\"border-bottom:1px solid rgba(90, 90, 90, 0.25);padding:3px;text-align:left \">{TheCommonUtils.GetDateTimeString(TheBaseAssets.MyServiceHostInfo.cdeCTIM, -1)}</td><tr>";
            ret2 += $"<tr><th scope=\"rowgroup;\" style=\"background-color:rgba(90,90,90, 0.15); padding:3px; text-align:right\">Last Update at:</th><td style=\"border-bottom:1px solid rgba(90, 90, 90, 0.25);padding:3px;text-align:left \">{TheCommonUtils.GetDateTimeString(DateTimeOffset.Now, -1)}</td><tr>";
            ret2 += "</table>";

            if (!IsSmall)
            {
                ret2 += $"<h2>Service Routes:</h2><table style=\"margin-left:2%\">";
                ret2 += $"<tr><th scope=\"rowgroup;\" style=\"background-color:rgba(90,90,90, 0.15); padding:3px; text-align:right; width:200px;\">Configured Routes:</th><td style=\"border-bottom:1px solid rgba(90, 90, 90, 0.25);padding:3px;text-align:left \">{(string.IsNullOrEmpty(TheBaseAssets.MyServiceHostInfo.ServiceRoute) ? "No Routes are configured" : $"{TheBaseAssets.MyServiceHostInfo.ServiceRoute}")}</td></tr>";