Example #1
0
        public static void Main(string[] args)
        {
            // See https://support.microsoft.com/en-gb/help/821268/contention-poor-performance-and-deadlocks-when-you-make-calls-to-web-s
            // Experimentation shows we need the ThreadPool to always spin up threads for good performance under load
            ThreadPool.GetMaxThreads(out var workerThreads, out var ioThreads);
            ThreadPool.SetMinThreads(workerThreads, ioThreads);

            Parser.Default.ParseArguments <SteamAuthArguments>(args)
            .WithParsed(parsedArgs =>
            {
                Log.Logger = new LoggerConfiguration()
                             .WriteTo.Console(new RenderedCompactJsonFormatter())
                             .Enrich.FromLogContext()
                             .CreateLogger();

                var steamDeveloperKey = Secrets.GetEnvSecret(SteamSymmetricKey).Trim();


                var server = GrpcBaseServer.Build(parsedArgs);
                server.AddService
                (
                    AuthService.BindService
                    (
                        new SteamAuthImpl
                        (
                            parsedArgs.ProjectName,
                            PlayerAuthServiceClient.Create
                            (
                                endpoint: new PlatformApiEndpoint(/*host*/ "steamauth.api.com", /*pot*/ 443, /*insecure*/ true),
                                credentials: null, //new PlatformRefreshTokenCredential()
                                settings: null
                            ),
                            analytics: null
                        )
                    )
                );

                var serverTask = Task.Run(() => server.Start());
                var signalTask = Task.Run(() => UnixSignal.WaitAny(new[] { new UnixSignal(Signum.SIGINT), new UnixSignal(Signum.SIGTERM) }));
                Log.Information("Steam authentication server started up");
                Task.WaitAny(serverTask, signalTask);

                if (signalTask.IsCompleted)
                {
                    Log.Information($"Received UNIX signal {signalTask.Result}");
                    Log.Information("Server shutting down...");
                    server.Shutdown();
                    serverTask.Wait();
                    Log.Information("Server stopped cleanly");
                }
                else
                {
                    /* The server task has completed; we can just exit. */
                    Log.Information("The PlayFab authentication server has stopped itself or encountered an unhandled exception.");
                }

                Environment.Exit(0);
            });
        }
Example #2
0
 public void TestNoEmitAny()
 {
     using (UnixSignal u = new UnixSignal(Signum.SIGINT))
     {
         int idx = UnixSignal.WaitAny(new UnixSignal[] { u }, 5100);
         Assert.AreEqual(idx, 5100);
     }
 }
Example #3
0
 static Thread CreateWaitAnyThread(params UnixSignal[] usignals)
 {
     return(new Thread(delegate()
     {
         int idx = UnixSignal.WaitAny(usignals, 30000);
         Assert.AreEqual(idx >= 0 && idx < usignals.Length, true);
     }));
 }
Example #4
0
 public UnixExitSignal()
 {
     Task.Factory.StartNew(() =>
     {
         // blocking call to wait for any kill signal
         UnixSignal.WaitAny(_signals, -1);
         RaiseExit();
     });
 }
Example #5
0
 public UnixExitSignal()
 {
     Task.Factory.StartNew(() =>
     {
         // blocking call to wait for any kill signal
         int index = UnixSignal.WaitAny(signals, -1);
         Exit?.Invoke(null, EventArgs.Empty);
     });
 }
