github.com/cellofellow/gopkg@v0.0.0-20140722061823-eec0544a62ad/osext/winsvc/mgr/service.go (about)

     1  // Copyright 2012 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package mgr
     6  
     7  import (
     8  	"chai2010.gopkg/osext/winsvc/svc"
     9  	"chai2010.gopkg/osext/winsvc/winapi"
    10  	"syscall"
    11  )
    12  
    13  // TODO(brainman): use EnumDependentServices to enumerate dependent services
    14  
    15  // TODO(brainman): use EnumServicesStatus to enumerates services
    16  //                 in the specified service control manager database
    17  
    18  // Service is used to access Windows service.
    19  type Service struct {
    20  	Name   string
    21  	Handle syscall.Handle
    22  }
    23  
    24  // Delete marks service s for deletion from the service control manager database.
    25  func (s *Service) Delete() error {
    26  	return winapi.DeleteService(s.Handle)
    27  }
    28  
    29  // Close relinquish access to service s.
    30  func (s *Service) Close() error {
    31  	return winapi.CloseServiceHandle(s.Handle)
    32  }
    33  
    34  // Start starts service s.
    35  func (s *Service) Start(args []string) error {
    36  	var p **uint16
    37  	if len(args) > 0 {
    38  		vs := make([]*uint16, len(args))
    39  		for i, _ := range vs {
    40  			vs[i] = syscall.StringToUTF16Ptr(args[i])
    41  		}
    42  		p = &vs[0]
    43  	}
    44  	return winapi.StartService(s.Handle, uint32(len(args)), p)
    45  }
    46  
    47  // Control sends state change request c to servce s.
    48  func (s *Service) Control(c svc.Cmd) (svc.Status, error) {
    49  	var t winapi.SERVICE_STATUS
    50  	err := winapi.ControlService(s.Handle, uint32(c), &t)
    51  	if err != nil {
    52  		return svc.Status{}, err
    53  	}
    54  	return svc.Status{
    55  		State:   svc.State(t.CurrentState),
    56  		Accepts: svc.Accepted(t.ControlsAccepted),
    57  	}, nil
    58  }
    59  
    60  // Query returns current status of service s.
    61  func (s *Service) Query() (svc.Status, error) {
    62  	var t winapi.SERVICE_STATUS
    63  	err := winapi.QueryServiceStatus(s.Handle, &t)
    64  	if err != nil {
    65  		return svc.Status{}, err
    66  	}
    67  	return svc.Status{
    68  		State:   svc.State(t.CurrentState),
    69  		Accepts: svc.Accepted(t.ControlsAccepted),
    70  	}, nil
    71  }