Browse code

Remove Job from Info API

Two main things
- Create a real struct Info for all of the data with the proper types
- Add test for REST API get info

Signed-off-by: Hu Keping <hukeping@huawei.com>

Hu Keping authored on 2015/04/11 02:26:30
Showing 7 changed files
... ...
@@ -1,12 +1,11 @@
1 1
 package client
2 2
 
3 3
 import (
4
+	"encoding/json"
4 5
 	"fmt"
5 6
 	"os"
6
-	"time"
7 7
 
8
-	"github.com/Sirupsen/logrus"
9
-	"github.com/docker/docker/engine"
8
+	"github.com/docker/docker/api/types"
10 9
 	flag "github.com/docker/docker/pkg/mflag"
11 10
 	"github.com/docker/docker/pkg/units"
12 11
 )
... ...
@@ -19,127 +18,75 @@ func (cli *DockerCli) CmdInfo(args ...string) error {
19 19
 	cmd.Require(flag.Exact, 0)
20 20
 	cmd.ParseFlags(args, false)
21 21
 
22
-	body, _, err := readBody(cli.call("GET", "/info", nil, nil))
22
+	rdr, _, err := cli.call("GET", "/info", nil, nil)
23 23
 	if err != nil {
24 24
 		return err
25 25
 	}
26 26
 
27
-	out := engine.NewOutput()
28
-	remoteInfo, err := out.AddEnv()
29
-	if err != nil {
30
-		return err
27
+	info := &types.Info{}
28
+	if err := json.NewDecoder(rdr).Decode(info); err != nil {
29
+		return fmt.Errorf("Error reading remote info: %v", err)
31 30
 	}
32 31
 
33
-	if _, err := out.Write(body); err != nil {
34
-		logrus.Errorf("Error reading remote info: %s", err)
35
-		return err
36
-	}
37
-	out.Close()
38
-
39
-	if remoteInfo.Exists("Containers") {
40
-		fmt.Fprintf(cli.out, "Containers: %d\n", remoteInfo.GetInt("Containers"))
41
-	}
42
-	if remoteInfo.Exists("Images") {
43
-		fmt.Fprintf(cli.out, "Images: %d\n", remoteInfo.GetInt("Images"))
44
-	}
45
-	if remoteInfo.Exists("Driver") {
46
-		fmt.Fprintf(cli.out, "Storage Driver: %s\n", remoteInfo.Get("Driver"))
47
-	}
48
-	if remoteInfo.Exists("DriverStatus") {
49
-		var driverStatus [][2]string
50
-		if err := remoteInfo.GetJson("DriverStatus", &driverStatus); err != nil {
51
-			return err
52
-		}
53
-		for _, pair := range driverStatus {
32
+	fmt.Fprintf(cli.out, "Containers: %d\n", info.Containers)
33
+	fmt.Fprintf(cli.out, "Images: %d\n", info.Images)
34
+	fmt.Fprintf(cli.out, "Storage Driver: %s\n", info.Driver)
35
+	if info.DriverStatus != nil {
36
+		for _, pair := range info.DriverStatus {
54 37
 			fmt.Fprintf(cli.out, " %s: %s\n", pair[0], pair[1])
55 38
 		}
56 39
 	}
57
-	if remoteInfo.Exists("ExecutionDriver") {
58
-		fmt.Fprintf(cli.out, "Execution Driver: %s\n", remoteInfo.Get("ExecutionDriver"))
59
-	}
60
-	if remoteInfo.Exists("LoggingDriver") {
61
-		fmt.Fprintf(cli.out, "Logging Driver: %s\n", remoteInfo.Get("LoggingDriver"))
62
-	}
63
-	if remoteInfo.Exists("KernelVersion") {
64
-		fmt.Fprintf(cli.out, "Kernel Version: %s\n", remoteInfo.Get("KernelVersion"))
65
-	}
66
-	if remoteInfo.Exists("OperatingSystem") {
67
-		fmt.Fprintf(cli.out, "Operating System: %s\n", remoteInfo.Get("OperatingSystem"))
68
-	}
69
-	if remoteInfo.Exists("NCPU") {
70
-		fmt.Fprintf(cli.out, "CPUs: %d\n", remoteInfo.GetInt("NCPU"))
71
-	}
72
-	if remoteInfo.Exists("MemTotal") {
73
-		fmt.Fprintf(cli.out, "Total Memory: %s\n", units.BytesSize(float64(remoteInfo.GetInt64("MemTotal"))))
74
-	}
75
-	if remoteInfo.Exists("Name") {
76
-		fmt.Fprintf(cli.out, "Name: %s\n", remoteInfo.Get("Name"))
77
-	}
78
-	if remoteInfo.Exists("ID") {
79
-		fmt.Fprintf(cli.out, "ID: %s\n", remoteInfo.Get("ID"))
80
-	}
40
+	fmt.Fprintf(cli.out, "Execution Driver: %s\n", info.ExecutionDriver)
41
+	fmt.Fprintf(cli.out, "Logging Driver: %s\n", info.LoggingDriver)
42
+	fmt.Fprintf(cli.out, "Kernel Version: %s\n", info.KernelVersion)
43
+	fmt.Fprintf(cli.out, "Operating System: %s\n", info.OperatingSystem)
44
+	fmt.Fprintf(cli.out, "CPUs: %d\n", info.NCPU)
45
+	fmt.Fprintf(cli.out, "Total Memory: %s\n", units.BytesSize(float64(info.MemTotal)))
46
+	fmt.Fprintf(cli.out, "Name: %s\n", info.Name)
47
+	fmt.Fprintf(cli.out, "ID: %s\n", info.ID)
81 48
 
82
-	if remoteInfo.GetBool("Debug") || os.Getenv("DEBUG") != "" {
83
-		if remoteInfo.Exists("Debug") {
84
-			fmt.Fprintf(cli.out, "Debug mode (server): %v\n", remoteInfo.GetBool("Debug"))
85
-		}
49
+	if info.Debug || os.Getenv("DEBUG") != "" {
50
+		fmt.Fprintf(cli.out, "Debug mode (server): %v\n", info.Debug)
86 51
 		fmt.Fprintf(cli.out, "Debug mode (client): %v\n", os.Getenv("DEBUG") != "")
87
-		if remoteInfo.Exists("NFd") {
88
-			fmt.Fprintf(cli.out, "File Descriptors: %d\n", remoteInfo.GetInt("NFd"))
89
-		}
90
-		if remoteInfo.Exists("NGoroutines") {
91
-			fmt.Fprintf(cli.out, "Goroutines: %d\n", remoteInfo.GetInt("NGoroutines"))
92
-		}
93
-		if remoteInfo.Exists("SystemTime") {
94
-			t, err := remoteInfo.GetTime("SystemTime")
95
-			if err != nil {
96
-				logrus.Errorf("Error reading system time: %v", err)
97
-			} else {
98
-				fmt.Fprintf(cli.out, "System Time: %s\n", t.Format(time.UnixDate))
99
-			}
100
-		}
101
-		if remoteInfo.Exists("NEventsListener") {
102
-			fmt.Fprintf(cli.out, "EventsListeners: %d\n", remoteInfo.GetInt("NEventsListener"))
103
-		}
104
-		if initSha1 := remoteInfo.Get("InitSha1"); initSha1 != "" {
105
-			fmt.Fprintf(cli.out, "Init SHA1: %s\n", initSha1)
106
-		}
107
-		if initPath := remoteInfo.Get("InitPath"); initPath != "" {
108
-			fmt.Fprintf(cli.out, "Init Path: %s\n", initPath)
109
-		}
110
-		if root := remoteInfo.Get("DockerRootDir"); root != "" {
111
-			fmt.Fprintf(cli.out, "Docker Root Dir: %s\n", root)
112
-		}
52
+		fmt.Fprintf(cli.out, "File Descriptors: %d\n", info.NFd)
53
+		fmt.Fprintf(cli.out, "Goroutines: %d\n", info.NGoroutines)
54
+		fmt.Fprintf(cli.out, "System Time: %s\n", info.SystemTime)
55
+		fmt.Fprintf(cli.out, "EventsListeners: %d\n", info.NEventsListener)
56
+		fmt.Fprintf(cli.out, "Init SHA1: %s\n", info.InitSha1)
57
+		fmt.Fprintf(cli.out, "Init Path: %s\n", info.InitPath)
58
+		fmt.Fprintf(cli.out, "Docker Root Dir: %s\n", info.DockerRootDir)
113 59
 	}
114
-	if remoteInfo.Exists("HttpProxy") {
115
-		fmt.Fprintf(cli.out, "Http Proxy: %s\n", remoteInfo.Get("HttpProxy"))
60
+
61
+	if info.HttpProxy != "" {
62
+		fmt.Fprintf(cli.out, "Http Proxy: %s\n", info.HttpProxy)
116 63
 	}
117
-	if remoteInfo.Exists("HttpsProxy") {
118
-		fmt.Fprintf(cli.out, "Https Proxy: %s\n", remoteInfo.Get("HttpsProxy"))
64
+	if info.HttpsProxy != "" {
65
+		fmt.Fprintf(cli.out, "Https Proxy: %s\n", info.HttpsProxy)
119 66
 	}
120
-	if remoteInfo.Exists("NoProxy") {
121
-		fmt.Fprintf(cli.out, "No Proxy: %s\n", remoteInfo.Get("NoProxy"))
67
+	if info.NoProxy != "" {
68
+		fmt.Fprintf(cli.out, "No Proxy: %s\n", info.NoProxy)
122 69
 	}
123
-	if len(remoteInfo.GetList("IndexServerAddress")) != 0 {
70
+
71
+	if info.IndexServerAddress != "" {
124 72
 		cli.LoadConfigFile()
125
-		u := cli.configFile.Configs[remoteInfo.Get("IndexServerAddress")].Username
73
+		u := cli.configFile.Configs[info.IndexServerAddress].Username
126 74
 		if len(u) > 0 {
127 75
 			fmt.Fprintf(cli.out, "Username: %v\n", u)
128
-			fmt.Fprintf(cli.out, "Registry: %v\n", remoteInfo.GetList("IndexServerAddress"))
76
+			fmt.Fprintf(cli.out, "Registry: %v\n", info.IndexServerAddress)
129 77
 		}
130 78
 	}
131
-	if remoteInfo.Exists("MemoryLimit") && !remoteInfo.GetBool("MemoryLimit") {
79
+	if !info.MemoryLimit {
132 80
 		fmt.Fprintf(cli.err, "WARNING: No memory limit support\n")
133 81
 	}
134
-	if remoteInfo.Exists("SwapLimit") && !remoteInfo.GetBool("SwapLimit") {
82
+	if !info.SwapLimit {
135 83
 		fmt.Fprintf(cli.err, "WARNING: No swap limit support\n")
136 84
 	}
137
-	if remoteInfo.Exists("IPv4Forwarding") && !remoteInfo.GetBool("IPv4Forwarding") {
85
+	if !info.IPv4Forwarding {
138 86
 		fmt.Fprintf(cli.err, "WARNING: IPv4 forwarding is disabled.\n")
139 87
 	}
140
-	if remoteInfo.Exists("Labels") {
88
+	if info.Labels != nil {
141 89
 		fmt.Fprintln(cli.out, "Labels:")
142
-		for _, attribute := range remoteInfo.GetList("Labels") {
90
+		for _, attribute := range info.Labels {
143 91
 			fmt.Fprintf(cli.out, " %s\n", attribute)
144 92
 		}
145 93
 	}
... ...
@@ -367,8 +367,13 @@ func getImagesViz(eng *engine.Engine, version version.Version, w http.ResponseWr
367 367
 
368 368
 func getInfo(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
369 369
 	w.Header().Set("Content-Type", "application/json")
370
-	eng.ServeHTTP(w, r)
371
-	return nil
370
+
371
+	info, err := getDaemon(eng).SystemInfo()
372
+	if err != nil {
373
+		return err
374
+	}
375
+
376
+	return writeJSON(w, http.StatusOK, info)
372 377
 }
373 378
 
374 379
 func getEvents(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
... ...
@@ -34,33 +34,6 @@ func TesthttpError(t *testing.T) {
34 34
 	}
35 35
 }
36 36
 
37
-func TestGetInfo(t *testing.T) {
38
-	eng := engine.New()
39
-	var called bool
40
-	eng.Register("info", func(job *engine.Job) error {
41
-		called = true
42
-		v := &engine.Env{}
43
-		v.SetInt("Containers", 1)
44
-		v.SetInt("Images", 42000)
45
-		if _, err := v.WriteTo(job.Stdout); err != nil {
46
-			return err
47
-		}
48
-		return nil
49
-	})
50
-	r := serveRequest("GET", "/info", nil, eng, t)
51
-	if !called {
52
-		t.Fatalf("handler was not called")
53
-	}
54
-	v := readEnv(r.Body, t)
55
-	if v.GetInt("Images") != 42000 {
56
-		t.Fatalf("%#v\n", v)
57
-	}
58
-	if v.GetInt("Containers") != 1 {
59
-		t.Fatalf("%#v\n", v)
60
-	}
61
-	assertContentType(r, "application/json", t)
62
-}
63
-
64 37
 func TestGetContainersByName(t *testing.T) {
65 38
 	eng := engine.New()
66 39
 	name := "container_name"
... ...
@@ -122,3 +122,36 @@ type Version struct {
122 122
 	Arch          string
123 123
 	KernelVersion string `json:",omitempty"`
124 124
 }
125
+
126
+// GET "/info"
127
+type Info struct {
128
+	ID                 string
129
+	Containers         int
130
+	Images             int
131
+	Driver             string
132
+	DriverStatus       [][2]string
133
+	MemoryLimit        bool
134
+	SwapLimit          bool
135
+	IPv4Forwarding     bool
136
+	Debug              bool
137
+	NFd                int
138
+	NGoroutines        int
139
+	SystemTime         string
140
+	ExecutionDriver    string
141
+	LoggingDriver      string
142
+	NEventsListener    int
143
+	KernelVersion      string
144
+	OperatingSystem    string
145
+	IndexServerAddress string
146
+	RegistryConfig     interface{}
147
+	InitSha1           string
148
+	InitPath           string
149
+	NCPU               int
150
+	MemTotal           int64
151
+	DockerRootDir      string
152
+	HttpProxy          string
153
+	HttpsProxy         string
154
+	NoProxy            string
155
+	Name               string
156
+	Labels             []string
157
+}
... ...
@@ -119,7 +119,6 @@ type Daemon struct {
119 119
 func (daemon *Daemon) Install(eng *engine.Engine) error {
120 120
 	for name, method := range map[string]engine.Handler{
121 121
 		"container_inspect": daemon.ContainerInspect,
122
-		"info":              daemon.CmdInfo,
123 122
 		"execCreate":        daemon.ContainerExecCreate,
124 123
 		"execStart":         daemon.ContainerExecStart,
125 124
 	} {
... ...
@@ -6,8 +6,8 @@ import (
6 6
 	"time"
7 7
 
8 8
 	"github.com/Sirupsen/logrus"
9
+	"github.com/docker/docker/api/types"
9 10
 	"github.com/docker/docker/autogen/dockerversion"
10
-	"github.com/docker/docker/engine"
11 11
 	"github.com/docker/docker/pkg/fileutils"
12 12
 	"github.com/docker/docker/pkg/parsers/kernel"
13 13
 	"github.com/docker/docker/pkg/parsers/operatingsystem"
... ...
@@ -16,7 +16,7 @@ import (
16 16
 	"github.com/docker/docker/utils"
17 17
 )
18 18
 
19
-func (daemon *Daemon) CmdInfo(job *engine.Job) error {
19
+func (daemon *Daemon) SystemInfo() (*types.Info, error) {
20 20
 	images, _ := daemon.Graph().Map()
21 21
 	var imgcount int
22 22
 	if images == nil {
... ...
@@ -52,47 +52,46 @@ func (daemon *Daemon) CmdInfo(job *engine.Job) error {
52 52
 		initPath = daemon.SystemInitPath()
53 53
 	}
54 54
 
55
-	v := &engine.Env{}
56
-	v.SetJson("ID", daemon.ID)
57
-	v.SetInt("Containers", len(daemon.List()))
58
-	v.SetInt("Images", imgcount)
59
-	v.Set("Driver", daemon.GraphDriver().String())
60
-	v.SetJson("DriverStatus", daemon.GraphDriver().Status())
61
-	v.SetBool("MemoryLimit", daemon.SystemConfig().MemoryLimit)
62
-	v.SetBool("SwapLimit", daemon.SystemConfig().SwapLimit)
63
-	v.SetBool("IPv4Forwarding", !daemon.SystemConfig().IPv4ForwardingDisabled)
64
-	v.SetBool("Debug", os.Getenv("DEBUG") != "")
65
-	v.SetInt("NFd", fileutils.GetTotalUsedFds())
66
-	v.SetInt("NGoroutines", runtime.NumGoroutine())
67
-	v.Set("SystemTime", time.Now().Format(time.RFC3339Nano))
68
-	v.Set("ExecutionDriver", daemon.ExecutionDriver().Name())
69
-	v.Set("LoggingDriver", daemon.defaultLogConfig.Type)
70
-	v.SetInt("NEventsListener", daemon.EventsService.SubscribersCount())
71
-	v.Set("KernelVersion", kernelVersion)
72
-	v.Set("OperatingSystem", operatingSystem)
73
-	v.Set("IndexServerAddress", registry.IndexServerAddress())
74
-	v.SetJson("RegistryConfig", daemon.RegistryService.Config)
75
-	v.Set("InitSha1", dockerversion.INITSHA1)
76
-	v.Set("InitPath", initPath)
77
-	v.SetInt("NCPU", runtime.NumCPU())
78
-	v.SetInt64("MemTotal", meminfo.MemTotal)
79
-	v.Set("DockerRootDir", daemon.Config().Root)
55
+	v := &types.Info{
56
+		ID:                 daemon.ID,
57
+		Containers:         len(daemon.List()),
58
+		Images:             imgcount,
59
+		Driver:             daemon.GraphDriver().String(),
60
+		DriverStatus:       daemon.GraphDriver().Status(),
61
+		MemoryLimit:        daemon.SystemConfig().MemoryLimit,
62
+		SwapLimit:          daemon.SystemConfig().SwapLimit,
63
+		IPv4Forwarding:     !daemon.SystemConfig().IPv4ForwardingDisabled,
64
+		Debug:              os.Getenv("DEBUG") != "",
65
+		NFd:                fileutils.GetTotalUsedFds(),
66
+		NGoroutines:        runtime.NumGoroutine(),
67
+		SystemTime:         time.Now().Format(time.RFC3339Nano),
68
+		ExecutionDriver:    daemon.ExecutionDriver().Name(),
69
+		LoggingDriver:      daemon.defaultLogConfig.Type,
70
+		NEventsListener:    daemon.EventsService.SubscribersCount(),
71
+		KernelVersion:      kernelVersion,
72
+		OperatingSystem:    operatingSystem,
73
+		IndexServerAddress: registry.IndexServerAddress(),
74
+		RegistryConfig:     daemon.RegistryService.Config,
75
+		InitSha1:           dockerversion.INITSHA1,
76
+		InitPath:           initPath,
77
+		NCPU:               runtime.NumCPU(),
78
+		MemTotal:           meminfo.MemTotal,
79
+		DockerRootDir:      daemon.Config().Root,
80
+		Labels:             daemon.Config().Labels,
81
+	}
82
+
80 83
 	if httpProxy := os.Getenv("http_proxy"); httpProxy != "" {
81
-		v.Set("HttpProxy", httpProxy)
84
+		v.HttpProxy = httpProxy
82 85
 	}
83 86
 	if httpsProxy := os.Getenv("https_proxy"); httpsProxy != "" {
84
-		v.Set("HttpsProxy", httpsProxy)
87
+		v.HttpsProxy = httpsProxy
85 88
 	}
86 89
 	if noProxy := os.Getenv("no_proxy"); noProxy != "" {
87
-		v.Set("NoProxy", noProxy)
90
+		v.NoProxy = noProxy
88 91
 	}
89
-
90 92
 	if hostname, err := os.Hostname(); err == nil {
91
-		v.SetJson("Name", hostname)
93
+		v.Name = hostname
92 94
 	}
93
-	v.SetList("Labels", daemon.Config().Labels)
94
-	if _, err := v.WriteTo(job.Stdout); err != nil {
95
-		return err
96
-	}
97
-	return nil
95
+
96
+	return v, nil
98 97
 }
99 98
new file mode 100644
... ...
@@ -0,0 +1,38 @@
0
+package main
1
+
2
+import (
3
+	"net/http"
4
+	"strings"
5
+	"testing"
6
+)
7
+
8
+func TestInfoApi(t *testing.T) {
9
+	endpoint := "/info"
10
+
11
+	statusCode, body, err := sockRequest("GET", endpoint, nil)
12
+	if err != nil || statusCode != http.StatusOK {
13
+		t.Fatalf("Expected %d from info request, got %d", http.StatusOK, statusCode)
14
+	}
15
+
16
+	// always shown fields
17
+	stringsToCheck := []string{
18
+		"ID",
19
+		"Containers",
20
+		"Images",
21
+		"ExecutionDriver",
22
+		"LoggingDriver",
23
+		"OperatingSystem",
24
+		"NCPU",
25
+		"MemTotal",
26
+		"KernelVersion",
27
+		"Driver"}
28
+
29
+	out := string(body)
30
+	for _, linePrefix := range stringsToCheck {
31
+		if !strings.Contains(out, linePrefix) {
32
+			t.Errorf("couldn't find string %v in output", linePrefix)
33
+		}
34
+	}
35
+
36
+	logDone("container REST API - check GET /info")
37
+}