Пример #1
0
        /// <summary>
        /// Handles the UI timer events.
        /// </summary>
        /// <param name="state"></param>
        /// <param name="status"></param>
        private void OnUITimer(ServiceState state, string status)
        {
            bool enableStart    = false;
            bool enableStop     = false;
            bool enableShutdown = false;

            SetStatus(state.ToString());

            switch (state)
            {
            case ServiceState.Stopped:

                enableStart = true;
                SysLog.Flush();
                break;

            case ServiceState.Running:

                enableStop     = true;
                enableShutdown = true;
                break;

            case ServiceState.Shutdown:

                enableStop = true;
                break;
            }

            startButton.Enabled    = enableStart;
            stopButton.Enabled     = enableStop;
            shutDownButton.Enabled = enableShutdown;
            displayStatus.Text     = status;
        }
Пример #2
0
        void SetStatus()
        {
            if (ServiceManager.ServiceIsInstalled(serviceName))
            {
                ServiceState status = ServiceManager.GetServiceStatus(serviceName);

                if (status == ServiceState.Running)
                {
                    tbStatus.Text       = "Status: Running";
                    tbStatus.Background = green;
                }
                else
                {
                    tbStatus.Text       = $"Status: {status.ToString()}";
                    tbStatus.Background = green;
                }

                btnRemove.IsEnabled = true;
            }
            else
            {
                tbStatus.Text       = "Status: not installed";
                tbStatus.Background = red;
                btnRemove.IsEnabled = false;
            }
        }
Пример #3
0
        private void DisplayServiceStatus(ServiceState state)
        {
            rtbOutput.InvokeIfRequired(() =>
            {
                string sname = _theService.ServiceName;

                lbStatus.Text = string.Format("Service: '{0}' {1}...", sname, state.ToString());

                switch (state)
                {
                case ServiceState.Failed:
                case ServiceState.Stopped:
                case ServiceState.Paused:
                    btnStart.Enabled = true;
                    btnStop.Enabled  = false;
                    break;

                case ServiceState.Started:
                    btnStart.Enabled = false;
                    btnStop.Enabled  = true;
                    break;

                case ServiceState.Pausing:
                case ServiceState.Starting:
                case ServiceState.Stopping:
                    btnStart.Enabled = false;
                    btnStop.Enabled  = false;
                    break;
                }
            });
        }
Пример #4
0
        public static string[] GetInstalledServices()
        {
            string[]    rsl = new string[0];
            RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Wisp\Servers");

            if (key == null)
            {
                return(rsl);
            }
            string[] servers = key.GetSubKeyNames();
            rsl = new string[servers.Length];
            for (int i = 0; i < servers.Length; i++)
            {
                try
                {
                    string       server     = servers[i];
                    string       serverName = (string)Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Wisp\Servers\" + server, "ServiceName", "");
                    string       desc       = (string)Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Wisp\Servers\" + server, "Description", "");
                    ServiceState state      = ServiceInstaller.GetServiceStatus(serverName);
                    rsl[i] = serverName + "|" + state.ToString() + "|" + desc;
                }
                catch (Exception e)
                {
                    Log1.Logger("Service").Error("Failed to get installed Wisp service info. " + e.Message);
                }
            }

            return(rsl);
        }
Пример #5
0
 public static string CreateJson(ServiceState ss, States itemState)
 {
     return(JsonConvert.SerializeObject(
                new commandUpdateResultLog()
     {
         ServiceState = ss.ToString(),
         ItemState = itemState.ToString()
     }));
 }
Пример #6
0
        /// <summary>
        /// Perform actions based on current status and prediction.
        /// </summary>
        /// <param name="prediction"></param>
        private void DispatchPrediction(PredictionArgs prediction)
        {
            if (prediction == null)
            {
                Debug.WriteLine("DISPATCH: null prediction");
                // do nothing
                return;
            }

            lock (_lockStatus)
            {
                if (ServiceState == ServiceStateCode.Idle || ServiceState == ServiceStateCode.Training)
                {
                    Debug.WriteLine("DISPATCH: skip state " + ServiceState.ToString());
                    // do nothing
                    return;
                }

                // update prediction counter
                var previousCounter = ConsecutiveCorrectPredictions;
                var currentCounter  = (prediction.Success ? previousCounter + 1 : 0);
                ConsecutiveCorrectPredictions = currentCounter;

                if (
                    (previousCounter >= NotificationThreshold && currentCounter == 0) ||
                    (previousCounter < NotificationThreshold && currentCounter == NotificationThreshold))
                {
                    Debug.WriteLine("DISPATCH: prediction threshold passed");

                    // notify all subscribers about prediction
                    var contextId =
                        prediction.PredictedScenario == null
                        ? null : prediction.PredictedScenario.ContextId.ToString();
                    DoReportPrediction(contextId);
                }

                if (ServiceState == ServiceStateCode.Tracking)
                {
                    if (prediction.Success)
                    {
                        Debug.WriteLine("DISPATCH: success in tracking state.");
                        // no need to track
                        _tracker.Enabled = false;
                    }
                    else
                    {
                        Debug.WriteLine("DISPATCH: failure in tracking state.");
                        // training needed
                        _tracker.ScenarioId =
                            prediction.PredictedScenario == null
                            ? null : prediction.PredictedScenario.Id.ToString();
                        _tracker.Enabled = true;
                    }
                }
            }
        }
