Beispiel #1
0
        //Returns -1 on full success on reading
        private int ReadUntilFailure(byte[] _Input)
        {
            int SuccessOffset = 0;

            while (SuccessOffset < _Input.Length)
            {
                Node NewNode = null;
                try
                {
                    var Offset = Convert.BufferToNode(out NewNode, FileType, _Input, SuccessOffset);
                    SuccessOffset += Offset;
                }
                catch (Exception ex)
                {
                    if (ex is IndexOutOfRangeException || ex is ArgumentException)
                    {
                        return(SuccessOffset);
                    }
                    throw;
                }

                BTaskWrapper.Run(() =>
                {
                    OnNodeRead_TS(NewNode);
                });
            }
            return(-1);
        }
Beispiel #2
0
        public BWebServiceResponse ProcessRequest(HttpListenerContext _Context, Action <string> _ErrorMessageAction = null)
        {
            bDoNotGetDBClearance =
                BWebUtilities.DoesContextContainHeader(out List <string> DNGDBCs, out string _, _Context, "do-not-get-db-clearance") &&
                BUtility.CheckAndGetFirstStringFromList(DNGDBCs, out string DNGDBC) &&
                DNGDBC == "true";

            BTaskWrapper.Run(() =>
            {
                var Response = OnRequestCallback?.Invoke(_Context, _ErrorMessageAction);
                if (Response.HasValue)
                {
                    Responses.Enqueue(Response.Value);
                }

                try
                {
                    WaitUntilSignal.Set();
                }
                catch (Exception) { }
            });

            try
            {
                WaitUntilSignal.WaitOne();
            }
            catch (Exception) { }

            if (!Responses.TryDequeue(out BWebServiceResponse FirstResponse))
            {
                FirstResponse = BWebResponse.InternalError("Unexpected error in concurrence.");
            }
            return(FirstResponse);
        }
Beispiel #3
0
        public static void Initialize(
            IBDatabaseServiceInterface _DatabaseService,
            IBFileServiceInterface _FileService,
            string _DeploymentBranchName,
            string _DeploymentBuildNumber,
            string _CadProcessServiceName,
            Dictionary <string, string> _FileWorkerEnvironmentVariables,
            System.Action _InitFailedAction,
            Action <string> _ErrorMessageAction = null)
        {
            FileWorkerEnvironmentVariables = _FileWorkerEnvironmentVariables;
            DeploymentBranchName           = _DeploymentBranchName;
            DeploymentBuildNumber          = _DeploymentBuildNumber;


            FileService     = _FileService;
            DatabaseService = _DatabaseService;
            Instance        = new BatchProcessingCreationService();

            string CadProcessServiceName = _CadProcessServiceName;

            BTaskWrapper.Run(() =>
            {
                while (true)
                {
                    try
                    {
                        V1Service CadProcessService = Instance.K8sManager.GetServiceByNameAndNamespace(CadProcessServiceName, SERVICE_NAMESPACE);

                        if (CadProcessService != null &&
                            CadProcessService.Status != null &&
                            CadProcessService.Status.LoadBalancer != null &&
                            CadProcessService.Status.LoadBalancer.Ingress != null &&
                            CadProcessService.Status.LoadBalancer.Ingress.Any()

                            && CadProcessService.Spec != null &&
                            CadProcessService.Spec.Ports != null &&
                            CadProcessService.Spec.Ports.Any() &&
                            !string.IsNullOrWhiteSpace(CadProcessService.Status.LoadBalancer.Ingress.First().Ip))
                        {
                            CadProcessUrl = $"http://{CadProcessService.Status.LoadBalancer.Ingress.First().Ip}:{CadProcessService.Spec.Ports.First().Port}/";
                            WaitInit.Set();
                            break;
                        }
                        else
                        {
                            Thread.Sleep(1000);
                        }
                    }
                    catch (Exception ex)
                    {
                        _ErrorMessageAction?.Invoke($"Failed to initialize Batch process environment: {ex.Message}\n{ex.StackTrace}");
                        //If we fail at this point then it means the cluster master endpoint is unavailable or there is no ingress which means batch process can't system can't initialize.
                        //This can happen instantly or 5 minutes after the program started depending on if an ingress is still being created and how long it takes so decide what to do in provided action
                        _InitFailedAction.Invoke();
                    }
                }
            });
        }
