daemon.go 12 KB

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