Example #6
0
        public static void SetupSignalHandlers(SignalHandler signal_handler)
        {
            UnixSignal[] signals = new UnixSignal [] {
                new UnixSignal(Mono.Unix.Native.Signum.SIGINT),
                new UnixSignal(Mono.Unix.Native.Signum.SIGTERM),
                new UnixSignal(Mono.Unix.Native.Signum.SIGUSR1),
                new UnixSignal(Mono.Unix.Native.Signum.SIGUSR2)
            };

            // Ignore SIGPIPE
            // FIXME: Shouldn't this be done in every thread ?
            Mono.Unix.Native.Stdlib.SetSignalAction(Mono.Unix.Native.Signum.SIGPIPE, Mono.Unix.Native.SignalAction.Ignore);

            // Work around a mono feature/bug
            // https://bugzilla.novell.com/show_bug.cgi?id=381928
            // When beagle crashes, mono will try to print a stack trace and then call abort()
            // The abort somehow calls back into beagle and causes a deadlock
            if (Environment.GetEnvironmentVariable("BEAGLE_MONO_DEBUG_FLAG_IS_SET") == null)
            {
                Mono.Unix.Native.Stdlib.SetSignalAction(Mono.Unix.Native.Signum.SIGABRT, Mono.Unix.Native.SignalAction.Default);
            }

            Thread signal_thread = new Thread(delegate() {
                Log.Debug("Starting signal handler thread");
                int signal_handler_timeout = -1;
                while (!MainloopFinished)
                {
                    int index = UnixSignal.WaitAny(signals, signal_handler_timeout);

                    if (index > 3)
                    {
                        continue;
                    }
                    Mono.Unix.Native.Signum signal = signals [index].Signum;

                    // Set shutdown flag to true so that other threads can stop initializing
                    if (signal == Mono.Unix.Native.Signum.SIGINT ||
                        signal == Mono.Unix.Native.Signum.SIGTERM)
                    {
                        ShutdownRequested      = true;
                        signal_handler_timeout = 200;                         // 200 ms
                    }

                    if (signal_handler == null)
                    {
                        continue;
                    }

                    // Do all signal handling work in the main loop and not in the signal handler.
                    GLib.Idle.Add(new GLib.IdleHandler(delegate() { signal_handler((int)signal); return(false); }));
                }
                Log.Debug("Exiting signal handler thread");
            });

            signal_thread.Start();
        }
Example #7
0
        public static void Main(string[] args)
        {
            // See https://support.microsoft.com/en-gb/help/821268/contention-poor-performance-and-deadlocks-when-you-make-calls-to-web-s
            // Experimentation shows we need the ThreadPool to always spin up threads for good performance under load
            ThreadPool.GetMaxThreads(out var workerThreads, out var ioThreads);
            ThreadPool.SetMinThreads(workerThreads, ioThreads);

            Parser.Default.ParseArguments <PlayFabAuthArguments>(args)
            .WithParsed(parsedArgs =>
            {
                Log.Logger = new LoggerConfiguration()
                             .WriteTo.Console(new RenderedCompactJsonFormatter())
                             .Enrich.FromLogContext()
                             .CreateLogger();

                var spatialRefreshToken = Secrets.GetEnvSecret(SpatialRefreshTokenEnvironmentVariable).Trim();
                var playfabDeveloperKey = Secrets.GetEnvSecret(PlayFabSecretKeyEnvironmentVariable).Trim();

                PlayFabSettings.DeveloperSecretKey = playfabDeveloperKey;
                PlayFabSettings.TitleId            = parsedArgs.PlayFabTitleId;

                IAnalyticsSender analyticsSender = new AnalyticsSenderBuilder("playfab_auth")
                                                   .WithCommandLineArgs(parsedArgs)
                                                   .With(new LogExceptionStrategy(Log.Logger))
                                                   .Build();

                var server = GrpcBaseServer.Build(parsedArgs);
                server.AddService(AuthService.BindService(
                                      new PlayFabAuthImpl(
                                          parsedArgs.SpatialProject,
                                          PlayerAuthServiceClient.Create(
                                              credentials: new PlatformRefreshTokenCredential(spatialRefreshToken)),
                                          analyticsSender)
                                      ));
                var serverTask = Task.Run(() => server.Start());
                var signalTask = Task.Run(() => UnixSignal.WaitAny(new[] { new UnixSignal(Signum.SIGINT), new UnixSignal(Signum.SIGTERM) }));
                Log.Information("PlayFab authentication server started up");
                Task.WaitAny(serverTask, signalTask);

                if (signalTask.IsCompleted)
                {
                    Log.Information($"Received UNIX signal {signalTask.Result}");
                    Log.Information("Server shutting down...");
                    server.Shutdown();
                    serverTask.Wait();
                    Log.Information("Server stopped cleanly");
                }
                else
                {
                    /* The server task has completed; we can just exit. */
                    Log.Information("The PlayFab authentication server has stopped itself or encountered an unhandled exception.");
                }

                Environment.Exit(0);
            });
        }