Beispiel #4
0
 private void GrantRandomAccessRecursive(HierarchyNode _Node, List <ulong> _SetThisListWith_NewUniqueID = null, int _AtThisIndex = -1)
 {
     BTaskWrapper.Run(() =>
     {
         var Result = GrantRandomAccessRecursive_Internal(_Node);
         if (_SetThisListWith_NewUniqueID != null && _AtThisIndex >= 0)
         {
             _SetThisListWith_NewUniqueID[_AtThisIndex] = Result;
         }
         OnTaskCompleted();
     });
 }
Beispiel #5
0
        public void Dispose()
        {
            GrantRandomAccess();

            BTaskWrapper.Run(() =>
            {
                WriteToStream(FileTypeStreamMap[ENodeType.Hierarchy], HierarchySortedQueue);
                Writing = false;
                if (Interlocked.Decrement(ref Remaining) == 0)
                {
                    try
                    {
                        WaitFor.Set();
                    }
                    catch (Exception)
                    {
                    }
                }
            });


            try
            {
                WaitFor.WaitOne();
                WaitFor.Close();
                FileTypeStreamMap[ENodeType.Hierarchy].IOStream.Flush();
                FileTypeStreamMap[ENodeType.Metadata].IOStream.Flush();
                FileTypeStreamMap[ENodeType.Geometry].IOStream.Flush();

                FileTypeStreamMap[ENodeType.Hierarchy].IOStream.Close();
                FileTypeStreamMap[ENodeType.Metadata].IOStream.Close();
                FileTypeStreamMap[ENodeType.Geometry].IOStream.Close();
            }
            catch (Exception) { }

            try
            {
                WaitForRemainedParallelTasks.Close();
            }
            catch (Exception) { }
        }
Beispiel #6
0
        public ManualResetEvent StartProcessingBatchData(Action <string> _ErrorMessageAction = null)
        {
            CurrentFileSet++;

            State = RUNNING_STATE;

            ManualResetEvent WaitFiles  = new ManualResetEvent(false);
            ManualResetEvent GlobalWait = new ManualResetEvent(false);

            ProcessQueue(_ErrorMessageAction, WaitFiles, NodesToWrite, EDeflateCompression.Compress);

            BTaskWrapper.Run(() =>
            {
                try
                {
                    WaitFiles.WaitOne();

                    if (State != FAILED_STATE)
                    {
                        EndProcessingBatchData(_ErrorMessageAction);
                    }
                    else
                    {
                        //Just set the state, health checker should see this and take action
                        _ErrorMessageAction?.Invoke($"[{DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.fffff")}] Write Failed");
                    }
                }
                catch (Exception ex)
                {
                    _ErrorMessageAction?.Invoke($"[{DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.fffff")}] {ex.Message}\n{ex.StackTrace}");
                    //Just set the state, health checker should see this and take action
                    State = FAILED_STATE;
                }
                finally
                {
                    GlobalWait.Set();
                }
            });

            return(GlobalWait);
        }
Beispiel #7
0
        public void Start(string _MaintenanceModeCheckUrl, Action <string> _ErrorMessageAction = null)
        {
            MaintenanceModeCheckUrl = _MaintenanceModeCheckUrl;
            ErrorMessageAction      = _ErrorMessageAction;

            BTaskWrapper.Run(() =>
            {
                Thread.CurrentThread.IsBackground = true;

                try
                {
                    do
                    {
                        CheckMaintenanceMode();

                        Thread.Sleep(2500);
                    } while (true);
                }
                catch (Exception) { }
            });
        }
