daemon.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. // +build daemon
  2. package main
  3. import (
  4. "fmt"
  5. "io"
  6. "os"
  7. "path/filepath"
  8. "time"
  9. "github.com/Sirupsen/logrus"
  10. apiserver "github.com/docker/docker/api/server"
  11. "github.com/docker/docker/autogen/dockerversion"
  12. "github.com/docker/docker/daemon"
  13. _ "github.com/docker/docker/daemon/execdriver/lxc"
  14. _ "github.com/docker/docker/daemon/execdriver/native"
  15. "github.com/docker/docker/pkg/homedir"
  16. flag "github.com/docker/docker/pkg/mflag"
  17. "github.com/docker/docker/pkg/pidfile"
  18. "github.com/docker/docker/pkg/signal"
  19. "github.com/docker/docker/pkg/system"
  20. "github.com/docker/docker/pkg/timeutils"
  21. "github.com/docker/docker/registry"
  22. )
  23. const CanDaemon = true
  24. var (
  25. daemonCfg = &daemon.Config{}
  26. registryCfg = &registry.Options{}
  27. )
  28. func init() {
  29. daemonCfg.InstallFlags()
  30. registryCfg.InstallFlags()
  31. }
  32. func migrateKey() (err error) {
  33. // Migrate trust key if exists at ~/.docker/key.json and owned by current user
  34. oldPath := filepath.Join(homedir.Get(), ".docker", defaultTrustKeyFile)
  35. newPath := filepath.Join(getDaemonConfDir(), defaultTrustKeyFile)
  36. if _, statErr := os.Stat(newPath); os.IsNotExist(statErr) && currentUserIsOwner(oldPath) {
  37. defer func() {
  38. // Ensure old path is removed if no error occurred
  39. if err == nil {
  40. err = os.Remove(oldPath)
  41. } else {
  42. logrus.Warnf("Key migration failed, key file not removed at %s", oldPath)
  43. }
  44. }()
  45. if err := os.MkdirAll(getDaemonConfDir(), os.FileMode(0644)); err != nil {
  46. return fmt.Errorf("Unable to create daemon configuration directory: %s", err)
  47. }
  48. newFile, err := os.OpenFile(newPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
  49. if err != nil {
  50. return fmt.Errorf("error creating key file %q: %s", newPath, err)
  51. }
  52. defer newFile.Close()
  53. oldFile, err := os.Open(oldPath)
  54. if err != nil {
  55. return fmt.Errorf("error opening key file %q: %s", oldPath, err)
  56. }
  57. defer oldFile.Close()
  58. if _, err := io.Copy(newFile, oldFile); err != nil {
  59. return fmt.Errorf("error copying key: %s", err)
  60. }
  61. logrus.Infof("Migrated key from %s to %s", oldPath, newPath)
  62. }
  63. return nil
  64. }
  65. func mainDaemon() {
  66. if flag.NArg() != 0 {
  67. flag.Usage()
  68. return
  69. }
  70. logrus.SetFormatter(&logrus.TextFormatter{TimestampFormat: timeutils.RFC3339NanoFixed})
  71. var pfile *pidfile.PidFile
  72. if daemonCfg.Pidfile != "" {
  73. pf, err := pidfile.New(daemonCfg.Pidfile)
  74. if err != nil {
  75. logrus.Fatalf("Error starting daemon: %v", err)
  76. }
  77. pfile = pf
  78. defer func() {
  79. if err := pfile.Remove(); err != nil {
  80. logrus.Error(err)
  81. }
  82. }()
  83. }
  84. if err := migrateKey(); err != nil {
  85. logrus.Fatal(err)
  86. }
  87. daemonCfg.TrustKeyPath = *flTrustKey
  88. registryService := registry.NewService(registryCfg)
  89. d, err := daemon.NewDaemon(daemonCfg, registryService)
  90. if err != nil {
  91. if pfile != nil {
  92. if err := pfile.Remove(); err != nil {
  93. logrus.Error(err)
  94. }
  95. }
  96. logrus.Fatalf("Error starting daemon: %v", err)
  97. }
  98. logrus.Info("Daemon has completed initialization")
  99. logrus.WithFields(logrus.Fields{
  100. "version": dockerversion.VERSION,
  101. "commit": dockerversion.GITCOMMIT,
  102. "execdriver": d.ExecutionDriver().Name(),
  103. "graphdriver": d.GraphDriver().String(),
  104. }).Info("Docker daemon")
  105. serverConfig := &apiserver.ServerConfig{
  106. Logging: true,
  107. EnableCors: daemonCfg.EnableCors,
  108. CorsHeaders: daemonCfg.CorsHeaders,
  109. Version: dockerversion.VERSION,
  110. SocketGroup: daemonCfg.SocketGroup,
  111. Tls: *flTls,
  112. TlsVerify: *flTlsVerify,
  113. TlsCa: *flCa,
  114. TlsCert: *flCert,
  115. TlsKey: *flKey,
  116. }
  117. api := apiserver.New(serverConfig)
  118. // The serve API routine never exits unless an error occurs
  119. // We need to start it as a goroutine and wait on it so
  120. // daemon doesn't exit
  121. serveAPIWait := make(chan error)
  122. go func() {
  123. if err := api.ServeApi(flHosts); err != nil {
  124. logrus.Errorf("ServeAPI error: %v", err)
  125. serveAPIWait <- err
  126. return
  127. }
  128. serveAPIWait <- nil
  129. }()
  130. signal.Trap(func() {
  131. api.Close()
  132. <-serveAPIWait
  133. shutdownDaemon(d, 15)
  134. if pfile != nil {
  135. if err := pfile.Remove(); err != nil {
  136. logrus.Error(err)
  137. }
  138. }
  139. })
  140. // after the daemon is done setting up we can tell the api to start
  141. // accepting connections with specified daemon
  142. api.AcceptConnections(d)
  143. // Daemon is fully initialized and handling API traffic
  144. // Wait for serve API to complete
  145. errAPI := <-serveAPIWait
  146. shutdownDaemon(d, 15)
  147. if errAPI != nil {
  148. if pfile != nil {
  149. if err := pfile.Remove(); err != nil {
  150. logrus.Error(err)
  151. }
  152. }
  153. logrus.Fatalf("Shutting down due to ServeAPI error: %v", errAPI)
  154. }
  155. }
  156. // shutdownDaemon just wraps daemon.Shutdown() to handle a timeout in case
  157. // d.Shutdown() is waiting too long to kill container or worst it's
  158. // blocked there
  159. func shutdownDaemon(d *daemon.Daemon, timeout time.Duration) {
  160. ch := make(chan struct{})
  161. go func() {
  162. d.Shutdown()
  163. close(ch)
  164. }()
  165. select {
  166. case <-ch:
  167. logrus.Debug("Clean shutdown succeded")
  168. case <-time.After(timeout * time.Second):
  169. logrus.Error("Force shutdown daemon")
  170. }
  171. }
  172. // currentUserIsOwner checks whether the current user is the owner of the given
  173. // file.
  174. func currentUserIsOwner(f string) bool {
  175. if fileInfo, err := system.Stat(f); err == nil && fileInfo != nil {
  176. if int(fileInfo.Uid()) == os.Getuid() {
  177. return true
  178. }
  179. }
  180. return false
  181. }