Пример #1
0
            public override ExternalCallResponse Execute()
            {
                Script.NonEmpty(nameof(Script));

                var results = new List <step>();

                foreach (var step in Script.Children)
                {
                    try
                    {
                        var result = Context.ExecCommandAsync(step).GetAwaiter().GetResult();
                        results.Add(new step {
                            src = step.RootPath, ok = true, result = result
                        });
                    }
                    catch (Exception error)
                    {
                        var e = new WrappedExceptionData(error, false, true);
                        results.Add(new step {
                            src = step.RootPath, ok = false, result = e
                        });
                    }
                }

                return(new ExternalCallResponse(ContentType.JSON, new { OK = true, results = results }.ToJson(JsonWritingOptions.PrettyPrintRowsAsMapASCII)));
            }
Пример #2
0
        public void WrappedExceptionData_Slim()
        {
            try
            {
                throw new AzosException("Oy vei!", new AzosException("Inside"))
                      {
                          Code = 223322, Source = "Karlson"
                      };
            }
            catch (Exception caught)
            {
                var wed = new WrappedExceptionData(caught);
                var ser = new Azos.Serialization.Slim.SlimSerializer();

                using (var ms = new MemoryStream())
                {
                    ser.Serialize(ms, wed);
                    ms.Position = 0;

                    var bin = ms.ToArray();
                    Console.WriteLine();
                    Console.WriteLine($"Bin {bin.Length} bytes:");
                    Console.WriteLine($"-----------------------------");
                    Console.WriteLine(bin.ToDumpString(DumpFormat.Hex));

                    var wed2 = ser.Deserialize(ms) as WrappedExceptionData;
                    averWrappedExceptionEquality(wed, wed2);
                }
            }
        }
Пример #3
0
        public void WrappedExceptionData_BSON()
        {
            try
            {
                throw new AzosException("Oy vei!", new AzosException("Inside"))
                      {
                          Code = 223322, Source = "Karlson"
                      };
            }
            catch (Exception caught)
            {
                var wed = new WrappedExceptionData(caught);
                var ser = new Azos.Serialization.BSON.BSONSerializer();

                var doc = ser.Serialize(wed);

                var    wed2 = new WrappedExceptionData();
                object ctx  = null;
                wed2.DeserializeFromBSON(ser, doc, ref ctx);

                Console.WriteLine();
                Console.WriteLine($"BSON:");
                Console.WriteLine($"-----------------------------");
                Console.WriteLine(doc.ToJSON());

                averWrappedExceptionEquality(wed, wed2);
            }
        }
Пример #4
0
        private static int governedConsoleMainBody(BootArgs args)
        {
            Console.CancelKeyPress += (_, e) => {
                var app = s_Application;//capture
                if (app != null)
                {
                    app.Stop();
                    e.Cancel = true;
                }
            };

            try
            {
                try
                {
                    Start(args);

                    //blocks until application is running
                    while (true)
                    {
                        var stopped = s_Application.WaitForStopOrShutdown(5000);
                        if (stopped)
                        {
                            break;
                        }
                    }
                }
                finally
                {
                    Stop();
                }

                return(0);
            }
            catch (Exception error)
            {
                var wrap         = new WrappedExceptionData(error, true);
                var errorContent = "App Root exception, details: \n" + wrap.ToJson(JsonWritingOptions.PrettyPrintRowsAsMap);
                var crashFile    = "{0:yyyyMMdd-HHmmssff}-{1}-{2}.crash.log".Args(
                    DateTime.Now,
                    System.Reflection.Assembly.GetEntryAssembly().GetName().Name,
                    s_AppId.Default("unset"));

                try
                {
                    System.IO.File.WriteAllText(crashFile, errorContent);
                    Console.WriteLine(errorContent);
                }
                catch { }

                return(-100);
            }
        }
Пример #5
0
        /// <summary>
        /// Handles request synchronously in the context of the calling thread. Returns NULL for one-way calls
        /// </summary>
        public ResponseMsg HandleRequestFailure(FID reqID, bool oneWay, Exception failure, object bindingSpecCtx)
        {
            if (oneWay)
            {
                return(null);
            }

            var red      = new WrappedExceptionData(failure);
            var response = new ResponseMsg(reqID, red);

            response.__SetBindingSpecificContext(bindingSpecCtx);

            return(response);
        }
Пример #6
0
        public static void ShowRemoteExceptionData(WrappedExceptionData data, int lvl)
        {
            var ind = "".PadLeft(lvl);

            Console.WriteLine(ind + "Application: " + data.ApplicationName);
            Console.WriteLine(ind + "Code: {0}  Source: {1}".Args(data.Code, data.Source));
            Console.WriteLine(ind + "Type: " + data.TypeName);
            Console.WriteLine(ind + "Message: " + data.Message);
            Console.WriteLine(ind + "Stack: " + data.StackTrace);
            if (data.InnerException != null)
            {
                Console.WriteLine(ind + "Inner exception: ");
                ShowRemoteExceptionData(data.InnerException, lvl + 2);
            }
        }
