docker.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. package main
  2. import (
  3. "crypto/tls"
  4. "crypto/x509"
  5. "fmt"
  6. "io/ioutil"
  7. "log"
  8. "net"
  9. "os"
  10. "path/filepath"
  11. "runtime"
  12. "strings"
  13. "github.com/docker/docker/api"
  14. "github.com/docker/docker/api/client"
  15. "github.com/docker/docker/builtins"
  16. "github.com/docker/docker/dockerversion"
  17. "github.com/docker/docker/engine"
  18. "github.com/docker/docker/opts"
  19. flag "github.com/docker/docker/pkg/mflag"
  20. "github.com/docker/docker/pkg/parsers/kernel"
  21. "github.com/docker/docker/sysinit"
  22. "github.com/docker/docker/utils"
  23. )
  24. const (
  25. defaultCaFile = "ca.pem"
  26. defaultKeyFile = "key.pem"
  27. defaultCertFile = "cert.pem"
  28. )
  29. var (
  30. dockerConfDir = os.Getenv("DOCKER_CONFIG")
  31. )
  32. func main() {
  33. if len(dockerConfDir) == 0 {
  34. dockerConfDir = filepath.Join(os.Getenv("HOME"), ".docker")
  35. }
  36. if selfPath := utils.SelfPath(); strings.Contains(selfPath, ".dockerinit") {
  37. // Running in init mode
  38. sysinit.SysInit()
  39. return
  40. }
  41. var (
  42. flVersion = flag.Bool([]string{"v", "-version"}, false, "Print version information and quit")
  43. flDaemon = flag.Bool([]string{"d", "-daemon"}, false, "Enable daemon mode")
  44. flGraphOpts opts.ListOpts
  45. flDebug = flag.Bool([]string{"D", "-debug"}, false, "Enable debug mode")
  46. flAutoRestart = flag.Bool([]string{"r", "-restart"}, true, "Restart previously running containers")
  47. bridgeName = flag.String([]string{"b", "-bridge"}, "", "Attach containers to a pre-existing network bridge\nuse 'none' to disable container networking")
  48. bridgeIp = flag.String([]string{"#bip", "-bip"}, "", "Use this CIDR notation address for the network bridge's IP, not compatible with -b")
  49. pidfile = flag.String([]string{"p", "-pidfile"}, "/var/run/docker.pid", "Path to use for daemon PID file")
  50. flRoot = flag.String([]string{"g", "-graph"}, "/var/lib/docker", "Path to use as the root of the Docker runtime")
  51. flSocketGroup = flag.String([]string{"G", "-group"}, "docker", "Group to assign the unix socket specified by -H when running in daemon mode\nuse '' (the empty string) to disable setting of a group")
  52. flEnableCors = flag.Bool([]string{"#api-enable-cors", "-api-enable-cors"}, false, "Enable CORS headers in the remote API")
  53. flDns = opts.NewListOpts(opts.ValidateIPAddress)
  54. flDnsSearch = opts.NewListOpts(opts.ValidateDnsSearch)
  55. flEnableIptables = flag.Bool([]string{"#iptables", "-iptables"}, true, "Enable Docker's addition of iptables rules")
  56. flEnableIpForward = flag.Bool([]string{"#ip-forward", "-ip-forward"}, true, "Enable net.ipv4.ip_forward")
  57. flDefaultIp = flag.String([]string{"#ip", "-ip"}, "0.0.0.0", "Default IP address to use when binding container ports")
  58. flInterContainerComm = flag.Bool([]string{"#icc", "-icc"}, true, "Enable inter-container communication")
  59. flGraphDriver = flag.String([]string{"s", "-storage-driver"}, "", "Force the Docker runtime to use a specific storage driver")
  60. flExecDriver = flag.String([]string{"e", "-exec-driver"}, "native", "Force the Docker runtime to use a specific exec driver")
  61. flHosts = opts.NewListOpts(api.ValidateHost)
  62. flMtu = flag.Int([]string{"#mtu", "-mtu"}, 0, "Set the containers network MTU\nif no value is provided: default to the default route MTU or 1500 if no default route is available")
  63. flTls = flag.Bool([]string{"-tls"}, false, "Use TLS; implied by tls-verify flags")
  64. flTlsVerify = flag.Bool([]string{"-tlsverify"}, false, "Use TLS and verify the remote (daemon: verify client, client: verify daemon)")
  65. flCa = flag.String([]string{"-tlscacert"}, filepath.Join(dockerConfDir, defaultCaFile), "Trust only remotes providing a certificate signed by the CA given here")
  66. flCert = flag.String([]string{"-tlscert"}, filepath.Join(dockerConfDir, defaultCertFile), "Path to TLS certificate file")
  67. flKey = flag.String([]string{"-tlskey"}, filepath.Join(dockerConfDir, defaultKeyFile), "Path to TLS key file")
  68. flSelinuxEnabled = flag.Bool([]string{"-selinux-enabled"}, false, "Enable selinux support. SELinux does not presently support the BTRFS storage driver")
  69. )
  70. flag.Var(&flDns, []string{"#dns", "-dns"}, "Force Docker to use specific DNS servers")
  71. flag.Var(&flDnsSearch, []string{"-dns-search"}, "Force Docker to use specific DNS search domains")
  72. flag.Var(&flHosts, []string{"H", "-host"}, "The socket(s) to bind to in daemon mode\nspecified using one or more tcp://host:port, unix:///path/to/socket, fd://* or fd://socketfd.")
  73. flag.Var(&flGraphOpts, []string{"-storage-opt"}, "Set storage driver options")
  74. flag.Parse()
  75. if *flVersion {
  76. showVersion()
  77. return
  78. }
  79. if flHosts.Len() == 0 {
  80. defaultHost := os.Getenv("DOCKER_HOST")
  81. if defaultHost == "" || *flDaemon {
  82. // If we do not have a host, default to unix socket
  83. defaultHost = fmt.Sprintf("unix://%s", api.DEFAULTUNIXSOCKET)
  84. }
  85. if _, err := api.ValidateHost(defaultHost); err != nil {
  86. log.Fatal(err)
  87. }
  88. flHosts.Set(defaultHost)
  89. }
  90. if *bridgeName != "" && *bridgeIp != "" {
  91. log.Fatal("You specified -b & --bip, mutually exclusive options. Please specify only one.")
  92. }
  93. if !*flEnableIptables && !*flInterContainerComm {
  94. log.Fatal("You specified --iptables=false with --icc=false. ICC uses iptables to function. Please set --icc or --iptables to true.")
  95. }
  96. if net.ParseIP(*flDefaultIp) == nil {
  97. log.Fatalf("Specified --ip=%s is not in correct format \"0.0.0.0\".", *flDefaultIp)
  98. }
  99. if *flDebug {
  100. os.Setenv("DEBUG", "1")
  101. }
  102. if *flDaemon {
  103. if flag.NArg() != 0 {
  104. flag.Usage()
  105. return
  106. }
  107. // get the canonical path to the Docker root directory
  108. root := *flRoot
  109. var realRoot string
  110. if _, err := os.Stat(root); err != nil && os.IsNotExist(err) {
  111. realRoot = root
  112. } else {
  113. realRoot, err = utils.ReadSymlinkedDirectory(root)
  114. if err != nil {
  115. log.Fatalf("Unable to get the full path to root (%s): %s", root, err)
  116. }
  117. }
  118. if err := checkKernelAndArch(); err != nil {
  119. log.Fatal(err)
  120. }
  121. eng := engine.New()
  122. // Load builtins
  123. if err := builtins.Register(eng); err != nil {
  124. log.Fatal(err)
  125. }
  126. // handle the pidfile early. https://github.com/docker/docker/issues/6973
  127. if len(*pidfile) > 0 {
  128. job := eng.Job("initserverpidfile", *pidfile)
  129. if err := job.Run(); err != nil {
  130. log.Fatal(err)
  131. }
  132. }
  133. // load the daemon in the background so we can immediately start
  134. // the http api so that connections don't fail while the daemon
  135. // is booting
  136. go func() {
  137. // Load plugin: httpapi
  138. job := eng.Job("initserver")
  139. // include the variable here too, for the server config
  140. job.Setenv("Pidfile", *pidfile)
  141. job.Setenv("Root", realRoot)
  142. job.SetenvBool("AutoRestart", *flAutoRestart)
  143. job.SetenvList("Dns", flDns.GetAll())
  144. job.SetenvList("DnsSearch", flDnsSearch.GetAll())
  145. job.SetenvBool("EnableIptables", *flEnableIptables)
  146. job.SetenvBool("EnableIpForward", *flEnableIpForward)
  147. job.Setenv("BridgeIface", *bridgeName)
  148. job.Setenv("BridgeIP", *bridgeIp)
  149. job.Setenv("DefaultIp", *flDefaultIp)
  150. job.SetenvBool("InterContainerCommunication", *flInterContainerComm)
  151. job.Setenv("GraphDriver", *flGraphDriver)
  152. job.SetenvList("GraphOptions", flGraphOpts.GetAll())
  153. job.Setenv("ExecDriver", *flExecDriver)
  154. job.SetenvInt("Mtu", *flMtu)
  155. job.SetenvBool("EnableSelinuxSupport", *flSelinuxEnabled)
  156. job.SetenvList("Sockets", flHosts.GetAll())
  157. if err := job.Run(); err != nil {
  158. log.Fatal(err)
  159. }
  160. // after the daemon is done setting up we can tell the api to start
  161. // accepting connections
  162. if err := eng.Job("acceptconnections").Run(); err != nil {
  163. log.Fatal(err)
  164. }
  165. }()
  166. // TODO actually have a resolved graphdriver to show?
  167. log.Printf("docker daemon: %s %s; execdriver: %s; graphdriver: %s",
  168. dockerversion.VERSION,
  169. dockerversion.GITCOMMIT,
  170. *flExecDriver,
  171. *flGraphDriver)
  172. // Serve api
  173. job := eng.Job("serveapi", flHosts.GetAll()...)
  174. job.SetenvBool("Logging", true)
  175. job.SetenvBool("EnableCors", *flEnableCors)
  176. job.Setenv("Version", dockerversion.VERSION)
  177. job.Setenv("SocketGroup", *flSocketGroup)
  178. job.SetenvBool("Tls", *flTls)
  179. job.SetenvBool("TlsVerify", *flTlsVerify)
  180. job.Setenv("TlsCa", *flCa)
  181. job.Setenv("TlsCert", *flCert)
  182. job.Setenv("TlsKey", *flKey)
  183. job.SetenvBool("BufferRequests", true)
  184. if err := job.Run(); err != nil {
  185. log.Fatal(err)
  186. }
  187. } else {
  188. if flHosts.Len() > 1 {
  189. log.Fatal("Please specify only one -H")
  190. }
  191. protoAddrParts := strings.SplitN(flHosts.GetAll()[0], "://", 2)
  192. var (
  193. cli *client.DockerCli
  194. tlsConfig tls.Config
  195. )
  196. tlsConfig.InsecureSkipVerify = true
  197. // If we should verify the server, we need to load a trusted ca
  198. if *flTlsVerify {
  199. *flTls = true
  200. certPool := x509.NewCertPool()
  201. file, err := ioutil.ReadFile(*flCa)
  202. if err != nil {
  203. log.Fatalf("Couldn't read ca cert %s: %s", *flCa, err)
  204. }
  205. certPool.AppendCertsFromPEM(file)
  206. tlsConfig.RootCAs = certPool
  207. tlsConfig.InsecureSkipVerify = false
  208. }
  209. // If tls is enabled, try to load and send client certificates
  210. if *flTls || *flTlsVerify {
  211. _, errCert := os.Stat(*flCert)
  212. _, errKey := os.Stat(*flKey)
  213. if errCert == nil && errKey == nil {
  214. *flTls = true
  215. cert, err := tls.LoadX509KeyPair(*flCert, *flKey)
  216. if err != nil {
  217. log.Fatalf("Couldn't load X509 key pair: %s. Key encrypted?", err)
  218. }
  219. tlsConfig.Certificates = []tls.Certificate{cert}
  220. }
  221. }
  222. if *flTls || *flTlsVerify {
  223. cli = client.NewDockerCli(os.Stdin, os.Stdout, os.Stderr, protoAddrParts[0], protoAddrParts[1], &tlsConfig)
  224. } else {
  225. cli = client.NewDockerCli(os.Stdin, os.Stdout, os.Stderr, protoAddrParts[0], protoAddrParts[1], nil)
  226. }
  227. if err := cli.ParseCommands(flag.Args()...); err != nil {
  228. if sterr, ok := err.(*utils.StatusError); ok {
  229. if sterr.Status != "" {
  230. log.Println(sterr.Status)
  231. }
  232. os.Exit(sterr.StatusCode)
  233. }
  234. log.Fatal(err)
  235. }
  236. }
  237. }
  238. func showVersion() {
  239. fmt.Printf("Docker version %s, build %s\n", dockerversion.VERSION, dockerversion.GITCOMMIT)
  240. }
  241. func checkKernelAndArch() error {
  242. // Check for unsupported architectures
  243. if runtime.GOARCH != "amd64" {
  244. return fmt.Errorf("The Docker runtime currently only supports amd64 (not %s). This will change in the future. Aborting.", runtime.GOARCH)
  245. }
  246. // Check for unsupported kernel versions
  247. // FIXME: it would be cleaner to not test for specific versions, but rather
  248. // test for specific functionalities.
  249. // Unfortunately we can't test for the feature "does not cause a kernel panic"
  250. // without actually causing a kernel panic, so we need this workaround until
  251. // the circumstances of pre-3.8 crashes are clearer.
  252. // For details see http://github.com/docker/docker/issues/407
  253. if k, err := kernel.GetKernelVersion(); err != nil {
  254. log.Printf("WARNING: %s\n", err)
  255. } else {
  256. if kernel.CompareKernelVersion(k, &kernel.KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0}) < 0 {
  257. if os.Getenv("DOCKER_NOWARN_KERNEL_VERSION") == "" {
  258. log.Printf("WARNING: You are running linux kernel version %s, which might be unstable running docker. Please upgrade your kernel to 3.8.0.", k.String())
  259. }
  260. }
  261. }
  262. return nil
  263. }