Browse code

Parse daemon configuration in daemon.Config.InstallFlags instead of main

Signed-off-by: Solomon Hykes <solomon@docker.com>

Solomon Hykes authored on 2014/08/10 10:18:32
Showing 6 changed files
... ...
@@ -1,8 +1,11 @@
1 1
 package daemon
2 2
 
3 3
 import (
4
-	"github.com/docker/docker/daemon/networkdriver"
5 4
 	"net"
5
+
6
+	"github.com/docker/docker/daemon/networkdriver"
7
+	"github.com/docker/docker/opts"
8
+	flag "github.com/docker/docker/pkg/mflag"
6 9
 )
7 10
 
8 11
 const (
... ...
@@ -11,7 +14,7 @@ const (
11 11
 )
12 12
 
13 13
 // Config define the configuration of a docker daemon
14
-//  These are the configuration settings that you pass
14
+// These are the configuration settings that you pass
15 15
 // to the docker daemon when you launch it with say: `docker -d -e lxc`
16 16
 // FIXME: separate runtime configuration from http api configuration
17 17
 type Config struct {
... ...
@@ -36,6 +39,31 @@ type Config struct {
36 36
 	Sockets                     []string
37 37
 }
38 38
 
39
+// InstallFlags adds command-line options to the top-level flag parser for
40
+// the current process.
41
+// Subsequent calls to `flag.Parse` will populate config with values parsed
42
+// from the command-line.
43
+func (config *Config) InstallFlags() {
44
+	flag.StringVar(&config.Pidfile, []string{"p", "-pidfile"}, "/var/run/docker.pid", "Path to use for daemon PID file")
45
+	flag.StringVar(&config.Root, []string{"g", "-graph"}, "/var/lib/docker", "Path to use as the root of the Docker runtime")
46
+	flag.BoolVar(&config.AutoRestart, []string{"r", "-restart"}, true, "Restart previously running containers")
47
+	flag.BoolVar(&config.EnableIptables, []string{"#iptables", "-iptables"}, true, "Enable Docker's addition of iptables rules")
48
+	flag.BoolVar(&config.EnableIpForward, []string{"#ip-forward", "-ip-forward"}, true, "Enable net.ipv4.ip_forward")
49
+	flag.StringVar(&config.BridgeIP, []string{"#bip", "-bip"}, "", "Use this CIDR notation address for the network bridge's IP, not compatible with -b")
50
+	flag.StringVar(&config.BridgeIface, []string{"b", "-bridge"}, "", "Attach containers to a pre-existing network bridge\nuse 'none' to disable container networking")
51
+	flag.BoolVar(&config.InterContainerCommunication, []string{"#icc", "-icc"}, true, "Enable inter-container communication")
52
+	flag.StringVar(&config.GraphDriver, []string{"s", "-storage-driver"}, "", "Force the Docker runtime to use a specific storage driver")
53
+	flag.StringVar(&config.ExecDriver, []string{"e", "-exec-driver"}, "native", "Force the Docker runtime to use a specific exec driver")
54
+	flag.BoolVar(&config.EnableSelinuxSupport, []string{"-selinux-enabled"}, false, "Enable selinux support. SELinux does not presently support the BTRFS storage driver")
55
+	flag.IntVar(&config.Mtu, []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
+	opts.IPVar(&config.DefaultIp, []string{"#ip", "-ip"}, "0.0.0.0", "Default IP address to use when binding container ports")
57
+	opts.ListVar(&config.GraphOptions, []string{"-storage-opt"}, "Set storage driver options")
58
+	// FIXME: why the inconsistency between "hosts" and "sockets"?
59
+	opts.HostListVar(&config.Sockets, []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.")
60
+	opts.IPListVar(&config.Dns, []string{"#dns", "-dns"}, "Force Docker to use specific DNS servers")
61
+	opts.DnsSearchListVar(&config.DnsSearch, []string{"-dns-search"}, "Force Docker to use specific DNS search domains")
62
+}
63
+
39 64
 func GetDefaultNetworkMtu() int {
40 65
 	if iface, err := networkdriver.GetDefaultRouteIface(); err == nil {
41 66
 		return iface.MTU
... ...
@@ -672,6 +672,14 @@ func NewDaemon(config *Config, eng *engine.Engine) (*Daemon, error) {
672 672
 }
673 673
 
674 674
 func NewDaemonFromDirectory(config *Config, eng *engine.Engine) (*Daemon, error) {
675
+	// Apply configuration defaults
676
+	if config.Mtu == 0 {
677
+		// FIXME: GetDefaultNetwork Mtu doesn't need to be public anymore
678
+		config.Mtu = GetDefaultNetworkMtu()
679
+	}
680
+	// FIXME: DisableNetworkBidge doesn't need to be public anymore
681
+	config.DisableNetwork = config.BridgeIface == DisableNetworkBridge
682
+
675 683
 	// Claim the pidfile first, to avoid any and all unexpected race conditions.
676 684
 	// Some of the init doesn't need a pidfile lock - but let's not try to be smart.
677 685
 	if config.Pidfile != "" {
... ...
@@ -4,7 +4,6 @@ package main
4 4
 
5 5
 import (
6 6
 	"log"
7
-	"net"
8 7
 
9 8
 	"github.com/docker/docker/builtins"
10 9
 	"github.com/docker/docker/daemon"
... ...
@@ -18,22 +17,32 @@ import (
18 18
 
19 19
 const CanDaemon = true
20 20
 
21
+var (
22
+	daemonCfg = &daemon.Config{}
23
+)
24
+
25
+func init() {
26
+	daemonCfg.InstallFlags()
27
+}
28
+
21 29
 func mainDaemon() {
22 30
 	if flag.NArg() != 0 {
23 31
 		flag.Usage()
24 32
 		return
25 33
 	}
26 34
 
27
-	if *bridgeName != "" && *bridgeIp != "" {
35
+	// FIXME: validate daemon.Config values in a method of daemon.Config
36
+	if daemonCfg.BridgeIface != "" && daemonCfg.BridgeIP != "" {
28 37
 		log.Fatal("You specified -b & --bip, mutually exclusive options. Please specify only one.")
29 38
 	}
30 39
 
31
-	if !*flEnableIptables && !*flInterContainerComm {
40
+	if !daemonCfg.EnableIptables && !daemonCfg.InterContainerCommunication {
32 41
 		log.Fatal("You specified --iptables=false with --icc=false. ICC uses iptables to function. Please set --icc or --iptables to true.")
33 42
 	}
34 43
 
35
-	if net.ParseIP(*flDefaultIp) == nil {
36
-		log.Fatalf("Specified --ip=%s is not in correct format \"0.0.0.0\".", *flDefaultIp)
44
+	// FIXME: move this validation to opts.IpOpt
45
+	if daemonCfg.DefaultIp == nil {
46
+		log.Fatalf("Specified --ip is not in correct format \"0.0.0.0\".")
37 47
 	}
38 48
 
39 49
 	eng := engine.New()
... ...
@@ -47,34 +56,7 @@ func mainDaemon() {
47 47
 	// the http api so that connections don't fail while the daemon
48 48
 	// is booting
49 49
 	go func() {
50
-		// FIXME: daemon config and CLI flag parsing should be directly integrated
51
-		cfg := &daemon.Config{
52
-			Pidfile:                     *pidfile,
53
-			Root:                        *flRoot,
54
-			AutoRestart:                 *flAutoRestart,
55
-			EnableIptables:              *flEnableIptables,
56
-			EnableIpForward:             *flEnableIpForward,
57
-			BridgeIP:                    *bridgeIp,
58
-			BridgeIface:                 *bridgeName,
59
-			DefaultIp:                   net.ParseIP(*flDefaultIp),
60
-			InterContainerCommunication: *flInterContainerComm,
61
-			GraphDriver:                 *flGraphDriver,
62
-			ExecDriver:                  *flExecDriver,
63
-			EnableSelinuxSupport:        *flSelinuxEnabled,
64
-			GraphOptions:                flGraphOpts.GetAll(),
65
-			Dns:                         flDns.GetAll(),
66
-			DnsSearch:                   flDnsSearch.GetAll(),
67
-			Mtu:                         *flMtu,
68
-			Sockets:                     flHosts.GetAll(),
69
-		}
70
-		// FIXME this should be initialized in NewDaemon or somewhere in daemon.
71
-		// Currently it is copy-pasted in `integration` to create test daemons that work.
72
-		if cfg.Mtu == 0 {
73
-			cfg.Mtu = daemon.GetDefaultNetworkMtu()
74
-		}
75
-		cfg.DisableNetwork = cfg.BridgeIface == daemon.DisableNetworkBridge
76
-
77
-		d, err := daemon.NewDaemon(cfg, eng)
50
+		d, err := daemon.NewDaemon(daemonCfg, eng)
78 51
 		if err != nil {
79 52
 			log.Fatal(err)
80 53
 		}
... ...
@@ -91,11 +73,13 @@ func mainDaemon() {
91 91
 	log.Printf("docker daemon: %s %s; execdriver: %s; graphdriver: %s",
92 92
 		dockerversion.VERSION,
93 93
 		dockerversion.GITCOMMIT,
94
-		*flExecDriver,
95
-		*flGraphDriver)
94
+		daemonCfg.ExecDriver,
95
+		daemonCfg.GraphDriver,
96
+	)
96 97
 
97 98
 	// Serve api
98
-	job := eng.Job("serveapi", flHosts.GetAll()...)
99
+	// FIXME: 'Sockets' should not be part of daemon.Config
100
+	job := eng.Job("serveapi", daemonCfg.Sockets...)
99 101
 	job.SetenvBool("Logging", true)
100 102
 	job.SetenvBool("EnableCors", *flEnableCors)
101 103
 	job.Setenv("Version", dockerversion.VERSION)
... ...
@@ -27,8 +27,8 @@ func main() {
27 27
 	if reexec.Init() {
28 28
 		return
29 29
 	}
30
-
31 30
 	flag.Parse()
31
+	// FIXME: validate daemon flags here
32 32
 
33 33
 	if *flVersion {
34 34
 		showVersion()
... ...
@@ -38,7 +38,7 @@ func main() {
38 38
 		os.Setenv("DEBUG", "1")
39 39
 	}
40 40
 
41
-	if flHosts.Len() == 0 {
41
+	if len(daemonCfg.Sockets) == 0 {
42 42
 		defaultHost := os.Getenv("DOCKER_HOST")
43 43
 		if defaultHost == "" || *flDaemon {
44 44
 			// If we do not have a host, default to unix socket
... ...
@@ -47,7 +47,7 @@ func main() {
47 47
 		if _, err := api.ValidateHost(defaultHost); err != nil {
48 48
 			log.Fatal(err)
49 49
 		}
50
-		flHosts.Set(defaultHost)
50
+		daemonCfg.Sockets = append(daemonCfg.Sockets, defaultHost)
51 51
 	}
52 52
 
53 53
 	if *flDaemon {
... ...
@@ -55,10 +55,10 @@ func main() {
55 55
 		return
56 56
 	}
57 57
 
58
-	if flHosts.Len() > 1 {
58
+	if len(daemonCfg.Sockets) > 1 {
59 59
 		log.Fatal("Please specify only one -H")
60 60
 	}
61
-	protoAddrParts := strings.SplitN(flHosts.GetAll()[0], "://", 2)
61
+	protoAddrParts := strings.SplitN(daemonCfg.Sockets[0], "://", 2)
62 62
 
63 63
 	var (
64 64
 		cli       *client.DockerCli
... ...
@@ -4,8 +4,6 @@ import (
4 4
 	"os"
5 5
 	"path/filepath"
6 6
 
7
-	"github.com/docker/docker/api"
8
-	"github.com/docker/docker/opts"
9 7
 	flag "github.com/docker/docker/pkg/mflag"
10 8
 )
11 9
 
... ...
@@ -20,30 +18,13 @@ func init() {
20 20
 }
21 21
 
22 22
 var (
23
-	flVersion            = flag.Bool([]string{"v", "-version"}, false, "Print version information and quit")
24
-	flDaemon             = flag.Bool([]string{"d", "-daemon"}, false, "Enable daemon mode")
25
-	flGraphOpts          = opts.NewListOpts(nil)
26
-	flDebug              = flag.Bool([]string{"D", "-debug"}, false, "Enable debug mode")
27
-	flAutoRestart        = flag.Bool([]string{"r", "-restart"}, true, "Restart previously running containers")
28
-	bridgeName           = flag.String([]string{"b", "-bridge"}, "", "Attach containers to a pre-existing network bridge\nuse 'none' to disable container networking")
29
-	bridgeIp             = flag.String([]string{"#bip", "-bip"}, "", "Use this CIDR notation address for the network bridge's IP, not compatible with -b")
30
-	pidfile              = flag.String([]string{"p", "-pidfile"}, "/var/run/docker.pid", "Path to use for daemon PID file")
31
-	flRoot               = flag.String([]string{"g", "-graph"}, "/var/lib/docker", "Path to use as the root of the Docker runtime")
32
-	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")
33
-	flEnableCors         = flag.Bool([]string{"#api-enable-cors", "-api-enable-cors"}, false, "Enable CORS headers in the remote API")
34
-	flDns                = opts.NewListOpts(opts.ValidateIPAddress)
35
-	flDnsSearch          = opts.NewListOpts(opts.ValidateDnsSearch)
36
-	flEnableIptables     = flag.Bool([]string{"#iptables", "-iptables"}, true, "Enable Docker's addition of iptables rules")
37
-	flEnableIpForward    = flag.Bool([]string{"#ip-forward", "-ip-forward"}, true, "Enable net.ipv4.ip_forward")
38
-	flDefaultIp          = flag.String([]string{"#ip", "-ip"}, "0.0.0.0", "Default IP address to use when binding container ports")
39
-	flInterContainerComm = flag.Bool([]string{"#icc", "-icc"}, true, "Enable inter-container communication")
40
-	flGraphDriver        = flag.String([]string{"s", "-storage-driver"}, "", "Force the Docker runtime to use a specific storage driver")
41
-	flExecDriver         = flag.String([]string{"e", "-exec-driver"}, "native", "Force the Docker runtime to use a specific exec driver")
42
-	flHosts              = opts.NewListOpts(api.ValidateHost)
43
-	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")
44
-	flTls                = flag.Bool([]string{"-tls"}, false, "Use TLS; implied by tls-verify flags")
45
-	flTlsVerify          = flag.Bool([]string{"-tlsverify"}, false, "Use TLS and verify the remote (daemon: verify client, client: verify daemon)")
46
-	flSelinuxEnabled     = flag.Bool([]string{"-selinux-enabled"}, false, "Enable selinux support. SELinux does not presently support the BTRFS storage driver")
23
+	flVersion     = flag.Bool([]string{"v", "-version"}, false, "Print version information and quit")
24
+	flDaemon      = flag.Bool([]string{"d", "-daemon"}, false, "Enable daemon mode")
25
+	flDebug       = flag.Bool([]string{"D", "-debug"}, false, "Enable debug mode")
26
+	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")
27
+	flEnableCors  = flag.Bool([]string{"#api-enable-cors", "-api-enable-cors"}, false, "Enable CORS headers in the remote API")
28
+	flTls         = flag.Bool([]string{"-tls"}, false, "Use TLS; implied by tls-verify flags")
29
+	flTlsVerify   = flag.Bool([]string{"-tlsverify"}, false, "Use TLS and verify the remote (daemon: verify client, client: verify daemon)")
47 30
 
48 31
 	// these are initialized in init() below since their default values depend on dockerCertPath which isn't fully initialized until init() runs
49 32
 	flCa   *string
... ...
@@ -55,9 +36,4 @@ func init() {
55 55
 	flCa = flag.String([]string{"-tlscacert"}, filepath.Join(dockerCertPath, defaultCaFile), "Trust only remotes providing a certificate signed by the CA given here")
56 56
 	flCert = flag.String([]string{"-tlscert"}, filepath.Join(dockerCertPath, defaultCertFile), "Path to TLS certificate file")
57 57
 	flKey = flag.String([]string{"-tlskey"}, filepath.Join(dockerCertPath, defaultKeyFile), "Path to TLS key file")
58
-
59
-	flag.Var(&flDns, []string{"#dns", "-dns"}, "Force Docker to use specific DNS servers")
60
-	flag.Var(&flDnsSearch, []string{"-dns-search"}, "Force Docker to use specific DNS search domains")
61
-	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.")
62
-	flag.Var(&flGraphOpts, []string{"-storage-opt"}, "Set storage driver options")
63 58
 }
... ...
@@ -186,12 +186,6 @@ func newTestEngine(t utils.Fataler, autorestart bool, root string) *engine.Engin
186 186
 		// otherwise NewDaemon will fail because of conflicting settings.
187 187
 		InterContainerCommunication: true,
188 188
 	}
189
-	// FIXME: this should be initialized in NewDaemon
190
-	// Currently it is copy-pasted from daemonMain()
191
-	if cfg.Mtu == 0 {
192
-		cfg.Mtu = daemon.GetDefaultNetworkMtu()
193
-	}
194
-	cfg.DisableNetwork = cfg.BridgeIface == daemon.DisableNetworkBridge
195 189
 	d, err := daemon.NewDaemon(cfg, eng)
196 190
 	if err != nil {
197 191
 		t.Fatal(err)