Пример #7
0
        private ResponseMsg handleRequest(RequestMsg request)
        {
            try
            {
                ServerCallContext.__SetThreadLevelContext(request);
                try
                {
                    var response = doWork(request);

                    var rhdr = ServerCallContext.GetResponseHeadersOrNull();

                    if (rhdr != null && response != null)
                    {
                        response.Headers = rhdr;
                    }

                    return(response);
                }
                finally
                {
                    ServerCallContext.__ResetThreadLevelContext();
                }
            }
            catch (Exception error)
            {
                if (request.OneWay)
                {         //because it is one-way, the caller will never know about it
                    this.WriteLog(LogSrc.Server,
                                  MessageType.Error,
                                  string.Format(StringConsts.GLUE_SERVER_ONE_WAY_CALL_ERROR + error.ToMessageWithType()),
                                  from: "SrvrHndlr.handleRequest(ReqMsg)",
                                  exception: error
                                  );
                    return(null);
                }
                else
                {
                    var red      = new WrappedExceptionData(error);
                    var response = new ResponseMsg(request.RequestID, red);
                    response.__SetBindingSpecificContext(request);
                    return(response);
                }
            }
        }
Пример #8
0
        protected override ResponseMsg DoDecodeResponse(WireFrame frame, MemoryStream ms)
        {
            var utf8 = ms.GetBuffer();
            var json = Encoding.UTF8.GetString(utf8, (int)ms.Position, (int)ms.Length - (int)ms.Position);
            var data = json.JSONToDataObject() as JSONDataMap;

            if (data == null)
            {
                throw new ProtocolException(StringConsts.GLUE_BINDING_RESPONSE_ERROR.Args(nameof(AppTermBinding), "data==null"));
            }


            var reqID    = new FID(data["request-id"].AsULong(handling: ConvertErrorHandling.Throw));
            var instance = data["instance"].AsNullableGUID(handling: ConvertErrorHandling.Throw);

            object returnValue = data["return"];

            if (returnValue == null || returnValue is string)
            {
                //return as-is
            }
            else if (returnValue is JSONDataMap map)//error or Remote Terminal
            {
                var errorContent = map["error-content"].AsString();
                if (errorContent != null)
                {
                    returnValue = WrappedExceptionData.FromBase64(errorContent);
                }
                else
                {
                    returnValue = new Contracts.RemoteTerminalInfo(map);
                }
            }
            else
            {
                throw new ProtocolException(StringConsts.GLUE_BINDING_RESPONSE_ERROR.Args(nameof(AppTermBinding), "data.return is " + returnValue.GetType().FullName));
            }


            var result = new ResponseMsg(reqID, instance, returnValue);

            return(result);
        }
Пример #9
0
        private void averWrappedExceptionEquality(WrappedExceptionData d1, WrappedExceptionData d2)
        {
            Aver.IsNotNull(d1);
            Aver.IsNotNull(d2);
            Aver.AreNotSameRef(d1, d2);

            Aver.AreEqual(d1.Message, d2.Message);
            Aver.AreEqual(d1.Code, d2.Code);
            Aver.AreEqual(d1.Source, d2.Source);
            Aver.AreEqual(d1.TypeName, d2.TypeName);
            Aver.AreEqual(d1.ApplicationName, d2.ApplicationName);
            Aver.AreEqual(d1.StackTrace, d2.StackTrace);
            Aver.AreEqual(d1.WrappedData, d2.WrappedData);

            if (d1.InnerException != null)
            {
                averWrappedExceptionEquality(d1.InnerException, d2.InnerException);
            }
        }
Пример #10
0
        private void averWrappedExceptionEquality(WrappedExceptionData d1, WrappedExceptionData d2)
        {
            Aver.IsNotNull(d1);
            Aver.IsNotNull(d2);
            Aver.AreNotSameRef(d1, d2);

            Aver.AreEqual(d1.Message, d2.Message);
            Aver.AreEqual(d1.Code, d2.Code);
            Aver.AreEqual(d1.Source, d2.Source);
            Aver.AreEqual(d1.TypeName, d2.TypeName);
            Aver.AreEqual(d1.AppName, d2.AppName);
            Aver.AreEqual(d1.AppId, d2.AppId);
            Aver.AreEqual(d1.StackTrace, d2.StackTrace);
            Aver.AreEqual(d1.ExternalStatus.ToJson(), d2.ExternalStatus.ToJson());

            if (d1.InnerException != null)
            {
                averWrappedExceptionEquality(d1.InnerException, d2.InnerException);
            }
        }
