Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restart a service with dependent services?

Starting with a csharp-example and duly noting related SO questions ( Restart a windows services from C# and Cannot restart a Service) and various other questions relating to restarting just one service, I'm wondering what the best method is for restarting a service with dependent services (e.g. Message Queuing, on which Message Queuing Triggers depends, or IIS, on which FTP Publishing and World Wide Web Publishing depend). The mmc snap-in does this automagically, but the code doesn't seem to provide the same functionality (at least not as easily).

MSDN documentation for Stop says "If any services depend on this service for their operation, they will be stopped before this service is stopped. The DependentServices property contains the set of services that depend on this one," and DependentServices returns an array of services. Assuming StartService() and StopService() follow the conventions outlined in the examples and such referenced above (except that they accept ServiceControllers and TimeSpans directly), I started with:

public static void RestartServiceWithDependents(ServiceController service, TimeSpan timeout)
{
    ServiceController[] dependentServices = service.DependentServices;

    RestartService(service, timeout); // will stop dependent services, see note below* about timeout...

    foreach (ServiceController dependentService in dependentServices)
    {
        StartService(dependentService, timeout);
    }
}

But what if the service dependencies are nested (recursive) or cyclical (if that's even possible...) - if Service A is depended on by Service B1 and Service B2 and Service C1 depends on Service B1, it seems 'restarting' Service A by this method would stop Service C1 but wouldn't restart it...

To make this example picture clearer, I'll follow the model in the services mmc snap-in:

The following system components depend on [Service A]:
  - Service B1
    - Service C1
  - Service B2

Is there a better way to go about this, or would it just have to recursively step into and stop each dependent service and then restart them all after it restarts the main service?

Additionally, will dependent but currently stopped services be listed under DependentServices? If so, wouldn't this restart them anyways? If so, should we control that as well? This just seems to get messier and messier...

*Note: I realize the timeout isn't being applied completely correctly here (overall timeout could be many many times longer than expected), but for now that's not the issue I'm concerned about - if you want to fix it, fine, but don't just say 'timeout's broken...'

Update: After some preliminary testing, I've discovered (/confirmed) the following behaviors:

  • Stopping a service (e.g. Service A) that other services (e.g. Service B1) depend on will stop the other services (including "nested" dependencies such as Service C1)
  • DependentServices does include dependent services in all states (Running, Stopped, etc.), and it also includes nested dependencies, i.e. Service_A.DependentServices would contain {Service B1, Service C1, Service B2} (in that order, as C1 depends on B1).
  • Starting a service that depends on others (e.g. Service B1 depends on Service A) will also start the requisite services.

The code above can therefore be simplified (at least in part) to just stop the main service (which will stop all dependent services) and then restarting the most-dependent services (e.g. Service C1 and Service B2) (or just restarting "all" the dependent services - it will skip the ones already started), but that really just defers the starting of the main service momentarily until one of the dependencies complain about it, so that doesn't really help.

Looks for now like just restarting all the dependencies is the simplest way, but that ignores (for now) managing services that are already stopped and such...

like image 211
johnny Avatar asked Oct 03 '11 18:10

johnny


1 Answers

Please notice that ServiceController.Stop() stops 'dependent' services and ServiceController.Start() starts 'dependent on' services - thus after stopping the service you'll only need to start services that are dependency tree's leaves.

Assuming no cyclic dependencies are allowed, the following code gets services that need to be started:

    private static void FillDependencyTreeLeaves(ServiceController controller, List<ServiceController> controllers)
    {
        bool dependencyAdded = false;
        foreach (ServiceController dependency in controller.DependentServices)
        {
            ServiceControllerStatus status = dependency.Status;
            // add only those that are actually running
            if (status != ServiceControllerStatus.Stopped && status != ServiceControllerStatus.StopPending)
            {
                dependencyAdded = true;
                FillDependencyTreeLeaves(dependency, controllers);
            }
        }
        // if no dependency has been added, the service is dependency tree's leaf
        if (!dependencyAdded && !controllers.Contains(controller))
        {
            controllers.Add(controller);
        }
    }

And with a simple method (e.g. extension method):

    public static void Restart(this ServiceController controller)
    {
        List<ServiceController> dependencies = new List<ServiceController>();
        FillDependencyTreeLeaves(controller, dependencies);
        controller.Stop();
        controller.WaitForStatus(ServiceControllerStatus.Stopped);
        foreach (ServiceController dependency in dependencies)
        {
            dependency.Start();
            dependency.WaitForStatus(ServiceControllerStatus.Running);
        }
    }

You can simply restart a service:

    using (ServiceController controller = new ServiceController("winmgmt"))
    {
        controller.Restart();
    }

Points of interest:

For code clearity I didn't add:

  • timeouts
  • error-checking

Please notice, that the application may end up in a strange state, when some services are restarted and some are not...

like image 183
marchewek Avatar answered Sep 16 '22 23:09

marchewek