docker.go 10 KB

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