Example #8
0
        public UnixExitSignal()
        {
            new Thread(() =>
            {
                // blocking call to wait for any kill signal
                UnixSignal.WaitAny(Signals, -1);

                Exit?.Invoke(this, EventArgs.Empty);
            }).Start();
        }
Example #9
0
        public SnapOsUnixExitSignal()
        {
            ThreadPool.QueueUserWorkItem(_ =>
            {
                // blocking call to wait for any kill signal
                UnixSignal.WaitAny(_signals, -1);

                Exit?.Invoke(null, EventArgs.Empty);
            });
        }
Example #10
0
        void ListenForSignal()
        {
            try
            {
                var          intr    = new UnixSignal(Signum.SIGINT);
                var          term    = new UnixSignal(Signum.SIGTERM);
                var          hup     = new UnixSignal(Signum.SIGHUP);
                var          usr2    = new UnixSignal(Signum.SIGUSR2);
                UnixSignal[] signals = { intr, term, hup, usr2 };

                _logger.Info("Start listening for unix signals");

                for (_running = true; _running;)
                {
                    var idx = UnixSignal.WaitAny(signals, 1000);
                    if (idx < 0 || idx >= signals.Length)
                    {
                        continue;
                    }
                    if (!_running)
                    {
                        return;
                    }

                    _logger.Info("LinuxSignal: received signal " + signals[idx].Signum);

                    if ((intr.IsSet || term.IsSet))
                    {
                        intr.Reset();
                        term.Reset();

                        _logger.Info("LinuxSignal: stopping...");

                        _running = false;
                        OnExit();
                        Environment.Exit(0);
                    }
                    else if (hup.IsSet)
                    {
                        // Ignore. Could be used to reload configuration.
                        hup.Reset();
                    }
                    else if (usr2.IsSet)
                    {
                        usr2.Reset();
                        // do something
                    }
                }
            }
            catch
            {
                _logger.Info("Unable to listen on unix signals");
            }
            _logger.Info("Finished listening to unix signals");
        }
