node.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package daemon
  2. import (
  3. "context"
  4. "strings"
  5. "time"
  6. "github.com/docker/docker/api/types"
  7. "github.com/docker/docker/api/types/swarm"
  8. "github.com/gotestyourself/gotestyourself/assert"
  9. )
  10. // NodeConstructor defines a swarm node constructor
  11. type NodeConstructor func(*swarm.Node)
  12. // GetNode returns a swarm node identified by the specified id
  13. func (d *Daemon) GetNode(t assert.TestingT, id string) *swarm.Node {
  14. cli := d.NewClientT(t)
  15. defer cli.Close()
  16. node, _, err := cli.NodeInspectWithRaw(context.Background(), id)
  17. assert.NilError(t, err)
  18. assert.Check(t, node.ID == id)
  19. return &node
  20. }
  21. // RemoveNode removes the specified node
  22. func (d *Daemon) RemoveNode(t assert.TestingT, id string, force bool) {
  23. cli := d.NewClientT(t)
  24. defer cli.Close()
  25. options := types.NodeRemoveOptions{
  26. Force: force,
  27. }
  28. err := cli.NodeRemove(context.Background(), id, options)
  29. assert.NilError(t, err)
  30. }
  31. // UpdateNode updates a swarm node with the specified node constructor
  32. func (d *Daemon) UpdateNode(t assert.TestingT, id string, f ...NodeConstructor) {
  33. cli := d.NewClientT(t)
  34. defer cli.Close()
  35. for i := 0; ; i++ {
  36. node := d.GetNode(t, id)
  37. for _, fn := range f {
  38. fn(node)
  39. }
  40. err := cli.NodeUpdate(context.Background(), node.ID, node.Version, node.Spec)
  41. if i < 10 && err != nil && strings.Contains(err.Error(), "update out of sequence") {
  42. time.Sleep(100 * time.Millisecond)
  43. continue
  44. }
  45. assert.NilError(t, err)
  46. return
  47. }
  48. }
  49. // ListNodes returns the list of the current swarm nodes
  50. func (d *Daemon) ListNodes(t assert.TestingT) []swarm.Node {
  51. cli := d.NewClientT(t)
  52. defer cli.Close()
  53. nodes, err := cli.NodeList(context.Background(), types.NodeListOptions{})
  54. assert.NilError(t, err)
  55. return nodes
  56. }