node.go 1.9 KB

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