networks.go 9.7 KB

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