Beispiel #8
0
        public void RunResetProcessLoop(Action <string> _ErrorMessageAction = null)
        {
            BTaskWrapper.Run(() =>
            {
                while (true)
                {
                    ManualResetEvent Wait = StartProcessingBatchData(_ErrorMessageAction);
                    Wait.WaitOne();
                    QueueComplete        = false;
                    ExpectedMessageCount = -1;
                    QueuedMessageCount++;
                    GeometryNodeToAssemble.Clear();
                    NodesToWrite.Clear();
                    WriteComplete    = true;
                    HierarchyWritten = false;
                    WriteCompleteWait.WaitOne();

                    WriteCompleteWait.Reset();
                }
            });
        }
Beispiel #9
0
        public XStreamWriter(Dictionary <ENodeType, StreamStruct> _FileTypeStreamMap)
        {
            FileTypeStreamMap = _FileTypeStreamMap ?? throw new NullReferenceException("File type stream map must not be null.");

            if (!FileTypeStreamMap.ContainsKey(ENodeType.Hierarchy) ||
                !FileTypeStreamMap.ContainsKey(ENodeType.Geometry) ||
                !FileTypeStreamMap.ContainsKey(ENodeType.Metadata))
            {
                throw new ArgumentException("Custom write order must contain all types.");
            }

            BTaskWrapper.Run(() =>
            {
                WriteToStreamContinuous(FileTypeStreamMap[ENodeType.Geometry], GeometrySortedQueue);
                if (Interlocked.Decrement(ref Remaining) == 0)
                {
                    try
                    {
                        WaitFor.Set();
                    }
                    catch (Exception)
                    {
                    }
                }
            });
            BTaskWrapper.Run(() =>
            {
                WriteToStreamContinuous(FileTypeStreamMap[ENodeType.Metadata], MetadataSortedQueue);
                if (Interlocked.Decrement(ref Remaining) == 0)
                {
                    try
                    {
                        WaitFor.Set();
                    }
                    catch (Exception)
                    {
                    }
                }
            });
        }
Beispiel #10
0
 public bool RegisterNewPod(V1Pod Pod, EPodType _PodType, string _BucketName, string _Filename, string _ZipTypeMainAssemblyIfAny, Action <string> _ErrorMessageAction = null)
 {
     try
     {
         if (!UpdatePodStatus(Pod, _PodType, _BucketName, _Filename, _ZipTypeMainAssemblyIfAny))
         {
             throw new Exception("Could not create/update pod status");
         }
         if (!AddToPodList(Pod.Name()))
         {
             throw new Exception("Could not add pod to list");
         }
         BTaskWrapper.Run(() =>
         {
             TrackPodHealthAndStatus(Pod, _PodType, _BucketName, _Filename, _ZipTypeMainAssemblyIfAny, _PodType == EPodType.ProcessPod);
         });
         return(true);
     }
     catch (Exception ex)
     {
         _ErrorMessageAction?.Invoke($"Failed to start health check for Pod {Pod.Name()} - {ex.Message}\n{ex.StackTrace}");
         return(false);
     }
 }