Пример #7
0
        /// <summary>
        /// Checks remote service state through WMI returns ServiceState
        /// </summary>
        /// <param name="svcName">string name of service</param>
        /// <returns>ServiceState.</returns>
        public ServiceState GetServiceState(string svcName)
        {
            ServiceState toReturn = ServiceState.Stopped;
            string       _state   = string.Empty;
            string       objPath  = string.Format("Win32_Service.Name='{0}'", svcName);

            using (ManagementObject service = new ManagementObject(ManScope, new ManagementPath(objPath), new ObjectGetOptions()))
            {
                try
                {
                    _state = service.Properties["State"].Value.ToString().Trim();
                    switch (_state)
                    {
                    case "Running":
                        toReturn = ServiceState.Running;
                        break;

                    case "Stopped":
                        toReturn = ServiceState.Stopped;
                        break;

                    case "Paused":
                        toReturn = ServiceState.Paused;
                        break;

                    case "Start Pending":
                        toReturn = ServiceState.StartPending;
                        break;

                    case "Stop Pending":
                        toReturn = ServiceState.StopPending;
                        break;

                    case "Continue Pending":
                        toReturn = ServiceState.ContinuePending;
                        break;

                    case "Pause Pending":
                        toReturn = ServiceState.PausePending;
                        break;
                    }

                    CDFMonitor.LogOutputHandler("ServiceState:" + toReturn.ToString());
                }
                catch (Exception ex)
                {
                    CDFMonitor.LogOutputHandler("GetServiceState:exception:" + ex.ToString());
                    return(ServiceState.Unknown);
                }
            }
            return(toReturn);
        }
Пример #8
0
        //---------------------------------------------------------------------------------------------
        //---------------------------------------------------------------------------------------------

        private void UpdateUserInterface()
        {
            toolStripStatusLabel1.Text = "Service State: " + _serviceState.ToString();

            switch (_serviceState)
            {
            case ServiceState.Stopped:
                buttonStart.Enabled = true;
                buttonPause.Enabled = false;
                buttonStop.Enabled  = false;
                break;

            case ServiceState.StartPending:
                buttonStart.Enabled = false;
                buttonPause.Enabled = false;
                buttonStop.Enabled  = false;
                break;

            case ServiceState.Running:
                buttonStart.Enabled = false;
                buttonPause.Enabled = true;
                buttonStop.Enabled  = true;
                break;

            case ServiceState.PausePending:
                buttonStart.Enabled = false;
                buttonPause.Enabled = false;
                buttonStop.Enabled  = false;
                break;

            case ServiceState.Paused:
                buttonStart.Enabled = true;
                buttonPause.Enabled = false;
                buttonStop.Enabled  = true;
                break;

            case ServiceState.ContinuePending:
                buttonStart.Enabled = false;
                buttonPause.Enabled = false;
                buttonStop.Enabled  = false;
                break;

            case ServiceState.StopPending:
                buttonStart.Enabled = false;
                buttonPause.Enabled = false;
                buttonStop.Enabled  = false;
                break;
            }

            Application.DoEvents();
        }
