network.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  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/pkg/plugingetter"
  13. "github.com/docker/docker/runconfig"
  14. "github.com/docker/libnetwork"
  15. lncluster "github.com/docker/libnetwork/cluster"
  16. "github.com/docker/libnetwork/driverapi"
  17. "github.com/docker/libnetwork/ipamapi"
  18. networktypes "github.com/docker/libnetwork/types"
  19. "github.com/pkg/errors"
  20. "github.com/sirupsen/logrus"
  21. "golang.org/x/net/context"
  22. )
  23. // NetworkControllerEnabled checks if the networking stack is enabled.
  24. // This feature depends on OS primitives and it's disabled in systems like Windows.
  25. func (daemon *Daemon) NetworkControllerEnabled() bool {
  26. return daemon.netController != nil
  27. }
  28. // FindNetwork function finds a network for a given string that can represent network name or id
  29. func (daemon *Daemon) FindNetwork(idName string) (libnetwork.Network, error) {
  30. // Find by Name
  31. n, err := daemon.GetNetworkByName(idName)
  32. if err != nil && !isNoSuchNetworkError(err) {
  33. return nil, err
  34. }
  35. if n != nil {
  36. return n, nil
  37. }
  38. // Find by id
  39. return daemon.GetNetworkByID(idName)
  40. }
  41. func isNoSuchNetworkError(err error) bool {
  42. _, ok := err.(libnetwork.ErrNoSuchNetwork)
  43. return ok
  44. }
  45. // GetNetworkByID function returns a network whose ID begins with the given prefix.
  46. // It fails with an error if no matching, or more than one matching, networks are found.
  47. func (daemon *Daemon) GetNetworkByID(partialID string) (libnetwork.Network, error) {
  48. list := daemon.GetNetworksByID(partialID)
  49. if len(list) == 0 {
  50. return nil, errors.WithStack(networkNotFound(partialID))
  51. }
  52. if len(list) > 1 {
  53. return nil, errors.WithStack(invalidIdentifier(partialID))
  54. }
  55. return list[0], nil
  56. }
  57. // GetNetworkByName function returns a network for a given network name.
  58. // If no network name is given, the default network is returned.
  59. func (daemon *Daemon) GetNetworkByName(name string) (libnetwork.Network, error) {
  60. c := daemon.netController
  61. if c == nil {
  62. return nil, libnetwork.ErrNoSuchNetwork(name)
  63. }
  64. if name == "" {
  65. name = c.Config().Daemon.DefaultNetwork
  66. }
  67. return c.NetworkByName(name)
  68. }
  69. // GetNetworksByID returns a list of networks whose ID partially matches zero or more networks
  70. func (daemon *Daemon) GetNetworksByID(partialID string) []libnetwork.Network {
  71. c := daemon.netController
  72. if c == nil {
  73. return nil
  74. }
  75. list := []libnetwork.Network{}
  76. l := func(nw libnetwork.Network) bool {
  77. if strings.HasPrefix(nw.ID(), partialID) {
  78. list = append(list, nw)
  79. }
  80. return false
  81. }
  82. c.WalkNetworks(l)
  83. return list
  84. }
  85. // getAllNetworks returns a list containing all networks
  86. func (daemon *Daemon) getAllNetworks() []libnetwork.Network {
  87. return daemon.netController.Networks()
  88. }
  89. type ingressJob struct {
  90. create *clustertypes.NetworkCreateRequest
  91. ip net.IP
  92. jobDone chan struct{}
  93. }
  94. var (
  95. ingressWorkerOnce sync.Once
  96. ingressJobsChannel chan *ingressJob
  97. ingressID string
  98. )
  99. func (daemon *Daemon) startIngressWorker() {
  100. ingressJobsChannel = make(chan *ingressJob, 100)
  101. go func() {
  102. // nolint: gosimple
  103. for {
  104. select {
  105. case r := <-ingressJobsChannel:
  106. if r.create != nil {
  107. daemon.setupIngress(r.create, r.ip, ingressID)
  108. ingressID = r.create.ID
  109. } else {
  110. daemon.releaseIngress(ingressID)
  111. ingressID = ""
  112. }
  113. close(r.jobDone)
  114. }
  115. }
  116. }()
  117. }
  118. // enqueueIngressJob adds a ingress add/rm request to the worker queue.
  119. // It guarantees the worker is started.
  120. func (daemon *Daemon) enqueueIngressJob(job *ingressJob) {
  121. ingressWorkerOnce.Do(daemon.startIngressWorker)
  122. ingressJobsChannel <- job
  123. }
  124. // SetupIngress setups ingress networking.
  125. // The function returns a channel which will signal the caller when the programming is completed.
  126. func (daemon *Daemon) SetupIngress(create clustertypes.NetworkCreateRequest, nodeIP string) (<-chan struct{}, error) {
  127. ip, _, err := net.ParseCIDR(nodeIP)
  128. if err != nil {
  129. return nil, err
  130. }
  131. done := make(chan struct{})
  132. daemon.enqueueIngressJob(&ingressJob{&create, ip, done})
  133. return done, nil
  134. }
  135. // ReleaseIngress releases the ingress networking.
  136. // The function returns a channel which will signal the caller when the programming is completed.
  137. func (daemon *Daemon) ReleaseIngress() (<-chan struct{}, error) {
  138. done := make(chan struct{})
  139. daemon.enqueueIngressJob(&ingressJob{nil, nil, done})
  140. return done, nil
  141. }
  142. func (daemon *Daemon) setupIngress(create *clustertypes.NetworkCreateRequest, ip net.IP, staleID string) {
  143. controller := daemon.netController
  144. controller.AgentInitWait()
  145. if staleID != "" && staleID != create.ID {
  146. daemon.releaseIngress(staleID)
  147. }
  148. if _, err := daemon.createNetwork(create.NetworkCreateRequest, create.ID, true); err != nil {
  149. // If it is any other error other than already
  150. // exists error log error and return.
  151. if _, ok := err.(libnetwork.NetworkNameError); !ok {
  152. logrus.Errorf("Failed creating ingress network: %v", err)
  153. return
  154. }
  155. // Otherwise continue down the call to create or recreate sandbox.
  156. }
  157. n, err := daemon.GetNetworkByID(create.ID)
  158. if err != nil {
  159. logrus.Errorf("Failed getting ingress network by id after creating: %v", err)
  160. }
  161. sb, err := controller.NewSandbox("ingress-sbox", libnetwork.OptionIngress())
  162. if err != nil {
  163. if _, ok := err.(networktypes.ForbiddenError); !ok {
  164. logrus.Errorf("Failed creating ingress sandbox: %v", err)
  165. }
  166. return
  167. }
  168. ep, err := n.CreateEndpoint("ingress-endpoint", libnetwork.CreateOptionIpam(ip, nil, nil, nil))
  169. if err != nil {
  170. logrus.Errorf("Failed creating ingress endpoint: %v", err)
  171. return
  172. }
  173. if err := ep.Join(sb, nil); err != nil {
  174. logrus.Errorf("Failed joining ingress sandbox to ingress endpoint: %v", err)
  175. return
  176. }
  177. if err := sb.EnableService(); err != nil {
  178. logrus.Errorf("Failed enabling service for ingress sandbox")
  179. }
  180. }
  181. func (daemon *Daemon) releaseIngress(id string) {
  182. controller := daemon.netController
  183. if err := controller.SandboxDestroy("ingress-sbox"); err != nil {
  184. logrus.Errorf("Failed to delete ingress sandbox: %v", err)
  185. }
  186. if id == "" {
  187. return
  188. }
  189. n, err := controller.NetworkByID(id)
  190. if err != nil {
  191. logrus.Errorf("failed to retrieve ingress network %s: %v", id, err)
  192. return
  193. }
  194. for _, ep := range n.Endpoints() {
  195. if err := ep.Delete(true); err != nil {
  196. logrus.Errorf("Failed to delete endpoint %s (%s): %v", ep.Name(), ep.ID(), err)
  197. return
  198. }
  199. }
  200. if err := n.Delete(); err != nil {
  201. logrus.Errorf("Failed to delete ingress network %s: %v", n.ID(), err)
  202. return
  203. }
  204. }
  205. // SetNetworkBootstrapKeys sets the bootstrap keys.
  206. func (daemon *Daemon) SetNetworkBootstrapKeys(keys []*networktypes.EncryptionKey) error {
  207. err := daemon.netController.SetKeys(keys)
  208. if err == nil {
  209. // Upon successful key setting dispatch the keys available event
  210. daemon.cluster.SendClusterEvent(lncluster.EventNetworkKeysAvailable)
  211. }
  212. return err
  213. }
  214. // UpdateAttachment notifies the attacher about the attachment config.
  215. func (daemon *Daemon) UpdateAttachment(networkName, networkID, containerID string, config *network.NetworkingConfig) error {
  216. if daemon.clusterProvider == nil {
  217. return fmt.Errorf("cluster provider is not initialized")
  218. }
  219. if err := daemon.clusterProvider.UpdateAttachment(networkName, containerID, config); err != nil {
  220. return daemon.clusterProvider.UpdateAttachment(networkID, containerID, config)
  221. }
  222. return nil
  223. }
  224. // WaitForDetachment makes the cluster manager wait for detachment of
  225. // the container from the network.
  226. func (daemon *Daemon) WaitForDetachment(ctx context.Context, networkName, networkID, taskID, containerID string) error {
  227. if daemon.clusterProvider == nil {
  228. return fmt.Errorf("cluster provider is not initialized")
  229. }
  230. return daemon.clusterProvider.WaitForDetachment(ctx, networkName, networkID, taskID, containerID)
  231. }
  232. // CreateManagedNetwork creates an agent network.
  233. func (daemon *Daemon) CreateManagedNetwork(create clustertypes.NetworkCreateRequest) error {
  234. _, err := daemon.createNetwork(create.NetworkCreateRequest, create.ID, true)
  235. return err
  236. }
  237. // CreateNetwork creates a network with the given name, driver and other optional parameters
  238. func (daemon *Daemon) CreateNetwork(create types.NetworkCreateRequest) (*types.NetworkCreateResponse, error) {
  239. resp, err := daemon.createNetwork(create, "", false)
  240. if err != nil {
  241. return nil, err
  242. }
  243. return resp, err
  244. }
  245. func (daemon *Daemon) createNetwork(create types.NetworkCreateRequest, id string, agent bool) (*types.NetworkCreateResponse, error) {
  246. if runconfig.IsPreDefinedNetwork(create.Name) && !agent {
  247. err := fmt.Errorf("%s is a pre-defined network and cannot be created", create.Name)
  248. return nil, notAllowedError{err}
  249. }
  250. var warning string
  251. nw, err := daemon.GetNetworkByName(create.Name)
  252. if err != nil {
  253. if _, ok := err.(libnetwork.ErrNoSuchNetwork); !ok {
  254. return nil, err
  255. }
  256. }
  257. if nw != nil {
  258. // check if user defined CheckDuplicate, if set true, return err
  259. // otherwise prepare a warning message
  260. if create.CheckDuplicate {
  261. return nil, libnetwork.NetworkNameError(create.Name)
  262. }
  263. warning = fmt.Sprintf("Network with name %s (id : %s) already exists", nw.Name(), nw.ID())
  264. }
  265. c := daemon.netController
  266. driver := create.Driver
  267. if driver == "" {
  268. driver = c.Config().Daemon.DefaultDriver
  269. }
  270. nwOptions := []libnetwork.NetworkOption{
  271. libnetwork.NetworkOptionEnableIPv6(create.EnableIPv6),
  272. libnetwork.NetworkOptionDriverOpts(create.Options),
  273. libnetwork.NetworkOptionLabels(create.Labels),
  274. libnetwork.NetworkOptionAttachable(create.Attachable),
  275. libnetwork.NetworkOptionIngress(create.Ingress),
  276. libnetwork.NetworkOptionScope(create.Scope),
  277. }
  278. if create.ConfigOnly {
  279. nwOptions = append(nwOptions, libnetwork.NetworkOptionConfigOnly())
  280. }
  281. if create.IPAM != nil {
  282. ipam := create.IPAM
  283. v4Conf, v6Conf, err := getIpamConfig(ipam.Config)
  284. if err != nil {
  285. return nil, err
  286. }
  287. nwOptions = append(nwOptions, libnetwork.NetworkOptionIpam(ipam.Driver, "", v4Conf, v6Conf, ipam.Options))
  288. }
  289. if create.Internal {
  290. nwOptions = append(nwOptions, libnetwork.NetworkOptionInternalNetwork())
  291. }
  292. if agent {
  293. nwOptions = append(nwOptions, libnetwork.NetworkOptionDynamic())
  294. nwOptions = append(nwOptions, libnetwork.NetworkOptionPersist(false))
  295. }
  296. if create.ConfigFrom != nil {
  297. nwOptions = append(nwOptions, libnetwork.NetworkOptionConfigFrom(create.ConfigFrom.Network))
  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. if runtime.GOOS == "solaris" {
  371. return errors.New("docker network connect is unsupported on Solaris platform")
  372. }
  373. container, err := daemon.GetContainer(containerName)
  374. if err != nil {
  375. return err
  376. }
  377. return daemon.ConnectToNetwork(container, networkName, endpointConfig)
  378. }
  379. // DisconnectContainerFromNetwork disconnects the given container from
  380. // the given network. If either cannot be found, an err is returned.
  381. func (daemon *Daemon) DisconnectContainerFromNetwork(containerName string, networkName string, force bool) error {
  382. if runtime.GOOS == "solaris" {
  383. return errors.New("docker network disconnect is unsupported on Solaris platform")
  384. }
  385. container, err := daemon.GetContainer(containerName)
  386. if err != nil {
  387. if force {
  388. return daemon.ForceEndpointDelete(containerName, networkName)
  389. }
  390. return err
  391. }
  392. return daemon.DisconnectFromNetwork(container, networkName, force)
  393. }
  394. // GetNetworkDriverList returns the list of plugins drivers
  395. // registered for network.
  396. func (daemon *Daemon) GetNetworkDriverList() []string {
  397. if !daemon.NetworkControllerEnabled() {
  398. return nil
  399. }
  400. pluginList := daemon.netController.BuiltinDrivers()
  401. managedPlugins := daemon.PluginStore.GetAllManagedPluginsByCap(driverapi.NetworkPluginEndpointType)
  402. for _, plugin := range managedPlugins {
  403. pluginList = append(pluginList, plugin.Name())
  404. }
  405. pluginMap := make(map[string]bool)
  406. for _, plugin := range pluginList {
  407. pluginMap[plugin] = true
  408. }
  409. networks := daemon.netController.Networks()
  410. for _, network := range networks {
  411. if !pluginMap[network.Type()] {
  412. pluginList = append(pluginList, network.Type())
  413. pluginMap[network.Type()] = true
  414. }
  415. }
  416. sort.Strings(pluginList)
  417. return pluginList
  418. }
  419. // DeleteManagedNetwork deletes an agent network.
  420. func (daemon *Daemon) DeleteManagedNetwork(networkID string) error {
  421. return daemon.deleteNetwork(networkID, true)
  422. }
  423. // DeleteNetwork destroys a network unless it's one of docker's predefined networks.
  424. func (daemon *Daemon) DeleteNetwork(networkID string) error {
  425. return daemon.deleteNetwork(networkID, false)
  426. }
  427. func (daemon *Daemon) deleteNetwork(networkID string, dynamic bool) error {
  428. nw, err := daemon.FindNetwork(networkID)
  429. if err != nil {
  430. return err
  431. }
  432. if runconfig.IsPreDefinedNetwork(nw.Name()) && !dynamic {
  433. err := fmt.Errorf("%s is a pre-defined network and cannot be removed", nw.Name())
  434. return notAllowedError{err}
  435. }
  436. if dynamic && !nw.Info().Dynamic() {
  437. if runconfig.IsPreDefinedNetwork(nw.Name()) {
  438. // Predefined networks now support swarm services. Make this
  439. // a no-op when cluster requests to remove the predefined network.
  440. return nil
  441. }
  442. err := fmt.Errorf("%s is not a dynamic network", nw.Name())
  443. return notAllowedError{err}
  444. }
  445. if err := nw.Delete(); err != nil {
  446. return err
  447. }
  448. // If this is not a configuration only network, we need to
  449. // update the corresponding remote drivers' reference counts
  450. if !nw.Info().ConfigOnly() {
  451. daemon.pluginRefCount(nw.Type(), driverapi.NetworkPluginEndpointType, plugingetter.Release)
  452. ipamType, _, _, _ := nw.Info().IpamConfig()
  453. daemon.pluginRefCount(ipamType, ipamapi.PluginEndpointType, plugingetter.Release)
  454. daemon.LogNetworkEvent(nw, "destroy")
  455. }
  456. return nil
  457. }
  458. // GetNetworks returns a list of all networks
  459. func (daemon *Daemon) GetNetworks() []libnetwork.Network {
  460. return daemon.getAllNetworks()
  461. }
  462. // clearAttachableNetworks removes the attachable networks
  463. // after disconnecting any connected container
  464. func (daemon *Daemon) clearAttachableNetworks() {
  465. for _, n := range daemon.GetNetworks() {
  466. if !n.Info().Attachable() {
  467. continue
  468. }
  469. for _, ep := range n.Endpoints() {
  470. epInfo := ep.Info()
  471. if epInfo == nil {
  472. continue
  473. }
  474. sb := epInfo.Sandbox()
  475. if sb == nil {
  476. continue
  477. }
  478. containerID := sb.ContainerID()
  479. if err := daemon.DisconnectContainerFromNetwork(containerID, n.ID(), true); err != nil {
  480. logrus.Warnf("Failed to disconnect container %s from swarm network %s on cluster leave: %v",
  481. containerID, n.Name(), err)
  482. }
  483. }
  484. if err := daemon.DeleteManagedNetwork(n.ID()); err != nil {
  485. logrus.Warnf("Failed to remove swarm network %s on cluster leave: %v", n.Name(), err)
  486. }
  487. }
  488. }