Stop using deprecated SockRequest

Signed-off-by: Stanislav Bondarenko <stanislav.bondarenko@gmail.com>
This commit is contained in:
Stanislav Bondarenko 2017-05-23 23:56:26 -04:00
parent cdf870bd0b
commit 0fd5a65428
32 changed files with 1399 additions and 1165 deletions

View File

@ -14,8 +14,10 @@ import (
"strings" "strings"
"time" "time"
"github.com/docker/docker/api"
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/events" "github.com/docker/docker/api/types/events"
"github.com/docker/docker/client"
"github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/integration-cli/checker"
"github.com/docker/docker/integration-cli/request" "github.com/docker/docker/integration-cli/request"
"github.com/docker/docker/opts" "github.com/docker/docker/opts"
@ -752,6 +754,16 @@ func (d *Daemon) ReloadConfig() error {
return nil return nil
} }
// NewClient creates new client based on daemon's socket path
func (d *Daemon) NewClient() (*client.Client, error) {
httpClient, err := request.NewHTTPClient(d.Sock())
if err != nil {
return nil, err
}
return client.NewClient(d.Sock(), api.DefaultVersion, httpClient, nil)
}
// WaitInspectWithArgs waits for the specified expression to be equals to the specified expected string in the given time. // WaitInspectWithArgs waits for the specified expression to be equals to the specified expected string in the given time.
// Deprecated: use cli.WaitCmd instead // Deprecated: use cli.WaitCmd instead
func WaitInspectWithArgs(dockerBinary, name, expr, expected string, timeout time.Duration, arg ...string) error { func WaitInspectWithArgs(dockerBinary, name, expr, expected string, timeout time.Duration, arg ...string) error {

View File

@ -1,7 +1,6 @@
package daemon package daemon
import ( import (
"context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"net/http" "net/http"
@ -11,10 +10,10 @@ import (
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/filters" "github.com/docker/docker/api/types/filters"
"github.com/docker/docker/api/types/swarm" "github.com/docker/docker/api/types/swarm"
"github.com/docker/docker/client"
"github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/integration-cli/checker"
"github.com/go-check/check" "github.com/go-check/check"
"github.com/pkg/errors" "github.com/pkg/errors"
"golang.org/x/net/context"
) )
// Swarm is a test daemon with helpers for participating in a swarm. // Swarm is a test daemon with helpers for participating in a swarm.
@ -30,10 +29,12 @@ func (d *Swarm) Init(req swarm.InitRequest) error {
if req.ListenAddr == "" { if req.ListenAddr == "" {
req.ListenAddr = d.ListenAddr req.ListenAddr = d.ListenAddr
} }
status, out, err := d.SockRequest("POST", "/swarm/init", req) cli, err := d.NewClient()
if status != http.StatusOK { if err != nil {
return fmt.Errorf("initializing swarm: invalid statuscode %v, %q", status, out) return fmt.Errorf("initializing swarm: failed to create client %v", err)
} }
defer cli.Close()
_, err = cli.SwarmInit(context.Background(), req)
if err != nil { if err != nil {
return fmt.Errorf("initializing swarm: %v", err) return fmt.Errorf("initializing swarm: %v", err)
} }
@ -50,10 +51,12 @@ func (d *Swarm) Join(req swarm.JoinRequest) error {
if req.ListenAddr == "" { if req.ListenAddr == "" {
req.ListenAddr = d.ListenAddr req.ListenAddr = d.ListenAddr
} }
status, out, err := d.SockRequest("POST", "/swarm/join", req) cli, err := d.NewClient()
if status != http.StatusOK { if err != nil {
return fmt.Errorf("joining swarm: invalid statuscode %v, %q", status, out) return fmt.Errorf("joining swarm: failed to create client %v", err)
} }
defer cli.Close()
err = cli.SwarmJoin(context.Background(), req)
if err != nil { if err != nil {
return fmt.Errorf("joining swarm: %v", err) return fmt.Errorf("joining swarm: %v", err)
} }
@ -67,14 +70,12 @@ func (d *Swarm) Join(req swarm.JoinRequest) error {
// Leave forces daemon to leave current cluster. // Leave forces daemon to leave current cluster.
func (d *Swarm) Leave(force bool) error { func (d *Swarm) Leave(force bool) error {
url := "/swarm/leave" cli, err := d.NewClient()
if force { if err != nil {
url += "?force=1" return fmt.Errorf("leaving swarm: failed to create client %v", err)
}
status, out, err := d.SockRequest("POST", url, nil)
if status != http.StatusOK {
return fmt.Errorf("leaving swarm: invalid statuscode %v, %q", status, out)
} }
defer cli.Close()
err = cli.SwarmLeave(context.Background(), force)
if err != nil { if err != nil {
err = fmt.Errorf("leaving swarm: %v", err) err = fmt.Errorf("leaving swarm: %v", err)
} }
@ -83,28 +84,27 @@ func (d *Swarm) Leave(force bool) error {
// SwarmInfo returns the swarm information of the daemon // SwarmInfo returns the swarm information of the daemon
func (d *Swarm) SwarmInfo() (swarm.Info, error) { func (d *Swarm) SwarmInfo() (swarm.Info, error) {
var info struct { cli, err := d.NewClient()
Swarm swarm.Info
}
status, dt, err := d.SockRequest("GET", "/info", nil)
if status != http.StatusOK {
return info.Swarm, fmt.Errorf("get swarm info: invalid statuscode %v", status)
}
if err != nil { if err != nil {
return info.Swarm, fmt.Errorf("get swarm info: %v", err) return swarm.Info{}, fmt.Errorf("get swarm info: %v", err)
} }
if err := json.Unmarshal(dt, &info); err != nil {
return info.Swarm, err info, err := cli.Info(context.Background())
if err != nil {
return swarm.Info{}, fmt.Errorf("get swarm info: %v", err)
} }
return info.Swarm, nil return info.Swarm, nil
} }
// Unlock tries to unlock a locked swarm // Unlock tries to unlock a locked swarm
func (d *Swarm) Unlock(req swarm.UnlockRequest) error { func (d *Swarm) Unlock(req swarm.UnlockRequest) error {
status, out, err := d.SockRequest("POST", "/swarm/unlock", req) cli, err := d.NewClient()
if status != http.StatusOK { if err != nil {
return fmt.Errorf("unlocking swarm: invalid statuscode %v, %q", status, out) return fmt.Errorf("unlocking swarm: failed to create client %v", err)
} }
defer cli.Close()
err = cli.SwarmUnlock(context.Background(), req)
if err != nil { if err != nil {
err = errors.Wrap(err, "unlocking swarm") err = errors.Wrap(err, "unlocking swarm")
} }
@ -129,19 +129,19 @@ type SpecConstructor func(*swarm.Spec)
// CreateServiceWithOptions creates a swarm service given the specified service constructors // CreateServiceWithOptions creates a swarm service given the specified service constructors
// and auth config // and auth config
func (d *Swarm) CreateServiceWithOptions(c *check.C, opts types.ServiceCreateOptions, f ...ServiceConstructor) string { func (d *Swarm) CreateServiceWithOptions(c *check.C, opts types.ServiceCreateOptions, f ...ServiceConstructor) string {
cl, err := client.NewClient(d.Sock(), "", nil, nil)
c.Assert(err, checker.IsNil, check.Commentf("failed to create client"))
defer cl.Close()
var service swarm.Service var service swarm.Service
for _, fn := range f { for _, fn := range f {
fn(&service) fn(&service)
} }
cli, err := d.NewClient()
c.Assert(err, checker.IsNil)
defer cli.Close()
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel() defer cancel()
res, err := cl.ServiceCreate(ctx, service.Spec, opts) res, err := cli.ServiceCreate(ctx, service.Spec, opts)
c.Assert(err, checker.IsNil) c.Assert(err, checker.IsNil)
return res.ID return res.ID
} }
@ -153,28 +153,31 @@ func (d *Swarm) CreateService(c *check.C, f ...ServiceConstructor) string {
// GetService returns the swarm service corresponding to the specified id // GetService returns the swarm service corresponding to the specified id
func (d *Swarm) GetService(c *check.C, id string) *swarm.Service { func (d *Swarm) GetService(c *check.C, id string) *swarm.Service {
var service swarm.Service cli, err := d.NewClient()
status, out, err := d.SockRequest("GET", "/services/"+id, nil) c.Assert(err, checker.IsNil)
c.Assert(err, checker.IsNil, check.Commentf(string(out))) defer cli.Close()
c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out)))
c.Assert(json.Unmarshal(out, &service), checker.IsNil) service, _, err := cli.ServiceInspectWithRaw(context.Background(), id, types.ServiceInspectOptions{})
c.Assert(err, checker.IsNil)
return &service return &service
} }
// GetServiceTasks returns the swarm tasks for the specified service // GetServiceTasks returns the swarm tasks for the specified service
func (d *Swarm) GetServiceTasks(c *check.C, service string) []swarm.Task { func (d *Swarm) GetServiceTasks(c *check.C, service string) []swarm.Task {
var tasks []swarm.Task cli, err := d.NewClient()
c.Assert(err, checker.IsNil)
defer cli.Close()
filterArgs := filters.NewArgs() filterArgs := filters.NewArgs()
filterArgs.Add("desired-state", "running") filterArgs.Add("desired-state", "running")
filterArgs.Add("service", service) filterArgs.Add("service", service)
filters, err := filters.ToParam(filterArgs)
c.Assert(err, checker.IsNil)
status, out, err := d.SockRequest("GET", "/tasks?filters="+filters, nil) options := types.TaskListOptions{
c.Assert(err, checker.IsNil, check.Commentf(string(out))) Filters: filterArgs,
c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out))) }
c.Assert(json.Unmarshal(out, &tasks), checker.IsNil)
tasks, err := cli.TaskList(context.Background(), options)
c.Assert(err, checker.IsNil)
return tasks return tasks
} }
@ -252,17 +255,19 @@ func (d *Swarm) CheckServiceTasks(service string) func(*check.C) (interface{}, c
// CheckRunningTaskNetworks returns the number of times each network is referenced from a task. // CheckRunningTaskNetworks returns the number of times each network is referenced from a task.
func (d *Swarm) CheckRunningTaskNetworks(c *check.C) (interface{}, check.CommentInterface) { func (d *Swarm) CheckRunningTaskNetworks(c *check.C) (interface{}, check.CommentInterface) {
var tasks []swarm.Task cli, err := d.NewClient()
c.Assert(err, checker.IsNil)
defer cli.Close()
filterArgs := filters.NewArgs() filterArgs := filters.NewArgs()
filterArgs.Add("desired-state", "running") filterArgs.Add("desired-state", "running")
filters, err := filters.ToParam(filterArgs)
c.Assert(err, checker.IsNil)
status, out, err := d.SockRequest("GET", "/tasks?filters="+filters, nil) options := types.TaskListOptions{
c.Assert(err, checker.IsNil, check.Commentf(string(out))) Filters: filterArgs,
c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out))) }
c.Assert(json.Unmarshal(out, &tasks), checker.IsNil)
tasks, err := cli.TaskList(context.Background(), options)
c.Assert(err, checker.IsNil)
result := make(map[string]int) result := make(map[string]int)
for _, task := range tasks { for _, task := range tasks {
@ -275,17 +280,19 @@ func (d *Swarm) CheckRunningTaskNetworks(c *check.C) (interface{}, check.Comment
// CheckRunningTaskImages returns the times each image is running as a task. // CheckRunningTaskImages returns the times each image is running as a task.
func (d *Swarm) CheckRunningTaskImages(c *check.C) (interface{}, check.CommentInterface) { func (d *Swarm) CheckRunningTaskImages(c *check.C) (interface{}, check.CommentInterface) {
var tasks []swarm.Task cli, err := d.NewClient()
c.Assert(err, checker.IsNil)
defer cli.Close()
filterArgs := filters.NewArgs() filterArgs := filters.NewArgs()
filterArgs.Add("desired-state", "running") filterArgs.Add("desired-state", "running")
filters, err := filters.ToParam(filterArgs)
c.Assert(err, checker.IsNil)
status, out, err := d.SockRequest("GET", "/tasks?filters="+filters, nil) options := types.TaskListOptions{
c.Assert(err, checker.IsNil, check.Commentf(string(out))) Filters: filterArgs,
c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out))) }
c.Assert(json.Unmarshal(out, &tasks), checker.IsNil)
tasks, err := cli.TaskList(context.Background(), options)
c.Assert(err, checker.IsNil)
result := make(map[string]int) result := make(map[string]int)
for _, task := range tasks { for _, task := range tasks {
@ -310,246 +317,281 @@ func (d *Swarm) CheckNodeReadyCount(c *check.C) (interface{}, check.CommentInter
// GetTask returns the swarm task identified by the specified id // GetTask returns the swarm task identified by the specified id
func (d *Swarm) GetTask(c *check.C, id string) swarm.Task { func (d *Swarm) GetTask(c *check.C, id string) swarm.Task {
var task swarm.Task cli, err := d.NewClient()
c.Assert(err, checker.IsNil)
defer cli.Close()
status, out, err := d.SockRequest("GET", "/tasks/"+id, nil) task, _, err := cli.TaskInspectWithRaw(context.Background(), id)
c.Assert(err, checker.IsNil, check.Commentf(string(out))) c.Assert(err, checker.IsNil)
c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out)))
c.Assert(json.Unmarshal(out, &task), checker.IsNil)
return task return task
} }
// UpdateService updates a swarm service with the specified service constructor // UpdateService updates a swarm service with the specified service constructor
func (d *Swarm) UpdateService(c *check.C, service *swarm.Service, f ...ServiceConstructor) { func (d *Swarm) UpdateService(c *check.C, service *swarm.Service, f ...ServiceConstructor) {
cli, err := d.NewClient()
c.Assert(err, checker.IsNil)
defer cli.Close()
for _, fn := range f { for _, fn := range f {
fn(service) fn(service)
} }
url := fmt.Sprintf("/services/%s/update?version=%d", service.ID, service.Version.Index)
status, out, err := d.SockRequest("POST", url, service.Spec) _, err = cli.ServiceUpdate(context.Background(), service.ID, service.Version, service.Spec, types.ServiceUpdateOptions{})
c.Assert(err, checker.IsNil, check.Commentf(string(out))) c.Assert(err, checker.IsNil)
c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out)))
} }
// RemoveService removes the specified service // RemoveService removes the specified service
func (d *Swarm) RemoveService(c *check.C, id string) { func (d *Swarm) RemoveService(c *check.C, id string) {
status, out, err := d.SockRequest("DELETE", "/services/"+id, nil) cli, err := d.NewClient()
c.Assert(err, checker.IsNil, check.Commentf(string(out))) c.Assert(err, checker.IsNil)
c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out))) defer cli.Close()
err = cli.ServiceRemove(context.Background(), id)
c.Assert(err, checker.IsNil)
} }
// GetNode returns a swarm node identified by the specified id // GetNode returns a swarm node identified by the specified id
func (d *Swarm) GetNode(c *check.C, id string) *swarm.Node { func (d *Swarm) GetNode(c *check.C, id string) *swarm.Node {
var node swarm.Node cli, err := d.NewClient()
status, out, err := d.SockRequest("GET", "/nodes/"+id, nil) c.Assert(err, checker.IsNil)
c.Assert(err, checker.IsNil, check.Commentf(string(out))) defer cli.Close()
c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out)))
c.Assert(json.Unmarshal(out, &node), checker.IsNil) node, _, err := cli.NodeInspectWithRaw(context.Background(), id)
c.Assert(err, checker.IsNil)
c.Assert(node.ID, checker.Equals, id) c.Assert(node.ID, checker.Equals, id)
return &node return &node
} }
// RemoveNode removes the specified node // RemoveNode removes the specified node
func (d *Swarm) RemoveNode(c *check.C, id string, force bool) { func (d *Swarm) RemoveNode(c *check.C, id string, force bool) {
url := "/nodes/" + id cli, err := d.NewClient()
if force { c.Assert(err, checker.IsNil)
url += "?force=1" defer cli.Close()
}
status, out, err := d.SockRequest("DELETE", url, nil) options := types.NodeRemoveOptions{
c.Assert(err, checker.IsNil, check.Commentf(string(out))) Force: force,
c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out))) }
err = cli.NodeRemove(context.Background(), id, options)
c.Assert(err, checker.IsNil)
} }
// UpdateNode updates a swarm node with the specified node constructor // UpdateNode updates a swarm node with the specified node constructor
func (d *Swarm) UpdateNode(c *check.C, id string, f ...NodeConstructor) { func (d *Swarm) UpdateNode(c *check.C, id string, f ...NodeConstructor) {
cli, err := d.NewClient()
c.Assert(err, checker.IsNil)
defer cli.Close()
for i := 0; ; i++ { for i := 0; ; i++ {
node := d.GetNode(c, id) node := d.GetNode(c, id)
for _, fn := range f { for _, fn := range f {
fn(node) fn(node)
} }
url := fmt.Sprintf("/nodes/%s/update?version=%d", node.ID, node.Version.Index)
status, out, err := d.SockRequest("POST", url, node.Spec) err = cli.NodeUpdate(context.Background(), node.ID, node.Version, node.Spec)
if i < 10 && strings.Contains(string(out), "update out of sequence") { if i < 10 && err != nil && strings.Contains(err.Error(), "update out of sequence") {
time.Sleep(100 * time.Millisecond) time.Sleep(100 * time.Millisecond)
continue continue
} }
c.Assert(err, checker.IsNil, check.Commentf(string(out))) c.Assert(err, checker.IsNil)
c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out)))
return return
} }
} }
// ListNodes returns the list of the current swarm nodes // ListNodes returns the list of the current swarm nodes
func (d *Swarm) ListNodes(c *check.C) []swarm.Node { func (d *Swarm) ListNodes(c *check.C) []swarm.Node {
status, out, err := d.SockRequest("GET", "/nodes", nil) cli, err := d.NewClient()
c.Assert(err, checker.IsNil, check.Commentf(string(out))) c.Assert(err, checker.IsNil)
c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out))) defer cli.Close()
nodes, err := cli.NodeList(context.Background(), types.NodeListOptions{})
c.Assert(err, checker.IsNil)
nodes := []swarm.Node{}
c.Assert(json.Unmarshal(out, &nodes), checker.IsNil)
return nodes return nodes
} }
// ListServices returns the list of the current swarm services // ListServices returns the list of the current swarm services
func (d *Swarm) ListServices(c *check.C) []swarm.Service { func (d *Swarm) ListServices(c *check.C) []swarm.Service {
status, out, err := d.SockRequest("GET", "/services", nil) cli, err := d.NewClient()
c.Assert(err, checker.IsNil, check.Commentf(string(out))) c.Assert(err, checker.IsNil)
c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out))) defer cli.Close()
services := []swarm.Service{} services, err := cli.ServiceList(context.Background(), types.ServiceListOptions{})
c.Assert(json.Unmarshal(out, &services), checker.IsNil) c.Assert(err, checker.IsNil)
return services return services
} }
// CreateSecret creates a secret given the specified spec // CreateSecret creates a secret given the specified spec
func (d *Swarm) CreateSecret(c *check.C, secretSpec swarm.SecretSpec) string { func (d *Swarm) CreateSecret(c *check.C, secretSpec swarm.SecretSpec) string {
status, out, err := d.SockRequest("POST", "/secrets/create", secretSpec) cli, err := d.NewClient()
c.Assert(err, checker.IsNil)
defer cli.Close()
c.Assert(err, checker.IsNil, check.Commentf(string(out))) scr, err := cli.SecretCreate(context.Background(), secretSpec)
c.Assert(status, checker.Equals, http.StatusCreated, check.Commentf("output: %q", string(out))) c.Assert(err, checker.IsNil)
var scr types.SecretCreateResponse
c.Assert(json.Unmarshal(out, &scr), checker.IsNil)
return scr.ID return scr.ID
} }
// ListSecrets returns the list of the current swarm secrets // ListSecrets returns the list of the current swarm secrets
func (d *Swarm) ListSecrets(c *check.C) []swarm.Secret { func (d *Swarm) ListSecrets(c *check.C) []swarm.Secret {
status, out, err := d.SockRequest("GET", "/secrets", nil) cli, err := d.NewClient()
c.Assert(err, checker.IsNil, check.Commentf(string(out))) c.Assert(err, checker.IsNil)
c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out))) defer cli.Close()
secrets := []swarm.Secret{} secrets, err := cli.SecretList(context.Background(), types.SecretListOptions{})
c.Assert(json.Unmarshal(out, &secrets), checker.IsNil) c.Assert(err, checker.IsNil)
return secrets return secrets
} }
// GetSecret returns a swarm secret identified by the specified id // GetSecret returns a swarm secret identified by the specified id
func (d *Swarm) GetSecret(c *check.C, id string) *swarm.Secret { func (d *Swarm) GetSecret(c *check.C, id string) *swarm.Secret {
var secret swarm.Secret cli, err := d.NewClient()
status, out, err := d.SockRequest("GET", "/secrets/"+id, nil) c.Assert(err, checker.IsNil)
c.Assert(err, checker.IsNil, check.Commentf(string(out))) defer cli.Close()
c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out)))
c.Assert(json.Unmarshal(out, &secret), checker.IsNil) secret, _, err := cli.SecretInspectWithRaw(context.Background(), id)
c.Assert(err, checker.IsNil)
return &secret return &secret
} }
// DeleteSecret removes the swarm secret identified by the specified id // DeleteSecret removes the swarm secret identified by the specified id
func (d *Swarm) DeleteSecret(c *check.C, id string) { func (d *Swarm) DeleteSecret(c *check.C, id string) {
status, out, err := d.SockRequest("DELETE", "/secrets/"+id, nil) cli, err := d.NewClient()
c.Assert(err, checker.IsNil, check.Commentf(string(out))) c.Assert(err, checker.IsNil)
c.Assert(status, checker.Equals, http.StatusNoContent, check.Commentf("output: %q", string(out))) defer cli.Close()
err = cli.SecretRemove(context.Background(), id)
c.Assert(err, checker.IsNil)
} }
// UpdateSecret updates the swarm secret identified by the specified id // UpdateSecret updates the swarm secret identified by the specified id
// Currently, only label update is supported. // Currently, only label update is supported.
func (d *Swarm) UpdateSecret(c *check.C, id string, f ...SecretConstructor) { func (d *Swarm) UpdateSecret(c *check.C, id string, f ...SecretConstructor) {
cli, err := d.NewClient()
c.Assert(err, checker.IsNil)
defer cli.Close()
secret := d.GetSecret(c, id) secret := d.GetSecret(c, id)
for _, fn := range f { for _, fn := range f {
fn(secret) fn(secret)
} }
url := fmt.Sprintf("/secrets/%s/update?version=%d", secret.ID, secret.Version.Index)
status, out, err := d.SockRequest("POST", url, secret.Spec) err = cli.SecretUpdate(context.Background(), secret.ID, secret.Version, secret.Spec)
c.Assert(err, checker.IsNil, check.Commentf(string(out)))
c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out))) c.Assert(err, checker.IsNil)
} }
// CreateConfig creates a config given the specified spec // CreateConfig creates a config given the specified spec
func (d *Swarm) CreateConfig(c *check.C, configSpec swarm.ConfigSpec) string { func (d *Swarm) CreateConfig(c *check.C, configSpec swarm.ConfigSpec) string {
status, out, err := d.SockRequest("POST", "/configs/create", configSpec) cli, err := d.NewClient()
c.Assert(err, checker.IsNil)
defer cli.Close()
c.Assert(err, checker.IsNil, check.Commentf(string(out))) scr, err := cli.ConfigCreate(context.Background(), configSpec)
c.Assert(status, checker.Equals, http.StatusCreated, check.Commentf("output: %q", string(out))) c.Assert(err, checker.IsNil)
var scr types.ConfigCreateResponse
c.Assert(json.Unmarshal(out, &scr), checker.IsNil)
return scr.ID return scr.ID
} }
// ListConfigs returns the list of the current swarm configs // ListConfigs returns the list of the current swarm configs
func (d *Swarm) ListConfigs(c *check.C) []swarm.Config { func (d *Swarm) ListConfigs(c *check.C) []swarm.Config {
status, out, err := d.SockRequest("GET", "/configs", nil) cli, err := d.NewClient()
c.Assert(err, checker.IsNil, check.Commentf(string(out))) c.Assert(err, checker.IsNil)
c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out))) defer cli.Close()
configs := []swarm.Config{} configs, err := cli.ConfigList(context.Background(), types.ConfigListOptions{})
c.Assert(json.Unmarshal(out, &configs), checker.IsNil) c.Assert(err, checker.IsNil)
return configs return configs
} }
// GetConfig returns a swarm config identified by the specified id // GetConfig returns a swarm config identified by the specified id
func (d *Swarm) GetConfig(c *check.C, id string) *swarm.Config { func (d *Swarm) GetConfig(c *check.C, id string) *swarm.Config {
var config swarm.Config cli, err := d.NewClient()
status, out, err := d.SockRequest("GET", "/configs/"+id, nil) c.Assert(err, checker.IsNil)
c.Assert(err, checker.IsNil, check.Commentf(string(out))) defer cli.Close()
c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out)))
c.Assert(json.Unmarshal(out, &config), checker.IsNil) config, _, err := cli.ConfigInspectWithRaw(context.Background(), id)
c.Assert(err, checker.IsNil)
return &config return &config
} }
// DeleteConfig removes the swarm config identified by the specified id // DeleteConfig removes the swarm config identified by the specified id
func (d *Swarm) DeleteConfig(c *check.C, id string) { func (d *Swarm) DeleteConfig(c *check.C, id string) {
status, out, err := d.SockRequest("DELETE", "/configs/"+id, nil) cli, err := d.NewClient()
c.Assert(err, checker.IsNil, check.Commentf(string(out))) c.Assert(err, checker.IsNil)
c.Assert(status, checker.Equals, http.StatusNoContent, check.Commentf("output: %q", string(out))) defer cli.Close()
err = cli.ConfigRemove(context.Background(), id)
c.Assert(err, checker.IsNil)
} }
// UpdateConfig updates the swarm config identified by the specified id // UpdateConfig updates the swarm config identified by the specified id
// Currently, only label update is supported. // Currently, only label update is supported.
func (d *Swarm) UpdateConfig(c *check.C, id string, f ...ConfigConstructor) { func (d *Swarm) UpdateConfig(c *check.C, id string, f ...ConfigConstructor) {
cli, err := d.NewClient()
c.Assert(err, checker.IsNil)
defer cli.Close()
config := d.GetConfig(c, id) config := d.GetConfig(c, id)
for _, fn := range f { for _, fn := range f {
fn(config) fn(config)
} }
url := fmt.Sprintf("/configs/%s/update?version=%d", config.ID, config.Version.Index)
status, out, err := d.SockRequest("POST", url, config.Spec) err = cli.ConfigUpdate(context.Background(), config.ID, config.Version, config.Spec)
c.Assert(err, checker.IsNil, check.Commentf(string(out))) c.Assert(err, checker.IsNil)
c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out)))
} }
// GetSwarm returns the current swarm object // GetSwarm returns the current swarm object
func (d *Swarm) GetSwarm(c *check.C) swarm.Swarm { func (d *Swarm) GetSwarm(c *check.C) swarm.Swarm {
var sw swarm.Swarm cli, err := d.NewClient()
status, out, err := d.SockRequest("GET", "/swarm", nil) c.Assert(err, checker.IsNil)
c.Assert(err, checker.IsNil, check.Commentf(string(out))) defer cli.Close()
c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out)))
c.Assert(json.Unmarshal(out, &sw), checker.IsNil) sw, err := cli.SwarmInspect(context.Background())
c.Assert(err, checker.IsNil)
return sw return sw
} }
// UpdateSwarm updates the current swarm object with the specified spec constructors // UpdateSwarm updates the current swarm object with the specified spec constructors
func (d *Swarm) UpdateSwarm(c *check.C, f ...SpecConstructor) { func (d *Swarm) UpdateSwarm(c *check.C, f ...SpecConstructor) {
cli, err := d.NewClient()
c.Assert(err, checker.IsNil)
defer cli.Close()
sw := d.GetSwarm(c) sw := d.GetSwarm(c)
for _, fn := range f { for _, fn := range f {
fn(&sw.Spec) fn(&sw.Spec)
} }
url := fmt.Sprintf("/swarm/update?version=%d", sw.Version.Index)
status, out, err := d.SockRequest("POST", url, sw.Spec) err = cli.SwarmUpdate(context.Background(), sw.Version, sw.Spec, swarm.UpdateFlags{})
c.Assert(err, checker.IsNil, check.Commentf(string(out))) c.Assert(err, checker.IsNil)
c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out)))
} }
// RotateTokens update the swarm to rotate tokens // RotateTokens update the swarm to rotate tokens
func (d *Swarm) RotateTokens(c *check.C) { func (d *Swarm) RotateTokens(c *check.C) {
var sw swarm.Swarm cli, err := d.NewClient()
status, out, err := d.SockRequest("GET", "/swarm", nil) c.Assert(err, checker.IsNil)
c.Assert(err, checker.IsNil, check.Commentf(string(out))) defer cli.Close()
c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out)))
c.Assert(json.Unmarshal(out, &sw), checker.IsNil)
url := fmt.Sprintf("/swarm/update?version=%d&rotateWorkerToken=true&rotateManagerToken=true", sw.Version.Index) sw, err := cli.SwarmInspect(context.Background())
status, out, err = d.SockRequest("POST", url, sw.Spec) c.Assert(err, checker.IsNil)
c.Assert(err, checker.IsNil, check.Commentf(string(out)))
c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out))) flags := swarm.UpdateFlags{
RotateManagerToken: true,
RotateWorkerToken: true,
}
err = cli.SwarmUpdate(context.Background(), sw.Version, sw.Spec, flags)
c.Assert(err, checker.IsNil)
} }
// JoinTokens returns the current swarm join tokens // JoinTokens returns the current swarm join tokens
func (d *Swarm) JoinTokens(c *check.C) swarm.JoinTokens { func (d *Swarm) JoinTokens(c *check.C) swarm.JoinTokens {
var sw swarm.Swarm cli, err := d.NewClient()
status, out, err := d.SockRequest("GET", "/swarm", nil) c.Assert(err, checker.IsNil)
c.Assert(err, checker.IsNil, check.Commentf(string(out))) defer cli.Close()
c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out)))
c.Assert(json.Unmarshal(out, &sw), checker.IsNil) sw, err := cli.SwarmInspect(context.Background())
c.Assert(err, checker.IsNil)
return sw.JoinTokens return sw.JoinTokens
} }
@ -570,17 +612,14 @@ func (d *Swarm) CheckControlAvailable(c *check.C) (interface{}, check.CommentInt
// CheckLeader returns whether there is a leader on the swarm or not // CheckLeader returns whether there is a leader on the swarm or not
func (d *Swarm) CheckLeader(c *check.C) (interface{}, check.CommentInterface) { func (d *Swarm) CheckLeader(c *check.C) (interface{}, check.CommentInterface) {
errList := check.Commentf("could not get node list") cli, err := d.NewClient()
status, out, err := d.SockRequest("GET", "/nodes", nil) c.Assert(err, checker.IsNil)
if err != nil { defer cli.Close()
return err, errList
}
if status != http.StatusOK {
return fmt.Errorf("expected http status OK, got: %d", status), errList
}
var ls []swarm.Node errList := check.Commentf("could not get node list")
if err := json.Unmarshal(out, &ls); err != nil {
ls, err := cli.NodeList(context.Background(), types.NodeListOptions{})
if err != nil {
return err, errList return err, errList
} }

View File

@ -86,11 +86,13 @@ func (s *DockerSuite) TestPostContainersAttachContainerNotFound(c *check.C) {
} }
func (s *DockerSuite) TestGetContainersWsAttachContainerNotFound(c *check.C) { func (s *DockerSuite) TestGetContainersWsAttachContainerNotFound(c *check.C) {
status, body, err := request.SockRequest("GET", "/containers/doesnotexist/attach/ws", nil, daemonHost()) res, body, err := request.Get("/containers/doesnotexist/attach/ws")
c.Assert(status, checker.Equals, http.StatusNotFound) c.Assert(res.StatusCode, checker.Equals, http.StatusNotFound)
c.Assert(err, checker.IsNil)
b, err := request.ReadBody(body)
c.Assert(err, checker.IsNil) c.Assert(err, checker.IsNil)
expected := "No such container: doesnotexist" expected := "No such container: doesnotexist"
c.Assert(getErrorMessage(c, body), checker.Contains, expected) c.Assert(getErrorMessage(c, b), checker.Contains, expected)
} }
func (s *DockerSuite) TestPostContainersAttach(c *check.C) { func (s *DockerSuite) TestPostContainersAttach(c *check.C) {
@ -177,6 +179,7 @@ func (s *DockerSuite) TestPostContainersAttach(c *check.C) {
// Make sure we don't see "hello" if Logs is false // Make sure we don't see "hello" if Logs is false
client, err := client.NewEnvClient() client, err := client.NewEnvClient()
c.Assert(err, checker.IsNil) c.Assert(err, checker.IsNil)
defer client.Close()
cid, _ = dockerCmd(c, "run", "-di", "busybox", "/bin/sh", "-c", "echo hello; cat") cid, _ = dockerCmd(c, "run", "-di", "busybox", "/bin/sh", "-c", "echo hello; cat")
cid = strings.TrimSpace(cid) cid = strings.TrimSpace(cid)

View File

@ -1,12 +1,11 @@
package main package main
import ( import (
"net/http"
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/docker/docker/client"
"github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/integration-cli/checker"
"github.com/docker/docker/integration-cli/request"
"github.com/go-check/check" "github.com/go-check/check"
"golang.org/x/net/context"
) )
// Test case for #22244 // Test case for #22244
@ -16,11 +15,11 @@ func (s *DockerSuite) TestAuthAPI(c *check.C) {
Username: "no-user", Username: "no-user",
Password: "no-password", Password: "no-password",
} }
cli, err := client.NewEnvClient()
c.Assert(err, checker.IsNil)
defer cli.Close()
_, err = cli.RegistryLogin(context.Background(), config)
expected := "Get https://registry-1.docker.io/v2/: unauthorized: incorrect username or password" expected := "Get https://registry-1.docker.io/v2/: unauthorized: incorrect username or password"
status, body, err := request.SockRequest("POST", "/auth", config, daemonHost()) c.Assert(err.Error(), checker.Contains, expected)
c.Assert(err, check.IsNil)
c.Assert(status, check.Equals, http.StatusUnauthorized)
msg := getErrorMessage(c, body)
c.Assert(msg, checker.Contains, expected, check.Commentf("Expected: %v, got: %v", expected, msg))
} }

File diff suppressed because it is too large Load Diff

View File

@ -23,11 +23,15 @@ func (s *DockerSuite) TestAPICreateWithInvalidHealthcheckParams(c *check.C) {
}, },
} }
status, body, err := request.SockRequest("POST", "/containers/create?name="+name, config, daemonHost()) res, body, err := request.Post("/containers/create?name="+name, request.JSONBody(config))
c.Assert(err, check.IsNil) c.Assert(err, check.IsNil)
c.Assert(status, check.Equals, http.StatusBadRequest) c.Assert(res.StatusCode, check.Equals, http.StatusBadRequest)
buf, err := request.ReadBody(body)
c.Assert(err, checker.IsNil)
expected := fmt.Sprintf("Interval in Healthcheck cannot be less than %s", container.MinimumDuration) expected := fmt.Sprintf("Interval in Healthcheck cannot be less than %s", container.MinimumDuration)
c.Assert(getErrorMessage(c, body), checker.Contains, expected) c.Assert(getErrorMessage(c, buf), checker.Contains, expected)
// test invalid Interval in Healthcheck: larger than 0s but less than 1ms // test invalid Interval in Healthcheck: larger than 0s but less than 1ms
name = "test2" name = "test2"
@ -39,10 +43,14 @@ func (s *DockerSuite) TestAPICreateWithInvalidHealthcheckParams(c *check.C) {
"Retries": int(1000), "Retries": int(1000),
}, },
} }
status, body, err = request.SockRequest("POST", "/containers/create?name="+name, config, daemonHost()) res, body, err = request.Post("/containers/create?name="+name, request.JSONBody(config))
c.Assert(err, check.IsNil) c.Assert(err, check.IsNil)
c.Assert(status, check.Equals, http.StatusBadRequest)
c.Assert(getErrorMessage(c, body), checker.Contains, expected) buf, err = request.ReadBody(body)
c.Assert(err, checker.IsNil)
c.Assert(res.StatusCode, check.Equals, http.StatusBadRequest)
c.Assert(getErrorMessage(c, buf), checker.Contains, expected)
// test invalid Timeout in Healthcheck: less than 1ms // test invalid Timeout in Healthcheck: less than 1ms
name = "test3" name = "test3"
@ -54,11 +62,15 @@ func (s *DockerSuite) TestAPICreateWithInvalidHealthcheckParams(c *check.C) {
"Retries": int(1000), "Retries": int(1000),
}, },
} }
status, body, err = request.SockRequest("POST", "/containers/create?name="+name, config, daemonHost()) res, body, err = request.Post("/containers/create?name="+name, request.JSONBody(config))
c.Assert(err, check.IsNil) c.Assert(err, check.IsNil)
c.Assert(status, check.Equals, http.StatusBadRequest) c.Assert(res.StatusCode, check.Equals, http.StatusBadRequest)
buf, err = request.ReadBody(body)
c.Assert(err, checker.IsNil)
expected = fmt.Sprintf("Timeout in Healthcheck cannot be less than %s", container.MinimumDuration) expected = fmt.Sprintf("Timeout in Healthcheck cannot be less than %s", container.MinimumDuration)
c.Assert(getErrorMessage(c, body), checker.Contains, expected) c.Assert(getErrorMessage(c, buf), checker.Contains, expected)
// test invalid Retries in Healthcheck: less than 0 // test invalid Retries in Healthcheck: less than 0
name = "test4" name = "test4"
@ -70,11 +82,15 @@ func (s *DockerSuite) TestAPICreateWithInvalidHealthcheckParams(c *check.C) {
"Retries": int(-10), "Retries": int(-10),
}, },
} }
status, body, err = request.SockRequest("POST", "/containers/create?name="+name, config, daemonHost()) res, body, err = request.Post("/containers/create?name="+name, request.JSONBody(config))
c.Assert(err, check.IsNil) c.Assert(err, check.IsNil)
c.Assert(status, check.Equals, http.StatusBadRequest) c.Assert(res.StatusCode, check.Equals, http.StatusBadRequest)
buf, err = request.ReadBody(body)
c.Assert(err, checker.IsNil)
expected = "Retries in Healthcheck cannot be negative" expected = "Retries in Healthcheck cannot be negative"
c.Assert(getErrorMessage(c, body), checker.Contains, expected) c.Assert(getErrorMessage(c, buf), checker.Contains, expected)
// test invalid StartPeriod in Healthcheck: not 0 and less than 1ms // test invalid StartPeriod in Healthcheck: not 0 and less than 1ms
name = "test3" name = "test3"
@ -87,9 +103,13 @@ func (s *DockerSuite) TestAPICreateWithInvalidHealthcheckParams(c *check.C) {
"StartPeriod": 100 * time.Microsecond, "StartPeriod": 100 * time.Microsecond,
}, },
} }
status, body, err = request.SockRequest("POST", "/containers/create?name="+name, config, daemonHost()) res, body, err = request.Post("/containers/create?name="+name, request.JSONBody(config))
c.Assert(err, check.IsNil) c.Assert(err, check.IsNil)
c.Assert(status, check.Equals, http.StatusBadRequest) c.Assert(res.StatusCode, check.Equals, http.StatusBadRequest)
buf, err = request.ReadBody(body)
c.Assert(err, checker.IsNil)
expected = fmt.Sprintf("StartPeriod in Healthcheck cannot be less than %s", container.MinimumDuration) expected = fmt.Sprintf("StartPeriod in Healthcheck cannot be less than %s", container.MinimumDuration)
c.Assert(getErrorMessage(c, body), checker.Contains, expected) c.Assert(getErrorMessage(c, buf), checker.Contains, expected)
} }

