public void RunServer(HostControl hostControl)
        {
            hostController = hostControl;
            string appName = serverInfo.ServerExeName.Value.Substring(0, serverInfo.ServerExeName.Value.Length - 4);

            try
            {
                if (File.Exists(serverInfo.ServerPath.Value + "\\" + serverInfo.ServerExeName.Value))
                {
                    if (MonitoredAppExists(appName))
                    {
                        Process[] processList = Process.GetProcessesByName(appName);
                        if (processList.Length != 0)
                        {
                            InstanceProvider.GetServiceLogger().AppendLine($@"Application {appName} was found running! Killing to proceed.");
                            KillProcess(processList);
                        }
                    }
                    // Fires up a new process to run inside this one
                    CreateProcess();
                }
                else
                {
                    InstanceProvider.GetServiceLogger().AppendLine("The Bedrock Server is not accessible at " + serverInfo.ServerPath.Value + "\\" + serverInfo.ServerExeName.Value + "\r\nCheck if the file is at that location and that permissions are correct.");
                    hostControl.Stop();
                }
            }
            catch (Exception e)
            {
                InstanceProvider.GetServiceLogger().AppendLine($"Error Running Bedrock Server: {e.StackTrace}");
                hostControl.Stop();
            }
        }
        private void RunService()
        {
            try
            {
                var hasSecret = ConfigurationManager.AppSettings
                                .OfType <string>()
                                .Any(x => x.Equals("Secret"));

                if (!hasSecret || string.IsNullOrEmpty(ConfigurationManager.AppSettings["Secret"]))
                {
                    InitializeConfig(hasSecret);
                }

                var configDict = ConfigurationManager.AppSettings.AllKeys
                                 .ToDictionary(key => key, key => ConfigurationManager.AppSettings[key]);
                byte[] entropy = DecryptValue(configDict["Secret"], null);
                byte[] bytes   = DecryptValue(configDict["Password"], entropy);
                configDict["Password"] = Encoding.UTF8.GetString(bytes);
                var _sync = new Synchronizer(configDict);
                _monitor = new DirectoryMonitor(configDict["LocalDirectory"], _sync);
                _logger.Debug("Sync Service object init end");
                _monitor.StartMonitoring();
            } catch (CryptographicException ex)
            {
                _logger.Debug(ex);
                _logger.Error("Could not decrypt password. Clear the secret value and replace the password value in " +
                              "the config file in order to re-encrpyt password on next run.");
                _control.Stop();
            } catch (SessionException)
            {
                _logger.Error("Failed to initialize connection to remote host. Verify config information");
                _control.Stop();
            }
        }
        void HostControl.Stop()
        {
            if (_hostControl == null)
            {
                throw new InvalidOperationException("The HostControl reference has not been set, this is invalid");
            }

            _hostControl.Stop();
        }
Beispiel #4
0
        public bool Start(HostControl hostControl)
        {
            _log.Info("SampleService Starting...");

            hostControl.RequestAdditionalTime(TimeSpan.FromSeconds(10));

            Thread.Sleep(1000);

            if(_throwOnStart)
            {
                _log.Info("Throwing as requested");
                throw new InvalidOperationException("Throw on Start Requested");
            }

            ThreadPool.QueueUserWorkItem(x =>
                {
                    Thread.Sleep(3000);

                    if(_throwUnhandled)
                        throw new InvalidOperationException("Throw Unhandled In Random Thread");

                    _log.Info("Requesting stop");

                    hostControl.Stop();
                });
            _log.Info("SampleService Started");

            return true;
        }
Beispiel #5
0
 public bool Stop(HostControl hostControl)
 {
     Bootstrap.Stop();
     hostControl.Stop();
     _logger.Info("NameServer 服务停止成功");
     return(true);
 }
Beispiel #6
0
 public bool Stop(HostControl hostControl)
 {
     Service.Log = null;
     dirMap      = null;
     hostControl.Stop();
     return(true);
 }