Пример #11
0
        public static void ShowRemoteExceptionData(WrappedExceptionData data, int lvl)
        {
            var ind = "".PadLeft(lvl);

            Syscon.WriteLine(ind + "Application: {0}/{1} ".Args(data.AppName, data.AppId));
            Syscon.WriteLine(ind + "Code: {0}  Source: {1}".Args(data.Code, data.Source));
            Syscon.WriteLine(ind + "Type: " + data.TypeName);
            Syscon.WriteLine(ind + "Message: " + data.Message);
            Syscon.WriteLine(ind + "Stack: " + data.StackTrace);
            if (data.ExternalStatus != null)
            {
                Syscon.WriteLine(ind + "External details: ");
                Syscon.WriteLine(ind + data.ExternalStatus.ToJson(JsonWritingOptions.CompactASCII));
            }

            if (data.InnerException != null)
            {
                Syscon.WriteLine(ind + "Inner exception: ");
                ShowRemoteExceptionData(data.InnerException, lvl + 2);
            }
        }
Пример #12
0
        public void WrappedExceptionData_JSON()
        {
            try
            {
                throw new AzosException("Oy vei!", new AzosException("Inside"))
                      {
                          Code = 223322, Source = "Karlson"
                      };
            }
            catch (Exception caught)
            {
                var wed = new WrappedExceptionData(caught);

                var json = wed.ToJson(JsonWritingOptions.CompactRowsAsMap);

                json.See();

                var wed2 = JsonReader.ToDoc <WrappedExceptionData>(json);

                averWrappedExceptionEquality(wed, wed2);
            }
        }
Пример #13
0
        public void WrappedExceptionData_BASE64()
        {
            try
            {
                throw new AzosException("Oy vei!", new AzosException("Inside"))
                      {
                          Code = 223322, Source = "Karlson"
                      };
            }
            catch (Exception caught)
            {
                var wed    = new WrappedExceptionData(caught);
                var base64 = wed.ToBase64();

                Console.WriteLine();
                Console.WriteLine($"Base64 {base64.Length} bytes:");
                Console.WriteLine($"-----------------------------");
                Console.WriteLine(base64);

                var wed2 = WrappedExceptionData.FromBase64(base64);
                averWrappedExceptionEquality(wed, wed2);
            }
        }
Пример #14
0
        private static int interactiveConsoleMainBody(BootArgs args)
        {
            Console.CancelKeyPress += (_, e) => {
                var app = s_Application;//capture
                if (app != null)
                {
                    app.Stop();
                    e.Cancel = true;
                }
            };

            try
            {
                try
                {
                    Console.WriteLine("Azos Sky Application Host Process");
                    Console.WriteLine("Rev 2.0 July 3 2021 / Radio-86RK");
                    Console.WriteLine();
                    Console.WriteLine("Booting server daemon...");
                    Start(args);
                    Console.WriteLine("...server started");
                    Console.WriteLine("Application: {0} / `{1}`".Args(s_Application.AppId, s_Application.Name));
                    Console.WriteLine("Boot daemon: {0} / `{1}`".Args(s_Server.GetType().Name, s_Server.Name));
                    Console.WriteLine("Environment: {0}".Args(s_Application.EnvironmentName));
                    Console.WriteLine("Services provided: ");
                    Console.WriteLine("  " + s_Server.ServiceDescription.Default("n/a"));
                    Console.WriteLine();
                    Console.WriteLine("To stop the process enter 'exit' or 'stop' commands or hit <CTL+C>");

                    using (var term = new AppRemoteTerminal())
                    {
                        s_Application.InjectInto(term);

                        #region Perform SYSTEM Implicit Grant
                        //Impersonate the current call flow as local SYSTEM user.
                        //Warning: this code here is a very special case: a root server console.
                        //Never use the similar code in business applications as it bypasses all security
                        //by injecting the caller with SYSTEM-level privilege which results in implicit grant
                        //of all permission checks.
                        //Note: The session is injected with blank SysAuthToken() so this session is only granted locally
                        //and not capable of impersonating system on remote hosts
                        ExecutionContext.__SetThreadLevelSessionContext(new BaseSession(Guid.NewGuid(), 123)
                        {
                            User = new User(BlankCredentials.Instance, new SysAuthToken(), UserStatus.System, "sys", "Implicit grant", Rights.None)
                        });
                        #endregion

                        var wasPrompt = false;
                        while (s_Application.Active)
                        {
                            if (!wasPrompt)
                            {
                                Console.Write("{0}@{1}\n$ ".Args(s_Application.AppId, Platform.Computer.HostName));
                                wasPrompt = true;
                            }

                            if (!Console.KeyAvailable)
                            {
                                if (s_Application.WaitForStopOrShutdown(50))
                                {
                                    break;
                                }
                                continue;
                            }

                            var cmd = Console.ReadLine();
                            wasPrompt = false;

                            if (!s_Application.Active)
                            {
                                break;
                            }
                            if (cmd.IsNullOrWhiteSpace())
                            {
                                continue;
                            }
                            if (cmd.IsOneOf("quit", "exit", "stop"))
                            {
                                break;
                            }

                            try
                            {
                                var response = term.Execute(cmd);

                                if (response.StartsWith(AppRemoteTerminal.MARKUP_PRAGMA))
                                {
                                    ConsoleUtils.WriteMarkupContent(response);
                                }
                                else
                                {
                                    Console.WriteLine(response);
                                }
                            }
                            catch (Exception eterm)
                            {
                                ConsoleUtils.Error("Terminal error: ");
                                var wrap = new WrappedExceptionData(eterm, true);
                                Console.WriteLine(wrap.ToJson(JsonWritingOptions.PrettyPrintRowsAsMap));
                            }
                        }
                    }
                    Console.WriteLine("...shutting down now");
                    Console.WriteLine();
                }
                finally
                {
                    Stop();
                }

                return(0);
            }
            catch (Exception error)
            {
                ConsoleUtils.Error("App Root exception, details: ");
                var wrap = new WrappedExceptionData(error, true);
                Console.WriteLine(wrap.ToJson(JsonWritingOptions.PrettyPrintRowsAsMap));

                return(-100);
            }
        }