View File

@ -20,9 +20,9 @@ func (s *DockerSuite) TestExecResizeAPIHeightWidthNoInt(c *check.C) {
cleanedContainerID := strings.TrimSpace(out) cleanedContainerID := strings.TrimSpace(out)
endpoint := "/exec/" + cleanedContainerID + "/resize?h=foo&w=bar" endpoint := "/exec/" + cleanedContainerID + "/resize?h=foo&w=bar"
status, _, err := request.SockRequest("POST", endpoint, nil, daemonHost()) res, _, err := request.Post(endpoint)
c.Assert(err, checker.IsNil) c.Assert(err, checker.IsNil)
c.Assert(status, checker.Equals, http.StatusBadRequest) c.Assert(res.StatusCode, checker.Equals, http.StatusBadRequest)
} }
// Part of #14845 // Part of #14845
@ -36,16 +36,19 @@ func (s *DockerSuite) TestExecResizeImmediatelyAfterExecStart(c *check.C) {
"Cmd": []string{"/bin/sh"}, "Cmd": []string{"/bin/sh"},
} }
uri := fmt.Sprintf("/containers/%s/exec", name) uri := fmt.Sprintf("/containers/%s/exec", name)
status, body, err := request.SockRequest("POST", uri, data, daemonHost()) res, body, err := request.Post(uri, request.JSONBody(data))
if err != nil { if err != nil {
return err return err
} }
if status != http.StatusCreated { if res.StatusCode != http.StatusCreated {
return fmt.Errorf("POST %s is expected to return %d, got %d", uri, http.StatusCreated, status) return fmt.Errorf("POST %s is expected to return %d, got %d", uri, http.StatusCreated, res.StatusCode)
} }
buf, err := request.ReadBody(body)
c.Assert(err, checker.IsNil)
out := map[string]string{} out := map[string]string{}
err = json.Unmarshal(body, &out) err = json.Unmarshal(buf, &out)
if err != nil { if err != nil {
return fmt.Errorf("ExecCreate returned invalid json. Error: %q", err.Error()) return fmt.Errorf("ExecCreate returned invalid json. Error: %q", err.Error())
} }