Пример #9
0
        private void showServiceState()
        {
            ServiceState state = ServiceInstaller.GetServiceStatus(MY_SERVICE);

            txtState.Text = state.ToString();

            if (ServiceInstaller.ServiceIsInstalled(MY_SERVICE))
            {
                btnInstall.Text = "Uninstall";
            }
            else
            {
                btnInstall.Text = "Install";
            }

            if (state == ServiceState.Running)
            {
                btnStart.Text = "Stop";
            }
            else
            {
                btnStart.Text = "Start";
            }
        }
        private static void LogTransition(string component, string requester, ServiceState state)
        {
            if (state != ServiceState.Active)
            {
                Globals.LogEvent(DirectoryEventLogConstants.Tuple_ServerComponentStateSetOffline, Environment.MachineName, new object[]
                {
                    component,
                    requester,
                    state.ToString()
                });
                return;
            }
            bool flag = false;
            List <ServerComponentStates.ItemEntry> list        = null;
            List <ServerComponentStates.ItemEntry> localStates = ServerComponentStates.GetLocalStates(null, ServerComponentStates.ServerWideOfflineComponentId);

            foreach (ServerComponentStates.ItemEntry itemEntry in localStates)
            {
                if (itemEntry.State != ServiceState.Active && !string.Equals(itemEntry.Requester, requester, StringComparison.OrdinalIgnoreCase))
                {
                    flag = true;
                    break;
                }
            }
            if (!flag && !string.Equals(component, ServerComponentStates.ServerWideOfflineComponentId, StringComparison.OrdinalIgnoreCase))
            {
                list = ServerComponentStates.GetLocalStates(null, component);
                foreach (ServerComponentStates.ItemEntry itemEntry2 in list)
                {
                    if (itemEntry2.State != ServiceState.Active && !string.Equals(itemEntry2.Requester, requester, StringComparison.OrdinalIgnoreCase))
                    {
                        flag = true;
                        break;
                    }
                }
            }
            if (!flag)
            {
                DateTime dateTime = DateTime.UtcNow;
                foreach (ServerComponentStates.ItemEntry itemEntry3 in localStates)
                {
                    if (itemEntry3.State != ServiceState.Active && itemEntry3.Timestamp < dateTime)
                    {
                        dateTime = itemEntry3.Timestamp;
                    }
                }
                if (list != null)
                {
                    foreach (ServerComponentStates.ItemEntry itemEntry4 in list)
                    {
                        if (itemEntry4.State != ServiceState.Active && itemEntry4.Timestamp < dateTime)
                        {
                            dateTime = itemEntry4.Timestamp;
                        }
                    }
                }
                Globals.LogEvent(DirectoryEventLogConstants.Tuple_ServerComponentStateSetOnline, Environment.MachineName, new object[]
                {
                    component,
                    requester,
                    dateTime
                });
            }
        }
Пример #11
0
        //
        // "Starting a Service" by "Microsoft Corporation" is licensed under MS-PL
        //
        // Title?   Starting a Service
        // Author?  Microsoft Corporation
        // Source?  https://msdn.microsoft.com/en-us/library/windows/desktop/ms686315%28v=vs.85%29.aspx
        // License? MS-PL - https://opensource.org/licenses/MS-PL
        //
        private bool WaitForServiceStatus(IntPtr service, ServiceState waitStatus, ServiceState desiredStatus)
        {
            ServiceStatus status = new ServiceStatus();

            NativeMethods.QueryServiceStatus(service, status);
            if (status.dwCurrentState == desiredStatus)
            {
                return(true);
            }

            int  dwStartTickCount = Environment.TickCount;
            long dwOldCheckPoint  = status.dwCheckPoint;

            while (status.dwCurrentState == waitStatus)
            {
                // Do not wait longer than the wait hint. A good interval is
                // one tenth the wait hint, but no less than 1 second and no
                // more than 10 seconds.

                int dwWaitTime = (int)status.dwWaitHint / 10;

                if (dwWaitTime < 1000)
                {
                    dwWaitTime = 1000;
                }
                else if (dwWaitTime > 10000)
                {
                    dwWaitTime = 10000;
                }

                //logger.Debug("dwWaitTime = " + dwWaitTime);

                Thread.Sleep(dwWaitTime);

                // Check the status again.

                if (NativeMethods.QueryServiceStatus(service, status) == 0)
                {
                    logger.Error(GetLastErrorMessage());
                    break;
                }

                if (status.dwCheckPoint > dwOldCheckPoint)
                {
                    // The service is making progress.
                    dwStartTickCount = Environment.TickCount;
                    dwOldCheckPoint  = status.dwCheckPoint;
                }
                else
                {
                    if (Environment.TickCount - dwStartTickCount > status.dwWaitHint)
                    {
                        // No progress made within the wait hint.
                        break;
                    }
                }
            }

            if (status.dwCurrentState != desiredStatus)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendFormat("Service not {0}\n", desiredStatus.ToString());
                sb.AppendFormat("  Current State: {0}\n", status.dwCurrentState);
                sb.AppendFormat("  Exit Code    : {0}\n", status.dwWin32ExitCode);
                sb.AppendFormat("  Check Point  : {0}\n", status.dwCheckPoint);
                sb.AppendFormat("  Wait Hint    : {0}\n", status.dwWaitHint);
                logger.Warn(sb.ToString());
            }

            return(status.dwCurrentState == desiredStatus);
        }
Пример #12
0
 public void State(ServiceState state, string expectedMessage)
 {
     Assert.Equal(expectedMessage, state.ToString());
 }
