node.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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/docker/docker/internal/test"
  9. "github.com/gotestyourself/gotestyourself/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(t assert.TestingT, id string) *swarm.Node {
  15. if ht, ok := t.(test.HelperT); ok {
  16. ht.Helper()
  17. }
  18. cli := d.NewClientT(t)
  19. defer cli.Close()
  20. node, _, err := cli.NodeInspectWithRaw(context.Background(), id)
  21. assert.NilError(t, err)
  22. assert.Check(t, node.ID == id)
  23. return &node
  24. }
  25. // RemoveNode removes the specified node
  26. func (d *Daemon) RemoveNode(t assert.TestingT, id string, force bool) {
  27. if ht, ok := t.(test.HelperT); ok {
  28. ht.Helper()
  29. }
  30. cli := d.NewClientT(t)
  31. defer cli.Close()
  32. options := types.NodeRemoveOptions{
  33. Force: force,
  34. }
  35. err := cli.NodeRemove(context.Background(), id, options)
  36. assert.NilError(t, err)
  37. }
  38. // UpdateNode updates a swarm node with the specified node constructor
  39. func (d *Daemon) UpdateNode(t assert.TestingT, id string, f ...NodeConstructor) {
  40. if ht, ok := t.(test.HelperT); ok {
  41. ht.Helper()
  42. }
  43. cli := d.NewClientT(t)
  44. defer cli.Close()
  45. for i := 0; ; i++ {
  46. node := d.GetNode(t, id)
  47. for _, fn := range f {
  48. fn(node)
  49. }
  50. err := cli.NodeUpdate(context.Background(), node.ID, node.Version, node.Spec)
  51. if i < 10 && err != nil && strings.Contains(err.Error(), "update out of sequence") {
  52. time.Sleep(100 * time.Millisecond)
  53. continue
  54. }
  55. assert.NilError(t, err)
  56. return
  57. }
  58. }
  59. // ListNodes returns the list of the current swarm nodes
  60. func (d *Daemon) ListNodes(t assert.TestingT) []swarm.Node {
  61. if ht, ok := t.(test.HelperT); ok {
  62. ht.Helper()
  63. }
  64. cli := d.NewClientT(t)
  65. defer cli.Close()
  66. nodes, err := cli.NodeList(context.Background(), types.NodeListOptions{})
  67. assert.NilError(t, err)
  68. return nodes
  69. }