daemon.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. package main
  2. import (
  3. "crypto/tls"
  4. "fmt"
  5. "io"
  6. "os"
  7. "path/filepath"
  8. "runtime"
  9. "strings"
  10. "time"
  11. "github.com/Sirupsen/logrus"
  12. "github.com/docker/distribution/uuid"
  13. "github.com/docker/docker/api"
  14. apiserver "github.com/docker/docker/api/server"
  15. "github.com/docker/docker/api/server/middleware"
  16. "github.com/docker/docker/api/server/router"
  17. "github.com/docker/docker/api/server/router/build"
  18. "github.com/docker/docker/api/server/router/container"
  19. "github.com/docker/docker/api/server/router/image"
  20. "github.com/docker/docker/api/server/router/network"
  21. systemrouter "github.com/docker/docker/api/server/router/system"
  22. "github.com/docker/docker/api/server/router/volume"
  23. "github.com/docker/docker/builder/dockerfile"
  24. cliflags "github.com/docker/docker/cli/flags"
  25. "github.com/docker/docker/cliconfig"
  26. "github.com/docker/docker/daemon"
  27. "github.com/docker/docker/daemon/logger"
  28. "github.com/docker/docker/dockerversion"
  29. "github.com/docker/docker/libcontainerd"
  30. "github.com/docker/docker/opts"
  31. "github.com/docker/docker/pkg/authorization"
  32. "github.com/docker/docker/pkg/jsonlog"
  33. "github.com/docker/docker/pkg/listeners"
  34. flag "github.com/docker/docker/pkg/mflag"
  35. "github.com/docker/docker/pkg/pidfile"
  36. "github.com/docker/docker/pkg/signal"
  37. "github.com/docker/docker/pkg/system"
  38. "github.com/docker/docker/registry"
  39. "github.com/docker/docker/runconfig"
  40. "github.com/docker/docker/utils"
  41. "github.com/docker/go-connections/tlsconfig"
  42. )
  43. const (
  44. daemonConfigFileFlag = "-config-file"
  45. )
  46. // DaemonCli represents the daemon CLI.
  47. type DaemonCli struct {
  48. *daemon.Config
  49. commonFlags *cliflags.CommonFlags
  50. configFile *string
  51. }
  52. func presentInHelp(usage string) string { return usage }
  53. func absentFromHelp(string) string { return "" }
  54. // NewDaemonCli returns a pre-configured daemon CLI
  55. func NewDaemonCli() *DaemonCli {
  56. // TODO(tiborvass): remove InstallFlags?
  57. daemonConfig := new(daemon.Config)
  58. daemonConfig.LogConfig.Config = make(map[string]string)
  59. daemonConfig.ClusterOpts = make(map[string]string)
  60. if runtime.GOOS != "linux" {
  61. daemonConfig.V2Only = true
  62. }
  63. daemonConfig.InstallFlags(flag.CommandLine, presentInHelp)
  64. configFile := flag.CommandLine.String([]string{daemonConfigFileFlag}, defaultDaemonConfigFile, "Daemon configuration file")
  65. flag.CommandLine.Require(flag.Exact, 0)
  66. return &DaemonCli{
  67. Config: daemonConfig,
  68. commonFlags: cliflags.InitCommonFlags(),
  69. configFile: configFile,
  70. }
  71. }
  72. func migrateKey() (err error) {
  73. // Migrate trust key if exists at ~/.docker/key.json and owned by current user
  74. oldPath := filepath.Join(cliconfig.ConfigDir(), cliflags.DefaultTrustKeyFile)
  75. newPath := filepath.Join(getDaemonConfDir(), cliflags.DefaultTrustKeyFile)
  76. if _, statErr := os.Stat(newPath); os.IsNotExist(statErr) && currentUserIsOwner(oldPath) {
  77. defer func() {
  78. // Ensure old path is removed if no error occurred
  79. if err == nil {
  80. err = os.Remove(oldPath)
  81. } else {
  82. logrus.Warnf("Key migration failed, key file not removed at %s", oldPath)
  83. os.Remove(newPath)
  84. }
  85. }()
  86. if err := system.MkdirAll(getDaemonConfDir(), os.FileMode(0644)); err != nil {
  87. return fmt.Errorf("Unable to create daemon configuration directory: %s", err)
  88. }
  89. newFile, err := os.OpenFile(newPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
  90. if err != nil {
  91. return fmt.Errorf("error creating key file %q: %s", newPath, err)
  92. }
  93. defer newFile.Close()
  94. oldFile, err := os.Open(oldPath)
  95. if err != nil {
  96. return fmt.Errorf("error opening key file %q: %s", oldPath, err)
  97. }
  98. defer oldFile.Close()
  99. if _, err := io.Copy(newFile, oldFile); err != nil {
  100. return fmt.Errorf("error copying key: %s", err)
  101. }
  102. logrus.Infof("Migrated key from %s to %s", oldPath, newPath)
  103. }
  104. return nil
  105. }
  106. func (cli *DaemonCli) start() {
  107. // warn from uuid package when running the daemon
  108. uuid.Loggerf = logrus.Warnf
  109. flags := flag.CommandLine
  110. cli.commonFlags.PostParse()
  111. if cli.commonFlags.TrustKey == "" {
  112. cli.commonFlags.TrustKey = filepath.Join(getDaemonConfDir(), cliflags.DefaultTrustKeyFile)
  113. }
  114. cliConfig, err := loadDaemonCliConfig(cli.Config, flags, cli.commonFlags, *cli.configFile)
  115. if err != nil {
  116. fmt.Fprint(os.Stderr, err)
  117. os.Exit(1)
  118. }
  119. cli.Config = cliConfig
  120. if cli.Config.Debug {
  121. utils.EnableDebug()
  122. }
  123. if utils.ExperimentalBuild() {
  124. logrus.Warn("Running experimental build")
  125. }
  126. logrus.SetFormatter(&logrus.TextFormatter{
  127. TimestampFormat: jsonlog.RFC3339NanoFixed,
  128. DisableColors: cli.Config.RawLogs,
  129. })
  130. if err := setDefaultUmask(); err != nil {
  131. logrus.Fatalf("Failed to set umask: %v", err)
  132. }
  133. if len(cli.LogConfig.Config) > 0 {
  134. if err := logger.ValidateLogOpts(cli.LogConfig.Type, cli.LogConfig.Config); err != nil {
  135. logrus.Fatalf("Failed to set log opts: %v", err)
  136. }
  137. }
  138. var pfile *pidfile.PIDFile
  139. if cli.Pidfile != "" {
  140. pf, err := pidfile.New(cli.Pidfile)
  141. if err != nil {
  142. logrus.Fatalf("Error starting daemon: %v", err)
  143. }
  144. pfile = pf
  145. defer func() {
  146. if err := pfile.Remove(); err != nil {
  147. logrus.Error(err)
  148. }
  149. }()
  150. }
  151. serverConfig := &apiserver.Config{
  152. Logging: true,
  153. SocketGroup: cli.Config.SocketGroup,
  154. Version: dockerversion.Version,
  155. EnableCors: cli.Config.EnableCors,
  156. CorsHeaders: cli.Config.CorsHeaders,
  157. }
  158. if cli.Config.TLS {
  159. tlsOptions := tlsconfig.Options{
  160. CAFile: cli.Config.CommonTLSOptions.CAFile,
  161. CertFile: cli.Config.CommonTLSOptions.CertFile,
  162. KeyFile: cli.Config.CommonTLSOptions.KeyFile,
  163. }
  164. if cli.Config.TLSVerify {
  165. // server requires and verifies client's certificate
  166. tlsOptions.ClientAuth = tls.RequireAndVerifyClientCert
  167. }
  168. tlsConfig, err := tlsconfig.Server(tlsOptions)
  169. if err != nil {
  170. logrus.Fatal(err)
  171. }
  172. serverConfig.TLSConfig = tlsConfig
  173. }
  174. if len(cli.Config.Hosts) == 0 {
  175. cli.Config.Hosts = make([]string, 1)
  176. }
  177. api := apiserver.New(serverConfig)
  178. for i := 0; i < len(cli.Config.Hosts); i++ {
  179. var err error
  180. if cli.Config.Hosts[i], err = opts.ParseHost(cli.Config.TLS, cli.Config.Hosts[i]); err != nil {
  181. logrus.Fatalf("error parsing -H %s : %v", cli.Config.Hosts[i], err)
  182. }
  183. protoAddr := cli.Config.Hosts[i]
  184. protoAddrParts := strings.SplitN(protoAddr, "://", 2)
  185. if len(protoAddrParts) != 2 {
  186. logrus.Fatalf("bad format %s, expected PROTO://ADDR", protoAddr)
  187. }
  188. proto := protoAddrParts[0]
  189. addr := protoAddrParts[1]
  190. // It's a bad idea to bind to TCP without tlsverify.
  191. if proto == "tcp" && (serverConfig.TLSConfig == nil || serverConfig.TLSConfig.ClientAuth != tls.RequireAndVerifyClientCert) {
  192. logrus.Warn("[!] DON'T BIND ON ANY IP ADDRESS WITHOUT setting -tlsverify IF YOU DON'T KNOW WHAT YOU'RE DOING [!]")
  193. }
  194. l, err := listeners.Init(proto, addr, serverConfig.SocketGroup, serverConfig.TLSConfig)
  195. if err != nil {
  196. logrus.Fatal(err)
  197. }
  198. // If we're binding to a TCP port, make sure that a container doesn't try to use it.
  199. if proto == "tcp" {
  200. if err := allocateDaemonPort(addr); err != nil {
  201. logrus.Fatal(err)
  202. }
  203. }
  204. logrus.Debugf("Listener created for HTTP on %s (%s)", protoAddrParts[0], protoAddrParts[1])
  205. api.Accept(protoAddrParts[1], l...)
  206. }
  207. if err := migrateKey(); err != nil {
  208. logrus.Fatal(err)
  209. }
  210. cli.TrustKeyPath = cli.commonFlags.TrustKey
  211. registryService := registry.NewService(cli.Config.ServiceOptions)
  212. containerdRemote, err := libcontainerd.New(cli.getLibcontainerdRoot(), cli.getPlatformRemoteOptions()...)
  213. if err != nil {
  214. logrus.Fatal(err)
  215. }
  216. d, err := daemon.NewDaemon(cli.Config, registryService, containerdRemote)
  217. if err != nil {
  218. if pfile != nil {
  219. if err := pfile.Remove(); err != nil {
  220. logrus.Error(err)
  221. }
  222. }
  223. logrus.Fatalf("Error starting daemon: %v", err)
  224. }
  225. logrus.Info("Daemon has completed initialization")
  226. logrus.WithFields(logrus.Fields{
  227. "version": dockerversion.Version,
  228. "commit": dockerversion.GitCommit,
  229. "graphdriver": d.GraphDriverName(),
  230. }).Info("Docker daemon")
  231. cli.initMiddlewares(api, serverConfig)
  232. initRouter(api, d)
  233. reload := func(config *daemon.Config) {
  234. if err := d.Reload(config); err != nil {
  235. logrus.Errorf("Error reconfiguring the daemon: %v", err)
  236. return
  237. }
  238. if config.IsValueSet("debug") {
  239. debugEnabled := utils.IsDebugEnabled()
  240. switch {
  241. case debugEnabled && !config.Debug: // disable debug
  242. utils.DisableDebug()
  243. api.DisableProfiler()
  244. case config.Debug && !debugEnabled: // enable debug
  245. utils.EnableDebug()
  246. api.EnableProfiler()
  247. }
  248. }
  249. }
  250. setupConfigReloadTrap(*cli.configFile, flags, reload)
  251. // The serve API routine never exits unless an error occurs
  252. // We need to start it as a goroutine and wait on it so
  253. // daemon doesn't exit
  254. serveAPIWait := make(chan error)
  255. go api.Wait(serveAPIWait)
  256. signal.Trap(func() {
  257. api.Close()
  258. <-serveAPIWait
  259. shutdownDaemon(d, 15)
  260. if pfile != nil {
  261. if err := pfile.Remove(); err != nil {
  262. logrus.Error(err)
  263. }
  264. }
  265. })
  266. // after the daemon is done setting up we can notify systemd api
  267. notifySystem()
  268. // Daemon is fully initialized and handling API traffic
  269. // Wait for serve API to complete
  270. errAPI := <-serveAPIWait
  271. shutdownDaemon(d, 15)
  272. containerdRemote.Cleanup()
  273. if errAPI != nil {
  274. if pfile != nil {
  275. if err := pfile.Remove(); err != nil {
  276. logrus.Error(err)
  277. }
  278. }
  279. logrus.Fatalf("Shutting down due to ServeAPI error: %v", errAPI)
  280. }
  281. }
  282. // shutdownDaemon just wraps daemon.Shutdown() to handle a timeout in case
  283. // d.Shutdown() is waiting too long to kill container or worst it's
  284. // blocked there
  285. func shutdownDaemon(d *daemon.Daemon, timeout time.Duration) {
  286. ch := make(chan struct{})
  287. go func() {
  288. d.Shutdown()
  289. close(ch)
  290. }()
  291. select {
  292. case <-ch:
  293. logrus.Debug("Clean shutdown succeeded")
  294. case <-time.After(timeout * time.Second):
  295. logrus.Error("Force shutdown daemon")
  296. }
  297. }
  298. func loadDaemonCliConfig(config *daemon.Config, flags *flag.FlagSet, commonConfig *cliflags.CommonFlags, configFile string) (*daemon.Config, error) {
  299. config.Debug = commonConfig.Debug
  300. config.Hosts = commonConfig.Hosts
  301. config.LogLevel = commonConfig.LogLevel
  302. config.TLS = commonConfig.TLS
  303. config.TLSVerify = commonConfig.TLSVerify
  304. config.CommonTLSOptions = daemon.CommonTLSOptions{}
  305. if commonConfig.TLSOptions != nil {
  306. config.CommonTLSOptions.CAFile = commonConfig.TLSOptions.CAFile
  307. config.CommonTLSOptions.CertFile = commonConfig.TLSOptions.CertFile
  308. config.CommonTLSOptions.KeyFile = commonConfig.TLSOptions.KeyFile
  309. }
  310. if configFile != "" {
  311. c, err := daemon.MergeDaemonConfigurations(config, flags, configFile)
  312. if err != nil {
  313. if flags.IsSet(daemonConfigFileFlag) || !os.IsNotExist(err) {
  314. return nil, fmt.Errorf("unable to configure the Docker daemon with file %s: %v\n", configFile, err)
  315. }
  316. }
  317. // the merged configuration can be nil if the config file didn't exist.
  318. // leave the current configuration as it is if when that happens.
  319. if c != nil {
  320. config = c
  321. }
  322. }
  323. // Regardless of whether the user sets it to true or false, if they
  324. // specify TLSVerify at all then we need to turn on TLS
  325. if config.IsValueSet(cliflags.TLSVerifyKey) {
  326. config.TLS = true
  327. }
  328. // ensure that the log level is the one set after merging configurations
  329. cliflags.SetDaemonLogLevel(config.LogLevel)
  330. return config, nil
  331. }
  332. func initRouter(s *apiserver.Server, d *daemon.Daemon) {
  333. decoder := runconfig.ContainerDecoder{}
  334. routers := []router.Router{
  335. container.NewRouter(d, decoder),
  336. image.NewRouter(d, decoder),
  337. systemrouter.NewRouter(d),
  338. volume.NewRouter(d),
  339. build.NewRouter(dockerfile.NewBuildManager(d)),
  340. }
  341. if d.NetworkControllerEnabled() {
  342. routers = append(routers, network.NewRouter(d))
  343. }
  344. s.InitRouter(utils.IsDebugEnabled(), routers...)
  345. }
  346. func (cli *DaemonCli) initMiddlewares(s *apiserver.Server, cfg *apiserver.Config) {
  347. v := cfg.Version
  348. vm := middleware.NewVersionMiddleware(v, api.DefaultVersion, api.MinVersion)
  349. s.UseMiddleware(vm)
  350. if cfg.EnableCors {
  351. c := middleware.NewCORSMiddleware(cfg.CorsHeaders)
  352. s.UseMiddleware(c)
  353. }
  354. u := middleware.NewUserAgentMiddleware(v)
  355. s.UseMiddleware(u)
  356. if len(cli.Config.AuthorizationPlugins) > 0 {
  357. authZPlugins := authorization.NewPlugins(cli.Config.AuthorizationPlugins)
  358. handleAuthorization := authorization.NewMiddleware(authZPlugins)
  359. s.UseMiddleware(handleAuthorization)
  360. }
  361. }