github.com/makyo/juju@v0.0.0-20160425123129-2608902037e9/cmd/service/service_handler.go (about)

     1  // Copyright 2015 Canonical Ltd.
     2  // Copyright 2015 Cloudbase Solutions
     3  // Licensed under the AGPLv3, see LICENCE file for details.
     4  //
     5  // +build windows
     6  
     7  package service
     8  
     9  import (
    10  	"github.com/gabriel-samfira/sys/windows/svc"
    11  )
    12  
    13  // SystemService type that is responsible for managing the life-cycle of the service
    14  type SystemService struct {
    15  	// Name the label for the service. It is not used for any useful operation
    16  	// by the service handler.
    17  	Name string
    18  	// Cmd is the function the service handler will run as a service.
    19  	Cmd func(args []string) int
    20  	// Args is passed to Cmd() as function arguments.
    21  	Args []string
    22  }
    23  
    24  // Execute implements the svc.Handler interface
    25  func (s *SystemService) Execute(args []string, changeReq <-chan svc.ChangeRequest, changes chan<- svc.Status) (bool, uint32) {
    26  	const cmdsAccepted = svc.AcceptStop | svc.AcceptShutdown
    27  	changes <- svc.Status{State: svc.StartPending}
    28  
    29  	errChannel := make(chan int, 1)
    30  
    31  	go func() {
    32  		err := s.Cmd(s.Args)
    33  		errChannel <- err
    34  	}()
    35  
    36  	changes <- svc.Status{State: svc.Running, Accepts: cmdsAccepted}
    37  
    38  	for {
    39  		select {
    40  		case r := <-changeReq:
    41  			switch r.Cmd {
    42  			case svc.Interrogate:
    43  				changes <- r.CurrentStatus
    44  			case svc.Stop, svc.Shutdown:
    45  				changes <- svc.Status{State: svc.StopPending}
    46  				return false, 0
    47  			}
    48  		case err := <-errChannel:
    49  			return false, uint32(err)
    50  		}
    51  	}
    52  }
    53  
    54  // Run runs the service
    55  func (s *SystemService) Run() error {
    56  	return svc.Run(s.Name, s)
    57  }