service_windows.go 9.4 KB

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