Beispiel #7
0
        bool ServiceControl.Start(HostControl hostControl)
        {
            "Starting CodeSearch Indexer service".Info("Eventlog");
            "Starting service".Info();
            var sw = new Stopwatch();

            sw.Start();
            TheHostControl = hostControl;
            try
            {
                ConfigureExceptionHandling(hostControl);
                _cancellationTokenSource = new CancellationTokenSource();
                _updater       = new Indexer();
                _updaterThread = new Thread(() => _updater.Run(_cancellationTokenSource.Token))
                {
                    Name         = "UpdaterThread",
                    IsBackground = true,
                    Priority     = ThreadPriority.Normal
                };
                _updaterThread.Start();
            }
            catch (Exception e)
            {
                $"Exception {e.Message}".Info();
                TheHostControl?.Stop();
            }
            finally
            {
                sw.Stop();
                $"Exiting service start. Time elapsed: {sw.ElapsedMilliseconds}ms".Info();
                $"CodeSearch Indexer service start concluded, took {sw.ElapsedMilliseconds}ms".Info("Eventlog");
            }
            return(true);
        }
 /// <summary>
 /// Simulates the stop command being sent from the service host.
 /// </summary>
 public void Stop()
 {
     if (_serviceController != null)
     {
         _serviceController.Stop();
     }
 }
        public bool Start(HostControl hostControl)
        {
            _log.Info("SampleService Starting...");

            hostControl.RequestAdditionalTime(TimeSpan.FromSeconds(10));

            Thread.Sleep(1000);

            if (_throwOnStart)
            {
                _log.Info("Throwing as requested");
                throw new InvalidOperationException("Throw on Start Requested");
            }

            ThreadPool.QueueUserWorkItem(x =>
            {
                Thread.Sleep(3000);

                if (_throwUnhandled)
                {
                    throw new InvalidOperationException("Throw Unhandled In Random Thread");
                }

                _log.Info("Requesting stop");

                hostControl.Stop();
            });
            _log.Info("SampleService Started");

            return(true);
        }
 public bool Stop(HostControl hostControl)
 {
     _webServer.Dispose();
     _service.Join();
     hostControl.Stop();
     return(true);
 }
Beispiel #11
0
        public bool Start(HostControl hc)
        {
            //AddHostControlJob(hc);

            _logger.Info("Reading configuration");

            var connectionManagerDataSection = ConfigurationManager.GetSection(SchedulerTimeTableSection.SectionName) as SchedulerTimeTableSection;

            if (connectionManagerDataSection != null)
            {
                _logger.Info("{0} jobs have been read", connectionManagerDataSection.TimeTable.Count);

                _scheduler.Start();

                foreach (var item in connectionManagerDataSection.TimeTable)
                {
                    AddJob((SchedulerTimeTableItem)item);
                }

                _watcher.Start();

                _logger.Info("Scheduler service worker was started");

                return(true);
            }
            _logger.Error("Failed to read the job configuration, scheduler will be stopped");

            hc.Stop();

            return(true);
        }
Beispiel #12
0
        private void ProcessOnExited(object sender, EventArgs eventArgs)
        {
            // штатное завершение
            if (_osrmProcess.ExitCode == 0)
            {
                _logManager.MainLog.Info(Resource.ServiceRunner_ServiceNormalyTerminated);
                _hostControl?.Stop();
                return;
            }

            _logManager.MainLog.Error(Resource.ServiceRunner_ServiceCrashed);
            if (_serviceInfo.RestartAfterCrash)
            {
                if (_failsCount < _serviceInfo.RestartCountOnFail)
                {
                    _failsCount++;
                    _logManager.MainLog.Info(string.Format(Resource.ServiceRunner_TryingRestartMessageMask, _failsCount, _serviceInfo.RestartCountOnFail));
                    Stop();
                    Start();
                    _logManager.MainLog.Info(Resource.ServiceRunner_ServiceSuccessfullyRestarted);
                    return;
                }
            }
            _logManager.MainLog.Fatal(Resource.ServiceRunner_FailedToRestartService);
            throw new Exception(Resource.ServiceRunner_FailedToRestartService);
        }
 /// <summary>
 /// The Stop
 /// </summary>
 /// <param name="hostControl">The hostControl<see cref="HostControl"/></param>
 /// <returns>The <see cref="bool"/></returns>
 public bool Stop(HostControl hostControl)
 {
     _timer.Stop();
     _timer.Dispose();
     hostControl.Stop();
     return(true);
 }
        public bool Start(HostControl hostControl)
        {
            _hostControl = hostControl;

            if (_status != ServiceStatus.Stopped)
            {
                return(true);
            }
            try
            {
                _imageWatcherFactory.Create(out _imageWatcher, _imageWatcher_EndOfFileEventDetected);
                _imageWatcher.WatchDirectories(MonitoringPaths, ImageExtensions, NewPageTimeOut);

                _settingsExchanger.SubscribeToSettingsSender(GetCurrentServiceSettings, _statusQueueConfig);
                _settingsExchanger.SubscribeToSettingsReceiver(OnReceiveNewSettings, _controlQueueConfig);
            }
            catch
            {
                //log
                hostControl.Stop();
                return(true);
            }

            _status = ServiceStatus.Waiting;

            return(true);
        }