Beispiel #11
0
        /// <summary>
        ///
        /// <para>WriteLogs:</para>
        ///
        /// <para>Writes logs to the logging service</para>
        ///
        /// <para>Check <seealso cref="IBLoggingServiceInterface.WriteLogs"/> for detailed documentation</para>
        ///
        /// </summary>
        public bool WriteLogs(
            List <BLoggingParametersStruct> _Messages,
            string _LogGroupName,
            string _LogStreamName,
            bool _bAsync = true,
            Action <string> _ErrorMessageAction = null)
        {
            if (_Messages == null || _Messages.Count == 0)
            {
                return(false);
            }

            if (_bAsync)
            {
                BTaskWrapper.Run(() =>
                {
                    WriteLogs(_Messages, _LogGroupName, _LogStreamName, false, _ErrorMessageAction);
                });
                return(true);
            }
            else
            {
                _LogGroupName  = BUtility.EncodeStringForTagging(_LogGroupName);
                _LogStreamName = BUtility.EncodeStringForTagging(_LogStreamName);

                string SequenceToken = null;

                bool bLogStreamAndGroupExists = false;
                try
                {
                    var DescribeStreamRequest = new DescribeLogStreamsRequest(_LogGroupName);
                    using (var CreatedDescribeTask = CloudWatchLogsClient.DescribeLogStreamsAsync(DescribeStreamRequest))
                    {
                        CreatedDescribeTask.Wait();
                        if (CreatedDescribeTask.Result != null && CreatedDescribeTask.Result.LogStreams != null && CreatedDescribeTask.Result.LogStreams.Count > 0)
                        {
                            foreach (var Current in CreatedDescribeTask.Result.LogStreams)
                            {
                                if (Current != null && Current.LogStreamName == _LogStreamName)
                                {
                                    SequenceToken            = Current.UploadSequenceToken;
                                    bLogStreamAndGroupExists = true;
                                    break;
                                }
                            }
                        }
                    }
                }
                catch (Exception)
                {
                    bLogStreamAndGroupExists = false;
                }

                if (!bLogStreamAndGroupExists)
                {
                    try
                    {
                        var CreateGroupRequest = new CreateLogGroupRequest(_LogGroupName);
                        using (var CreatedGroupTask = CloudWatchLogsClient.CreateLogGroupAsync(CreateGroupRequest))
                        {
                            CreatedGroupTask.Wait();
                        }
                    }
                    catch (Exception e)
                    {
                        if (!(e is ResourceAlreadyExistsException))
                        {
                            _ErrorMessageAction?.Invoke("BLoggingServiceAWS->WriteLogs: " + e.Message + ", Trace: " + e.StackTrace);
                            return(false);
                        }
                    }

                    try
                    {
                        var CreateStreamRequest = new CreateLogStreamRequest(_LogGroupName, _LogStreamName);
                        using (var CreatedStreamTask = CloudWatchLogsClient.CreateLogStreamAsync(CreateStreamRequest))
                        {
                            CreatedStreamTask.Wait();
                        }
                    }
                    catch (Exception e)
                    {
                        if (!(e is ResourceAlreadyExistsException))
                        {
                            _ErrorMessageAction?.Invoke("BLoggingServiceAWS->WriteLogs: " + e.Message + ", Trace: " + e.StackTrace);
                            return(false);
                        }
                    }
                }

                var LogEvents = new List <InputLogEvent>();
                foreach (var Message in _Messages)
                {
                    var LogEvent = new InputLogEvent()
                    {
                        Message   = Message.Message,
                        Timestamp = DateTime.UtcNow
                    };

                    switch (Message.LogType)
                    {
                    case EBLoggingServiceLogType.Debug:
                        LogEvent.Message = "Debug-> " + LogEvent.Message;
                        break;

                    case EBLoggingServiceLogType.Info:
                        LogEvent.Message = "Info-> " + LogEvent.Message;
                        break;

                    case EBLoggingServiceLogType.Warning:
                        LogEvent.Message = "Warning-> " + LogEvent.Message;
                        break;

                    case EBLoggingServiceLogType.Error:
                        LogEvent.Message = "Error-> " + LogEvent.Message;
                        break;

                    case EBLoggingServiceLogType.Critical:
                        LogEvent.Message = "Critical-> " + LogEvent.Message;
                        break;
                    }

                    LogEvents.Add(LogEvent);
                }

                try
                {
                    var PutRequest = new PutLogEventsRequest(_LogGroupName, _LogStreamName, LogEvents)
                    {
                        SequenceToken = SequenceToken
                    };
                    using (var CreatedPutTask = CloudWatchLogsClient.PutLogEventsAsync(PutRequest))
                    {
                        CreatedPutTask.Wait();
                    }
                }
                catch (Exception e)
                {
                    _ErrorMessageAction?.Invoke("BLoggingServiceAWS->WriteLogs: " + e.Message + ", Trace: " + e.StackTrace);
                    return(false);
                }
                return(true);
            }
        }