View File

@ -10,9 +10,12 @@ import (
"net/http" "net/http"
"time" "time"
"github.com/docker/docker/api/types"
"github.com/docker/docker/client"
"github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/integration-cli/checker"
"github.com/docker/docker/integration-cli/request" "github.com/docker/docker/integration-cli/request"
"github.com/go-check/check" "github.com/go-check/check"
"golang.org/x/net/context"
) )
// Regression test for #9414 // Regression test for #9414
@ -20,12 +23,15 @@ func (s *DockerSuite) TestExecAPICreateNoCmd(c *check.C) {
name := "exec_test" name := "exec_test"
dockerCmd(c, "run", "-d", "-t", "--name", name, "busybox", "/bin/sh") dockerCmd(c, "run", "-d", "-t", "--name", name, "busybox", "/bin/sh")
status, body, err := request.SockRequest("POST", fmt.Sprintf("/containers/%s/exec", name), map[string]interface{}{"Cmd": nil}, daemonHost()) res, body, err := request.Post(fmt.Sprintf("/containers/%s/exec", name), request.JSONBody(map[string]interface{}{"Cmd": nil}))
c.Assert(err, checker.IsNil)
c.Assert(res.StatusCode, checker.Equals, http.StatusBadRequest)
b, err := request.ReadBody(body)
c.Assert(err, checker.IsNil) c.Assert(err, checker.IsNil)
c.Assert(status, checker.Equals, http.StatusBadRequest)
comment := check.Commentf("Expected message when creating exec command with no Cmd specified") comment := check.Commentf("Expected message when creating exec command with no Cmd specified")
c.Assert(getErrorMessage(c, body), checker.Contains, "No exec command specified", comment) c.Assert(getErrorMessage(c, b), checker.Contains, "No exec command specified", comment)
} }
func (s *DockerSuite) TestExecAPICreateNoValidContentType(c *check.C) { func (s *DockerSuite) TestExecAPICreateNoValidContentType(c *check.C) {
@ -55,12 +61,18 @@ func (s *DockerSuite) TestExecAPICreateContainerPaused(c *check.C) {
dockerCmd(c, "run", "-d", "-t", "--name", name, "busybox", "/bin/sh") dockerCmd(c, "run", "-d", "-t", "--name", name, "busybox", "/bin/sh")
dockerCmd(c, "pause", name) dockerCmd(c, "pause", name)
status, body, err := request.SockRequest("POST", fmt.Sprintf("/containers/%s/exec", name), map[string]interface{}{"Cmd": []string{"true"}}, daemonHost())
cli, err := client.NewEnvClient()
c.Assert(err, checker.IsNil) c.Assert(err, checker.IsNil)
c.Assert(status, checker.Equals, http.StatusConflict) defer cli.Close()
config := types.ExecConfig{
Cmd: []string{"true"},
}
_, err = cli.ContainerExecCreate(context.Background(), name, config)
comment := check.Commentf("Expected message when creating exec command with Container %s is paused", name) comment := check.Commentf("Expected message when creating exec command with Container %s is paused", name)
c.Assert(getErrorMessage(c, body), checker.Contains, "Container "+name+" is paused, unpause the container before exec", comment) c.Assert(err.Error(), checker.Contains, "Container "+name+" is paused, unpause the container before exec", comment)
} }
func (s *DockerSuite) TestExecAPIStart(c *check.C) { func (s *DockerSuite) TestExecAPIStart(c *check.C) {
@ -128,22 +140,23 @@ func (s *DockerSuite) TestExecAPIStartMultipleTimesError(c *check.C) {
func (s *DockerSuite) TestExecAPIStartWithDetach(c *check.C) { func (s *DockerSuite) TestExecAPIStartWithDetach(c *check.C) {
name := "foo" name := "foo"
runSleepingContainer(c, "-d", "-t", "--name", name) runSleepingContainer(c, "-d", "-t", "--name", name)
data := map[string]interface{}{
"cmd": []string{"true"},
"AttachStdin": true,
}
_, b, err := request.SockRequest("POST", fmt.Sprintf("/containers/%s/exec", name), data, daemonHost())
c.Assert(err, checker.IsNil, check.Commentf(string(b)))
createResp := struct { config := types.ExecConfig{
ID string `json:"Id"` Cmd: []string{"true"},
}{} AttachStderr: true,
c.Assert(json.Unmarshal(b, &createResp), checker.IsNil, check.Commentf(string(b))) }
cli, err := client.NewEnvClient()
c.Assert(err, checker.IsNil)
defer cli.Close()
createResp, err := cli.ContainerExecCreate(context.Background(), name, config)
c.Assert(err, checker.IsNil)
_, body, err := request.Post(fmt.Sprintf("/exec/%s/start", createResp.ID), request.RawString(`{"Detach": true}`), request.JSON) _, body, err := request.Post(fmt.Sprintf("/exec/%s/start", createResp.ID), request.RawString(`{"Detach": true}`), request.JSON)
c.Assert(err, checker.IsNil) c.Assert(err, checker.IsNil)
b, err = request.ReadBody(body) b, err := request.ReadBody(body)
comment := check.Commentf("response body: %s", b) comment := check.Commentf("response body: %s", b)
c.Assert(err, checker.IsNil, comment) c.Assert(err, checker.IsNil, comment)

View File

@ -1,38 +1,40 @@
package main package main
import ( import (
"encoding/json"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"net/url"
"strings" "strings"
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/image" "github.com/docker/docker/api/types/filters"
"github.com/docker/docker/client"
"github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/integration-cli/checker"
"github.com/docker/docker/integration-cli/cli" "github.com/docker/docker/integration-cli/cli"
"github.com/docker/docker/integration-cli/cli/build" "github.com/docker/docker/integration-cli/cli/build"
"github.com/docker/docker/integration-cli/request" "github.com/docker/docker/integration-cli/request"
"github.com/go-check/check" "github.com/go-check/check"
"golang.org/x/net/context"
) )
func (s *DockerSuite) TestAPIImagesFilter(c *check.C) { func (s *DockerSuite) TestAPIImagesFilter(c *check.C) {
cli, err := client.NewEnvClient()
c.Assert(err, checker.IsNil)
defer cli.Close()
name := "utest:tag1" name := "utest:tag1"
name2 := "utest/docker:tag2" name2 := "utest/docker:tag2"
name3 := "utest:5000/docker:tag3" name3 := "utest:5000/docker:tag3"
for _, n := range []string{name, name2, name3} { for _, n := range []string{name, name2, name3} {
dockerCmd(c, "tag", "busybox", n) dockerCmd(c, "tag", "busybox", n)
} }
type image types.ImageSummary getImages := func(filter string) []types.ImageSummary {
getImages := func(filter string) []image { filters := filters.NewArgs()
v := url.Values{} filters.Add("reference", filter)
v.Set("filter", filter) options := types.ImageListOptions{
status, b, err := request.SockRequest("GET", "/images/json?"+v.Encode(), nil, daemonHost()) All: false,
c.Assert(err, checker.IsNil) Filters: filters,
c.Assert(status, checker.Equals, http.StatusOK) }
images, err := cli.ImageList(context.Background(), options)
var images []image
err = json.Unmarshal(b, &images)
c.Assert(err, checker.IsNil) c.Assert(err, checker.IsNil)
return images return images
@ -74,6 +76,10 @@ func (s *DockerSuite) TestAPIImagesSaveAndLoad(c *check.C) {
} }
func (s *DockerSuite) TestAPIImagesDelete(c *check.C) { func (s *DockerSuite) TestAPIImagesDelete(c *check.C) {
cli, err := client.NewEnvClient()
c.Assert(err, checker.IsNil)
defer cli.Close()
if testEnv.DaemonPlatform() != "windows" { if testEnv.DaemonPlatform() != "windows" {
testRequires(c, Network) testRequires(c, Network)
} }
@ -83,20 +89,21 @@ func (s *DockerSuite) TestAPIImagesDelete(c *check.C) {
dockerCmd(c, "tag", name, "test:tag1") dockerCmd(c, "tag", name, "test:tag1")
status, _, err := request.SockRequest("DELETE", "/images/"+id, nil, daemonHost()) _, err = cli.ImageRemove(context.Background(), id, types.ImageRemoveOptions{})
c.Assert(err, checker.IsNil) c.Assert(err.Error(), checker.Contains, "unable to delete")
c.Assert(status, checker.Equals, http.StatusConflict)
status, _, err = request.SockRequest("DELETE", "/images/test:noexist", nil, daemonHost()) _, err = cli.ImageRemove(context.Background(), "test:noexist", types.ImageRemoveOptions{})
c.Assert(err, checker.IsNil) c.Assert(err.Error(), checker.Contains, "No such image")
c.Assert(status, checker.Equals, http.StatusNotFound) //Status Codes:404 no such image
status, _, err = request.SockRequest("DELETE", "/images/test:tag1", nil, daemonHost()) _, err = cli.ImageRemove(context.Background(), "test:tag1", types.ImageRemoveOptions{})
c.Assert(err, checker.IsNil) c.Assert(err, checker.IsNil)
c.Assert(status, checker.Equals, http.StatusOK)
} }
func (s *DockerSuite) TestAPIImagesHistory(c *check.C) { func (s *DockerSuite) TestAPIImagesHistory(c *check.C) {
cli, err := client.NewEnvClient()
c.Assert(err, checker.IsNil)
defer cli.Close()
if testEnv.DaemonPlatform() != "windows" { if testEnv.DaemonPlatform() != "windows" {
testRequires(c, Network) testRequires(c, Network)
} }
@ -104,13 +111,8 @@ func (s *DockerSuite) TestAPIImagesHistory(c *check.C) {
buildImageSuccessfully(c, name, build.WithDockerfile("FROM busybox\nENV FOO bar")) buildImageSuccessfully(c, name, build.WithDockerfile("FROM busybox\nENV FOO bar"))
id := getIDByName(c, name) id := getIDByName(c, name)
status, body, err := request.SockRequest("GET", "/images/"+id+"/history", nil, daemonHost()) historydata, err := cli.ImageHistory(context.Background(), id)
c.Assert(err, checker.IsNil) c.Assert(err, checker.IsNil)
c.Assert(status, checker.Equals, http.StatusOK)
var historydata []image.HistoryResponseItem
err = json.Unmarshal(body, &historydata)
c.Assert(err, checker.IsNil, check.Commentf("Error on unmarshal"))
c.Assert(historydata, checker.Not(checker.HasLen), 0) c.Assert(historydata, checker.Not(checker.HasLen), 0)
c.Assert(historydata[0].Tags[0], checker.Equals, "test-api-images-history:latest") c.Assert(historydata[0].Tags[0], checker.Equals, "test-api-images-history:latest")
@ -133,9 +135,8 @@ func (s *DockerSuite) TestAPIImagesImportBadSrc(c *check.C) {
} }
for _, te := range tt { for _, te := range tt {
res, b, err := request.SockRequestRaw("POST", strings.Join([]string{"/images/create?fromSrc=", te.fromSrc}, ""), nil, "application/json", daemonHost()) res, _, err := request.Post(strings.Join([]string{"/images/create?fromSrc=", te.fromSrc}, ""), request.JSON)
c.Assert(err, check.IsNil) c.Assert(err, check.IsNil)
b.Close()
c.Assert(res.StatusCode, checker.Equals, te.statusExp) c.Assert(res.StatusCode, checker.Equals, te.statusExp)
c.Assert(res.Header.Get("Content-Type"), checker.Equals, "application/json") c.Assert(res.Header.Get("Content-Type"), checker.Equals, "application/json")
} }
@ -156,11 +157,11 @@ func (s *DockerSuite) TestAPIImagesSearchJSONContentType(c *check.C) {
// Test case for 30027: image size reported as -1 in v1.12 client against v1.13 daemon. // Test case for 30027: image size reported as -1 in v1.12 client against v1.13 daemon.
// This test checks to make sure both v1.12 and v1.13 client against v1.13 daemon get correct `Size` after the fix. // This test checks to make sure both v1.12 and v1.13 client against v1.13 daemon get correct `Size` after the fix.
func (s *DockerSuite) TestAPIImagesSizeCompatibility(c *check.C) { func (s *DockerSuite) TestAPIImagesSizeCompatibility(c *check.C) {
status, b, err := request.SockRequest("GET", "/images/json", nil, daemonHost()) cli, err := client.NewEnvClient()
c.Assert(err, checker.IsNil) c.Assert(err, checker.IsNil)
c.Assert(status, checker.Equals, http.StatusOK) defer cli.Close()
var images []types.ImageSummary
err = json.Unmarshal(b, &images) images, err := cli.ImageList(context.Background(), types.ImageListOptions{})
c.Assert(err, checker.IsNil) c.Assert(err, checker.IsNil)
c.Assert(len(images), checker.Not(checker.Equals), 0) c.Assert(len(images), checker.Not(checker.Equals), 0)
for _, image := range images { for _, image := range images {
@ -177,11 +178,13 @@ func (s *DockerSuite) TestAPIImagesSizeCompatibility(c *check.C) {
VirtualSize int64 VirtualSize int64
Labels map[string]string Labels map[string]string
} }
status, b, err = request.SockRequest("GET", "/v1.24/images/json", nil, daemonHost())
var httpClient *http.Client
cli, err = client.NewClient(daemonHost(), "v1.24", httpClient, nil)
c.Assert(err, checker.IsNil) c.Assert(err, checker.IsNil)
c.Assert(status, checker.Equals, http.StatusOK) defer cli.Close()
var v124Images []v124Image
err = json.Unmarshal(b, &v124Images) v124Images, err := cli.ImageList(context.Background(), types.ImageListOptions{})
c.Assert(err, checker.IsNil) c.Assert(err, checker.IsNil)
c.Assert(len(v124Images), checker.Not(checker.Equals), 0) c.Assert(len(v124Images), checker.Not(checker.Equals), 0)
for _, image := range v124Images { for _, image := range v124Images {

View File

@ -4,17 +4,23 @@ import (
"encoding/json" "encoding/json"
"net/http" "net/http"
"fmt"
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/docker/docker/client"
"github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/integration-cli/checker"
"github.com/docker/docker/integration-cli/request" "github.com/docker/docker/integration-cli/request"
"github.com/go-check/check" "github.com/go-check/check"
"golang.org/x/net/context"
) )
func (s *DockerSuite) TestInfoAPI(c *check.C) { func (s *DockerSuite) TestInfoAPI(c *check.C) {
endpoint := "/info" cli, err := client.NewEnvClient()
c.Assert(err, checker.IsNil)
defer cli.Close()
status, body, err := request.SockRequest("GET", endpoint, nil, daemonHost()) info, err := cli.Info(context.Background())
c.Assert(status, checker.Equals, http.StatusOK)
c.Assert(err, checker.IsNil) c.Assert(err, checker.IsNil)
// always shown fields // always shown fields
@ -36,7 +42,7 @@ func (s *DockerSuite) TestInfoAPI(c *check.C) {
"ServerVersion", "ServerVersion",
"SecurityOptions"} "SecurityOptions"}
out := string(body) out := fmt.Sprintf("%+v", info)
for _, linePrefix := range stringsToCheck { for _, linePrefix := range stringsToCheck {
c.Assert(out, checker.Contains, linePrefix) c.Assert(out, checker.Contains, linePrefix)
} }
@ -63,13 +69,15 @@ func (s *DockerSuite) TestInfoAPIRuncCommit(c *check.C) {
func (s *DockerSuite) TestInfoAPIVersioned(c *check.C) { func (s *DockerSuite) TestInfoAPIVersioned(c *check.C) {
testRequires(c, DaemonIsLinux) // Windows only supports 1.25 or later testRequires(c, DaemonIsLinux) // Windows only supports 1.25 or later
endpoint := "/v1.20/info"
status, body, err := request.SockRequest("GET", endpoint, nil, daemonHost()) res, body, err := request.Get("/v1.20/info")
c.Assert(status, checker.Equals, http.StatusOK) c.Assert(res.StatusCode, checker.Equals, http.StatusOK)
c.Assert(err, checker.IsNil) c.Assert(err, checker.IsNil)
out := string(body) b, err := request.ReadBody(body)
c.Assert(err, checker.IsNil)
out := string(b)
c.Assert(out, checker.Contains, "ExecutionDriver") c.Assert(out, checker.Contains, "ExecutionDriver")
c.Assert(out, checker.Contains, "not supported") c.Assert(out, checker.Contains, "not supported")
} }

View File

@ -2,13 +2,14 @@ package main
import ( import (
"encoding/json" "encoding/json"
"net/http"
"strings" "strings"
"golang.org/x/net/context"
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/versions/v1p20" "github.com/docker/docker/api/types/versions/v1p20"
"github.com/docker/docker/client"
"github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/integration-cli/checker"
"github.com/docker/docker/integration-cli/request"
"github.com/docker/docker/pkg/stringutils" "github.com/docker/docker/pkg/stringutils"
"github.com/go-check/check" "github.com/go-check/check"
) )
@ -106,18 +107,14 @@ func (s *DockerSuite) TestInspectAPIContainerVolumeDriver(c *check.C) {
func (s *DockerSuite) TestInspectAPIImageResponse(c *check.C) { func (s *DockerSuite) TestInspectAPIImageResponse(c *check.C) {
dockerCmd(c, "tag", "busybox:latest", "busybox:mytag") dockerCmd(c, "tag", "busybox:latest", "busybox:mytag")
cli, err := client.NewEnvClient()
endpoint := "/images/busybox/json" c.Assert(err, checker.IsNil)
status, body, err := request.SockRequest("GET", endpoint, nil, daemonHost()) defer cli.Close()
imageJSON, _, err := cli.ImageInspectWithRaw(context.Background(), "busybox")
c.Assert(err, checker.IsNil) c.Assert(err, checker.IsNil)
c.Assert(status, checker.Equals, http.StatusOK)
var imageJSON types.ImageInspect
err = json.Unmarshal(body, &imageJSON)
c.Assert(err, checker.IsNil, check.Commentf("Unable to unmarshal body for latest version"))
c.Assert(imageJSON.RepoTags, checker.HasLen, 2) c.Assert(imageJSON.RepoTags, checker.HasLen, 2)
c.Assert(stringutils.InSlice(imageJSON.RepoTags, "busybox:latest"), checker.Equals, true) c.Assert(stringutils.InSlice(imageJSON.RepoTags, "busybox:latest"), checker.Equals, true)
c.Assert(stringutils.InSlice(imageJSON.RepoTags, "busybox:mytag"), checker.Equals, true) c.Assert(stringutils.InSlice(imageJSON.RepoTags, "busybox:mytag"), checker.Equals, true)
} }

View File

@ -4,12 +4,12 @@ package main
import ( import (
"encoding/json" "encoding/json"
"fmt"
"net/http" "net/http"
"github.com/docker/docker/client"
"github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/integration-cli/checker"
"github.com/docker/docker/integration-cli/request"
"github.com/go-check/check" "github.com/go-check/check"
"golang.org/x/net/context"
) )
// #16665 // #16665
@ -19,9 +19,11 @@ func (s *DockerSuite) TestInspectAPICpusetInConfigPre120(c *check.C) {
name := "cpusetinconfig-pre120" name := "cpusetinconfig-pre120"
dockerCmd(c, "run", "--name", name, "--cpuset-cpus", "0", "busybox", "true") dockerCmd(c, "run", "--name", name, "--cpuset-cpus", "0", "busybox", "true")
var httpClient *http.Client
status, body, err := request.SockRequest("GET", fmt.Sprintf("/v1.19/containers/%s/json", name), nil, daemonHost()) cli, err := client.NewClient(daemonHost(), "v1.19", httpClient, nil)
c.Assert(status, check.Equals, http.StatusOK) c.Assert(err, checker.IsNil)
defer cli.Close()
_, body, err := cli.ContainerInspectWithRaw(context.Background(), name, false)
c.Assert(err, check.IsNil) c.Assert(err, check.IsNil)
var inspectJSON map[string]interface{} var inspectJSON map[string]interface{}

View File

@ -7,9 +7,12 @@ import (
"strings" "strings"
"time" "time"
"github.com/docker/docker/api/types"
"github.com/docker/docker/client"
"github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/integration-cli/checker"
"github.com/docker/docker/integration-cli/request" "github.com/docker/docker/integration-cli/request"
"github.com/go-check/check" "github.com/go-check/check"
"golang.org/x/net/context"
) )
func (s *DockerSuite) TestLogsAPIWithStdout(c *check.C) { func (s *DockerSuite) TestLogsAPIWithStdout(c *check.C) {
@ -51,13 +54,13 @@ func (s *DockerSuite) TestLogsAPIWithStdout(c *check.C) {
func (s *DockerSuite) TestLogsAPINoStdoutNorStderr(c *check.C) { func (s *DockerSuite) TestLogsAPINoStdoutNorStderr(c *check.C) {
name := "logs_test" name := "logs_test"
dockerCmd(c, "run", "-d", "-t", "--name", name, "busybox", "/bin/sh") dockerCmd(c, "run", "-d", "-t", "--name", name, "busybox", "/bin/sh")
cli, err := client.NewEnvClient()
status, body, err := request.SockRequest("GET", fmt.Sprintf("/containers/%s/logs", name), nil, daemonHost())
c.Assert(status, checker.Equals, http.StatusBadRequest)
c.Assert(err, checker.IsNil) c.Assert(err, checker.IsNil)
defer cli.Close()
_, err = cli.ContainerLogs(context.Background(), name, types.ContainerLogsOptions{})
expected := "Bad parameters: you must choose at least one stream" expected := "Bad parameters: you must choose at least one stream"
c.Assert(getErrorMessage(c, body), checker.Contains, expected) c.Assert(err.Error(), checker.Contains, expected)
} }
// Regression test for #12704 // Regression test for #12704

View File

@ -1,9 +1,12 @@
package main package main
import ( import (
"context"
"net/http" "net/http"
"strings" "strings"
"github.com/docker/docker/api/types"
"github.com/docker/docker/client"
"github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/integration-cli/checker"
"github.com/docker/docker/integration-cli/request" "github.com/docker/docker/integration-cli/request"
"github.com/go-check/check" "github.com/go-check/check"
@ -12,10 +15,15 @@ import (
func (s *DockerSuite) TestResizeAPIResponse(c *check.C) { func (s *DockerSuite) TestResizeAPIResponse(c *check.C) {
out := runSleepingContainer(c, "-d") out := runSleepingContainer(c, "-d")
cleanedContainerID := strings.TrimSpace(out) cleanedContainerID := strings.TrimSpace(out)
cli, err := client.NewEnvClient()
c.Assert(err, checker.IsNil)
defer cli.Close()
endpoint := "/containers/" + cleanedContainerID + "/resize?h=40&w=40" options := types.ResizeOptions{
status, _, err := request.SockRequest("POST", endpoint, nil, daemonHost()) Height: 40,
c.Assert(status, check.Equals, http.StatusOK) Width: 40,
}
err = cli.ContainerResize(context.Background(), cleanedContainerID, options)
c.Assert(err, check.IsNil) c.Assert(err, check.IsNil)
} }
@ -24,8 +32,8 @@ func (s *DockerSuite) TestResizeAPIHeightWidthNoInt(c *check.C) {
cleanedContainerID := strings.TrimSpace(out) cleanedContainerID := strings.TrimSpace(out)
endpoint := "/containers/" + cleanedContainerID + "/resize?h=foo&w=bar" endpoint := "/containers/" + cleanedContainerID + "/resize?h=foo&w=bar"
status, _, err := request.SockRequest("POST", endpoint, nil, daemonHost()) res, _, err := request.Post(endpoint)
c.Assert(status, check.Equals, http.StatusBadRequest) c.Assert(res.StatusCode, check.Equals, http.StatusBadRequest)
c.Assert(err, check.IsNil) c.Assert(err, check.IsNil)
} }
@ -36,10 +44,15 @@ func (s *DockerSuite) TestResizeAPIResponseWhenContainerNotStarted(c *check.C) {
// make sure the exited container is not running // make sure the exited container is not running
dockerCmd(c, "wait", cleanedContainerID) dockerCmd(c, "wait", cleanedContainerID)
endpoint := "/containers/" + cleanedContainerID + "/resize?h=40&w=40" cli, err := client.NewEnvClient()
status, body, err := request.SockRequest("POST", endpoint, nil, daemonHost()) c.Assert(err, checker.IsNil)
c.Assert(status, check.Equals, http.StatusConflict) defer cli.Close()
c.Assert(err, check.IsNil)
c.Assert(getErrorMessage(c, body), checker.Contains, "is not running", check.Commentf("resize should fail with message 'Container is not running'")) options := types.ResizeOptions{
Height: 40,
Width: 40,
}
err = cli.ContainerResize(context.Background(), cleanedContainerID, options)
c.Assert(err.Error(), checker.Contains, "is not running")
} }

View File

@ -13,9 +13,11 @@ import (
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/versions" "github.com/docker/docker/api/types/versions"
"github.com/docker/docker/client"
"github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/integration-cli/checker"
"github.com/docker/docker/integration-cli/request" "github.com/docker/docker/integration-cli/request"
"github.com/go-check/check" "github.com/go-check/check"
"golang.org/x/net/context"
) )
var expectedNetworkInterfaceStats = strings.Split("rx_bytes rx_dropped rx_errors rx_packets tx_bytes tx_dropped tx_errors tx_packets", " ") var expectedNetworkInterfaceStats = strings.Split("rx_bytes rx_dropped rx_errors rx_packets tx_bytes tx_dropped tx_errors tx_packets", " ")
@ -260,14 +262,16 @@ func jsonBlobHasGTE121NetworkStats(blob map[string]interface{}) bool {
func (s *DockerSuite) TestAPIStatsContainerNotFound(c *check.C) { func (s *DockerSuite) TestAPIStatsContainerNotFound(c *check.C) {
testRequires(c, DaemonIsLinux) testRequires(c, DaemonIsLinux)
cli, err := client.NewEnvClient()
status, _, err := request.SockRequest("GET", "/containers/nonexistent/stats", nil, daemonHost())
c.Assert(err, checker.IsNil) c.Assert(err, checker.IsNil)
c.Assert(status, checker.Equals, http.StatusNotFound) defer cli.Close()
status, _, err = request.SockRequest("GET", "/containers/nonexistent/stats?stream=0", nil, daemonHost()) expected := "No such container: nonexistent"
c.Assert(err, checker.IsNil)
c.Assert(status, checker.Equals, http.StatusNotFound) _, err = cli.ContainerStats(context.Background(), "nonexistent", true)
c.Assert(err.Error(), checker.Contains, expected)
_, err = cli.ContainerStats(context.Background(), "nonexistent", false)
c.Assert(err.Error(), checker.Contains, expected)
} }
func (s *DockerSuite) TestAPIStatsNoStreamConnectedContainers(c *check.C) { func (s *DockerSuite) TestAPIStatsNoStreamConnectedContainers(c *check.C) {

View File

@ -3,12 +3,10 @@
package main package main
import ( import (
"fmt"
"net/http"
"github.com/docker/docker/api/types/swarm" "github.com/docker/docker/api/types/swarm"
"github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/integration-cli/checker"
"github.com/go-check/check" "github.com/go-check/check"
"golang.org/x/net/context"
) )
func (s *DockerSwarmSuite) TestAPISwarmConfigsEmptyList(c *check.C) { func (s *DockerSwarmSuite) TestAPISwarmConfigsEmptyList(c *check.C) {
@ -52,9 +50,15 @@ func (s *DockerSwarmSuite) TestAPISwarmConfigsDelete(c *check.C) {
c.Assert(config.ID, checker.Equals, id, check.Commentf("config: %v", config)) c.Assert(config.ID, checker.Equals, id, check.Commentf("config: %v", config))
d.DeleteConfig(c, config.ID) d.DeleteConfig(c, config.ID)
status, out, err := d.SockRequest("GET", "/configs/"+id, nil)
cli, err := d.NewClient()
c.Assert(err, checker.IsNil) c.Assert(err, checker.IsNil)
c.Assert(status, checker.Equals, http.StatusNotFound, check.Commentf("config delete: %s", string(out))) defer cli.Close()
expected := "no such config"
_, _, err = cli.ConfigInspectWithRaw(context.Background(), id)
c.Assert(err.Error(), checker.Contains, expected)
} }
func (s *DockerSwarmSuite) TestAPISwarmConfigsUpdate(c *check.C) { func (s *DockerSwarmSuite) TestAPISwarmConfigsUpdate(c *check.C) {
@ -110,9 +114,12 @@ func (s *DockerSwarmSuite) TestAPISwarmConfigsUpdate(c *check.C) {
config = d.GetConfig(c, id) config = d.GetConfig(c, id)
config.Spec.Data = []byte("TESTINGDATA2") config.Spec.Data = []byte("TESTINGDATA2")
url := fmt.Sprintf("/configs/%s/update?version=%d", config.ID, config.Version.Index) cli, err := d.NewClient()
status, out, err := d.SockRequest("POST", url, config.Spec) c.Assert(err, checker.IsNil)
defer cli.Close()
c.Assert(err, checker.IsNil, check.Commentf(string(out))) expected := "only updates to Labels are allowed"
c.Assert(status, checker.Equals, http.StatusBadRequest, check.Commentf("output: %q", string(out)))
err = cli.ConfigUpdate(context.Background(), config.ID, config.Version, config.Spec)
c.Assert(err.Error(), checker.Contains, expected)
} }

View File

@ -3,12 +3,12 @@
package main package main
import ( import (
"fmt"
"net/http" "net/http"
"github.com/docker/docker/api/types/swarm" "github.com/docker/docker/api/types/swarm"
"github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/integration-cli/checker"
"github.com/go-check/check" "github.com/go-check/check"
"golang.org/x/net/context"
) )
func (s *DockerSwarmSuite) TestAPISwarmSecretsEmptyList(c *check.C) { func (s *DockerSwarmSuite) TestAPISwarmSecretsEmptyList(c *check.C) {
@ -59,16 +59,19 @@ func (s *DockerSwarmSuite) TestAPISwarmSecretsDelete(c *check.C) {
c.Assert(secret.ID, checker.Equals, id, check.Commentf("secret: %v", secret)) c.Assert(secret.ID, checker.Equals, id, check.Commentf("secret: %v", secret))
d.DeleteSecret(c, secret.ID) d.DeleteSecret(c, secret.ID)
status, out, err := d.SockRequest("GET", "/secrets/"+id, nil)
c.Assert(err, checker.IsNil)
c.Assert(status, checker.Equals, http.StatusNotFound, check.Commentf("secret delete: %s", string(out)))
// delete non-existing secret, daemon should return a status code of 404 cli, err := d.NewClient()
c.Assert(err, checker.IsNil)
defer cli.Close()
expected := "no such secret"
_, _, err = cli.SecretInspectWithRaw(context.Background(), id)
c.Assert(err.Error(), checker.Contains, expected)
id = "non-existing" id = "non-existing"
status, out, err = d.SockRequest("DELETE", "/secrets/"+id, nil) expected = "secret non-existing not found"
c.Assert(err, checker.IsNil) err = cli.SecretRemove(context.Background(), id)
c.Assert(status, checker.Equals, http.StatusNotFound, check.Commentf("secret delete: %s", string(out))) c.Assert(err.Error(), checker.Contains, expected)
} }
func (s *DockerSwarmSuite) TestAPISwarmSecretsUpdate(c *check.C) { func (s *DockerSwarmSuite) TestAPISwarmSecretsUpdate(c *check.C) {
@ -124,9 +127,12 @@ func (s *DockerSwarmSuite) TestAPISwarmSecretsUpdate(c *check.C) {
secret = d.GetSecret(c, id) secret = d.GetSecret(c, id)
secret.Spec.Data = []byte("TESTINGDATA2") secret.Spec.Data = []byte("TESTINGDATA2")
url := fmt.Sprintf("/secrets/%s/update?version=%d", secret.ID, secret.Version.Index) cli, err := d.NewClient()
status, out, err := d.SockRequest("POST", url, secret.Spec) c.Assert(err, checker.IsNil)
defer cli.Close()
c.Assert(err, checker.IsNil, check.Commentf(string(out))) expected := "only updates to Labels are allowed"
c.Assert(status, checker.Equals, http.StatusBadRequest, check.Commentf("output: %q", string(out)))
err = cli.SecretUpdate(context.Background(), secret.ID, secret.Version, secret.Spec)
c.Assert(err.Error(), checker.Contains, expected)
} }

View File

@ -9,6 +9,7 @@ import (
"strings" "strings"
"time" "time"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/swarm" "github.com/docker/docker/api/types/swarm"
"github.com/docker/docker/api/types/swarm/runtime" "github.com/docker/docker/api/types/swarm/runtime"
"github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/integration-cli/checker"
@ -64,14 +65,24 @@ func (s *DockerSwarmSuite) TestAPISwarmServicesCreate(c *check.C) {
id := d.CreateService(c, simpleTestService, setInstances(instances)) id := d.CreateService(c, simpleTestService, setInstances(instances))
waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, instances) waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, instances)
// insertDefaults inserts UpdateConfig when service is fetched by ID cli, err := d.NewClient()
_, out, err := d.SockRequest("GET", "/services/"+id+"?insertDefaults=true", nil) c.Assert(err, checker.IsNil)
c.Assert(err, checker.IsNil, check.Commentf("%s", out)) defer cli.Close()
c.Assert(string(out), checker.Contains, "UpdateConfig")
options := types.ServiceInspectOptions{
InsertDefaults: true,
}
// insertDefaults inserts UpdateConfig when service is fetched by ID // insertDefaults inserts UpdateConfig when service is fetched by ID
_, out, err = d.SockRequest("GET", "/services/top?insertDefaults=true", nil) resp, _, err := cli.ServiceInspectWithRaw(context.Background(), id, options)
c.Assert(err, checker.IsNil, check.Commentf("%s", out)) out := fmt.Sprintf("%+v", resp)
c.Assert(err, checker.IsNil)
c.Assert(out, checker.Contains, "UpdateConfig")
// insertDefaults inserts UpdateConfig when service is fetched by ID
resp, _, err = cli.ServiceInspectWithRaw(context.Background(), "top", options)
out = fmt.Sprintf("%+v", resp)
c.Assert(err, checker.IsNil)
c.Assert(string(out), checker.Contains, "UpdateConfig") c.Assert(string(out), checker.Contains, "UpdateConfig")
service := d.GetService(c, id) service := d.GetService(c, id)
@ -195,7 +206,7 @@ func (s *DockerSwarmSuite) TestAPISwarmServicesUpdateStartFirst(c *check.C) {
// service image at start // service image at start
image1 := "busybox:latest" image1 := "busybox:latest"
// target image in update // target image in update
image2 := "testhealth" image2 := "testhealth:latest"
// service started from this image won't pass health check // service started from this image won't pass health check
_, _, err := d.BuildImageWithOut(image2, _, _, err := d.BuildImageWithOut(image2,

View File

@ -23,8 +23,10 @@ import (
"github.com/docker/docker/api/types/swarm" "github.com/docker/docker/api/types/swarm"
"github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/integration-cli/checker"
"github.com/docker/docker/integration-cli/daemon" "github.com/docker/docker/integration-cli/daemon"
"github.com/docker/docker/integration-cli/request"
"github.com/docker/swarmkit/ca" "github.com/docker/swarmkit/ca"
"github.com/go-check/check" "github.com/go-check/check"
"golang.org/x/net/context"
) )
var defaultReconciliationTimeout = 30 * time.Second var defaultReconciliationTimeout = 30 * time.Second
@ -228,17 +230,20 @@ func (s *DockerSwarmSuite) TestAPISwarmPromoteDemote(c *check.C) {
node := d1.GetNode(c, d1.NodeID) node := d1.GetNode(c, d1.NodeID)
node.Spec.Role = swarm.NodeRoleWorker node.Spec.Role = swarm.NodeRoleWorker
url := fmt.Sprintf("/nodes/%s/update?version=%d", node.ID, node.Version.Index) url := fmt.Sprintf("/nodes/%s/update?version=%d", node.ID, node.Version.Index)
status, out, err := d1.SockRequest("POST", url, node.Spec) res, body, err := request.DoOnHost(d1.Sock(), url, request.Method("POST"), request.JSONBody(node.Spec))
c.Assert(err, checker.IsNil) c.Assert(err, checker.IsNil)
c.Assert(status, checker.Equals, http.StatusBadRequest, check.Commentf("output: %q", string(out))) b, err := request.ReadBody(body)
c.Assert(err, checker.IsNil)
c.Assert(res.StatusCode, checker.Equals, http.StatusBadRequest, check.Commentf("output: %q", string(b)))
// The warning specific to demoting the last manager is best-effort and // The warning specific to demoting the last manager is best-effort and
// won't appear until the Role field of the demoted manager has been // won't appear until the Role field of the demoted manager has been
// updated. // updated.
// Yes, I know this looks silly, but checker.Matches is broken, since // Yes, I know this looks silly, but checker.Matches is broken, since
// it anchors the regexp contrary to the documentation, and this makes // it anchors the regexp contrary to the documentation, and this makes
// it impossible to match something that includes a line break. // it impossible to match something that includes a line break.
if !strings.Contains(string(out), "last manager of the swarm") { if !strings.Contains(string(b), "last manager of the swarm") {
c.Assert(string(out), checker.Contains, "this would result in a loss of quorum") c.Assert(string(b), checker.Contains, "this would result in a loss of quorum")
} }
info, err = d1.SwarmInfo() info, err = d1.SwarmInfo()
c.Assert(err, checker.IsNil) c.Assert(err, checker.IsNil)
@ -362,9 +367,11 @@ func (s *DockerSwarmSuite) TestAPISwarmRaftQuorum(c *check.C) {
var service swarm.Service var service swarm.Service
simpleTestService(&service) simpleTestService(&service)
service.Spec.Name = "top2" service.Spec.Name = "top2"
status, out, err := d1.SockRequest("POST", "/services/create", service.Spec) cli, err := d1.NewClient()
c.Assert(err, checker.IsNil) c.Assert(err, checker.IsNil)
c.Assert(status, checker.Equals, http.StatusInternalServerError, check.Commentf("deadline exceeded", string(out))) defer cli.Close()
_, err = cli.ServiceCreate(context.Background(), service.Spec, types.ServiceCreateOptions{})
c.Assert(err.Error(), checker.Contains, "deadline exceeded")
d2.Start(c) d2.Start(c)
@ -505,17 +512,17 @@ func (s *DockerSwarmSuite) TestAPISwarmInvalidAddress(c *check.C) {
req := swarm.InitRequest{ req := swarm.InitRequest{
ListenAddr: "", ListenAddr: "",
} }
status, _, err := d.SockRequest("POST", "/swarm/init", req) res, _, err := request.DoOnHost(d.Sock(), "/swarm/init", request.Method("POST"), request.JSONBody(req))
c.Assert(err, checker.IsNil) c.Assert(err, checker.IsNil)
c.Assert(status, checker.Equals, http.StatusBadRequest) c.Assert(res.StatusCode, checker.Equals, http.StatusBadRequest)
req2 := swarm.JoinRequest{ req2 := swarm.JoinRequest{
ListenAddr: "0.0.0.0:2377", ListenAddr: "0.0.0.0:2377",
RemoteAddrs: []string{""}, RemoteAddrs: []string{""},
} }
status, _, err = d.SockRequest("POST", "/swarm/join", req2) res, _, err = request.DoOnHost(d.Sock(), "/swarm/join", request.Method("POST"), request.JSONBody(req2))
c.Assert(err, checker.IsNil) c.Assert(err, checker.IsNil)
c.Assert(status, checker.Equals, http.StatusBadRequest) c.Assert(res.StatusCode, checker.Equals, http.StatusBadRequest)
} }
func (s *DockerSwarmSuite) TestAPISwarmForceNewCluster(c *check.C) { func (s *DockerSwarmSuite) TestAPISwarmForceNewCluster(c *check.C) {
@ -836,10 +843,11 @@ func (s *DockerSwarmSuite) TestAPISwarmServicesUpdateWithName(c *check.C) {
instances = 5 instances = 5
setInstances(instances)(service) setInstances(instances)(service)
url := fmt.Sprintf("/services/%s/update?version=%d", service.Spec.Name, service.Version.Index) cli, err := d.NewClient()
status, out, err := d.SockRequest("POST", url, service.Spec) c.Assert(err, checker.IsNil)
defer cli.Close()
_, err = cli.ServiceUpdate(context.Background(), service.Spec.Name, service.Version, service.Spec, types.ServiceUpdateOptions{})
c.Assert(err, checker.IsNil) c.Assert(err, checker.IsNil)
c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out)))
waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, instances) waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, instances)
} }
@ -867,51 +875,31 @@ func (s *DockerSwarmSuite) TestAPISwarmErrorHandling(c *check.C) {
// This test makes sure the fixes correctly output scopes instead. // This test makes sure the fixes correctly output scopes instead.
func (s *DockerSwarmSuite) TestAPIDuplicateNetworks(c *check.C) { func (s *DockerSwarmSuite) TestAPIDuplicateNetworks(c *check.C) {
d := s.AddDaemon(c, true, true) d := s.AddDaemon(c, true, true)
cli, err := d.NewClient()
c.Assert(err, checker.IsNil)
defer cli.Close()
name := "foo" name := "foo"
networkCreateRequest := types.NetworkCreateRequest{ networkCreate := types.NetworkCreate{
Name: name, CheckDuplicate: false,
NetworkCreate: types.NetworkCreate{
CheckDuplicate: false,
},
} }
var n1 types.NetworkCreateResponse networkCreate.Driver = "bridge"
networkCreateRequest.NetworkCreate.Driver = "bridge"
status, out, err := d.SockRequest("POST", "/networks/create", networkCreateRequest) n1, err := cli.NetworkCreate(context.Background(), name, networkCreate)
c.Assert(err, checker.IsNil, check.Commentf(string(out))) c.Assert(err, checker.IsNil)
c.Assert(status, checker.Equals, http.StatusCreated, check.Commentf(string(out)))
c.Assert(json.Unmarshal(out, &n1), checker.IsNil) networkCreate.Driver = "overlay"
var n2 types.NetworkCreateResponse n2, err := cli.NetworkCreate(context.Background(), name, networkCreate)
networkCreateRequest.NetworkCreate.Driver = "overlay" c.Assert(err, checker.IsNil)
status, out, err = d.SockRequest("POST", "/networks/create", networkCreateRequest)
c.Assert(err, checker.IsNil, check.Commentf(string(out)))
c.Assert(status, checker.Equals, http.StatusCreated, check.Commentf(string(out)))
c.Assert(json.Unmarshal(out, &n2), checker.IsNil)
var r1 types.NetworkResource
status, out, err = d.SockRequest("GET", "/networks/"+n1.ID, nil)
c.Assert(err, checker.IsNil, check.Commentf(string(out)))
c.Assert(status, checker.Equals, http.StatusOK, check.Commentf(string(out)))
c.Assert(json.Unmarshal(out, &r1), checker.IsNil)
r1, err := cli.NetworkInspect(context.Background(), n1.ID, types.NetworkInspectOptions{})
c.Assert(err, checker.IsNil)
c.Assert(r1.Scope, checker.Equals, "local") c.Assert(r1.Scope, checker.Equals, "local")
var r2 types.NetworkResource r2, err := cli.NetworkInspect(context.Background(), n2.ID, types.NetworkInspectOptions{})
c.Assert(err, checker.IsNil)
status, out, err = d.SockRequest("GET", "/networks/"+n2.ID, nil)
c.Assert(err, checker.IsNil, check.Commentf(string(out)))
c.Assert(status, checker.Equals, http.StatusOK, check.Commentf(string(out)))
c.Assert(json.Unmarshal(out, &r2), checker.IsNil)
c.Assert(r2.Scope, checker.Equals, "swarm") c.Assert(r2.Scope, checker.Equals, "swarm")
} }

View File

@ -5,9 +5,11 @@ package main
import ( import (
"strings" "strings"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/client"
"github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/integration-cli/checker"
"github.com/docker/docker/integration-cli/request"
"github.com/go-check/check" "github.com/go-check/check"
"golang.org/x/net/context"
) )
func (s *DockerSuite) TestAPIUpdateContainer(c *check.C) { func (s *DockerSuite) TestAPIUpdateContainer(c *check.C) {
@ -16,12 +18,19 @@ func (s *DockerSuite) TestAPIUpdateContainer(c *check.C) {
testRequires(c, swapMemorySupport) testRequires(c, swapMemorySupport)
name := "apiUpdateContainer" name := "apiUpdateContainer"
hostConfig := map[string]interface{}{ updateConfig := container.UpdateConfig{
"Memory": 314572800, Resources: container.Resources{
"MemorySwap": 524288000, Memory: 314572800,
MemorySwap: 524288000,
},
} }
dockerCmd(c, "run", "-d", "--name", name, "-m", "200M", "busybox", "top") dockerCmd(c, "run", "-d", "--name", name, "-m", "200M", "busybox", "top")
_, _, err := request.SockRequest("POST", "/containers/"+name+"/update", hostConfig, daemonHost()) cli, err := client.NewEnvClient()
c.Assert(err, check.IsNil)
defer cli.Close()
_, err = cli.ContainerUpdate(context.Background(), name, updateConfig)
c.Assert(err, check.IsNil) c.Assert(err, check.IsNil)
c.Assert(inspectField(c, name, "HostConfig.Memory"), checker.Equals, "314572800") c.Assert(inspectField(c, name, "HostConfig.Memory"), checker.Equals, "314572800")

View File

@ -1,24 +1,18 @@
package main package main
import ( import (
"encoding/json" "github.com/docker/docker/client"
"net/http"
"github.com/docker/docker/api/types"
"github.com/docker/docker/dockerversion" "github.com/docker/docker/dockerversion"
"github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/integration-cli/checker"
"github.com/docker/docker/integration-cli/request"
"github.com/go-check/check" "github.com/go-check/check"
"golang.org/x/net/context"
) )
func (s *DockerSuite) TestGetVersion(c *check.C) { func (s *DockerSuite) TestGetVersion(c *check.C) {
status, body, err := request.SockRequest("GET", "/version", nil, daemonHost()) cli, err := client.NewEnvClient()
c.Assert(status, checker.Equals, http.StatusOK)
c.Assert(err, checker.IsNil) c.Assert(err, checker.IsNil)
defer cli.Close()
var v types.Version v, err := cli.ServerVersion(context.Background())
c.Assert(json.Unmarshal(body, &v), checker.IsNil)
c.Assert(v.Version, checker.Equals, dockerversion.Version, check.Commentf("Version mismatch")) c.Assert(v.Version, checker.Equals, dockerversion.Version, check.Commentf("Version mismatch"))
} }

View File

@ -1,30 +1,29 @@
package main package main
import ( import (
"encoding/json"
"fmt" "fmt"
"net/http"
"path/filepath" "path/filepath"
"strings" "strings"
"time" "time"
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types/filters"
volumetypes "github.com/docker/docker/api/types/volume" volumetypes "github.com/docker/docker/api/types/volume"
"github.com/docker/docker/client"
"github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/integration-cli/checker"
"github.com/docker/docker/integration-cli/request"
"github.com/go-check/check" "github.com/go-check/check"
"golang.org/x/net/context"
) )
func (s *DockerSuite) TestVolumesAPIList(c *check.C) { func (s *DockerSuite) TestVolumesAPIList(c *check.C) {
prefix, _ := getPrefixAndSlashFromDaemonPlatform() prefix, _ := getPrefixAndSlashFromDaemonPlatform()
dockerCmd(c, "run", "-v", prefix+"/foo", "busybox") dockerCmd(c, "run", "-v", prefix+"/foo", "busybox")
status, b, err := request.SockRequest("GET", "/volumes", nil, daemonHost()) cli, err := client.NewEnvClient()
c.Assert(err, checker.IsNil) c.Assert(err, checker.IsNil)
c.Assert(status, checker.Equals, http.StatusOK) defer cli.Close()
var volumes volumetypes.VolumesListOKBody volumes, err := cli.VolumeList(context.Background(), filters.Args{})
c.Assert(json.Unmarshal(b, &volumes), checker.IsNil) c.Assert(err, checker.IsNil)
c.Assert(len(volumes.Volumes), checker.Equals, 1, check.Commentf("\n%v", volumes.Volumes)) c.Assert(len(volumes.Volumes), checker.Equals, 1, check.Commentf("\n%v", volumes.Volumes))
} }
@ -33,13 +32,13 @@ func (s *DockerSuite) TestVolumesAPICreate(c *check.C) {
config := volumetypes.VolumesCreateBody{ config := volumetypes.VolumesCreateBody{
Name: "test", Name: "test",
} }
status, b, err := request.SockRequest("POST", "/volumes/create", config, daemonHost())
c.Assert(err, check.IsNil)
c.Assert(status, check.Equals, http.StatusCreated, check.Commentf(string(b)))
var vol types.Volume cli, err := client.NewEnvClient()
err = json.Unmarshal(b, &vol)
c.Assert(err, checker.IsNil) c.Assert(err, checker.IsNil)
defer cli.Close()
vol, err := cli.VolumeCreate(context.Background(), config)
c.Assert(err, check.IsNil)
c.Assert(filepath.Base(filepath.Dir(vol.Mountpoint)), checker.Equals, config.Name) c.Assert(filepath.Base(filepath.Dir(vol.Mountpoint)), checker.Equals, config.Name)
} }
@ -48,49 +47,43 @@ func (s *DockerSuite) TestVolumesAPIRemove(c *check.C) {
prefix, _ := getPrefixAndSlashFromDaemonPlatform() prefix, _ := getPrefixAndSlashFromDaemonPlatform()
dockerCmd(c, "run", "-v", prefix+"/foo", "--name=test", "busybox") dockerCmd(c, "run", "-v", prefix+"/foo", "--name=test", "busybox")
status, b, err := request.SockRequest("GET", "/volumes", nil, daemonHost()) cli, err := client.NewEnvClient()
c.Assert(err, checker.IsNil) c.Assert(err, checker.IsNil)
c.Assert(status, checker.Equals, http.StatusOK) defer cli.Close()
var volumes volumetypes.VolumesListOKBody volumes, err := cli.VolumeList(context.Background(), filters.Args{})
c.Assert(json.Unmarshal(b, &volumes), checker.IsNil) c.Assert(err, checker.IsNil)
c.Assert(len(volumes.Volumes), checker.Equals, 1, check.Commentf("\n%v", volumes.Volumes))
v := volumes.Volumes[0] v := volumes.Volumes[0]
status, _, err = request.SockRequest("DELETE", "/volumes/"+v.Name, nil, daemonHost()) err = cli.VolumeRemove(context.Background(), v.Name, false)
c.Assert(err, checker.IsNil) c.Assert(err.Error(), checker.Contains, "volume is in use")
c.Assert(status, checker.Equals, http.StatusConflict, check.Commentf("Should not be able to remove a volume that is in use"))
dockerCmd(c, "rm", "-f", "test") dockerCmd(c, "rm", "-f", "test")
status, data, err := request.SockRequest("DELETE", "/volumes/"+v.Name, nil, daemonHost()) err = cli.VolumeRemove(context.Background(), v.Name, false)
c.Assert(err, checker.IsNil) c.Assert(err, checker.IsNil)
c.Assert(status, checker.Equals, http.StatusNoContent, check.Commentf(string(data)))
} }
func (s *DockerSuite) TestVolumesAPIInspect(c *check.C) { func (s *DockerSuite) TestVolumesAPIInspect(c *check.C) {
config := volumetypes.VolumesCreateBody{ config := volumetypes.VolumesCreateBody{
Name: "test", Name: "test",
} }
// sampling current time minus a minute so to now have false positive in case of delays // sampling current time minus a minute so to now have false positive in case of delays
now := time.Now().Truncate(time.Minute) now := time.Now().Truncate(time.Minute)
status, b, err := request.SockRequest("POST", "/volumes/create", config, daemonHost())
c.Assert(err, check.IsNil)
c.Assert(status, check.Equals, http.StatusCreated, check.Commentf(string(b)))
status, b, err = request.SockRequest("GET", "/volumes", nil, daemonHost()) cli, err := client.NewEnvClient()
c.Assert(err, checker.IsNil) c.Assert(err, checker.IsNil)
c.Assert(status, checker.Equals, http.StatusOK, check.Commentf(string(b))) defer cli.Close()
var volumes volumetypes.VolumesListOKBody _, err = cli.VolumeCreate(context.Background(), config)
c.Assert(json.Unmarshal(b, &volumes), checker.IsNil) c.Assert(err, check.IsNil)
volumes, err := cli.VolumeList(context.Background(), filters.Args{})
c.Assert(err, checker.IsNil)
c.Assert(len(volumes.Volumes), checker.Equals, 1, check.Commentf("\n%v", volumes.Volumes)) c.Assert(len(volumes.Volumes), checker.Equals, 1, check.Commentf("\n%v", volumes.Volumes))
var vol types.Volume vol, err := cli.VolumeInspect(context.Background(), config.Name)
status, b, err = request.SockRequest("GET", "/volumes/"+config.Name, nil, daemonHost())
c.Assert(err, checker.IsNil) c.Assert(err, checker.IsNil)
c.Assert(status, checker.Equals, http.StatusOK, check.Commentf(string(b)))
c.Assert(json.Unmarshal(b, &vol), checker.IsNil)
c.Assert(vol.Name, checker.Equals, config.Name) c.Assert(vol.Name, checker.Equals, config.Name)
// comparing CreatedAt field time for the new volume to now. Removing a minute from both to avoid false positive // comparing CreatedAt field time for the new volume to now. Removing a minute from both to avoid false positive

View File

@ -6,20 +6,22 @@ import (
"fmt" "fmt"
"io" "io"
"io/ioutil" "io/ioutil"
"net/http"
"os" "os"
"os/exec" "os/exec"
"strings" "strings"
"time" "time"
"github.com/docker/docker/api/types"
eventtypes "github.com/docker/docker/api/types/events" eventtypes "github.com/docker/docker/api/types/events"
"github.com/docker/docker/client"
eventstestutils "github.com/docker/docker/daemon/events/testutils" eventstestutils "github.com/docker/docker/daemon/events/testutils"
"github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/integration-cli/checker"
"github.com/docker/docker/integration-cli/cli" "github.com/docker/docker/integration-cli/cli"
"github.com/docker/docker/integration-cli/cli/build" "github.com/docker/docker/integration-cli/cli/build"
"github.com/docker/docker/integration-cli/request"
icmd "github.com/docker/docker/pkg/testutil/cmd" icmd "github.com/docker/docker/pkg/testutil/cmd"
"github.com/go-check/check" "github.com/go-check/check"
"golang.org/x/net/context"
) )
func (s *DockerSuite) TestEventsTimestampFormats(c *check.C) { func (s *DockerSuite) TestEventsTimestampFormats(c *check.C) {
@ -498,9 +500,15 @@ func (s *DockerSuite) TestEventsResize(c *check.C) {
cID := strings.TrimSpace(out) cID := strings.TrimSpace(out)
c.Assert(waitRun(cID), checker.IsNil) c.Assert(waitRun(cID), checker.IsNil)
endpoint := "/containers/" + cID + "/resize?h=80&w=24" cli, err := client.NewEnvClient()
status, _, err := request.SockRequest("POST", endpoint, nil, daemonHost()) c.Assert(err, checker.IsNil)
c.Assert(status, checker.Equals, http.StatusOK) defer cli.Close()
options := types.ResizeOptions{
Height: 80,
Width: 24,
}
err = cli.ContainerResize(context.Background(), cID, options)
c.Assert(err, checker.IsNil) c.Assert(err, checker.IsNil)
dockerCmd(c, "stop", cID) dockerCmd(c, "stop", cID)

View File

@ -5,7 +5,6 @@ package main
import ( import (
"bufio" "bufio"
"fmt" "fmt"
"net/http"
"os" "os"
"os/exec" "os/exec"
"reflect" "reflect"
@ -15,12 +14,13 @@ import (
"sync" "sync"
"time" "time"
"github.com/docker/docker/client"
"github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/integration-cli/checker"
"github.com/docker/docker/integration-cli/cli" "github.com/docker/docker/integration-cli/cli"
"github.com/docker/docker/integration-cli/cli/build" "github.com/docker/docker/integration-cli/cli/build"
"github.com/docker/docker/integration-cli/request"
icmd "github.com/docker/docker/pkg/testutil/cmd" icmd "github.com/docker/docker/pkg/testutil/cmd"
"github.com/go-check/check" "github.com/go-check/check"
"golang.org/x/net/context"
) )
func (s *DockerSuite) TestExec(c *check.C) { func (s *DockerSuite) TestExec(c *check.C) {
@ -357,16 +357,21 @@ func (s *DockerSuite) TestExecInspectID(c *check.C) {
} }
// But we should still be able to query the execID // But we should still be able to query the execID
sc, body, _ := request.SockRequest("GET", "/exec/"+execID+"/json", nil, daemonHost()) cli, err := client.NewEnvClient()
c.Assert(err, checker.IsNil)
defer cli.Close()
c.Assert(sc, checker.Equals, http.StatusOK, check.Commentf("received status != 200 OK: %d\n%s", sc, body)) _, err = cli.ContainerExecInspect(context.Background(), execID)
c.Assert(err, checker.IsNil)
// Now delete the container and then an 'inspect' on the exec should // Now delete the container and then an 'inspect' on the exec should
// result in a 404 (not 'container not running') // result in a 404 (not 'container not running')
out, ec := dockerCmd(c, "rm", "-f", id) out, ec := dockerCmd(c, "rm", "-f", id)
c.Assert(ec, checker.Equals, 0, check.Commentf("error removing container: %s", out)) c.Assert(ec, checker.Equals, 0, check.Commentf("error removing container: %s", out))
sc, body, _ = request.SockRequest("GET", "/exec/"+execID+"/json", nil, daemonHost())
c.Assert(sc, checker.Equals, http.StatusNotFound, check.Commentf("received status != 404: %d\n%s", sc, body)) _, err = cli.ContainerExecInspect(context.Background(), execID)
expected := "No such exec instance"
c.Assert(err.Error(), checker.Contains, expected)
} }
func (s *DockerSuite) TestLinksPingLinkedContainersOnRename(c *check.C) { func (s *DockerSuite) TestLinksPingLinkedContainersOnRename(c *check.C) {

View File

@ -1,16 +1,16 @@
package main package main
import ( import (
"fmt"
"net/http" "net/http"
"strings" "strings"
"time" "time"
"github.com/docker/docker/client"
"github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/integration-cli/checker"
"github.com/docker/docker/integration-cli/cli" "github.com/docker/docker/integration-cli/cli"
"github.com/docker/docker/integration-cli/request"
icmd "github.com/docker/docker/pkg/testutil/cmd" icmd "github.com/docker/docker/pkg/testutil/cmd"
"github.com/go-check/check" "github.com/go-check/check"
"golang.org/x/net/context"
) )
func (s *DockerSuite) TestKillContainer(c *check.C) { func (s *DockerSuite) TestKillContainer(c *check.C) {
@ -131,8 +131,10 @@ func (s *DockerSuite) TestKillStoppedContainerAPIPre120(c *check.C) {
testRequires(c, DaemonIsLinux) // Windows only supports 1.25 or later testRequires(c, DaemonIsLinux) // Windows only supports 1.25 or later
runSleepingContainer(c, "--name", "docker-kill-test-api", "-d") runSleepingContainer(c, "--name", "docker-kill-test-api", "-d")
dockerCmd(c, "stop", "docker-kill-test-api") dockerCmd(c, "stop", "docker-kill-test-api")
var httpClient *http.Client
status, _, err := request.SockRequest("POST", fmt.Sprintf("/v1.19/containers/%s/kill", "docker-kill-test-api"), nil, daemonHost()) cli, err := client.NewClient(daemonHost(), "v1.19", httpClient, nil)
c.Assert(err, check.IsNil)
defer cli.Close()
err = cli.ContainerKill(context.Background(), "docker-kill-test-api", "SIGKILL")
c.Assert(err, check.IsNil) c.Assert(err, check.IsNil)
c.Assert(status, check.Equals, http.StatusNoContent)
} }

View File

@ -1,14 +1,12 @@
package main package main
import ( import (
"encoding/json"
"net/http"
"strings" "strings"
"github.com/docker/docker/api/types" "github.com/docker/docker/client"
"github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/integration-cli/checker"
"github.com/docker/docker/integration-cli/request"
"github.com/go-check/check" "github.com/go-check/check"
"golang.org/x/net/context"
) )
func (s *DockerSuite) TestPluginLogDriver(c *check.C) { func (s *DockerSuite) TestPluginLogDriver(c *check.C) {
@ -36,13 +34,14 @@ func (s *DockerSuite) TestPluginLogDriverInfoList(c *check.C) {
pluginName := "cpuguy83/docker-logdriver-test" pluginName := "cpuguy83/docker-logdriver-test"
dockerCmd(c, "plugin", "install", pluginName) dockerCmd(c, "plugin", "install", pluginName)
status, body, err := request.SockRequest("GET", "/info", nil, daemonHost())
c.Assert(status, checker.Equals, http.StatusOK) cli, err := client.NewEnvClient()
c.Assert(err, checker.IsNil)
defer cli.Close()
info, err := cli.Info(context.Background())
c.Assert(err, checker.IsNil) c.Assert(err, checker.IsNil)
var info types.Info
err = json.Unmarshal(body, &info)
c.Assert(err, checker.IsNil)
drivers := strings.Join(info.Plugins.Log, " ") drivers := strings.Join(info.Plugins.Log, " ")
c.Assert(drivers, checker.Contains, "json-file") c.Assert(drivers, checker.Contains, "json-file")
c.Assert(drivers, checker.Not(checker.Contains), pluginName) c.Assert(drivers, checker.Not(checker.Contains), pluginName)

View File

@ -29,6 +29,7 @@ import (
remoteipam "github.com/docker/libnetwork/ipams/remote/api" remoteipam "github.com/docker/libnetwork/ipams/remote/api"
"github.com/go-check/check" "github.com/go-check/check"
"github.com/vishvananda/netlink" "github.com/vishvananda/netlink"
"golang.org/x/net/context"
) )
func (s *DockerSwarmSuite) TestSwarmUpdate(c *check.C) { func (s *DockerSwarmSuite) TestSwarmUpdate(c *check.C) {
@ -1843,19 +1844,17 @@ func (s *DockerSwarmSuite) TestNetworkInspectWithDuplicateNames(c *check.C) {
d := s.AddDaemon(c, true, true) d := s.AddDaemon(c, true, true)
name := "foo" name := "foo"
networkCreateRequest := types.NetworkCreateRequest{ options := types.NetworkCreate{
Name: name, CheckDuplicate: false,
NetworkCreate: types.NetworkCreate{ Driver: "bridge",
CheckDuplicate: false,
Driver: "bridge",
},
} }
var n1 types.NetworkCreateResponse cli, err := d.NewClient()
status, body, err := d.SockRequest("POST", "/networks/create", networkCreateRequest) c.Assert(err, checker.IsNil)
c.Assert(err, checker.IsNil, check.Commentf(string(body))) defer cli.Close()
c.Assert(status, checker.Equals, http.StatusCreated, check.Commentf(string(body)))
c.Assert(json.Unmarshal(body, &n1), checker.IsNil) n1, err := cli.NetworkCreate(context.Background(), name, options)
c.Assert(err, checker.IsNil)
// Full ID always works // Full ID always works
out, err := d.Cmd("network", "inspect", "--format", "{{.ID}}", n1.ID) out, err := d.Cmd("network", "inspect", "--format", "{{.ID}}", n1.ID)
@ -1867,12 +1866,8 @@ func (s *DockerSwarmSuite) TestNetworkInspectWithDuplicateNames(c *check.C) {
c.Assert(err, checker.IsNil, check.Commentf(out)) c.Assert(err, checker.IsNil, check.Commentf(out))
c.Assert(strings.TrimSpace(out), checker.Equals, n1.ID) c.Assert(strings.TrimSpace(out), checker.Equals, n1.ID)
var n2 types.NetworkCreateResponse n2, err := cli.NetworkCreate(context.Background(), name, options)
status, body, err = d.SockRequest("POST", "/networks/create", networkCreateRequest) c.Assert(err, checker.IsNil)
c.Assert(err, checker.IsNil, check.Commentf(string(body)))
c.Assert(status, checker.Equals, http.StatusCreated, check.Commentf(string(body)))
c.Assert(json.Unmarshal(body, &n2), checker.IsNil)
// Full ID always works // Full ID always works
out, err = d.Cmd("network", "inspect", "--format", "{{.ID}}", n1.ID) out, err = d.Cmd("network", "inspect", "--format", "{{.ID}}", n1.ID)
c.Assert(err, checker.IsNil, check.Commentf(out)) c.Assert(err, checker.IsNil, check.Commentf(out))
@ -1890,13 +1885,11 @@ func (s *DockerSwarmSuite) TestNetworkInspectWithDuplicateNames(c *check.C) {
out, err = d.Cmd("network", "rm", n2.ID) out, err = d.Cmd("network", "rm", n2.ID)
c.Assert(err, checker.IsNil, check.Commentf(out)) c.Assert(err, checker.IsNil, check.Commentf(out))
// Duplicates with name but with different driver // Dupliates with name but with different driver
networkCreateRequest.NetworkCreate.Driver = "overlay" options.Driver = "overlay"
status, body, err = d.SockRequest("POST", "/networks/create", networkCreateRequest) n2, err = cli.NetworkCreate(context.Background(), name, options)
c.Assert(err, checker.IsNil, check.Commentf(string(body))) c.Assert(err, checker.IsNil)
c.Assert(status, checker.Equals, http.StatusCreated, check.Commentf(string(body)))
c.Assert(json.Unmarshal(body, &n2), checker.IsNil)
// Full ID always works // Full ID always works
out, err = d.Cmd("network", "inspect", "--format", "{{.ID}}", n1.ID) out, err = d.Cmd("network", "inspect", "--format", "{{.ID}}", n1.ID)

View File

@ -3,17 +3,20 @@ package main
import ( import (
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"net/http"
"os" "os"
"os/exec" "os/exec"
"path/filepath" "path/filepath"
"strings" "strings"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/mount"
"github.com/docker/docker/api/types/network"
"github.com/docker/docker/client"
"github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/integration-cli/checker"
"github.com/docker/docker/integration-cli/cli/build" "github.com/docker/docker/integration-cli/cli/build"
"github.com/docker/docker/integration-cli/request"
icmd "github.com/docker/docker/pkg/testutil/cmd" icmd "github.com/docker/docker/pkg/testutil/cmd"
"github.com/go-check/check" "github.com/go-check/check"
"golang.org/x/net/context"
) )
func (s *DockerSuite) TestVolumeCLICreate(c *check.C) { func (s *DockerSuite) TestVolumeCLICreate(c *check.C) {
@ -607,25 +610,28 @@ func (s *DockerSuite) TestDuplicateMountpointsForVolumesFromAndMounts(c *check.C
err := os.MkdirAll("/tmp/data", 0755) err := os.MkdirAll("/tmp/data", 0755)
c.Assert(err, checker.IsNil) c.Assert(err, checker.IsNil)
// Mounts is available in API // Mounts is available in API
status, body, err := request.SockRequest("POST", "/containers/create?name=app", map[string]interface{}{ cli, err := client.NewEnvClient()
"Image": "busybox", c.Assert(err, checker.IsNil)
"Cmd": []string{"top"}, defer cli.Close()
"HostConfig": map[string]interface{}{
"VolumesFrom": []string{
"data1",
"data2",
},
"Mounts": []map[string]interface{}{
{
"Type": "bind",
"Source": "/tmp/data",
"Target": "/tmp/data",
},
}},
}, daemonHost())
c.Assert(err, checker.IsNil, check.Commentf(string(body))) config := container.Config{
c.Assert(status, checker.Equals, http.StatusCreated, check.Commentf(string(body))) Cmd: []string{"top"},
Image: "busybox",
}
hostConfig := container.HostConfig{
VolumesFrom: []string{"data1", "data2"},
Mounts: []mount.Mount{
{
Type: "bind",
Source: "/tmp/data",
Target: "/tmp/data",
},
},
}
_, err = cli.ContainerCreate(context.Background(), &config, &hostConfig, &network.NetworkingConfig{}, "app")
c.Assert(err, checker.IsNil)
// No volume will be referenced (mount is /tmp/data), this is backward compatible // No volume will be referenced (mount is /tmp/data), this is backward compatible
out, _ = dockerCmd(c, "inspect", "--format", "{{(index .Mounts 0).Name}}", "app") out, _ = dockerCmd(c, "inspect", "--format", "{{(index .Mounts 0).Name}}", "app")

View File

@ -22,9 +22,14 @@ func (s *DockerSuite) TestDeprecatedContainerAPIStartHostConfig(c *check.C) {
config := map[string]interface{}{ config := map[string]interface{}{
"Binds": []string{"/aa:/bb"}, "Binds": []string{"/aa:/bb"},
} }
status, _, err := request.SockRequest("POST", "/containers/"+name+"/start", config, daemonHost()) res, body, err := request.Post("/containers/"+name+"/start", request.JSONBody(config))
c.Assert(err, checker.IsNil) c.Assert(err, checker.IsNil)
c.Assert(status, checker.Equals, http.StatusBadRequest)
buf, err := request.ReadBody(body)
c.Assert(err, checker.IsNil)
c.Assert(res.StatusCode, checker.Equals, http.StatusBadRequest)
c.Assert(string(buf), checker.Contains, "was deprecated since API v1.22")
} }
func (s *DockerSuite) TestDeprecatedContainerAPIStartVolumeBinds(c *check.C) { func (s *DockerSuite) TestDeprecatedContainerAPIStartVolumeBinds(c *check.C) {
@ -40,17 +45,17 @@ func (s *DockerSuite) TestDeprecatedContainerAPIStartVolumeBinds(c *check.C) {
"Volumes": map[string]struct{}{path: {}}, "Volumes": map[string]struct{}{path: {}},
} }
status, _, err := request.SockRequest("POST", formatV123StartAPIURL("/containers/create?name="+name), config, daemonHost()) res, _, err := request.Post(formatV123StartAPIURL("/containers/create?name="+name), request.JSONBody(config))
c.Assert(err, checker.IsNil) c.Assert(err, checker.IsNil)
c.Assert(status, checker.Equals, http.StatusCreated) c.Assert(res.StatusCode, checker.Equals, http.StatusCreated)
bindPath := RandomTmpDirPath("test", testEnv.DaemonPlatform()) bindPath := RandomTmpDirPath("test", testEnv.DaemonPlatform())
config = map[string]interface{}{ config = map[string]interface{}{
"Binds": []string{bindPath + ":" + path}, "Binds": []string{bindPath + ":" + path},
} }
status, _, err = request.SockRequest("POST", formatV123StartAPIURL("/containers/"+name+"/start"), config, daemonHost()) res, _, err = request.Post(formatV123StartAPIURL("/containers/"+name+"/start"), request.JSONBody(config))
c.Assert(err, checker.IsNil) c.Assert(err, checker.IsNil)
c.Assert(status, checker.Equals, http.StatusNoContent) c.Assert(res.StatusCode, checker.Equals, http.StatusNoContent)
pth, err := inspectMountSourceField(name, path) pth, err := inspectMountSourceField(name, path)
c.Assert(err, checker.IsNil) c.Assert(err, checker.IsNil)
@ -67,9 +72,9 @@ func (s *DockerSuite) TestDeprecatedContainerAPIStartDupVolumeBinds(c *check.C)
"Volumes": map[string]struct{}{"/tmp": {}}, "Volumes": map[string]struct{}{"/tmp": {}},
} }
status, _, err := request.SockRequest("POST", formatV123StartAPIURL("/containers/create?name="+name), config, daemonHost()) res, _, err := request.Post(formatV123StartAPIURL("/containers/create?name="+name), request.JSONBody(config))
c.Assert(err, checker.IsNil) c.Assert(err, checker.IsNil)
c.Assert(status, checker.Equals, http.StatusCreated) c.Assert(res.StatusCode, checker.Equals, http.StatusCreated)
bindPath1 := RandomTmpDirPath("test1", testEnv.DaemonPlatform()) bindPath1 := RandomTmpDirPath("test1", testEnv.DaemonPlatform())
bindPath2 := RandomTmpDirPath("test2", testEnv.DaemonPlatform()) bindPath2 := RandomTmpDirPath("test2", testEnv.DaemonPlatform())
@ -77,10 +82,14 @@ func (s *DockerSuite) TestDeprecatedContainerAPIStartDupVolumeBinds(c *check.C)
config = map[string]interface{}{ config = map[string]interface{}{
"Binds": []string{bindPath1 + ":/tmp", bindPath2 + ":/tmp"}, "Binds": []string{bindPath1 + ":/tmp", bindPath2 + ":/tmp"},
} }
status, body, err := request.SockRequest("POST", formatV123StartAPIURL("/containers/"+name+"/start"), config, daemonHost()) res, body, err := request.Post(formatV123StartAPIURL("/containers/"+name+"/start"), request.JSONBody(config))
c.Assert(err, checker.IsNil) c.Assert(err, checker.IsNil)
c.Assert(status, checker.Equals, http.StatusBadRequest)
c.Assert(string(body), checker.Contains, "Duplicate mount point", check.Commentf("Expected failure due to duplicate bind mounts to same path, instead got: %q with error: %v", string(body), err)) buf, err := request.ReadBody(body)
c.Assert(err, checker.IsNil)
c.Assert(res.StatusCode, checker.Equals, http.StatusBadRequest)
c.Assert(string(buf), checker.Contains, "Duplicate mount point", check.Commentf("Expected failure due to duplicate bind mounts to same path, instead got: %q with error: %v", string(buf), err))
} }
func (s *DockerSuite) TestDeprecatedContainerAPIStartVolumesFrom(c *check.C) { func (s *DockerSuite) TestDeprecatedContainerAPIStartVolumesFrom(c *check.C) {
@ -97,16 +106,16 @@ func (s *DockerSuite) TestDeprecatedContainerAPIStartVolumesFrom(c *check.C) {
"Volumes": map[string]struct{}{volPath: {}}, "Volumes": map[string]struct{}{volPath: {}},
} }
status, _, err := request.SockRequest("POST", formatV123StartAPIURL("/containers/create?name="+name), config, daemonHost()) res, _, err := request.Post(formatV123StartAPIURL("/containers/create?name="+name), request.JSONBody(config))
c.Assert(err, checker.IsNil) c.Assert(err, checker.IsNil)
c.Assert(status, checker.Equals, http.StatusCreated) c.Assert(res.StatusCode, checker.Equals, http.StatusCreated)
config = map[string]interface{}{ config = map[string]interface{}{
"VolumesFrom": []string{volName}, "VolumesFrom": []string{volName},
} }
status, _, err = request.SockRequest("POST", formatV123StartAPIURL("/containers/"+name+"/start"), config, daemonHost()) res, _, err = request.Post(formatV123StartAPIURL("/containers/"+name+"/start"), request.JSONBody(config))
c.Assert(err, checker.IsNil) c.Assert(err, checker.IsNil)
c.Assert(status, checker.Equals, http.StatusNoContent) c.Assert(res.StatusCode, checker.Equals, http.StatusNoContent)
pth, err := inspectMountSourceField(name, volPath) pth, err := inspectMountSourceField(name, volPath)
c.Assert(err, checker.IsNil) c.Assert(err, checker.IsNil)
@ -127,9 +136,9 @@ func (s *DockerSuite) TestDeprecatedPostContainerBindNormalVolume(c *check.C) {
dockerCmd(c, "create", "-v", "/foo", "--name=two", "busybox") dockerCmd(c, "create", "-v", "/foo", "--name=two", "busybox")
bindSpec := map[string][]string{"Binds": {fooDir + ":/foo"}} bindSpec := map[string][]string{"Binds": {fooDir + ":/foo"}}
status, _, err := request.SockRequest("POST", formatV123StartAPIURL("/containers/two/start"), bindSpec, daemonHost()) res, _, err := request.Post(formatV123StartAPIURL("/containers/two/start"), request.JSONBody(bindSpec))
c.Assert(err, checker.IsNil) c.Assert(err, checker.IsNil)
c.Assert(status, checker.Equals, http.StatusNoContent) c.Assert(res.StatusCode, checker.Equals, http.StatusNoContent)
fooDir2, err := inspectMountSourceField("two", "/foo") fooDir2, err := inspectMountSourceField("two", "/foo")
c.Assert(err, checker.IsNil) c.Assert(err, checker.IsNil)

View File

@ -22,7 +22,7 @@ func (s *DockerNetworkSuite) TestDeprecatedDockerNetworkStartAPIWithHostconfig(c
"NetworkMode": netName, "NetworkMode": netName,
}, },
} }
_, _, err := request.SockRequest("POST", formatV123StartAPIURL("/containers/"+conName+"/start"), config, daemonHost()) _, _, err := request.Post(formatV123StartAPIURL("/containers/"+conName+"/start"), request.JSONBody(config))
c.Assert(err, checker.IsNil) c.Assert(err, checker.IsNil)
c.Assert(waitRun(conName), checker.IsNil) c.Assert(waitRun(conName), checker.IsNil)
networks := inspectField(c, conName, "NetworkSettings.Networks") networks := inspectField(c, conName, "NetworkSettings.Networks")

View File

@ -15,6 +15,7 @@ import (
"time" "time"
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/docker/docker/client"
"github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/integration-cli/checker"
"github.com/docker/docker/integration-cli/cli" "github.com/docker/docker/integration-cli/cli"
"github.com/docker/docker/integration-cli/daemon" "github.com/docker/docker/integration-cli/daemon"
@ -22,6 +23,7 @@ import (
"github.com/docker/docker/integration-cli/request" "github.com/docker/docker/integration-cli/request"
icmd "github.com/docker/docker/pkg/testutil/cmd" icmd "github.com/docker/docker/pkg/testutil/cmd"
"github.com/go-check/check" "github.com/go-check/check"
"golang.org/x/net/context"
) )
// Deprecated // Deprecated
@ -267,17 +269,12 @@ func daemonTime(c *check.C) time.Time {
if testEnv.LocalDaemon() { if testEnv.LocalDaemon() {
return time.Now() return time.Now()
} }
cli, err := client.NewEnvClient()
status, body, err := request.SockRequest("GET", "/info", nil, daemonHost())
c.Assert(err, check.IsNil) c.Assert(err, check.IsNil)
c.Assert(status, check.Equals, http.StatusOK) defer cli.Close()
type infoJSON struct { info, err := cli.Info(context.Background())
SystemTime string c.Assert(err, check.IsNil)
}
var info infoJSON
err = json.Unmarshal(body, &info)
c.Assert(err, check.IsNil, check.Commentf("unable to unmarshal GET /info response"))
dt, err := time.Parse(time.RFC3339Nano, info.SystemTime) dt, err := time.Parse(time.RFC3339Nano, info.SystemTime)
c.Assert(err, check.IsNil, check.Commentf("invalid time format in GET /info response")) c.Assert(err, check.IsNil, check.Commentf("invalid time format in GET /info response"))
@ -376,10 +373,12 @@ func waitInspectWithArgs(name, expr, expected string, timeout time.Duration, arg
} }
func getInspectBody(c *check.C, version, id string) []byte { func getInspectBody(c *check.C, version, id string) []byte {
endpoint := fmt.Sprintf("/%s/containers/%s/json", version, id) var httpClient *http.Client
status, body, err := request.SockRequest("GET", endpoint, nil, daemonHost()) cli, err := client.NewClient(daemonHost(), version, httpClient, nil)
c.Assert(err, check.IsNil)
defer cli.Close()
_, body, err := cli.ContainerInspectWithRaw(context.Background(), id, false)
c.Assert(err, check.IsNil) c.Assert(err, check.IsNil)
c.Assert(status, check.Equals, http.StatusOK)
return body return body
} }
@ -406,20 +405,17 @@ func minimalBaseImage() string {
} }
func getGoroutineNumber() (int, error) { func getGoroutineNumber() (int, error) {
i := struct { cli, err := client.NewEnvClient()
NGoroutines int
}{}
status, b, err := request.SockRequest("GET", "/info", nil, daemonHost())
if err != nil { if err != nil {
return 0, err return 0, err
} }
if status != http.StatusOK { defer cli.Close()
return 0, fmt.Errorf("http status code: %d", status)
} info, err := cli.Info(context.Background())
if err := json.Unmarshal(b, &i); err != nil { if err != nil {
return 0, err return 0, err
} }
return i.NGoroutines, nil return info.NGoroutines, nil
} }
func waitForGoroutines(expected int) error { func waitForGoroutines(expected int) error {

View File

@ -1,16 +1,14 @@
package environment package environment
import ( import (
"encoding/json"
"fmt"
"net/http"
"regexp" "regexp"
"strings" "strings"
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
volumetypes "github.com/docker/docker/api/types/volume" "github.com/docker/docker/api/types/filters"
"github.com/docker/docker/integration-cli/request" "github.com/docker/docker/client"
icmd "github.com/docker/docker/pkg/testutil/cmd" icmd "github.com/docker/docker/pkg/testutil/cmd"
"golang.org/x/net/context"
) )
type testingT interface { type testingT interface {
@ -26,15 +24,21 @@ type logT interface {
// and removing everything else. It's meant to run after any tests so that they don't // and removing everything else. It's meant to run after any tests so that they don't
// depend on each others. // depend on each others.
func (e *Execution) Clean(t testingT, dockerBinary string) { func (e *Execution) Clean(t testingT, dockerBinary string) {
cli, err := client.NewEnvClient()
if err != nil {
t.Fatalf("%v", err)
}
defer cli.Close()
if (e.DaemonPlatform() != "windows") || (e.DaemonPlatform() == "windows" && e.Isolation() == "hyperv") { if (e.DaemonPlatform() != "windows") || (e.DaemonPlatform() == "windows" && e.Isolation() == "hyperv") {
unpauseAllContainers(t, dockerBinary) unpauseAllContainers(t, dockerBinary)
} }
deleteAllContainers(t, dockerBinary) deleteAllContainers(t, dockerBinary)
deleteAllImages(t, dockerBinary, e.protectedElements.images) deleteAllImages(t, dockerBinary, e.protectedElements.images)
deleteAllVolumes(t, dockerBinary) deleteAllVolumes(t, cli)
deleteAllNetworks(t, dockerBinary, e.DaemonPlatform()) deleteAllNetworks(t, cli, e.DaemonPlatform())
if e.DaemonPlatform() == "linux" { if e.DaemonPlatform() == "linux" {
deleteAllPlugins(t, dockerBinary) deleteAllPlugins(t, cli, dockerBinary)
} }
} }
@ -108,41 +112,34 @@ func deleteAllImages(t testingT, dockerBinary string, protectedImages map[string
} }
} }
func deleteAllVolumes(t testingT, dockerBinary string) { func deleteAllVolumes(t testingT, c client.APIClient) {
volumes, err := getAllVolumes() var errs []string
volumes, err := getAllVolumes(c)
if err != nil { if err != nil {
t.Fatalf("%v", err) t.Fatalf("%v", err)
} }
var errs []string
for _, v := range volumes { for _, v := range volumes {
status, b, err := request.SockRequest("DELETE", "/volumes/"+v.Name, nil, request.DaemonHost()) err := c.VolumeRemove(context.Background(), v.Name, true)
if err != nil { if err != nil {
errs = append(errs, err.Error()) errs = append(errs, err.Error())
continue continue
} }
if status != http.StatusNoContent {
errs = append(errs, fmt.Sprintf("error deleting volume %s: %s", v.Name, string(b)))
}
} }
if len(errs) > 0 { if len(errs) > 0 {
t.Fatalf("%v", strings.Join(errs, "\n")) t.Fatalf("%v", strings.Join(errs, "\n"))
} }
} }
func getAllVolumes() ([]*types.Volume, error) { func getAllVolumes(c client.APIClient) ([]*types.Volume, error) {
var volumes volumetypes.VolumesListOKBody volumes, err := c.VolumeList(context.Background(), filters.Args{})
_, b, err := request.SockRequest("GET", "/volumes", nil, request.DaemonHost())
if err != nil { if err != nil {
return nil, err return nil, err
} }
if err := json.Unmarshal(b, &volumes); err != nil {
return nil, err
}
return volumes.Volumes, nil return volumes.Volumes, nil
} }
func deleteAllNetworks(t testingT, dockerBinary string, daemonPlatform string) { func deleteAllNetworks(t testingT, c client.APIClient, daemonPlatform string) {
networks, err := getAllNetworks() networks, err := getAllNetworks(c)
if err != nil { if err != nil {
t.Fatalf("%v", err) t.Fatalf("%v", err)
} }
@ -155,62 +152,47 @@ func deleteAllNetworks(t testingT, dockerBinary string, daemonPlatform string) {
// nat is a pre-defined network on Windows and cannot be removed // nat is a pre-defined network on Windows and cannot be removed
continue continue
} }
status, b, err := request.SockRequest("DELETE", "/networks/"+n.Name, nil, request.DaemonHost()) err := c.NetworkRemove(context.Background(), n.ID)
if err != nil { if err != nil {
errs = append(errs, err.Error()) errs = append(errs, err.Error())
continue continue
} }
if status != http.StatusNoContent {
errs = append(errs, fmt.Sprintf("error deleting network %s: %s", n.Name, string(b)))
}
} }
if len(errs) > 0 { if len(errs) > 0 {
t.Fatalf("%v", strings.Join(errs, "\n")) t.Fatalf("%v", strings.Join(errs, "\n"))
} }
} }
func getAllNetworks() ([]types.NetworkResource, error) { func getAllNetworks(c client.APIClient) ([]types.NetworkResource, error) {
var networks []types.NetworkResource networks, err := c.NetworkList(context.Background(), types.NetworkListOptions{})
_, b, err := request.SockRequest("GET", "/networks", nil, request.DaemonHost())
if err != nil { if err != nil {
return nil, err return nil, err
} }
if err := json.Unmarshal(b, &networks); err != nil {
return nil, err
}
return networks, nil return networks, nil
} }
func deleteAllPlugins(t testingT, dockerBinary string) { func deleteAllPlugins(t testingT, c client.APIClient, dockerBinary string) {
plugins, err := getAllPlugins() plugins, err := getAllPlugins(c)
if err != nil { if err != nil {
t.Fatalf("%v", err) t.Fatalf("%v", err)
} }
var errs []string var errs []string
for _, p := range plugins { for _, p := range plugins {
pluginName := p.Name err := c.PluginRemove(context.Background(), p.Name, types.PluginRemoveOptions{Force: true})
status, b, err := request.SockRequest("DELETE", "/plugins/"+pluginName+"?force=1", nil, request.DaemonHost())
if err != nil { if err != nil {
errs = append(errs, err.Error()) errs = append(errs, err.Error())
continue continue
} }
if status != http.StatusOK {
errs = append(errs, fmt.Sprintf("error deleting plugin %s: %s", p.Name, string(b)))
}
} }
if len(errs) > 0 { if len(errs) > 0 {
t.Fatalf("%v", strings.Join(errs, "\n")) t.Fatalf("%v", strings.Join(errs, "\n"))
} }
} }
func getAllPlugins() (types.PluginsListResponse, error) { func getAllPlugins(c client.APIClient) (types.PluginsListResponse, error) {
var plugins types.PluginsListResponse plugins, err := c.PluginList(context.Background(), filters.Args{})
_, b, err := request.SockRequest("GET", "/plugins", nil, request.DaemonHost())
if err != nil { if err != nil {
return nil, err return nil, err
} }
if err := json.Unmarshal(b, &plugins); err != nil {
return nil, err
}
return plugins, nil return plugins, nil
} }