Пример #13
0
        public static bool InstallService(string path, string serviceName, string description)
        {
            if (!File.Exists(path))
            {
                Log1.Logger("Service").Error("Error finding " + serviceName + " executable. After installation it should be in " + path + ", but it's not.");
                return(false);
            }

            Log1.Logger("Service").Info("Checking for existing " + serviceName + " service.");
            ServiceState state    = ServiceInstaller.GetServiceStatus(serviceName);
            int          maxTries = 20;
            int          tries    = 0;

            try
            {
                do
                {
                    switch (state)
                    {
                    case ServiceState.NotFound:
                    case ServiceState.Unknown:
                        Log1.Logger("Service").Info("Now installed instance of " + serviceName + " service found.");
                        Log1.Logger("Service").Info("Installing " + serviceName + " service.");
                        ServiceInstaller.InstallAndStart(serviceName, serviceName, path);
                        Registry.SetValue(@"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\" + serviceName, "Description", description);

                        Registry.SetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Wisp\Servers\" + serviceName, "ServiceName", serviceName);
                        Registry.SetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Wisp\Servers\" + serviceName, "Description", description);

                        break;

                    case ServiceState.Running:
                        Log1.Logger("Service").Info("Stopping " + serviceName + " service...");
                        ServiceInstaller.StopService(serviceName);
                        break;

                    case ServiceState.Stopped:
                        Log1.Logger("Service").Info(serviceName + " service is stopped. Restarting...");
                        object val = Registry.GetValue(@"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\" + serviceName, "ImagePath", "");
                        if (val == null)
                        {
                            ServiceInstaller.Uninstall(serviceName);
                            break;
                        }
                        ServiceInstaller.InstallAndStart(serviceName, serviceName, path);

                        break;

                    default:
                        Log1.Logger("Service").Info(serviceName + " service is " + state.ToString() + ". Waiting...");
                        break;
                    }

                    Thread.Sleep(500);
                    state = ServiceInstaller.GetServiceStatus(serviceName);
                    tries++;
                } while (tries < maxTries && state != ServiceState.Running);

                if (state != ServiceState.Running)
                {
                    return(false);
                }
            }
            catch (Exception e)
            {
                Log1.Logger("Service").Error("Error installing " + serviceName + ". ", e);
                return(false);
            }

            return(true);
        }
Пример #14
0
        public static string UninstallService(string serviceName)
        {
            if (!IsWispService(serviceName))
            {
                return(serviceName + " does not appear to be a known Wisp service.  Can't uninstall it.");
            }

            Log1.Logger("Service").Info("Checking for existing " + serviceName + " service.");
            ServiceState state       = ServiceInstaller.GetServiceStatus(serviceName);
            int          maxTries    = 10;
            int          tries       = 0;
            bool         uninstalled = false;

            try
            {
                do
                {
                    switch (state)
                    {
                    case ServiceState.NotFound:
                    case ServiceState.Unknown:
                        Registry.LocalMachine.DeleteSubKeyTree((@"SOFTWARE\Wisp\Servers\" + serviceName));
                        return(serviceName + " is no longer installed on this machine.");

                    case ServiceState.Running:
                        Log1.Logger("Service").Info("Stopping " + serviceName + " service...");
                        ServiceInstaller.StopService(serviceName);
                        break;

                    case ServiceState.Stopped:
                        Log1.Logger("Service").Info(serviceName + " service is stopped.");
                        object val = Registry.GetValue(@"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\" + serviceName, "ImagePath", "");
                        if (val != null)
                        {
                            uninstalled = ServiceInstaller.Uninstall(serviceName);
                            break;
                        }
                        break;

                    default:
                        Log1.Logger("Service").Info(serviceName + " service is " + state.ToString() + ". Waiting...");
                        break;
                    }
                    Thread.Sleep(500);
                    state = ServiceInstaller.GetServiceStatus(serviceName);
                    tries++;
                } while (!uninstalled && (tries < maxTries && state != ServiceState.Unknown && state != ServiceState.NotFound));

                if (state == ServiceState.Unknown || state == ServiceState.NotFound || uninstalled)
                {
                    Registry.LocalMachine.DeleteSubKeyTree((@"SOFTWARE\Wisp\Servers\" + serviceName));
                }

                string deployPath = (string)Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Wisp\", "TargetDir", Environment.CurrentDirectory);
                if (deployPath == null || deployPath.Length < 1)
                {
                    return("Uninstalled service, but unable to delete directory.  Deploy path is not set in the registry.");
                }

                string serverRoot = Path.Combine(deployPath, "Server", serviceName);
                if (Directory.Exists(serverRoot))
                {
                    Directory.Delete(serverRoot, true);
                }
            }
            catch (Exception e)
            {
                Log1.Logger("Service").Error("Error uninstalling " + serviceName + ". ", e);
                return("Error uninstalling " + serviceName + ". " + e.Message);
            }

            return(serviceName + " service Uninstalled");
        }