resource.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package agent
  2. import (
  3. "github.com/docker/swarmkit/api"
  4. "golang.org/x/net/context"
  5. )
  6. type resourceAllocator struct {
  7. agent *Agent
  8. }
  9. // ResourceAllocator is an interface to allocate resource such as
  10. // network attachments from a worker node.
  11. type ResourceAllocator interface {
  12. // AttachNetwork creates a network attachment in the manager
  13. // given a target network and a unique ID representing the
  14. // connecting entity and optionally a list of ipv4/ipv6
  15. // addresses to be assigned to the attachment. AttachNetwork
  16. // returns a unique ID for the attachment if successful or an
  17. // error in case of failure.
  18. AttachNetwork(ctx context.Context, id, target string, addresses []string) (string, error)
  19. // DetachNetworks deletes a network attachment for the passed
  20. // attachment ID. The attachment ID is obtained from a
  21. // previous AttachNetwork call.
  22. DetachNetwork(ctx context.Context, aID string) error
  23. }
  24. // AttachNetwork creates a network attachment.
  25. func (r *resourceAllocator) AttachNetwork(ctx context.Context, id, target string, addresses []string) (string, error) {
  26. var taskID string
  27. if err := r.agent.withSession(ctx, func(session *session) error {
  28. client := api.NewResourceAllocatorClient(session.conn.ClientConn)
  29. r, err := client.AttachNetwork(ctx, &api.AttachNetworkRequest{
  30. Config: &api.NetworkAttachmentConfig{
  31. Target: target,
  32. Addresses: addresses,
  33. },
  34. ContainerID: id,
  35. })
  36. if err != nil {
  37. return err
  38. }
  39. taskID = r.AttachmentID
  40. return nil
  41. }); err != nil {
  42. return "", err
  43. }
  44. return taskID, nil
  45. }
  46. // DetachNetwork deletes a network attachment.
  47. func (r *resourceAllocator) DetachNetwork(ctx context.Context, aID string) error {
  48. return r.agent.withSession(ctx, func(session *session) error {
  49. client := api.NewResourceAllocatorClient(session.conn.ClientConn)
  50. _, err := client.DetachNetwork(ctx, &api.DetachNetworkRequest{
  51. AttachmentID: aID,
  52. })
  53. return err
  54. })
  55. }
  56. // ResourceAllocator provides an interface to access resource
  57. // allocation methods such as AttachNetwork and DetachNetwork.
  58. func (a *Agent) ResourceAllocator() ResourceAllocator {
  59. return &resourceAllocator{agent: a}
  60. }