Пример #15
0
 public RemoteException(WrappedExceptionData data) : base(data.ToString())
 {
     m_Remote = data;
 }
Пример #16
0
 public RemoteException(string message, WrappedExceptionData data) : base(message)
 {
     m_Remote = data;
 }
Пример #17
0
        public static int consoleMainBody(string[] args)
        {
            Console.CancelKeyPress += (_, e) => {
                var app = s_Application;//capture
                if (app != null)
                {
                    app.Stop();
                    e.Cancel = true;
                }
            };

            try
            {
                try
                {
                    Console.WriteLine("Azos Sky Application Host Process");
                    Console.WriteLine("Rev 1.0 Nov 2020 / Radio-86RK");
                    Console.WriteLine();
                    Console.WriteLine("Booting server daemon...");
                    Start(args);
                    Console.WriteLine("...server started");
                    Console.WriteLine("Application: {0} / `{1}`".Args(s_Application.AppId, s_Application.Name));
                    Console.WriteLine("Boot daemon: {0} / `{1}`".Args(s_Server.GetType().Name, s_Server.Name));
                    Console.WriteLine("Environment: {0}".Args(s_Application.EnvironmentName));
                    Console.WriteLine("Services provided: ");
                    Console.WriteLine("  " + s_Server.ServiceDescription.Default("n/a"));
                    Console.WriteLine();
                    Console.WriteLine("To stop the process enter 'exit' or 'stop' commands or hit <CTL+C>");

                    using (var term = new AppRemoteTerminal())
                    {
                        s_Application.InjectInto(term);

                        //Impersonate the current call flow as SYSTEM
                        ExecutionContext.__SetThreadLevelSessionContext(new BaseSession(Guid.NewGuid(), 123)
                        {
                            User = new User(BlankCredentials.Instance, new SysAuthToken(), UserStatus.System, "sys", "Implicit grant", Rights.None)
                        });

                        while (s_Application.Active)
                        {
                            Console.Write("{0}@{1}\n$ ".Args(s_Application.AppId, Azos.Platform.Computer.HostName));
                            var cmd = Console.ReadLine();
                            if (cmd.IsNullOrWhiteSpace())
                            {
                                continue;
                            }
                            if (cmd.IsOneOf("quit", "exit", "stop"))
                            {
                                break;
                            }

                            try
                            {
                                var response = term.Execute(cmd);

                                if (response.StartsWith(AppRemoteTerminal.MARKUP_PRAGMA))
                                {
                                    ConsoleUtils.WriteMarkupContent(response);
                                }
                                else
                                {
                                    Console.WriteLine(response);
                                }
                            }
                            catch (Exception eterm)
                            {
                                ConsoleUtils.Error("Terminal error: ");
                                var wrap = new WrappedExceptionData(eterm, true);
                                Console.WriteLine(wrap.ToJson(JsonWritingOptions.PrettyPrintRowsAsMap));
                            }
                        }
                    }
                    Console.WriteLine("...shutting down now");
                    Console.WriteLine();
                }
                finally
                {
                    Stop();
                }

                return(0);
            }
            catch (Exception error)
            {
                ConsoleUtils.Error("App Root exception, details: ");
                var wrap = new WrappedExceptionData(error, true);
                Console.WriteLine(wrap.ToJson(JsonWritingOptions.PrettyPrintRowsAsMap));

                return(-100);
            }
        }
Пример #18
0
 public RemoteException(string message, WrappedExceptionData data, Exception inner) : base(message, inner)
 {
     m_Remote = data;
 }