network.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  1. package daemon
  2. import (
  3. "fmt"
  4. "net"
  5. "runtime"
  6. "sort"
  7. "strings"
  8. "sync"
  9. "github.com/docker/docker/api/types"
  10. "github.com/docker/docker/api/types/network"
  11. clustertypes "github.com/docker/docker/daemon/cluster/provider"
  12. "github.com/docker/docker/errdefs"
  13. "github.com/docker/docker/pkg/plugingetter"
  14. "github.com/docker/docker/runconfig"
  15. "github.com/docker/libnetwork"
  16. lncluster "github.com/docker/libnetwork/cluster"
  17. "github.com/docker/libnetwork/driverapi"
  18. "github.com/docker/libnetwork/ipamapi"
  19. networktypes "github.com/docker/libnetwork/types"
  20. "github.com/pkg/errors"
  21. "github.com/sirupsen/logrus"
  22. "golang.org/x/net/context"
  23. )
  24. // NetworkControllerEnabled checks if the networking stack is enabled.
  25. // This feature depends on OS primitives and it's disabled in systems like Windows.
  26. func (daemon *Daemon) NetworkControllerEnabled() bool {
  27. return daemon.netController != nil
  28. }
  29. // FindNetwork returns a network based on:
  30. // 1. Full ID
  31. // 2. Full Name
  32. // 3. Partial ID
  33. // as long as there is no ambiguity
  34. func (daemon *Daemon) FindNetwork(term string) (libnetwork.Network, error) {
  35. listByFullName := []libnetwork.Network{}
  36. listByPartialID := []libnetwork.Network{}
  37. for _, nw := range daemon.GetNetworks() {
  38. if nw.ID() == term {
  39. return nw, nil
  40. }
  41. if nw.Name() == term {
  42. listByFullName = append(listByFullName, nw)
  43. }
  44. if strings.HasPrefix(nw.ID(), term) {
  45. listByPartialID = append(listByPartialID, nw)
  46. }
  47. }
  48. switch {
  49. case len(listByFullName) == 1:
  50. return listByFullName[0], nil
  51. case len(listByFullName) > 1:
  52. return nil, errdefs.InvalidParameter(errors.Errorf("network %s is ambiguous (%d matches found on name)", term, len(listByFullName)))
  53. case len(listByPartialID) == 1:
  54. return listByPartialID[0], nil
  55. case len(listByPartialID) > 1:
  56. return nil, errdefs.InvalidParameter(errors.Errorf("network %s is ambiguous (%d matches found based on ID prefix)", term, len(listByPartialID)))
  57. }
  58. // Be very careful to change the error type here, the
  59. // libnetwork.ErrNoSuchNetwork error is used by the controller
  60. // to retry the creation of the network as managed through the swarm manager
  61. return nil, errdefs.NotFound(libnetwork.ErrNoSuchNetwork(term))
  62. }
  63. // GetNetworkByID function returns a network whose ID matches the given ID.
  64. // It fails with an error if no matching network is found.
  65. func (daemon *Daemon) GetNetworkByID(id string) (libnetwork.Network, error) {
  66. c := daemon.netController
  67. if c == nil {
  68. return nil, libnetwork.ErrNoSuchNetwork(id)
  69. }
  70. return c.NetworkByID(id)
  71. }
  72. // GetNetworkByName function returns a network for a given network name.
  73. // If no network name is given, the default network is returned.
  74. func (daemon *Daemon) GetNetworkByName(name string) (libnetwork.Network, error) {
  75. c := daemon.netController
  76. if c == nil {
  77. return nil, libnetwork.ErrNoSuchNetwork(name)
  78. }
  79. if name == "" {
  80. name = c.Config().Daemon.DefaultNetwork
  81. }
  82. return c.NetworkByName(name)
  83. }
  84. // GetNetworksByIDPrefix returns a list of networks whose ID partially matches zero or more networks
  85. func (daemon *Daemon) GetNetworksByIDPrefix(partialID string) []libnetwork.Network {
  86. c := daemon.netController
  87. if c == nil {
  88. return nil
  89. }
  90. list := []libnetwork.Network{}
  91. l := func(nw libnetwork.Network) bool {
  92. if strings.HasPrefix(nw.ID(), partialID) {
  93. list = append(list, nw)
  94. }
  95. return false
  96. }
  97. c.WalkNetworks(l)
  98. return list
  99. }
  100. // getAllNetworks returns a list containing all networks
  101. func (daemon *Daemon) getAllNetworks() []libnetwork.Network {
  102. c := daemon.netController
  103. if c == nil {
  104. return nil
  105. }
  106. return c.Networks()
  107. }
  108. type ingressJob struct {
  109. create *clustertypes.NetworkCreateRequest
  110. ip net.IP
  111. jobDone chan struct{}
  112. }
  113. var (
  114. ingressWorkerOnce sync.Once
  115. ingressJobsChannel chan *ingressJob
  116. ingressID string
  117. )
  118. func (daemon *Daemon) startIngressWorker() {
  119. ingressJobsChannel = make(chan *ingressJob, 100)
  120. go func() {
  121. // nolint: gosimple
  122. for {
  123. select {
  124. case r := <-ingressJobsChannel:
  125. if r.create != nil {
  126. daemon.setupIngress(r.create, r.ip, ingressID)
  127. ingressID = r.create.ID
  128. } else {
  129. daemon.releaseIngress(ingressID)
  130. ingressID = ""
  131. }
  132. close(r.jobDone)
  133. }
  134. }
  135. }()
  136. }
  137. // enqueueIngressJob adds a ingress add/rm request to the worker queue.
  138. // It guarantees the worker is started.
  139. func (daemon *Daemon) enqueueIngressJob(job *ingressJob) {
  140. ingressWorkerOnce.Do(daemon.startIngressWorker)
  141. ingressJobsChannel <- job
  142. }
  143. // SetupIngress setups ingress networking.
  144. // The function returns a channel which will signal the caller when the programming is completed.
  145. func (daemon *Daemon) SetupIngress(create clustertypes.NetworkCreateRequest, nodeIP string) (<-chan struct{}, error) {
  146. ip, _, err := net.ParseCIDR(nodeIP)
  147. if err != nil {
  148. return nil, err
  149. }
  150. done := make(chan struct{})
  151. daemon.enqueueIngressJob(&ingressJob{&create, ip, done})
  152. return done, nil
  153. }
  154. // ReleaseIngress releases the ingress networking.
  155. // The function returns a channel which will signal the caller when the programming is completed.
  156. func (daemon *Daemon) ReleaseIngress() (<-chan struct{}, error) {
  157. done := make(chan struct{})
  158. daemon.enqueueIngressJob(&ingressJob{nil, nil, done})
  159. return done, nil
  160. }
  161. func (daemon *Daemon) setupIngress(create *clustertypes.NetworkCreateRequest, ip net.IP, staleID string) {
  162. controller := daemon.netController
  163. controller.AgentInitWait()
  164. if staleID != "" && staleID != create.ID {
  165. daemon.releaseIngress(staleID)
  166. }
  167. if _, err := daemon.createNetwork(create.NetworkCreateRequest, create.ID, true); err != nil {
  168. // If it is any other error other than already
  169. // exists error log error and return.
  170. if _, ok := err.(libnetwork.NetworkNameError); !ok {
  171. logrus.Errorf("Failed creating ingress network: %v", err)
  172. return
  173. }
  174. // Otherwise continue down the call to create or recreate sandbox.
  175. }
  176. _, err := daemon.GetNetworkByID(create.ID)
  177. if err != nil {
  178. logrus.Errorf("Failed getting ingress network by id after creating: %v", err)
  179. }
  180. }
  181. func (daemon *Daemon) releaseIngress(id string) {
  182. controller := daemon.netController
  183. if id == "" {
  184. return
  185. }
  186. n, err := controller.NetworkByID(id)
  187. if err != nil {
  188. logrus.Errorf("failed to retrieve ingress network %s: %v", id, err)
  189. return
  190. }
  191. if err := n.Delete(); err != nil {
  192. logrus.Errorf("Failed to delete ingress network %s: %v", n.ID(), err)
  193. return
  194. }
  195. }
  196. // SetNetworkBootstrapKeys sets the bootstrap keys.
  197. func (daemon *Daemon) SetNetworkBootstrapKeys(keys []*networktypes.EncryptionKey) error {
  198. err := daemon.netController.SetKeys(keys)
  199. if err == nil {
  200. // Upon successful key setting dispatch the keys available event
  201. daemon.cluster.SendClusterEvent(lncluster.EventNetworkKeysAvailable)
  202. }
  203. return err
  204. }
  205. // UpdateAttachment notifies the attacher about the attachment config.
  206. func (daemon *Daemon) UpdateAttachment(networkName, networkID, containerID string, config *network.NetworkingConfig) error {
  207. if daemon.clusterProvider == nil {
  208. return fmt.Errorf("cluster provider is not initialized")
  209. }
  210. if err := daemon.clusterProvider.UpdateAttachment(networkName, containerID, config); err != nil {
  211. return daemon.clusterProvider.UpdateAttachment(networkID, containerID, config)
  212. }
  213. return nil
  214. }
  215. // WaitForDetachment makes the cluster manager wait for detachment of
  216. // the container from the network.
  217. func (daemon *Daemon) WaitForDetachment(ctx context.Context, networkName, networkID, taskID, containerID string) error {
  218. if daemon.clusterProvider == nil {
  219. return fmt.Errorf("cluster provider is not initialized")
  220. }
  221. return daemon.clusterProvider.WaitForDetachment(ctx, networkName, networkID, taskID, containerID)
  222. }
  223. // CreateManagedNetwork creates an agent network.
  224. func (daemon *Daemon) CreateManagedNetwork(create clustertypes.NetworkCreateRequest) error {
  225. _, err := daemon.createNetwork(create.NetworkCreateRequest, create.ID, true)
  226. return err
  227. }
  228. // CreateNetwork creates a network with the given name, driver and other optional parameters
  229. func (daemon *Daemon) CreateNetwork(create types.NetworkCreateRequest) (*types.NetworkCreateResponse, error) {
  230. resp, err := daemon.createNetwork(create, "", false)
  231. if err != nil {
  232. return nil, err
  233. }
  234. return resp, err
  235. }
  236. func (daemon *Daemon) createNetwork(create types.NetworkCreateRequest, id string, agent bool) (*types.NetworkCreateResponse, error) {
  237. if runconfig.IsPreDefinedNetwork(create.Name) && !agent {
  238. err := fmt.Errorf("%s is a pre-defined network and cannot be created", create.Name)
  239. return nil, errdefs.Forbidden(err)
  240. }
  241. var warning string
  242. nw, err := daemon.GetNetworkByName(create.Name)
  243. if err != nil {
  244. if _, ok := err.(libnetwork.ErrNoSuchNetwork); !ok {
  245. return nil, err
  246. }
  247. }
  248. if nw != nil {
  249. // check if user defined CheckDuplicate, if set true, return err
  250. // otherwise prepare a warning message
  251. if create.CheckDuplicate {
  252. if !agent || nw.Info().Dynamic() {
  253. return nil, libnetwork.NetworkNameError(create.Name)
  254. }
  255. }
  256. warning = fmt.Sprintf("Network with name %s (id : %s) already exists", nw.Name(), nw.ID())
  257. }
  258. c := daemon.netController
  259. driver := create.Driver
  260. if driver == "" {
  261. driver = c.Config().Daemon.DefaultDriver
  262. }
  263. nwOptions := []libnetwork.NetworkOption{
  264. libnetwork.NetworkOptionEnableIPv6(create.EnableIPv6),
  265. libnetwork.NetworkOptionDriverOpts(create.Options),
  266. libnetwork.NetworkOptionLabels(create.Labels),
  267. libnetwork.NetworkOptionAttachable(create.Attachable),
  268. libnetwork.NetworkOptionIngress(create.Ingress),
  269. libnetwork.NetworkOptionScope(create.Scope),
  270. }
  271. if create.ConfigOnly {
  272. nwOptions = append(nwOptions, libnetwork.NetworkOptionConfigOnly())
  273. }
  274. if create.IPAM != nil {
  275. ipam := create.IPAM
  276. v4Conf, v6Conf, err := getIpamConfig(ipam.Config)
  277. if err != nil {
  278. return nil, err
  279. }
  280. nwOptions = append(nwOptions, libnetwork.NetworkOptionIpam(ipam.Driver, "", v4Conf, v6Conf, ipam.Options))
  281. }
  282. if create.Internal {
  283. nwOptions = append(nwOptions, libnetwork.NetworkOptionInternalNetwork())
  284. }
  285. if agent {
  286. nwOptions = append(nwOptions, libnetwork.NetworkOptionDynamic())
  287. nwOptions = append(nwOptions, libnetwork.NetworkOptionPersist(false))
  288. }
  289. if create.ConfigFrom != nil {
  290. nwOptions = append(nwOptions, libnetwork.NetworkOptionConfigFrom(create.ConfigFrom.Network))
  291. }
  292. if agent && driver == "overlay" && (create.Ingress || runtime.GOOS == "windows") {
  293. nodeIP, exists := daemon.GetAttachmentStore().GetIPForNetwork(id)
  294. if !exists {
  295. return nil, fmt.Errorf("Failed to find a load balancer IP to use for network: %v", id)
  296. }
  297. nwOptions = append(nwOptions, libnetwork.NetworkOptionLBEndpoint(nodeIP))
  298. }
  299. n, err := c.NewNetwork(driver, create.Name, id, nwOptions...)
  300. if err != nil {
  301. if _, ok := err.(libnetwork.ErrDataStoreNotInitialized); ok {
  302. // nolint: golint
  303. return nil, errors.New("This node is not a swarm manager. Use \"docker swarm init\" or \"docker swarm join\" to connect this node to swarm and try again.")
  304. }
  305. return nil, err
  306. }
  307. daemon.pluginRefCount(driver, driverapi.NetworkPluginEndpointType, plugingetter.Acquire)
  308. if create.IPAM != nil {
  309. daemon.pluginRefCount(create.IPAM.Driver, ipamapi.PluginEndpointType, plugingetter.Acquire)
  310. }
  311. daemon.LogNetworkEvent(n, "create")
  312. return &types.NetworkCreateResponse{
  313. ID: n.ID(),
  314. Warning: warning,
  315. }, nil
  316. }
  317. func (daemon *Daemon) pluginRefCount(driver, capability string, mode int) {
  318. var builtinDrivers []string
  319. if capability == driverapi.NetworkPluginEndpointType {
  320. builtinDrivers = daemon.netController.BuiltinDrivers()
  321. } else if capability == ipamapi.PluginEndpointType {
  322. builtinDrivers = daemon.netController.BuiltinIPAMDrivers()
  323. }
  324. for _, d := range builtinDrivers {
  325. if d == driver {
  326. return
  327. }
  328. }
  329. if daemon.PluginStore != nil {
  330. _, err := daemon.PluginStore.Get(driver, capability, mode)
  331. if err != nil {
  332. logrus.WithError(err).WithFields(logrus.Fields{"mode": mode, "driver": driver}).Error("Error handling plugin refcount operation")
  333. }
  334. }
  335. }
  336. func getIpamConfig(data []network.IPAMConfig) ([]*libnetwork.IpamConf, []*libnetwork.IpamConf, error) {
  337. ipamV4Cfg := []*libnetwork.IpamConf{}
  338. ipamV6Cfg := []*libnetwork.IpamConf{}
  339. for _, d := range data {
  340. iCfg := libnetwork.IpamConf{}
  341. iCfg.PreferredPool = d.Subnet
  342. iCfg.SubPool = d.IPRange
  343. iCfg.Gateway = d.Gateway
  344. iCfg.AuxAddresses = d.AuxAddress
  345. ip, _, err := net.ParseCIDR(d.Subnet)
  346. if err != nil {
  347. return nil, nil, fmt.Errorf("Invalid subnet %s : %v", d.Subnet, err)
  348. }
  349. if ip.To4() != nil {
  350. ipamV4Cfg = append(ipamV4Cfg, &iCfg)
  351. } else {
  352. ipamV6Cfg = append(ipamV6Cfg, &iCfg)
  353. }
  354. }
  355. return ipamV4Cfg, ipamV6Cfg, nil
  356. }
  357. // UpdateContainerServiceConfig updates a service configuration.
  358. func (daemon *Daemon) UpdateContainerServiceConfig(containerName string, serviceConfig *clustertypes.ServiceConfig) error {
  359. container, err := daemon.GetContainer(containerName)
  360. if err != nil {
  361. return err
  362. }
  363. container.NetworkSettings.Service = serviceConfig
  364. return nil
  365. }
  366. // ConnectContainerToNetwork connects the given container to the given
  367. // network. If either cannot be found, an err is returned. If the
  368. // network cannot be set up, an err is returned.
  369. func (daemon *Daemon) ConnectContainerToNetwork(containerName, networkName string, endpointConfig *network.EndpointSettings) error {
  370. container, err := daemon.GetContainer(containerName)
  371. if err != nil {
  372. return err
  373. }
  374. return daemon.ConnectToNetwork(container, networkName, endpointConfig)
  375. }
  376. // DisconnectContainerFromNetwork disconnects the given container from
  377. // the given network. If either cannot be found, an err is returned.
  378. func (daemon *Daemon) DisconnectContainerFromNetwork(containerName string, networkName string, force bool) error {
  379. container, err := daemon.GetContainer(containerName)
  380. if err != nil {
  381. if force {
  382. return daemon.ForceEndpointDelete(containerName, networkName)
  383. }
  384. return err
  385. }
  386. return daemon.DisconnectFromNetwork(container, networkName, force)
  387. }
  388. // GetNetworkDriverList returns the list of plugins drivers
  389. // registered for network.
  390. func (daemon *Daemon) GetNetworkDriverList() []string {
  391. if !daemon.NetworkControllerEnabled() {
  392. return nil
  393. }
  394. pluginList := daemon.netController.BuiltinDrivers()
  395. managedPlugins := daemon.PluginStore.GetAllManagedPluginsByCap(driverapi.NetworkPluginEndpointType)
  396. for _, plugin := range managedPlugins {
  397. pluginList = append(pluginList, plugin.Name())
  398. }
  399. pluginMap := make(map[string]bool)
  400. for _, plugin := range pluginList {
  401. pluginMap[plugin] = true
  402. }
  403. networks := daemon.netController.Networks()
  404. for _, network := range networks {
  405. if !pluginMap[network.Type()] {
  406. pluginList = append(pluginList, network.Type())
  407. pluginMap[network.Type()] = true
  408. }
  409. }
  410. sort.Strings(pluginList)
  411. return pluginList
  412. }
  413. // DeleteManagedNetwork deletes an agent network.
  414. // The requirement of networkID is enforced.
  415. func (daemon *Daemon) DeleteManagedNetwork(networkID string) error {
  416. n, err := daemon.GetNetworkByID(networkID)
  417. if err != nil {
  418. return err
  419. }
  420. return daemon.deleteNetwork(n, true)
  421. }
  422. // DeleteNetwork destroys a network unless it's one of docker's predefined networks.
  423. func (daemon *Daemon) DeleteNetwork(networkID string) error {
  424. n, err := daemon.GetNetworkByID(networkID)
  425. if err != nil {
  426. return err
  427. }
  428. return daemon.deleteNetwork(n, false)
  429. }
  430. func (daemon *Daemon) deleteLoadBalancerSandbox(n libnetwork.Network) {
  431. controller := daemon.netController
  432. //The only endpoint left should be the LB endpoint (nw.Name() + "-endpoint")
  433. endpoints := n.Endpoints()
  434. if len(endpoints) == 1 {
  435. sandboxName := n.Name() + "-sbox"
  436. info := endpoints[0].Info()
  437. if info != nil {
  438. sb := info.Sandbox()
  439. if sb != nil {
  440. if err := sb.DisableService(); err != nil {
  441. logrus.Warnf("Failed to disable service on sandbox %s: %v", sandboxName, err)
  442. //Ignore error and attempt to delete the load balancer endpoint
  443. }
  444. }
  445. }
  446. if err := endpoints[0].Delete(true); err != nil {
  447. logrus.Warnf("Failed to delete endpoint %s (%s) in %s: %v", endpoints[0].Name(), endpoints[0].ID(), sandboxName, err)
  448. //Ignore error and attempt to delete the sandbox.
  449. }
  450. if err := controller.SandboxDestroy(sandboxName); err != nil {
  451. logrus.Warnf("Failed to delete %s sandbox: %v", sandboxName, err)
  452. //Ignore error and attempt to delete the network.
  453. }
  454. }
  455. }
  456. func (daemon *Daemon) deleteNetwork(nw libnetwork.Network, dynamic bool) error {
  457. if runconfig.IsPreDefinedNetwork(nw.Name()) && !dynamic {
  458. err := fmt.Errorf("%s is a pre-defined network and cannot be removed", nw.Name())
  459. return errdefs.Forbidden(err)
  460. }
  461. if dynamic && !nw.Info().Dynamic() {
  462. if runconfig.IsPreDefinedNetwork(nw.Name()) {
  463. // Predefined networks now support swarm services. Make this
  464. // a no-op when cluster requests to remove the predefined network.
  465. return nil
  466. }
  467. err := fmt.Errorf("%s is not a dynamic network", nw.Name())
  468. return errdefs.Forbidden(err)
  469. }
  470. if err := nw.Delete(); err != nil {
  471. return err
  472. }
  473. // If this is not a configuration only network, we need to
  474. // update the corresponding remote drivers' reference counts
  475. if !nw.Info().ConfigOnly() {
  476. daemon.pluginRefCount(nw.Type(), driverapi.NetworkPluginEndpointType, plugingetter.Release)
  477. ipamType, _, _, _ := nw.Info().IpamConfig()
  478. daemon.pluginRefCount(ipamType, ipamapi.PluginEndpointType, plugingetter.Release)
  479. daemon.LogNetworkEvent(nw, "destroy")
  480. }
  481. return nil
  482. }
  483. // GetNetworks returns a list of all networks
  484. func (daemon *Daemon) GetNetworks() []libnetwork.Network {
  485. return daemon.getAllNetworks()
  486. }
  487. // clearAttachableNetworks removes the attachable networks
  488. // after disconnecting any connected container
  489. func (daemon *Daemon) clearAttachableNetworks() {
  490. for _, n := range daemon.GetNetworks() {
  491. if !n.Info().Attachable() {
  492. continue
  493. }
  494. for _, ep := range n.Endpoints() {
  495. epInfo := ep.Info()
  496. if epInfo == nil {
  497. continue
  498. }
  499. sb := epInfo.Sandbox()
  500. if sb == nil {
  501. continue
  502. }
  503. containerID := sb.ContainerID()
  504. if err := daemon.DisconnectContainerFromNetwork(containerID, n.ID(), true); err != nil {
  505. logrus.Warnf("Failed to disconnect container %s from swarm network %s on cluster leave: %v",
  506. containerID, n.Name(), err)
  507. }
  508. }
  509. if err := daemon.DeleteManagedNetwork(n.ID()); err != nil {
  510. logrus.Warnf("Failed to remove swarm network %s on cluster leave: %v", n.Name(), err)
  511. }
  512. }
  513. }