docker.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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\nuse '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\nuse '' (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\nif 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\nspecified 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 runtime.GOOS != "linux" {
  90. log.Fatalf("The Docker daemon is only supported on linux")
  91. }
  92. if os.Geteuid() != 0 {
  93. log.Fatalf("The Docker daemon needs to be run as root")
  94. }
  95. if flag.NArg() != 0 {
  96. flag.Usage()
  97. return
  98. }
  99. // set up the TempDir to use a canonical path
  100. tmp := os.TempDir()
  101. realTmp, err := utils.ReadSymlinkedDirectory(tmp)
  102. if err != nil {
  103. log.Fatalf("Unable to get the full path to the TempDir (%s): %s", tmp, err)
  104. }
  105. os.Setenv("TMPDIR", realTmp)
  106. // get the canonical path to the Docker root directory
  107. root := *flRoot
  108. var realRoot string
  109. if _, err := os.Stat(root); err != nil && os.IsNotExist(err) {
  110. realRoot = root
  111. } else {
  112. realRoot, err = utils.ReadSymlinkedDirectory(root)
  113. if err != nil {
  114. log.Fatalf("Unable to get the full path to root (%s): %s", root, err)
  115. }
  116. }
  117. if err := checkKernelAndArch(); err != nil {
  118. log.Fatal(err)
  119. }
  120. eng := engine.New()
  121. // Load builtins
  122. if err := builtins.Register(eng); err != nil {
  123. log.Fatal(err)
  124. }
  125. // load the daemon in the background so we can immediately start
  126. // the http api so that connections don't fail while the daemon
  127. // is booting
  128. go func() {
  129. // Load plugin: httpapi
  130. job := eng.Job("initserver")
  131. job.Setenv("Pidfile", *pidfile)
  132. job.Setenv("Root", realRoot)
  133. job.SetenvBool("AutoRestart", *flAutoRestart)
  134. job.SetenvList("Dns", flDns.GetAll())
  135. job.SetenvList("DnsSearch", flDnsSearch.GetAll())
  136. job.SetenvBool("EnableIptables", *flEnableIptables)
  137. job.SetenvBool("EnableIpForward", *flEnableIpForward)
  138. job.Setenv("BridgeIface", *bridgeName)
  139. job.Setenv("BridgeIP", *bridgeIp)
  140. job.Setenv("DefaultIp", *flDefaultIp)
  141. job.SetenvBool("InterContainerCommunication", *flInterContainerComm)
  142. job.Setenv("GraphDriver", *flGraphDriver)
  143. job.Setenv("ExecDriver", *flExecDriver)
  144. job.SetenvInt("Mtu", *flMtu)
  145. job.SetenvBool("EnableSelinuxSupport", *flSelinuxEnabled)
  146. if err := job.Run(); err != nil {
  147. log.Fatal(err)
  148. }
  149. // after the daemon is done setting up we can tell the api to start
  150. // accepting connections
  151. if err := eng.Job("acceptconnections").Run(); err != nil {
  152. log.Fatal(err)
  153. }
  154. }()
  155. // TODO actually have a resolved graphdriver to show?
  156. log.Printf("docker daemon: %s %s; execdriver: %s; graphdriver: %s",
  157. dockerversion.VERSION,
  158. dockerversion.GITCOMMIT,
  159. *flExecDriver,
  160. *flGraphDriver)
  161. // Serve api
  162. job := eng.Job("serveapi", flHosts.GetAll()...)
  163. job.SetenvBool("Logging", true)
  164. job.SetenvBool("EnableCors", *flEnableCors)
  165. job.Setenv("Version", dockerversion.VERSION)
  166. job.Setenv("SocketGroup", *flSocketGroup)
  167. job.SetenvBool("Tls", *flTls)
  168. job.SetenvBool("TlsVerify", *flTlsVerify)
  169. job.Setenv("TlsCa", *flCa)
  170. job.Setenv("TlsCert", *flCert)
  171. job.Setenv("TlsKey", *flKey)
  172. job.SetenvBool("BufferRequests", true)
  173. if err := job.Run(); err != nil {
  174. log.Fatal(err)
  175. }
  176. } else {
  177. if flHosts.Len() > 1 {
  178. log.Fatal("Please specify only one -H")
  179. }
  180. protoAddrParts := strings.SplitN(flHosts.GetAll()[0], "://", 2)
  181. var (
  182. cli *client.DockerCli
  183. tlsConfig tls.Config
  184. )
  185. tlsConfig.InsecureSkipVerify = true
  186. // If we should verify the server, we need to load a trusted ca
  187. if *flTlsVerify {
  188. *flTls = true
  189. certPool := x509.NewCertPool()
  190. file, err := ioutil.ReadFile(*flCa)
  191. if err != nil {
  192. log.Fatalf("Couldn't read ca cert %s: %s", *flCa, err)
  193. }
  194. certPool.AppendCertsFromPEM(file)
  195. tlsConfig.RootCAs = certPool
  196. tlsConfig.InsecureSkipVerify = false
  197. }
  198. // If tls is enabled, try to load and send client certificates
  199. if *flTls || *flTlsVerify {
  200. _, errCert := os.Stat(*flCert)
  201. _, errKey := os.Stat(*flKey)
  202. if errCert == nil && errKey == nil {
  203. *flTls = true
  204. cert, err := tls.LoadX509KeyPair(*flCert, *flKey)
  205. if err != nil {
  206. log.Fatalf("Couldn't load X509 key pair: %s. Key encrypted?", err)
  207. }
  208. tlsConfig.Certificates = []tls.Certificate{cert}
  209. }
  210. }
  211. if *flTls || *flTlsVerify {
  212. cli = client.NewDockerCli(os.Stdin, os.Stdout, os.Stderr, protoAddrParts[0], protoAddrParts[1], &tlsConfig)
  213. } else {
  214. cli = client.NewDockerCli(os.Stdin, os.Stdout, os.Stderr, protoAddrParts[0], protoAddrParts[1], nil)
  215. }
  216. if err := cli.ParseCommands(flag.Args()...); err != nil {
  217. if sterr, ok := err.(*utils.StatusError); ok {
  218. if sterr.Status != "" {
  219. log.Println(sterr.Status)
  220. }
  221. os.Exit(sterr.StatusCode)
  222. }
  223. log.Fatal(err)
  224. }
  225. }
  226. }
  227. func showVersion() {
  228. fmt.Printf("Docker version %s, build %s\n", dockerversion.VERSION, dockerversion.GITCOMMIT)
  229. }
  230. func checkKernelAndArch() error {
  231. // Check for unsupported architectures
  232. if runtime.GOARCH != "amd64" {
  233. return fmt.Errorf("The docker runtime currently only supports amd64 (not %s). This will change in the future. Aborting.", runtime.GOARCH)
  234. }
  235. // Check for unsupported kernel versions
  236. // FIXME: it would be cleaner to not test for specific versions, but rather
  237. // test for specific functionalities.
  238. // Unfortunately we can't test for the feature "does not cause a kernel panic"
  239. // without actually causing a kernel panic, so we need this workaround until
  240. // the circumstances of pre-3.8 crashes are clearer.
  241. // For details see http://github.com/dotcloud/docker/issues/407
  242. if k, err := utils.GetKernelVersion(); err != nil {
  243. log.Printf("WARNING: %s\n", err)
  244. } else {
  245. if utils.CompareKernelVersion(k, &utils.KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0}) < 0 {
  246. if os.Getenv("DOCKER_NOWARN_KERNEL_VERSION") == "" {
  247. 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())
  248. }
  249. }
  250. }
  251. return nil
  252. }