Beispiel #15
0
 public bool Stop(HostControl hostControl)
 {
     Bootstrap.Stop();
     hostControl.Stop();
     _logger.Info("CommandService 服务停止成功");
     return(true);
 }
Beispiel #16
0
 public bool Shutdown(HostControl hostControl)
 {
     Logger.Debug("BackendRootService is shutting down...");
     Logger.Debug("BackendRootService stops.");
     //Stop the root service
     hostControl.Stop();
     return(true);
 }
Beispiel #17
0
 void ThreadFault(Exception e, int errorCount, HostControl hc)
 {
     if (errorCount > 5 || ++threadsErrorCount > 5)
     {
         Log.ErrorException($"too many errors:{errorCount} or threadErrors:{threadsErrorCount}, service is going to be stopped", e);
         hc.Stop(TopshelfExitCode.AbnormalExit);
     }
 }
Beispiel #18
0
        //
        // Restart
        //

        public void Restart(string reason)
        {
            Restarted = true;

            Log.Info("[runtime] Restarting in 8s: {Reason:l}", reason);

            Task.Delay(TimeSpan.FromSeconds(8)).ContinueWith(_ => _hostControl.Stop());
        }
 public int Stop()
 {
     if (_control == null)
     {
         return(-1);
     }
     _control.Stop();
     return(0);
 }
Beispiel #20
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="hostControl"></param>
        /// <returns></returns>
        public override bool Stop(HostControl hostControl)
        {
            // Set the flag to signal to the queue to stop processing.
            IsRunning = false;

            hostControl.Stop();

            //
            return(true);
        }
Beispiel #21
0
 public bool Stop(HostControl hostControl)
 {
     try
     {
         hostControl.Stop();
     }
     finally
     {
         _timer.Stop();
     }
     return(true);
 }
        private async void Login()
        {
            LoginInfo loginInfo = new LoginInfo();

            string json = JsonConvert.SerializeObject(loginInfo);

            var data = new StringContent(json, Encoding.UTF8, "application/json");

            var url      = "url";
            var response = await client.PostAsync(url, data);

            hostControl.Stop();
        }
Beispiel #23
0
 public Boolean Start(HostControl hostControl)
 {
     try
     {
         return(StartMonitor());
     }
     catch (Exception ex)
     {
         _logger.ErrorFormat(ex, "Exception during startup: " + ex.Message);
         hostControl.Stop();
         return(false);
     }
 }
        public bool Start(HostControl hostControl)
        {
            if (ActiveRolesClient == null)
            {
                if (!InitActiveRolesClient())
                {
                    Log.Fatal("Failed to create ActiveRolesClient");
                    return(false);
                }
            }

            if (SafeguardClient == null)
            {
                if (!InitSafeguardClient())
                {
                    Log.Fatal("Failed to create SafeguardClient");
                    return(false);
                }
            }

            if (IsTest)
            {
                Log.Info("Test mode enabled.  Stopping service before listening.");
                hostControl.Stop();
                return(true);
            }

            // Start listener
            try
            {
                if (Listener == null)
                {
                    Listener = SafeguardClient.GetEventListener();
                }
                foreach (var e in Events)
                {
                    Listener.RegisterEventHandler(e.name, HandleAccessRequestEvent);
                }
                Listener.Start();

                Log.Info("Service Started");
                return(true);
            }
            catch (Exception e)
            {
                Log.Fatal(e.Message);
            }

            return(false);
        }