Beispiel #12
0
        //EBVMInstanceStatus is the condition in here
        private int PerformActionOnInstances(
            Tuple <string, EBVMInstanceAction, EBVMInstanceStatus>[] _Operations,
            Action _OnCompleted,
            Action _OnFailure,
            Action <string> _ErrorMessageAction = null)
        {
            int ProgressStackIx = Interlocked.Increment(ref CurrentActionIndex);

            var ProgressStack = new Stack <object>();

            if (_Operations != null && _Operations.Length > 0)
            {
                lock (ProgressStacks_Lock)
                {
                    ProgressStacks.Add(ProgressStackIx, ProgressStack);
                }

                var Service = GetService(); //Will be disposed in async methods
                var Request = new BatchRequest(Service);

                foreach (var _Operation in _Operations)
                {
                    var FoundInstance = FindInstanceByUniqueName(_Operation.Item1, _ErrorMessageAction);
                    if (FoundInstance != null)
                    {
                        if (GetStatusFromString(FoundInstance.Status) == _Operation.Item3)
                        {
                            IClientServiceRequest RequestAction = null;
                            if (_Operation.Item2 == EBVMInstanceAction.Start)
                            {
                                RequestAction = Service.Instances.Start(ProjectID, ZoneName, FoundInstance.Name);
                            }
                            else if (_Operation.Item2 == EBVMInstanceAction.Stop)
                            {
                                RequestAction = Service.Instances.Stop(ProjectID, ZoneName, FoundInstance.Name);
                            }

                            if (RequestAction != null)
                            {
                                Request.Queue <Instance>(RequestAction,
                                                         (Content, Error, i, Message) =>
                                {
                                    lock (ProgressStacks_Lock)
                                    {
                                        if (ProgressStacks.TryGetValue(ProgressStackIx, out Stack <object> FoundStack) && FoundStack.Count > 0)
                                        {
                                            if (Error != null)
                                            {
                                                _ErrorMessageAction?.Invoke("BVMServiceGC->PerformActionOnInstances->Error: " + Error.Message);
                                                FoundStack.Clear();
                                                _OnFailure?.Invoke();
                                            }
                                            else
                                            {
                                                FoundStack.Pop();
                                                if (FoundStack.Count == 0)
                                                {
                                                    ProgressStacks.Remove(ProgressStackIx);
                                                    _OnCompleted?.Invoke();
                                                }
                                            }
                                        }
                                    }
                                });
                                ProgressStack.Push(new object());
                            }
                        }
                    }
                }
                if (ProgressStack.Count > 0)
                {
                    BTaskWrapper.Run(() =>
                    {
                        Thread.CurrentThread.IsBackground = true;

                        try
                        {
                            using (var CreatedTask = Request.ExecuteAsync())
                            {
                                CreatedTask.Wait();
                            }
                        }
                        catch (Exception e)
                        {
                            _ErrorMessageAction?.Invoke("BVMServiceGC->PerformActionOnInstances->Exception: " + e.Message);
                            _OnFailure?.Invoke();
                        }
                        Service?.Dispose();
                    });
                }
                else
                {
                    lock (ProgressStacks_Lock)
                    {
                        ProgressStacks.Remove(ProgressStackIx);
                    }
                    Service?.Dispose();
                }
            }
            return(ProgressStack.Count);
        }
