install.go 1.8 KB

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