Example #11
0
        static void Main(string[] args)
        {
            var config  = new AppSettings();
            var hostUrl = config.GetRequiredString("API.Url");
            var host    = new AppHostConsole();

            host.Init();

            var log = LogManager.GetLogger(typeof(Program));

            Console.WriteLine(@"
        ____               __                              _ 
       / __/___  _________/ /__  ________     ____ _____  (_)
      / /_/ __ \/ ___/ __  / _ \/ ___/ _ \   / __ `/ __ \/ / 
     / __/ /_/ / /  / /_/ /  __/ /  /  __/  / /_/ / /_/ / /  
    /_/  \____/_/   \__,_/\___/_/   \___/   \__,_/ .___/_/   
                                                /_/          
                            by Stefan Schoeb, Oliver Zuercher");

            Console.WriteLine();
            Console.WriteLine("starting on {0}...".Fmt(hostUrl));

            host.Start(hostUrl);

            var defaultColor = Console.ForegroundColor;

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("ready!");
            Console.ForegroundColor = defaultColor;

            //log.Info("REST API started");

            if (Environment.OSVersion.Platform == PlatformID.Unix)
            {
                var signals = new[] { new UnixSignal(Signum.SIGINT), new UnixSignal(Signum.SIGTERM) };

                // Wait for a unix signal
                for (bool exit = false; !exit;)
                {
                    int id = UnixSignal.WaitAny(signals);

                    if (id >= 0 && id < signals.Length)
                    {
                        if (signals[id].IsSet)
                        {
                            exit = true;
                        }
                    }
                }
            }
            else
            {
                Console.ReadLine();
            }
        }
Example #12
0
        static void Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                         .WriteTo.Console(new RenderedCompactJsonFormatter())
                         .Enrich.FromLogContext()
                         .CreateLogger();

            // See https://support.microsoft.com/en-gb/help/821268/contention-poor-performance-and-deadlocks-when-you-make-calls-to-web-s
            // Experimentation shows we need the ThreadPool to always spin up threads for good performance under load
            ThreadPool.GetMaxThreads(out var workerThreads, out var ioThreads);
            ThreadPool.SetMinThreads(workerThreads, ioThreads);

            Parser.Default.ParseArguments <GatewayArgs>(args)
            .WithParsed(parsedArgs =>
            {
                var spatialRefreshToken = Secrets.GetEnvSecret(SpatialRefreshTokenEnvironmentVariable);

                var memoryStoreClientManager =
                    new RedisClientManager(parsedArgs.RedisConnectionString);

                var playerAuthClient =
                    PlayerAuthServiceClient.Create(
                        credentials: new PlatformRefreshTokenCredential(spatialRefreshToken));

                IAnalyticsSender analyticsSender = new AnalyticsSenderBuilder("gateway_gateway")
                                                   .WithCommandLineArgs(parsedArgs)
                                                   .With(new LogExceptionStrategy(Log.Logger))
                                                   .Build();

                var server = GrpcBaseServer.Build(parsedArgs);
                server.AddInterceptor(new PlayerIdentityTokenValidatingInterceptor(
                                          playerAuthClient,
                                          memoryStoreClientManager.GetRawClient(Database.CACHE)));
                server.AddService(
                    GatewayService.BindService(new GatewayServiceImpl(memoryStoreClientManager, playerAuthClient, analyticsSender)));

                var serverTask = Task.Run(() => server.Start());
                var signalTask = Task.Run(() => UnixSignal.WaitAny(new[] { new UnixSignal(Signum.SIGINT), new UnixSignal(Signum.SIGTERM) }));
                Task.WaitAny(serverTask, signalTask);

                if (signalTask.IsCompleted)
                {
                    Log.Information($"Received UNIX signal {signalTask.Result}");
                    Log.Information("Server shutting down...");
                    server.Shutdown();
                    serverTask.Wait();
                    Log.Information("Server stopped cleanly");
                }
                else
                {
                    /* The server task has completed; we can just exit. */
                    Log.Information("The Gateway server has stopped itself or encountered an unhandled exception.");
                }
            });
        }
Example #13
0
        static void Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                         .WriteTo.Console(new RenderedCompactJsonFormatter())
                         .Enrich.FromLogContext()
                         .CreateLogger();

            // See https://support.microsoft.com/en-gb/help/821268/contention-poor-performance-and-deadlocks-when-you-make-calls-to-web-s
            ThreadPool.SetMaxThreads(100, 100);
            ThreadPool.SetMinThreads(50, 50);

            Parser.Default.ParseArguments <DeploymentPoolArgs>(args)
            .WithParsed(parsedArgs =>
            {
                parsedArgs.Validate();
                var spatialRefreshToken = Environment.GetEnvironmentVariable(SpatialRefreshTokenEnvironmentVariable) ??
                                          throw new Exception(
                    $"{SpatialRefreshTokenEnvironmentVariable} environment variable is required.");
                if (spatialRefreshToken == "")
                {
                    throw new ArgumentException("Refresh token should not be empty");
                }
                var spatialDeploymentClient =
                    DeploymentServiceClient.Create(credentials: new PlatformRefreshTokenCredential(spatialRefreshToken));
                var spatialSnapshotClient =
                    SnapshotServiceClient.Create(credentials: new PlatformRefreshTokenCredential(spatialRefreshToken));
                var platformInvoker = new PlatformInvoker(parsedArgs, spatialDeploymentClient, spatialSnapshotClient);


                var cancelTokenSource = new CancellationTokenSource();
                var cancelToken       = cancelTokenSource.Token;

                var metricsServer  = new MetricServer(parsedArgs.MetricsPort).Start();
                var dplPool        = new DeploymentPool(parsedArgs, spatialDeploymentClient, platformInvoker, cancelToken);
                var dplPoolTask    = Task.Run(() => dplPool.Start());
                var unixSignalTask = Task.Run(() => UnixSignal.WaitAny(new[] { new UnixSignal(Signum.SIGINT), new UnixSignal(Signum.SIGTERM) }));
                Task.WaitAny(dplPoolTask, unixSignalTask);

                if (unixSignalTask.IsCompleted)
                {
                    Log.Information($"Received UNIX signal {unixSignalTask.Result}");
                    Log.Information("Server shutting down...");
                    cancelTokenSource.Cancel();
                    metricsServer.StopAsync();
                    dplPoolTask.Wait();
                    Log.Information("Server stopped cleanly");
                }
                else
                {
                    /* The server task has completed; we can just exit. */
                    Log.Information($"The deployment pool has stopped itself or encountered an unhandled exception {dplPoolTask.Exception}");
                }
            });
        }
        public static void Main(string[] args)
        {
            //FeuerwehrCloud.Helper.Logger.WriteLine ("*****************************************************");
            //FeuerwehrCloud.Helper.Logger.WriteLine (">> Insights.Initialize(...)");
            //Xamarin.Insights.Initialize ("6a06545960cad8ccb572bb228b21470f3e1d5c09"); //,Application.ProductVersion,"FeuerwehrCloud.DEIVA"); //, , "FeuerwehrCloud.DEIVA", null,);
            //FeuerwehrCloud.Helper.Logger.WriteLine (">> Insights.Identify("+System.Environment.MachineName+")");
            //Insights.Identify (System.Environment.MachineName, new System.Collections.Generic.Dictionary<string, string> {
            //	{ Insights.Traits.Name,  System.Environment.MachineName }
            //});
            //FeuerwehrCloud.Helper.Logger.WriteLine (">> Insights.ForceDataTransmission = true;");
            //Insights.ForceDataTransmission = true;
            //FeuerwehrCloud.Helper.Logger.WriteLine ("Insights.Track (\"StartUp\");");
            //Insights.Track ("StartUp");
            //FeuerwehrCloud.Helper.Logger.WriteLine ("*****************************************************");
            Service P;

            using (P = StartServer())
            {
                //System.Environment.CurrentDirectory = "/Volumes/Macintosh HD/FeuerwehrCloud - Source/FeuerwehrCloud.Service/bin/Debug";
                //System.IO.Directory.SetCurrentDirectory ("/Volumes/Macintosh HD/FeuerwehrCloud - Source/FeuerwehrCloud.Service/bin/Debug");
                                #if __WINDOWS__
                for (bool exit = false; !exit;)
                {
                    System.Threading.Thread.Sleep(0);
                    Application.DoEvents();
                }
                                #else
                UnixSignal [] signals = new UnixSignal[] {
                    new UnixSignal(Signum.SIGINT),
                    new UnixSignal(Signum.SIGTERM),
                    new UnixSignal(Signum.SIGHUP),
                    new UnixSignal(Signum.SIGUSR2),
                    new UnixSignal(Signum.SIGQUIT)
                    //new UnixSignal(Signum.SIGSEGV),
                    //
                };

                for (bool exit = false; !exit;)
                {
                    int id = UnixSignal.WaitAny(signals);

                    if (id >= 0 && id < signals.Length)
                    {
                        if (signals[id].IsSet)
                        {
                            exit = true;
                            P.Dispose();
                            System.Environment.Exit(1);
                        }
                    }
                }
                                #endif
            }
        }
Example #15
0
        private static void WaitForExit()
        {
            var signals = new UnixSignal[] {
                new UnixSignal(Signum.SIGINT),
                new UnixSignal(Signum.SIGTERM)
            };
            var index  = UnixSignal.WaitAny(signals);
            var signal = signals[index].Signum;

            Console.WriteLine($"Received Signal: {signal}");
        }
Example #16
0
        public static void SignalHandler()
        {
            var sig  = new UnixSignal(Mono.Unix.Native.Signum.SIGUSR2);
            var sigs = new UnixSignal[] { sig };

            do
            {
                UnixSignal.WaitAny(sigs, new TimeSpan(0, 1, 0));
                covertool.SaveData();
            } while (debugee != null && !debugee.HasExited);
        }
Example #17
0
 private static void WaitForTermination()
 {
     if (IsRunningOnMono())
     {
         UnixSignal.WaitAny(GetUnixTerminationSignals());
     }
     else
     {
         Console.WriteLine("Press enter to stop the application.");
         Console.ReadLine();
     }
 }
Example #18
0
 private static void Initialize()
 {
     _signals = new UnixSignal[] {
         new UnixSignal(Mono.Unix.Native.Signum.SIGTERM),
         new UnixSignal(Mono.Unix.Native.Signum.SIGINT)
     };
     _signalThread = new Thread(delegate() {
         UnixSignal.WaitAny(_signals, -1);
         System.Environment.Exit(-1);
     });
     _signalThread.Start();
 }
Example #19
0
 private static void WaitForTerminationOnUnix()
 {
     Console.WriteLine("To stop process send a termination signal.");
     // on mono, processes will usually run as daemons - this allows you to listen
     // for termination signals (ctrl+c, shutdown, etc) and finalize correctly
     UnixSignal.WaitAny(new[] {
         new UnixSignal(Signum.SIGINT),
         new UnixSignal(Signum.SIGTERM),
         new UnixSignal(Signum.SIGQUIT),
         new UnixSignal(Signum.SIGHUP)
     });
 }
Example #20
0
 private static void WaitForTerminator()
 {
     if (IsRunningOnMono())
     {
         var terminationSignals = GetUnixTerminationSignals();
         UnixSignal.WaitAny(terminationSignals);
     }
     else
     {
         Console.ReadLine();
     }
 }
Example #21
0
        public void TestWaitAnyFailsWithMore64Signals()
        {
            UnixSignal s1 = new UnixSignal(Signum.SIGINT);

            UnixSignal[] signals = new UnixSignal[65];
            for (int i = 0; i < 65; ++i)
            {
                signals[i] = s1;
            }

            Assert.That(UnixSignal.WaitAny(signals, new TimeSpan(0, 0, 1)), Is.EqualTo(-1));
        }
        public bool HandleSignal(Action <Signum> signalFunc)
        {
            if (_signals == null)
            {
                if (Logger != null)
                {
                    Logger.Warning(typeof(UnixSignalHandler), "Unix signals not supported on this platform");
                }
                return(false);
            }

            if (_signalThread != null && _signalThread.IsAlive)
            {
                return(true);
            }

            _signalThread = new Thread(() =>
            {
                try
                {
                    if (_signals != null)
                    {
                        // Wait for a signal to be delivered
                        var index  = UnixSignal.WaitAny(_signals);
                        var signal = _signals[index].Signum;
                        _signaled  = true;

                        if (signalFunc != null)
                        {
                            signalFunc(signal);
                        }
                    }
                }
                catch (ThreadAbortException)
                {
                    // eat it
                }
                catch (Exception ex)
                {
                    if (Logger != null)
                    {
                        Logger.Error(typeof(UnixSignalHandler), "Error occurred in signal thread: " + ex.Message);
                    }
                }
            })
            {
                IsBackground = true
            };

            _signalThread.Start();
            return(true);
        }
Example #23
0
        /// <summary>
        /// Launches a background thread to listen for POSIX signals.
        /// Exit on two signal 2's or one signal 15.
        /// </summary>
        static void InstallSignalHandler(RCRunner runner)
        {
#if __MonoCS__
            UnixSignal[] signals =
            {
                new UnixSignal(Mono.Unix.Native.Signum.SIGTERM),
                new UnixSignal(Mono.Unix.Native.Signum.SIGINT)
            };
            Thread signalThread = new Thread(delegate()
            {
                while (true)
                {
                    int index = UnixSignal.WaitAny(signals, -1);
                    if (index < 0)
                    {
                        continue;
                    }
                    Mono.Unix.Native.Signum signal = signals[index].Signum;
                    if (signal == Mono.Unix.Native.Signum.SIGTERM)
                    {
                        ThreadPool.QueueUserWorkItem(delegate(object state)
                        {
                            RCSystem.Log.Record(0, 0, "runner", 0, "signal", "SIGTERM");
                            runner.Abort(15);
                        });
                    }
                    else if (signal == Mono.Unix.Native.Signum.SIGINT)
                    {
                        if (!_firstSigint)
                        {
                            _firstSigint = true;
                            ThreadPool.QueueUserWorkItem(delegate(object state)
                            {
                                RCSystem.Log.Record(0, 0, "runner", 0, "signal", "SIGINT");
                                runner.Interupt();
                            });
                        }
                        else
                        {
                            ThreadPool.QueueUserWorkItem(delegate(object state)
                            {
                                RCSystem.Log.Record(0, 0, "runner", 0, "signal", "SIGINT (exiting)");
                                runner.Abort(2);
                            });
                        }
                    }
                }
            });
            signalThread.IsBackground = true;
            signalThread.Start();
#endif
        }
Example #24
0
        public UnixExitSignal()
        {
            Task.Factory.StartNew(() =>
            {
                // blocking call to wait for any kill signal
                UnixSignal.WaitAny(signals, -1);

                if (Exit != null)
                {
                    Exit(null, EventArgs.Empty);
                }
            });
        }
Example #25
0
        public UnixConsoleCtrl()
        {
            Task.Factory.StartNew(() =>
            {
                // blocking call to wait for any kill signal
                int index = UnixSignal.WaitAny(signals, -1);

                if (OnExit != null)
                {
                    OnExit(this, EventArgs.Empty);
                }
            });
        }
 public void WaitForConsole()
 {
     Console.WriteLine("Running on {0}...", endpointAddress);
     if (Is_running_on_Mono)
     {
         Console.WriteLine("Ctrl-C to stop service host");
         UnixSignal.WaitAny(UnixTerminationSignals);
     }
     else
     {
         Console.WriteLine("ENTER to stop service host");
         Console.ReadLine();
     }
 }
Example #27
0
        private static void _processUnixInit()
        {
            UnixSignal[] signals = new UnixSignal[] {
                new UnixSignal(Mono.Unix.Native.Signum.SIGTERM),
                new UnixSignal(Mono.Unix.Native.Signum.SIGABRT),
                new UnixSignal(Mono.Unix.Native.Signum.SIGINT),
                new UnixSignal(Mono.Unix.Native.Signum.SIGUSR1)
            };

            UnixSignalThread = new System.Threading.Thread(() => {
                int index      = UnixSignal.WaitAny(signals, -1);
                ThreadsRunning = false;
            });
        }
Example #28
0
        public static void Main()
        {
            Log.Info("Starting server on port {0}", Port);

            var server = new Server();

            server.StartServer(Port).Wait();

            // Use Unix Signals
            UnixSignal.WaitAny(GetUnixTerminationSignals());
            server.Stop();

            Log.Info("Shutting down server");
        }
Example #29
0
 public void Setup()
 {
     new Thread(() =>
     {
         // Blocking operation with infinite expectation of any signal
         UnixSignal.WaitAny(Signals, -1);
         if (Core.LocalAdmin.Singleton == null)
         {
             return;
         }
         Core.LocalAdmin.Singleton !.ExitAction = Core.LocalAdmin.ShutdownAction.SilentShutdown;
         Core.LocalAdmin.Singleton !.Exit(0);
     }).Start();
 }
Example #30
0
        static void Main(string[] args)
        {
            try
            {
                _serviceHost = new ServiceHost(typeof(RGBLedService));

                // Returns a list of ipaddress configuration
                var ips = Dns.GetHostEntry(Dns.GetHostName());

                // Select the first entry. I hope it's this maschines IP
                var ipAddress = ips.AddressList.First(ipa => ipa.AddressFamily == AddressFamily.InterNetwork);

                _serviceHost.Opening += serviceHost_Opening;
                _serviceHost.Opened  += serviceHost_Opened;
                _serviceHost.Closed  += serviceHost_Closed;
                _serviceHost.Closing += serviceHost_Closing;
                _serviceHost.Open();
                Console.WriteLine("Your IP-Address: " + ipAddress);

                UnixSignal[] signals = new UnixSignal[] {
                    new UnixSignal(Signum.SIGINT),
                    new UnixSignal(Signum.SIGTERM),
                };

                // Wait for a unix signal
                var exit = false;
                while (!exit)
                {
                    var id = UnixSignal.WaitAny(signals);
                    if (id < 0 || id >= signals.Length)
                    {
                        continue;
                    }
                    if (signals[id].IsSet)
                    {
                        exit = true;
                    }
                }

                _serviceHost.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine("Press ENTER to end service");
                Console.ReadLine();
                return;
            }
        }