service_windows.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. package main
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "io/ioutil"
  7. "log"
  8. "os"
  9. "os/exec"
  10. "path/filepath"
  11. "time"
  12. "unsafe"
  13. "github.com/docker/docker/pkg/system"
  14. "github.com/sirupsen/logrus"
  15. "github.com/spf13/pflag"
  16. "golang.org/x/sys/windows"
  17. "golang.org/x/sys/windows/svc"
  18. "golang.org/x/sys/windows/svc/debug"
  19. "golang.org/x/sys/windows/svc/eventlog"
  20. "golang.org/x/sys/windows/svc/mgr"
  21. )
  22. var (
  23. flServiceName *string
  24. flRegisterService *bool
  25. flUnregisterService *bool
  26. flRunService *bool
  27. setStdHandle = windows.NewLazySystemDLL("kernel32.dll").NewProc("SetStdHandle")
  28. oldStderr windows.Handle
  29. panicFile *os.File
  30. service *handler
  31. )
  32. const (
  33. // These should match the values in event_messages.mc.
  34. eventInfo = 1
  35. eventWarn = 1
  36. eventError = 1
  37. eventDebug = 2
  38. eventPanic = 3
  39. eventFatal = 4
  40. eventExtraOffset = 10 // Add this to any event to get a string that supports extended data
  41. )
  42. func installServiceFlags(flags *pflag.FlagSet) {
  43. flServiceName = flags.String("service-name", "docker", "Set the Windows service name")
  44. flRegisterService = flags.Bool("register-service", false, "Register the service and exit")
  45. flUnregisterService = flags.Bool("unregister-service", false, "Unregister the service and exit")
  46. flRunService = flags.Bool("run-service", false, "")
  47. flags.MarkHidden("run-service")
  48. }
  49. type handler struct {
  50. tosvc chan bool
  51. fromsvc chan error
  52. daemonCli *DaemonCli
  53. }
  54. type etwHook struct {
  55. log *eventlog.Log
  56. }
  57. func (h *etwHook) Levels() []logrus.Level {
  58. return []logrus.Level{
  59. logrus.PanicLevel,
  60. logrus.FatalLevel,
  61. logrus.ErrorLevel,
  62. logrus.WarnLevel,
  63. logrus.InfoLevel,
  64. logrus.DebugLevel,
  65. }
  66. }
  67. func (h *etwHook) Fire(e *logrus.Entry) error {
  68. var (
  69. etype uint16
  70. eid uint32
  71. )
  72. switch e.Level {
  73. case logrus.PanicLevel:
  74. etype = windows.EVENTLOG_ERROR_TYPE
  75. eid = eventPanic
  76. case logrus.FatalLevel:
  77. etype = windows.EVENTLOG_ERROR_TYPE
  78. eid = eventFatal
  79. case logrus.ErrorLevel:
  80. etype = windows.EVENTLOG_ERROR_TYPE
  81. eid = eventError
  82. case logrus.WarnLevel:
  83. etype = windows.EVENTLOG_WARNING_TYPE
  84. eid = eventWarn
  85. case logrus.InfoLevel:
  86. etype = windows.EVENTLOG_INFORMATION_TYPE
  87. eid = eventInfo
  88. case logrus.DebugLevel:
  89. etype = windows.EVENTLOG_INFORMATION_TYPE
  90. eid = eventDebug
  91. default:
  92. return errors.New("unknown level")
  93. }
  94. // If there is additional data, include it as a second string.
  95. exts := ""
  96. if len(e.Data) > 0 {
  97. fs := bytes.Buffer{}
  98. for k, v := range e.Data {
  99. fs.WriteString(k)
  100. fs.WriteByte('=')
  101. fmt.Fprint(&fs, v)
  102. fs.WriteByte(' ')
  103. }
  104. exts = fs.String()[:fs.Len()-1]
  105. eid += eventExtraOffset
  106. }
  107. if h.log == nil {
  108. fmt.Fprintf(os.Stderr, "%s [%s]\n", e.Message, exts)
  109. return nil
  110. }
  111. var (
  112. ss [2]*uint16
  113. err error
  114. )
  115. ss[0], err = windows.UTF16PtrFromString(e.Message)
  116. if err != nil {
  117. return err
  118. }
  119. count := uint16(1)
  120. if exts != "" {
  121. ss[1], err = windows.UTF16PtrFromString(exts)
  122. if err != nil {
  123. return err
  124. }
  125. count++
  126. }
  127. return windows.ReportEvent(h.log.Handle, etype, 0, eid, 0, count, 0, &ss[0], nil)
  128. }
  129. func getServicePath() (string, error) {
  130. p, err := exec.LookPath(os.Args[0])
  131. if err != nil {
  132. return "", err
  133. }
  134. return filepath.Abs(p)
  135. }
  136. func registerService() error {
  137. p, err := getServicePath()
  138. if err != nil {
  139. return err
  140. }
  141. m, err := mgr.Connect()
  142. if err != nil {
  143. return err
  144. }
  145. defer m.Disconnect()
  146. depends := []string{}
  147. // This dependency is required on build 14393 (RS1)
  148. // it is added to the platform in newer builds
  149. if system.GetOSVersion().Build == 14393 {
  150. depends = append(depends, "ConDrv")
  151. }
  152. c := mgr.Config{
  153. ServiceType: windows.SERVICE_WIN32_OWN_PROCESS,
  154. StartType: mgr.StartAutomatic,
  155. ErrorControl: mgr.ErrorNormal,
  156. Dependencies: depends,
  157. DisplayName: "Docker Engine",
  158. }
  159. // Configure the service to launch with the arguments that were just passed.
  160. args := []string{"--run-service"}
  161. for _, a := range os.Args[1:] {
  162. if a != "--register-service" && a != "--unregister-service" {
  163. args = append(args, a)
  164. }
  165. }
  166. s, err := m.CreateService(*flServiceName, p, c, args...)
  167. if err != nil {
  168. return err
  169. }
  170. defer s.Close()
  171. // See http://stackoverflow.com/questions/35151052/how-do-i-configure-failure-actions-of-a-windows-service-written-in-go
  172. const (
  173. scActionNone = 0
  174. scActionRestart = 1
  175. scActionReboot = 2
  176. scActionRunCommand = 3
  177. serviceConfigFailureActions = 2
  178. )
  179. type serviceFailureActions struct {
  180. ResetPeriod uint32
  181. RebootMsg *uint16
  182. Command *uint16
  183. ActionsCount uint32
  184. Actions uintptr
  185. }
  186. type scAction struct {
  187. Type uint32
  188. Delay uint32
  189. }
  190. t := []scAction{
  191. {Type: scActionRestart, Delay: uint32(60 * time.Second / time.Millisecond)},
  192. {Type: scActionRestart, Delay: uint32(60 * time.Second / time.Millisecond)},
  193. {Type: scActionNone},
  194. }
  195. lpInfo := serviceFailureActions{ResetPeriod: uint32(24 * time.Hour / time.Second), ActionsCount: uint32(3), Actions: uintptr(unsafe.Pointer(&t[0]))}
  196. err = windows.ChangeServiceConfig2(s.Handle, serviceConfigFailureActions, (*byte)(unsafe.Pointer(&lpInfo)))
  197. if err != nil {
  198. return err
  199. }
  200. return eventlog.Install(*flServiceName, p, false, eventlog.Info|eventlog.Warning|eventlog.Error)
  201. }
  202. func unregisterService() error {
  203. m, err := mgr.Connect()
  204. if err != nil {
  205. return err
  206. }
  207. defer m.Disconnect()
  208. s, err := m.OpenService(*flServiceName)
  209. if err != nil {
  210. return err
  211. }
  212. defer s.Close()
  213. eventlog.Remove(*flServiceName)
  214. err = s.Delete()
  215. if err != nil {
  216. return err
  217. }
  218. return nil
  219. }
  220. // initService is the entry point for running the daemon as a Windows
  221. // service. It returns an indication to stop (if registering/un-registering);
  222. // an indication of whether it is running as a service; and an error.
  223. func initService(daemonCli *DaemonCli) (bool, bool, error) {
  224. if *flUnregisterService {
  225. if *flRegisterService {
  226. return true, false, errors.New("--register-service and --unregister-service cannot be used together")
  227. }
  228. return true, false, unregisterService()
  229. }
  230. if *flRegisterService {
  231. return true, false, registerService()
  232. }
  233. if !*flRunService {
  234. return false, false, nil
  235. }
  236. interactive, err := svc.IsAnInteractiveSession()
  237. if err != nil {
  238. return false, false, err
  239. }
  240. h := &handler{
  241. tosvc: make(chan bool),
  242. fromsvc: make(chan error),
  243. daemonCli: daemonCli,
  244. }
  245. var log *eventlog.Log
  246. if !interactive {
  247. log, err = eventlog.Open(*flServiceName)
  248. if err != nil {
  249. return false, false, err
  250. }
  251. }
  252. logrus.AddHook(&etwHook{log})
  253. logrus.SetOutput(ioutil.Discard)
  254. service = h
  255. go func() {
  256. if interactive {
  257. err = debug.Run(*flServiceName, h)
  258. } else {
  259. err = svc.Run(*flServiceName, h)
  260. }
  261. h.fromsvc <- err
  262. }()
  263. // Wait for the first signal from the service handler.
  264. err = <-h.fromsvc
  265. if err != nil {
  266. return false, false, err
  267. }
  268. return false, true, nil
  269. }
  270. func (h *handler) started() error {
  271. // This must be delayed until daemonCli initializes Config.Root
  272. err := initPanicFile(filepath.Join(h.daemonCli.Config.Root, "panic.log"))
  273. if err != nil {
  274. return err
  275. }
  276. h.tosvc <- false
  277. return nil
  278. }
  279. func (h *handler) stopped(err error) {
  280. logrus.Debugf("Stopping service: %v", err)
  281. h.tosvc <- err != nil
  282. <-h.fromsvc
  283. }
  284. func (h *handler) Execute(_ []string, r <-chan svc.ChangeRequest, s chan<- svc.Status) (bool, uint32) {
  285. s <- svc.Status{State: svc.StartPending, Accepts: 0}
  286. // Unblock initService()
  287. h.fromsvc <- nil
  288. // Wait for initialization to complete.
  289. failed := <-h.tosvc
  290. if failed {
  291. logrus.Debug("Aborting service start due to failure during initialization")
  292. return true, 1
  293. }
  294. s <- svc.Status{State: svc.Running, Accepts: svc.AcceptStop | svc.AcceptShutdown | svc.Accepted(windows.SERVICE_ACCEPT_PARAMCHANGE)}
  295. logrus.Debug("Service running")
  296. Loop:
  297. for {
  298. select {
  299. case failed = <-h.tosvc:
  300. break Loop
  301. case c := <-r:
  302. switch c.Cmd {
  303. case svc.Cmd(windows.SERVICE_CONTROL_PARAMCHANGE):
  304. h.daemonCli.reloadConfig()
  305. case svc.Interrogate:
  306. s <- c.CurrentStatus
  307. case svc.Stop, svc.Shutdown:
  308. s <- svc.Status{State: svc.StopPending, Accepts: 0}
  309. h.daemonCli.stop()
  310. }
  311. }
  312. }
  313. removePanicFile()
  314. if failed {
  315. return true, 1
  316. }
  317. return false, 0
  318. }
  319. func initPanicFile(path string) error {
  320. var err error
  321. panicFile, err = os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0)
  322. if err != nil {
  323. return err
  324. }
  325. st, err := panicFile.Stat()
  326. if err != nil {
  327. return err
  328. }
  329. // If there are contents in the file already, move the file out of the way
  330. // and replace it.
  331. if st.Size() > 0 {
  332. panicFile.Close()
  333. os.Rename(path, path+".old")
  334. panicFile, err = os.Create(path)
  335. if err != nil {
  336. return err
  337. }
  338. }
  339. // Update STD_ERROR_HANDLE to point to the panic file so that Go writes to
  340. // it when it panics. Remember the old stderr to restore it before removing
  341. // the panic file.
  342. sh := windows.STD_ERROR_HANDLE
  343. h, err := windows.GetStdHandle(uint32(sh))
  344. if err != nil {
  345. return err
  346. }
  347. oldStderr = h
  348. r, _, err := setStdHandle.Call(uintptr(sh), uintptr(panicFile.Fd()))
  349. if r == 0 && err != nil {
  350. return err
  351. }
  352. // Reset os.Stderr to the panic file (so fmt.Fprintf(os.Stderr,...) actually gets redirected)
  353. os.Stderr = os.NewFile(uintptr(panicFile.Fd()), "/dev/stderr")
  354. // Force threads that panic to write to stderr (the panicFile handle now), otherwise it will go into the ether
  355. log.SetOutput(os.Stderr)
  356. return nil
  357. }
  358. func removePanicFile() {
  359. if st, err := panicFile.Stat(); err == nil {
  360. if st.Size() == 0 {
  361. sh := windows.STD_ERROR_HANDLE
  362. setStdHandle.Call(uintptr(sh), uintptr(oldStderr))
  363. panicFile.Close()
  364. os.Remove(panicFile.Name())
  365. }
  366. }
  367. }