docker.go 11 KB

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