Beispiel #13
0
        public void Run(Action <string> _ServerLogAction = null)
        {
            var bStartSucceed       = new BValue <bool>(false);
            var WaitForFirstSuccess = new ManualResetEvent(false);

            BTaskWrapper.Run(() =>
            {
                var WaitForException = new ManualResetEvent(false);
                int FailureCount     = 0;
                do
                {
                    try
                    {
                        lock (Listener)
                        {
                            Listener.Start();
                        }

                        bStartSucceed.Set(true);
                        try
                        {
                            WaitForFirstSuccess.Set();
                        }
                        catch (Exception) {}

                        FailureCount = 0;

                        try
                        {
                            WaitForException.WaitOne();
                            //Do not close WaitForException! Can be reused.
                        }
                        catch (Exception) { }
                    }
                    catch (Exception e)
                    {
                        _ServerLogAction?.Invoke("BWebService->Run->HttpListener->Start: " + e.Message + ", trace: " + e.Message);

                        try
                        {
                            WaitForException.Set();
                        }
                        catch (Exception) { }

                        Thread.Sleep(1000);
                    }
                } while (++FailureCount < 10);

                try
                {
                    WaitForFirstSuccess.Set(); //When exhausted
                }
                catch (Exception) { }
            });

            try
            {
                WaitForFirstSuccess.WaitOne();
                //Do not close WaitForFirstSuccess! Can be reused.
            }
            catch (Exception) {}

            if (!bStartSucceed.Get())
            {
                _ServerLogAction?.Invoke("BWebService->Run: HttpListener.Start() has failed.");
                return;
            }

            BTaskWrapper.Run(() =>
            {
                _ServerLogAction?.Invoke("BWebserver->Run: Server is running. Listening port " + ServerPort);

                while (Listener.IsListening)
                {
                    HttpListenerContext Context = null;

                    int FailureCount = 0;
                    bool bSuccess;
                    do
                    {
                        try
                        {
                            lock (Listener)
                            {
                                Context = Listener.GetContext();
                            }
                            bSuccess     = true;
                            FailureCount = 0;
                        }
                        catch (Exception e)
                        {
                            _ServerLogAction?.Invoke("BWebService->Run->HttpListener->GetContext: " + e.Message + ", trace: " + e.Message);
                            bSuccess = false;
                            Thread.Sleep(1000);
                        }
                    } while (!bSuccess && ++FailureCount < 10);

                    if (Context == null)
                    {
                        continue;
                    }

                    BTaskWrapper.Run(() =>
                    {
                        if (Context == null)
                        {
                            return;
                        }
                        try
                        {
                            Context.Response.AppendHeader("Access-Control-Allow-Origin", "*");

                            bool bIsWebhookRequest =
                                BWebUtilities.DoesContextContainHeader(out List <string> _, out string _, Context, "webhook-request-callback") &&
                                BWebUtilities.DoesContextContainHeader(out List <string> _, out string _, Context, "webhook-request-origin");

                            if (Context.Request.HttpMethod == "OPTIONS" && !bIsWebhookRequest)
                            {
                                Context.Response.AppendHeader("Access-Control-Allow-Headers", "*");
                                Context.Response.AppendHeader("Access-Control-Allow-Credentials", "true");
                                Context.Response.AppendHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH");
                                Context.Response.AppendHeader("Access-Control-Max-Age", "-1");
                                Context.Response.StatusCode = BWebResponse.Status_OK_Code;
                            }
                            else
                            {
                                if (PrefixesToListen == null)
                                {
                                    _ServerLogAction?.Invoke("BWebserver->Run: PrefixesToListen is null.");
                                    WriteInternalError(Context.Response, "Code: WS-PTLN.");
                                    return;
                                }
                                if (!LookForListenersFromRequest(out BWebServiceBase _Callback, Context))
                                {
                                    if (Context.Request.RawUrl.EndsWith("/ping"))
                                    {
                                        WriteOK(Context.Response, "pong");
                                        return;
                                    }
                                    _ServerLogAction?.Invoke($"BWebserver->Run: Request is not being listened. Request: {Context.Request.RawUrl}");
                                    WriteNotFound(Context.Response, "Request is not being listened.");
                                    return;
                                }

                                var Response = _Callback.OnRequest(Context, _ServerLogAction);

                                Context.Response.StatusCode = Response.StatusCode;

                                foreach (var CurrentHeader in Response.Headers)
                                {
                                    foreach (var Value in CurrentHeader.Value)
                                    {
                                        if (CurrentHeader.Key.ToLower() != "access-control-allow-origin")
                                        {
                                            Context.Response.AppendHeader(CurrentHeader.Key, Value);
                                        }
                                    }
                                }

                                if (Response.ResponseContentType != null)
                                {
                                    Context.Response.ContentType = Response.ResponseContentType;
                                }

                                if (Response.ResponseContent.Type == EBStringOrStreamEnum.String)
                                {
                                    byte[] Buffer = Encoding.UTF8.GetBytes(Response.ResponseContent.String);
                                    if (Buffer != null)
                                    {
                                        Context.Response.ContentLength64 = Buffer.Length;
                                        if (Buffer.Length > 0)
                                        {
                                            Context.Response.OutputStream.Write(Buffer, 0, Buffer.Length);
                                        }
                                    }
                                    else
                                    {
                                        Context.Response.ContentLength64 = 0;
                                    }
                                }
                                else
                                {
                                    if (Response.ResponseContent.Stream != null && Response.ResponseContent.StreamLength > 0)
                                    {
                                        Context.Response.ContentLength64 = Response.ResponseContent.StreamLength;
                                        Response.ResponseContent.Stream.CopyTo(Context.Response.OutputStream);
                                    }
                                    else
                                    {
                                        _ServerLogAction?.Invoke("BWebserver->Error: Response is stream, but stream object is " + (Response.ResponseContent.Stream == null ? "null" : "valid") + " and content length is " + Response.ResponseContent.StreamLength);
                                        WriteInternalError(Context.Response, "Code: WS-STRMINV.");
                                        return;
                                    }
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            try
                            {
                                WriteInternalError(Context.Response, "An unexpected internal error has occured: " + e.Message);
                            }
                            catch (Exception) { }

                            _ServerLogAction?.Invoke("Uncaught exception in the request handle: " + e.Message + ", trace: " + e.StackTrace);
                        }
                        finally
                        {
                            //Always close the stream
                            try { Context.Response.OutputStream.Close(); } catch (Exception) { }
                            try { Context.Response.OutputStream.Dispose(); } catch (Exception) { }
                            //try { Context.Response.Close(); } catch (Exception) { }
                        }
                    });
                }
            });
        }
Beispiel #14
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="_Messages"></param>
        /// <param name="_LogGroupName"></param>
        /// <param name="_LogStreamName"></param>
        /// <param name="_bAsync"></param>
        /// <param name="_ErrorMessageAction"></param>
        /// <returns></returns>
        public bool WriteLogs(List <BLoggingParametersStruct> _Messages, string _LogGroupName, string _LogStreamName, bool _bAsync = true, Action <string> _ErrorMessageAction = null)
        {
            if (_Messages == null || _Messages.Count == 0)
            {
                return(false);
            }

            if (_bAsync)
            {
                BTaskWrapper.Run(() =>
                {
                    WriteLogs(_Messages, _LogGroupName, _LogStreamName, false, _ErrorMessageAction);
                });
                return(true);
            }
            else
            {
                _LogGroupName  = BUtility.EncodeStringForTagging(_LogGroupName);
                _LogStreamName = BUtility.EncodeStringForTagging(_LogStreamName);

                if (!BUtility.CalculateStringMD5(DateTime.Now.Subtract(DateTime.MinValue.AddYears(1969)).TotalMilliseconds.ToString(), out string Timestamp, _ErrorMessageAction))
                {
                    _ErrorMessageAction?.Invoke("BLoggingServiceAzure->WriteLogs: Timestamp generation has failed.");
                    return(false);
                }

                string StreamIDBase = _LogGroupName + "-" + _LogStreamName + "-" + Timestamp;

                try
                {
                    using (AzureLogger.BeginScope(StreamIDBase))
                    {
                        foreach (var Message in _Messages)
                        {
                            var level   = LogLevel.Information;
                            var message = "Info-> " + Message.Message;

                            switch (Message.LogType)
                            {
                            case EBLoggingServiceLogType.Debug:
                                level   = LogLevel.Debug;
                                message = "Debug-> " + Message.Message;
                                break;

                            case EBLoggingServiceLogType.Warning:
                                level   = LogLevel.Warning;
                                message = "Warning-> " + Message.Message;
                                break;

                            case EBLoggingServiceLogType.Error:
                                level   = LogLevel.Error;
                                message = "Error-> " + Message.Message;
                                break;

                            case EBLoggingServiceLogType.Critical:
                                level   = LogLevel.Critical;
                                message = "Critical-> " + Message.Message;
                                break;

                            default:
                                level   = LogLevel.Information;
                                message = "Info-> " + Message.Message;
                                break;
                            }

                            AzureLogger.Log(level, message);
                        }
                    }

                    // Explicitly call Flush() followed by sleep is required in Console Apps.
                    // This is to ensure that even if application terminates, telemetry is sent to the back-end.
                    AzureTelemetryChannel?.Flush();
                    Thread.Sleep(1000);

                    return(true);
                }
                catch (Exception e)
                {
                    _ErrorMessageAction?.Invoke("BLoggingServiceAzure->WriteLogs: " + e.Message + ", Trace: " + e.StackTrace);
                }
            }

            return(false);
        }
Beispiel #15
0
        /// <summary>
        ///
        /// <para>WriteLogs:</para>
        ///
        /// <para>Writes logs to the logging service</para>
        ///
        /// <para>Check <seealso cref="IBLoggingServiceInterface.WriteLogs"/> for detailed documentation</para>
        ///
        /// </summary>
        public bool WriteLogs(
            List <BLoggingParametersStruct> _Messages,
            string _LogGroupName,
            string _LogStreamName,
            bool _bAsync = true,
            Action <string> _ErrorMessageAction = null)
        {
            if (_Messages == null || _Messages.Count == 0)
            {
                return(false);
            }

            if (_bAsync)
            {
                BTaskWrapper.Run(() =>
                {
                    WriteLogs(_Messages, _LogGroupName, _LogStreamName, false, _ErrorMessageAction);
                });
                return(true);
            }
            else
            {
                if (!BUtility.CalculateStringMD5(DateTime.Now.Subtract(DateTime.MinValue.AddYears(1969)).TotalMilliseconds.ToString(), out string Timestamp, _ErrorMessageAction))
                {
                    _ErrorMessageAction?.Invoke("BLoggingServiceGC->WriteLogs: Timestamp generation has failed.");
                    return(false);
                }

                _LogGroupName  = BUtility.EncodeStringForTagging(_LogGroupName);
                _LogStreamName = BUtility.EncodeStringForTagging(_LogStreamName);

                string StreamIDBase = _LogGroupName + "-" + _LogStreamName + "-" + Timestamp;
                try
                {
                    var LogEntries = new LogEntry[_Messages.Count];

                    int i = 0;
                    foreach (var Message in _Messages)
                    {
                        LogEntries[i] = new LogEntry
                        {
                            LogName     = new LogName(ProjectID, StreamIDBase + "-" + (i + 1).ToString()).ToString(),
                            TextPayload = Message.Message
                        };

                        switch (Message.LogType)
                        {
                        case EBLoggingServiceLogType.Debug:
                            LogEntries[i].Severity = LogSeverity.Debug;
                            break;

                        case EBLoggingServiceLogType.Info:
                            LogEntries[i].Severity = LogSeverity.Info;
                            break;

                        case EBLoggingServiceLogType.Warning:
                            LogEntries[i].Severity = LogSeverity.Warning;
                            break;

                        case EBLoggingServiceLogType.Error:
                            LogEntries[i].Severity = LogSeverity.Error;
                            break;

                        case EBLoggingServiceLogType.Critical:
                            LogEntries[i].Severity = LogSeverity.Critical;
                            break;
                        }

                        i++;
                    }

                    LoggingServiceClient.WriteLogEntries(
                        LogNameOneof.From(new LogName(ProjectID, StreamIDBase)),
                        ResourceName,
                        new Dictionary <string, string>()
                    {
                        ["LogGroup"]  = _LogGroupName,
                        ["LogStream"] = _LogStreamName
                    },
                        LogEntries);

                    return(true);
                }
                catch (Exception e)
                {
                    _ErrorMessageAction?.Invoke("BLoggingServiceGC->WriteLogs: " + e.Message + ", Trace: " + e.StackTrace);
                }
            }
            return(false);
        }