github.com/gogf/gkafka@v1.0.1-0.20190702070843-033a14468069/third/golang.org/x/sys/windows/svc/example/install.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  // +build windows
     6  
     7  package main
     8  
     9  import (
    10  	"fmt"
    11  	"os"
    12  	"path/filepath"
    13  
    14  	"github.com/gogf/gkafka/third/golang.org/x/sys/windows/svc/eventlog"
    15  	"github.com/gogf/gkafka/third/golang.org/x/sys/windows/svc/mgr"
    16  )
    17  
    18  func exePath() (string, error) {
    19  	prog := os.Args[0]
    20  	p, err := filepath.Abs(prog)
    21  	if err != nil {
    22  		return "", err
    23  	}
    24  	fi, err := os.Stat(p)
    25  	if err == nil {
    26  		if !fi.Mode().IsDir() {
    27  			return p, nil
    28  		}
    29  		err = fmt.Errorf("%s is directory", p)
    30  	}
    31  	if filepath.Ext(p) == "" {
    32  		p += ".exe"
    33  		fi, err := os.Stat(p)
    34  		if err == nil {
    35  			if !fi.Mode().IsDir() {
    36  				return p, nil
    37  			}
    38  			err = fmt.Errorf("%s is directory", p)
    39  		}
    40  	}
    41  	return "", err
    42  }
    43  
    44  func installService(name, desc string) error {
    45  	exepath, err := exePath()
    46  	if err != nil {
    47  		return err
    48  	}
    49  	m, err := mgr.Connect()
    50  	if err != nil {
    51  		return err
    52  	}
    53  	defer m.Disconnect()
    54  	s, err := m.OpenService(name)
    55  	if err == nil {
    56  		s.Close()
    57  		return fmt.Errorf("service %s already exists", name)
    58  	}
    59  	s, err = m.CreateService(name, exepath, mgr.Config{DisplayName: desc}, "is", "auto-started")
    60  	if err != nil {
    61  		return err
    62  	}
    63  	defer s.Close()
    64  	err = eventlog.InstallAsEventCreate(name, eventlog.Error|eventlog.Warning|eventlog.Info)
    65  	if err != nil {
    66  		s.Delete()
    67  		return fmt.Errorf("SetupEventLogSource() failed: %s", err)
    68  	}
    69  	return nil
    70  }
    71  
    72  func removeService(name string) error {
    73  	m, err := mgr.Connect()
    74  	if err != nil {
    75  		return err
    76  	}
    77  	defer m.Disconnect()
    78  	s, err := m.OpenService(name)
    79  	if err != nil {
    80  		return fmt.Errorf("service %s is not installed", name)
    81  	}
    82  	defer s.Close()
    83  	err = s.Delete()
    84  	if err != nil {
    85  		return err
    86  	}
    87  	err = eventlog.Remove(name)
    88  	if err != nil {
    89  		return fmt.Errorf("RemoveEventLogSource() failed: %s", err)
    90  	}
    91  	return nil
    92  }