johnny
johnny

Reputation: 4154

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:

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...

Upvotes: 11

Views: 8856

Answers (3)

marchewek
marchewek

Reputation: 561

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...

Upvotes: 2

johnny
johnny

Reputation: 4154

Alright, finally implemented this. I've posted it as a separate answer as I had already come to this conclusion in the original update to my question, which was posted prior to the first answer.

Again, the StartService(), StopService() and RestartService() methods follow the conventions outlined in the examples and such already referenced in the question itself (i.e. they wrap Start/Stop behavior to avoid "already started/stopped"-type exceptions) with the addendum that if a Service is passed in (as is the case below), Refresh() is called on that service before checking its Status.

public static void RestartServiceWithDependents(ServiceController service, TimeSpan timeout)
{
    int tickCount1 = Environment.TickCount; // record when the task started

    // Get a list of all services that depend on this one (including nested
    //  dependencies)
    ServiceController[] dependentServices = service.DependentServices;

    // Restart the base service - will stop dependent services first
    RestartService(service, timeout);

    // Restore dependent services to their previous state - works because no
    //  Refresh() has taken place on this collection, so while the dependent
    //  services themselves may have been stopped in the meantime, their
    //  previous state is preserved in the collection.
    foreach (ServiceController dependentService in dependentServices)
    {
        // record when the previous task "ended"
        int tickCount2 = Environment.TickCount;
        // update remaining timeout
        timeout.Subtract(TimeSpan.FromMilliseconds(tickCount2 - tickCount1));
        // update task start time
        tickCount1 = tickCount2;
        switch (dependentService.Status)
        {
            case ServiceControllerStatus.Stopped:
            case ServiceControllerStatus.StopPending:
                // This Stop/StopPending section isn't really necessary in this
                //  case as it doesn't *do* anything, but it's included for
                //  completeness & to make the code easier to understand...
                break;
            case ServiceControllerStatus.Running:
            case ServiceControllerStatus.StartPending:
                StartService(dependentService, timeout);
                break;
            case ServiceControllerStatus.Paused:
            case ServiceControllerStatus.PausePending:
                StartService(dependentService, timeout);
                // I don't "wait" here for pause, but you can if you want to...
                dependentService.Pause();
                break;
        }
    }
}

Upvotes: 4

Orion Edwards
Orion Edwards

Reputation: 123622

It sounds like you want to restart a "base" service and have all the things that rely on it get restarted as well. If so, you can't just restart all the dependant services, because they may not have been running beforehand. There's no API for this that I'm aware of.

The way I'd do it is just write a recursive function to scan all the dependant services (and their dependancies), and add all the services which were running to a list in order.

When you restart the base service, you can then just run through this list and start everything. Provided you haven't re-sorted the list, the services should start in the right order, and all will be well.

Upvotes: 1

Related Questions