github.com/docker/docker@v299999999.0.0-20200612211812-aaf470eca7b5+incompatible/testutil/daemon/node.go (about)

     1  package daemon
     2  
     3  import (
     4  	"context"
     5  	"strings"
     6  	"testing"
     7  	"time"
     8  
     9  	"github.com/docker/docker/api/types"
    10  	"github.com/docker/docker/api/types/swarm"
    11  	"gotest.tools/v3/assert"
    12  )
    13  
    14  // NodeConstructor defines a swarm node constructor
    15  type NodeConstructor func(*swarm.Node)
    16  
    17  // GetNode returns a swarm node identified by the specified id
    18  func (d *Daemon) GetNode(t testing.TB, id string, errCheck ...func(error) bool) *swarm.Node {
    19  	t.Helper()
    20  	cli := d.NewClientT(t)
    21  	defer cli.Close()
    22  
    23  	node, _, err := cli.NodeInspectWithRaw(context.Background(), id)
    24  	if err != nil {
    25  		for _, f := range errCheck {
    26  			if f(err) {
    27  				return nil
    28  			}
    29  		}
    30  	}
    31  	assert.NilError(t, err, "[%s] (*Daemon).GetNode: NodeInspectWithRaw(%q) failed", d.id, id)
    32  	assert.Check(t, node.ID == id)
    33  	return &node
    34  }
    35  
    36  // RemoveNode removes the specified node
    37  func (d *Daemon) RemoveNode(t testing.TB, id string, force bool) {
    38  	t.Helper()
    39  	cli := d.NewClientT(t)
    40  	defer cli.Close()
    41  
    42  	options := types.NodeRemoveOptions{
    43  		Force: force,
    44  	}
    45  	err := cli.NodeRemove(context.Background(), id, options)
    46  	assert.NilError(t, err)
    47  }
    48  
    49  // UpdateNode updates a swarm node with the specified node constructor
    50  func (d *Daemon) UpdateNode(t testing.TB, id string, f ...NodeConstructor) {
    51  	t.Helper()
    52  	cli := d.NewClientT(t)
    53  	defer cli.Close()
    54  
    55  	for i := 0; ; i++ {
    56  		node := d.GetNode(t, id)
    57  		for _, fn := range f {
    58  			fn(node)
    59  		}
    60  
    61  		err := cli.NodeUpdate(context.Background(), node.ID, node.Version, node.Spec)
    62  		if i < 10 && err != nil && strings.Contains(err.Error(), "update out of sequence") {
    63  			time.Sleep(100 * time.Millisecond)
    64  			continue
    65  		}
    66  		assert.NilError(t, err)
    67  		return
    68  	}
    69  }
    70  
    71  // ListNodes returns the list of the current swarm nodes
    72  func (d *Daemon) ListNodes(t testing.TB) []swarm.Node {
    73  	t.Helper()
    74  	cli := d.NewClientT(t)
    75  	defer cli.Close()
    76  
    77  	nodes, err := cli.NodeList(context.Background(), types.NodeListOptions{})
    78  	assert.NilError(t, err)
    79  
    80  	return nodes
    81  }