networks.go 9.2 KB

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