summaryrefslogtreecommitdiff
path: root/pkg/helper/windows_install.go
diff options
context:
space:
mode:
Diffstat (limited to 'pkg/helper/windows_install.go')
-rw-r--r--pkg/helper/windows_install.go91
1 files changed, 91 insertions, 0 deletions
diff --git a/pkg/helper/windows_install.go b/pkg/helper/windows_install.go
new file mode 100644
index 0000000..6743e2a
--- /dev/null
+++ b/pkg/helper/windows_install.go
@@ -0,0 +1,91 @@
+// +build windows
+// Copyright 2012 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package helper
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+
+ "golang.org/x/sys/windows/svc/eventlog"
+ "golang.org/x/sys/windows/svc/mgr"
+)
+
+func exePath() (string, error) {
+ prog := os.Args[0]
+ p, err := filepath.Abs(prog)
+ if err != nil {
+ return "", err
+ }
+ fi, err := os.Stat(p)
+ if err == nil {
+ if !fi.Mode().IsDir() {
+ return p, nil
+ }
+ err = fmt.Errorf("%s is directory", p)
+ }
+ if filepath.Ext(p) == "" {
+ p += ".exe"
+ fi, err := os.Stat(p)
+ if err == nil {
+ if !fi.Mode().IsDir() {
+ return p, nil
+ }
+ err = fmt.Errorf("%s is directory", p)
+ }
+ }
+ return "", err
+}
+
+func installService(name, desc string) error {
+ exepath, err := exePath()
+ if err != nil {
+ return err
+ }
+ m, err := mgr.Connect()
+ if err != nil {
+ return err
+ }
+ defer m.Disconnect()
+ s, err := m.OpenService(name)
+ if err == nil {
+ s.Close()
+ return fmt.Errorf("service %s already exists", name)
+ }
+ s, err = m.CreateService(name, exepath, mgr.Config{DisplayName: desc}, "is", "auto-started")
+ if err != nil {
+ return err
+ }
+ defer s.Close()
+ err = eventlog.InstallAsEventCreate(name, eventlog.Error|eventlog.Warning|eventlog.Info)
+ if err != nil {
+ s.Delete()
+ return fmt.Errorf("SetupEventLogSource() failed: %s", err)
+ }
+ return nil
+}
+
+func removeService(name string) error {
+ m, err := mgr.Connect()
+ if err != nil {
+ return err
+ }
+ defer m.Disconnect()
+ s, err := m.OpenService(name)
+ if err != nil {
+ return fmt.Errorf("service %s is not installed", name)
+ }
+ defer s.Close()
+ err = s.Delete()
+ if err != nil {
+ return err
+ }
+ err = eventlog.Remove(name)
+ if err != nil {
+ return fmt.Errorf("RemoveEventLogSource() failed: %s", err)
+ }
+ return nil
+}