Beispiel #25
0
 /// <summary>
 /// Force service to end - testing purposes
 /// </summary>
 private void ForceCrash()
 {
     // 50/50 chance to exit abnormally or throw exception
     if (new Random().Next(2) % 2 == 0)
     {
         _log.Debug($"[{Environment.CurrentManagedThreadId}] Abnormal Exit");
         _hostControl.Stop(TopshelfExitCode.AbnormalExit);
     }
     else
     {
         _log.Debug($"[{Environment.CurrentManagedThreadId}] Stop Exception Thrown");
         throw new Exception("Stop Exception");
     }
 }
Beispiel #26
0
 public bool Stop(HostControl hostControl)
 {
     try
     {
         Bootstrap.Stop();
         hostControl.Stop();
         _logger.Info("BrokerServer 服务停止成功");
         return(true);
     }
     catch (Exception e)
     {
         _logger.Error(e.Message);
         return(true);
     }
 }
Beispiel #27
0
        void TerminateHandler(object obj)
        {
            HostControl hc = obj as HostControl;

            log.Debug("Initializing Handler for SIGINT");
            UnixSignal signal = new UnixSignal(Signum.SIGINT);

            if (signal.WaitOne())
            {
                log.Debug("Control-C Pressed!");
            }
            log.Debug("handler Terminated");

            hc.Stop();
        }
Beispiel #28
0
        public InteractiveModule(HostControl hostControl)
        {
            StaticConfiguration.DisableErrorTraces = false;

            Get["/version"] = _ =>
            {
                var updateManager = new UpdateManager(null);
                return Response.AsJson(updateManager.CurrentlyInstalledVersion()?.ToString());
            };

            Post["/stop"] = _ =>
            {
                Task.Run(() => hostControl.Stop());
                return HttpStatusCode.OK;
            };
        }
        public InteractiveModule(HostControl hostControl)
        {
            StaticConfiguration.DisableErrorTraces = false;

            Get["/version"] = _ =>
            {
                var updateManager = new UpdateManager(null);
                return(Response.AsJson(updateManager.CurrentlyInstalledVersion()?.ToString()));
            };

            Post["/stop"] = _ =>
            {
                Task.Run(() => hostControl.Stop());
                return(HttpStatusCode.OK);
            };
        }
        private void ControlService(ServiceControllerStatus newStatus)
        {
            switch (newStatus)
            {
            case ServiceControllerStatus.Paused:
                Stop();
                break;

            case ServiceControllerStatus.Stopped:
                _hostControl.Stop();
                break;

            case ServiceControllerStatus.Running:     //this is impossible in this case xD
                break;
            }
        }
Beispiel #31
0
        private void ClusterNeedsToRestart(string message)
        {
            Cluster.Leave(Cluster.SelfAddress);

            // Common EventId to cause external resource to trigger a restart on this service.
            var errorMessage = "EventId:5 " + message;

            _logger.Error(errorMessage);

            // Give enough time for messages to get sent to other members that we have left the cluster.
            Thread.Sleep(5000);


            if (_hostControl != null)
            {
                _hostControl.Stop();
            }
        }
        public bool Start(HostControl hostControl)
        {
            Console.WriteLine("I exhibit bad behavior, but I started on command.");

            ThreadPool.QueueUserWorkItem(x =>
            {
                Thread.Sleep(5000);

                _log.Info("Stopping for no particular reason");

                hostControl.Stop();

                //                _log.Info("Dying an ungraceful death");
                //
                //                throw new InvalidOperationException("Oh, what a world.");
            });

            return(true);
        }
        public bool Start(HostControl hostControl)
        {
            Console.WriteLine("I exhibit bad behavior, but I started on command.");

            ThreadPool.QueueUserWorkItem(x =>
            {
                Thread.Sleep(5000);

                _log.Info("Stopping for no particular reason");

                hostControl.Stop();

                //                _log.Info("Dying an ungraceful death");
                //
                //                throw new InvalidOperationException("Oh, what a world.");
            });

            return true;
        }
Beispiel #34
0
        public bool Start(HostControl hostControl)
        {
            _log.Info("SampleService Starting...");

            hostControl.RequestAdditionalTime(TimeSpan.FromSeconds(10));

            Thread.Sleep(1000);

            ThreadPool.QueueUserWorkItem(x =>
                {
                    Thread.Sleep(3000);

                    _log.Info("Requesting stop");

                    hostControl.Stop();
                });
            _log.Info("SampleService Started");

            return true;
        }
Beispiel #35
0
 private static void StopServiceForUpdating(HostControl control)
 {
     control.Stop();
 }