networks.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. package cluster // import "github.com/docker/docker/daemon/cluster"
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/containerd/log"
  6. apitypes "github.com/docker/docker/api/types"
  7. "github.com/docker/docker/api/types/filters"
  8. "github.com/docker/docker/api/types/network"
  9. types "github.com/docker/docker/api/types/swarm"
  10. "github.com/docker/docker/daemon/cluster/convert"
  11. internalnetwork "github.com/docker/docker/daemon/network"
  12. "github.com/docker/docker/errdefs"
  13. "github.com/docker/docker/internal/compatcontext"
  14. "github.com/docker/docker/runconfig"
  15. swarmapi "github.com/moby/swarmkit/v2/api"
  16. "github.com/pkg/errors"
  17. )
  18. // GetNetworks returns all current cluster managed networks.
  19. func (c *Cluster) GetNetworks(filter filters.Args) ([]apitypes.NetworkResource, error) {
  20. var f *swarmapi.ListNetworksRequest_Filters
  21. if filter.Len() > 0 {
  22. f = &swarmapi.ListNetworksRequest_Filters{}
  23. if filter.Contains("name") {
  24. f.Names = filter.Get("name")
  25. f.NamePrefixes = filter.Get("name")
  26. }
  27. if filter.Contains("id") {
  28. f.IDPrefixes = filter.Get("id")
  29. }
  30. }
  31. list, err := c.getNetworks(f)
  32. if err != nil {
  33. return nil, err
  34. }
  35. filterPredefinedNetworks(&list)
  36. return internalnetwork.FilterNetworks(list, filter)
  37. }
  38. func filterPredefinedNetworks(networks *[]apitypes.NetworkResource) {
  39. if networks == nil {
  40. return
  41. }
  42. var idxs []int
  43. for i, n := range *networks {
  44. if v, ok := n.Labels["com.docker.swarm.predefined"]; ok && v == "true" {
  45. idxs = append(idxs, i)
  46. }
  47. }
  48. for i, idx := range idxs {
  49. idx -= i
  50. *networks = append((*networks)[:idx], (*networks)[idx+1:]...)
  51. }
  52. }
  53. func (c *Cluster) getNetworks(filters *swarmapi.ListNetworksRequest_Filters) ([]apitypes.NetworkResource, error) {
  54. c.mu.RLock()
  55. defer c.mu.RUnlock()
  56. state := c.currentNodeState()
  57. if !state.IsActiveManager() {
  58. return nil, c.errNoManager(state)
  59. }
  60. ctx := context.TODO()
  61. ctx, cancel := c.getRequestContext(ctx)
  62. defer cancel()
  63. r, err := state.controlClient.ListNetworks(ctx, &swarmapi.ListNetworksRequest{Filters: filters})
  64. if err != nil {
  65. return nil, err
  66. }
  67. networks := make([]apitypes.NetworkResource, 0, len(r.Networks))
  68. for _, network := range r.Networks {
  69. networks = append(networks, convert.BasicNetworkFromGRPC(*network))
  70. }
  71. return networks, nil
  72. }
  73. // GetNetwork returns a cluster network by an ID.
  74. func (c *Cluster) GetNetwork(input string) (apitypes.NetworkResource, error) {
  75. var network *swarmapi.Network
  76. if err := c.lockedManagerAction(func(ctx context.Context, state nodeState) error {
  77. n, err := getNetwork(ctx, state.controlClient, input)
  78. if err != nil {
  79. return err
  80. }
  81. network = n
  82. return nil
  83. }); err != nil {
  84. return apitypes.NetworkResource{}, err
  85. }
  86. return convert.BasicNetworkFromGRPC(*network), nil
  87. }
  88. // GetNetworksByName returns cluster managed networks by name.
  89. // It is ok to have multiple networks here. #18864
  90. func (c *Cluster) GetNetworksByName(name string) ([]apitypes.NetworkResource, error) {
  91. // Note that swarmapi.GetNetworkRequest.Name is not functional.
  92. // So we cannot just use that with c.GetNetwork.
  93. return c.getNetworks(&swarmapi.ListNetworksRequest_Filters{
  94. Names: []string{name},
  95. })
  96. }
  97. func attacherKey(target, containerID string) string {
  98. return containerID + ":" + target
  99. }
  100. // UpdateAttachment signals the attachment config to the attachment
  101. // waiter who is trying to start or attach the container to the
  102. // network.
  103. func (c *Cluster) UpdateAttachment(target, containerID string, config *network.NetworkingConfig) error {
  104. c.mu.Lock()
  105. attacher, ok := c.attachers[attacherKey(target, containerID)]
  106. if !ok || attacher == nil {
  107. c.mu.Unlock()
  108. return fmt.Errorf("could not find attacher for container %s to network %s", containerID, target)
  109. }
  110. if attacher.inProgress {
  111. log.G(context.TODO()).Debugf("Discarding redundant notice of resource allocation on network %s for task id %s", target, attacher.taskID)
  112. c.mu.Unlock()
  113. return nil
  114. }
  115. attacher.inProgress = true
  116. c.mu.Unlock()
  117. attacher.attachWaitCh <- config
  118. return nil
  119. }
  120. // WaitForDetachment waits for the container to stop or detach from
  121. // the network.
  122. func (c *Cluster) WaitForDetachment(ctx context.Context, networkName, networkID, taskID, containerID string) error {
  123. c.mu.RLock()
  124. attacher, ok := c.attachers[attacherKey(networkName, containerID)]
  125. if !ok {
  126. attacher, ok = c.attachers[attacherKey(networkID, containerID)]
  127. }
  128. state := c.currentNodeState()
  129. if state.swarmNode == nil || state.swarmNode.Agent() == nil {
  130. c.mu.RUnlock()
  131. return errors.New("invalid cluster node while waiting for detachment")
  132. }
  133. c.mu.RUnlock()
  134. agent := state.swarmNode.Agent()
  135. if ok && attacher != nil &&
  136. attacher.detachWaitCh != nil &&
  137. attacher.attachCompleteCh != nil {
  138. // Attachment may be in progress still so wait for
  139. // attachment to complete.
  140. select {
  141. case <-attacher.attachCompleteCh:
  142. case <-ctx.Done():
  143. return ctx.Err()
  144. }
  145. if attacher.taskID == taskID {
  146. select {
  147. case <-attacher.detachWaitCh:
  148. case <-ctx.Done():
  149. return ctx.Err()
  150. }
  151. }
  152. }
  153. return agent.ResourceAllocator().DetachNetwork(ctx, taskID)
  154. }
  155. // AttachNetwork generates an attachment request towards the manager.
  156. func (c *Cluster) AttachNetwork(target string, containerID string, addresses []string) (*network.NetworkingConfig, error) {
  157. aKey := attacherKey(target, containerID)
  158. c.mu.Lock()
  159. state := c.currentNodeState()
  160. if state.swarmNode == nil || state.swarmNode.Agent() == nil {
  161. c.mu.Unlock()
  162. return nil, errors.New("invalid cluster node while attaching to network")
  163. }
  164. if attacher, ok := c.attachers[aKey]; ok {
  165. c.mu.Unlock()
  166. return attacher.config, nil
  167. }
  168. agent := state.swarmNode.Agent()
  169. attachWaitCh := make(chan *network.NetworkingConfig)
  170. detachWaitCh := make(chan struct{})
  171. attachCompleteCh := make(chan struct{})
  172. c.attachers[aKey] = &attacher{
  173. attachWaitCh: attachWaitCh,
  174. attachCompleteCh: attachCompleteCh,
  175. detachWaitCh: detachWaitCh,
  176. }
  177. c.mu.Unlock()
  178. ctx := context.TODO()
  179. ctx, cancel := c.getRequestContext(ctx)
  180. defer cancel()
  181. taskID, err := agent.ResourceAllocator().AttachNetwork(ctx, containerID, target, addresses)
  182. if err != nil {
  183. c.mu.Lock()
  184. delete(c.attachers, aKey)
  185. c.mu.Unlock()
  186. return nil, fmt.Errorf("Could not attach to network %s: %v", target, err)
  187. }
  188. c.mu.Lock()
  189. c.attachers[aKey].taskID = taskID
  190. close(attachCompleteCh)
  191. c.mu.Unlock()
  192. log.G(ctx).Debugf("Successfully attached to network %s with task id %s", target, taskID)
  193. release := func() {
  194. ctx := compatcontext.WithoutCancel(ctx)
  195. ctx, cancel := c.getRequestContext(ctx)
  196. defer cancel()
  197. if err := agent.ResourceAllocator().DetachNetwork(ctx, taskID); err != nil {
  198. log.G(ctx).Errorf("Failed remove network attachment %s to network %s on allocation failure: %v",
  199. taskID, target, err)
  200. }
  201. }
  202. var config *network.NetworkingConfig
  203. select {
  204. case config = <-attachWaitCh:
  205. case <-ctx.Done():
  206. release()
  207. return nil, fmt.Errorf("attaching to network failed, make sure your network options are correct and check manager logs: %v", ctx.Err())
  208. }
  209. c.mu.Lock()
  210. c.attachers[aKey].config = config
  211. c.mu.Unlock()
  212. log.G(ctx).Debugf("Successfully allocated resources on network %s for task id %s", target, taskID)
  213. return config, nil
  214. }
  215. // DetachNetwork unblocks the waiters waiting on WaitForDetachment so
  216. // that a request to detach can be generated towards the manager.
  217. func (c *Cluster) DetachNetwork(target string, containerID string) error {
  218. aKey := attacherKey(target, containerID)
  219. c.mu.Lock()
  220. attacher, ok := c.attachers[aKey]
  221. delete(c.attachers, aKey)
  222. c.mu.Unlock()
  223. if !ok {
  224. return fmt.Errorf("could not find network attachment for container %s to network %s", containerID, target)
  225. }
  226. close(attacher.detachWaitCh)
  227. return nil
  228. }
  229. // CreateNetwork creates a new cluster managed network.
  230. func (c *Cluster) CreateNetwork(s apitypes.NetworkCreateRequest) (string, error) {
  231. if runconfig.IsPreDefinedNetwork(s.Name) {
  232. err := notAllowedError(fmt.Sprintf("%s is a pre-defined network and cannot be created", s.Name))
  233. return "", errors.WithStack(err)
  234. }
  235. var resp *swarmapi.CreateNetworkResponse
  236. if err := c.lockedManagerAction(func(ctx context.Context, state nodeState) error {
  237. networkSpec := convert.BasicNetworkCreateToGRPC(s)
  238. r, err := state.controlClient.CreateNetwork(ctx, &swarmapi.CreateNetworkRequest{Spec: &networkSpec})
  239. if err != nil {
  240. return err
  241. }
  242. resp = r
  243. return nil
  244. }); err != nil {
  245. return "", err
  246. }
  247. return resp.Network.ID, nil
  248. }
  249. // RemoveNetwork removes a cluster network.
  250. func (c *Cluster) RemoveNetwork(input string) error {
  251. return c.lockedManagerAction(func(ctx context.Context, state nodeState) error {
  252. network, err := getNetwork(ctx, state.controlClient, input)
  253. if err != nil {
  254. return err
  255. }
  256. _, err = state.controlClient.RemoveNetwork(ctx, &swarmapi.RemoveNetworkRequest{NetworkID: network.ID})
  257. return err
  258. })
  259. }
  260. func (c *Cluster) populateNetworkID(ctx context.Context, client swarmapi.ControlClient, s *types.ServiceSpec) error {
  261. // Always prefer NetworkAttachmentConfigs from TaskTemplate
  262. // but fallback to service spec for backward compatibility
  263. networks := s.TaskTemplate.Networks
  264. if len(networks) == 0 {
  265. networks = s.Networks //nolint:staticcheck // ignore SA1019: field is deprecated.
  266. }
  267. for i, n := range networks {
  268. apiNetwork, err := getNetwork(ctx, client, n.Target)
  269. if err != nil {
  270. ln, _ := c.config.Backend.FindNetwork(n.Target)
  271. if ln != nil && runconfig.IsPreDefinedNetwork(ln.Name()) {
  272. // Need to retrieve the corresponding predefined swarm network
  273. // and use its id for the request.
  274. apiNetwork, err = getNetwork(ctx, client, ln.Name())
  275. if err != nil {
  276. return errors.Wrap(errdefs.NotFound(err), "could not find the corresponding predefined swarm network")
  277. }
  278. goto setid
  279. }
  280. if ln != nil && !ln.Dynamic() {
  281. errMsg := fmt.Sprintf("The network %s cannot be used with services. Only networks scoped to the swarm can be used, such as those created with the overlay driver.", ln.Name())
  282. return errors.WithStack(notAllowedError(errMsg))
  283. }
  284. return err
  285. }
  286. setid:
  287. networks[i].Target = apiNetwork.ID
  288. }
  289. return nil
  290. }