networks.go 9.3 KB

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