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/Sirupsen/logrus"
  10. apierrors "github.com/docker/docker/api/errors"
  11. "github.com/docker/docker/api/types"
  12. "github.com/docker/docker/api/types/network"
  13. clustertypes "github.com/docker/docker/daemon/cluster/provider"
  14. "github.com/docker/docker/pkg/plugingetter"
  15. "github.com/docker/docker/runconfig"
  16. "github.com/docker/libnetwork"
  17. lncluster "github.com/docker/libnetwork/cluster"
  18. "github.com/docker/libnetwork/driverapi"
  19. "github.com/docker/libnetwork/ipamapi"
  20. networktypes "github.com/docker/libnetwork/types"
  21. "github.com/pkg/errors"
  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 function finds a network for a given string that can represent network name or id
  30. func (daemon *Daemon) FindNetwork(idName string) (libnetwork.Network, error) {
  31. // Find by Name
  32. n, err := daemon.GetNetworkByName(idName)
  33. if err != nil && !isNoSuchNetworkError(err) {
  34. return nil, err
  35. }
  36. if n != nil {
  37. return n, nil
  38. }
  39. // Find by id
  40. return daemon.GetNetworkByID(idName)
  41. }
  42. func isNoSuchNetworkError(err error) bool {
  43. _, ok := err.(libnetwork.ErrNoSuchNetwork)
  44. return ok
  45. }
  46. // GetNetworkByID function returns a network whose ID begins with the given prefix.
  47. // It fails with an error if no matching, or more than one matching, networks are found.
  48. func (daemon *Daemon) GetNetworkByID(partialID string) (libnetwork.Network, error) {
  49. list := daemon.GetNetworksByID(partialID)
  50. if len(list) == 0 {
  51. return nil, libnetwork.ErrNoSuchNetwork(partialID)
  52. }
  53. if len(list) > 1 {
  54. return nil, libnetwork.ErrInvalidID(partialID)
  55. }
  56. return list[0], nil
  57. }
  58. // GetNetworkByName function returns a network for a given network name.
  59. // If no network name is given, the default network is returned.
  60. func (daemon *Daemon) GetNetworkByName(name string) (libnetwork.Network, error) {
  61. c := daemon.netController
  62. if c == nil {
  63. return nil, libnetwork.ErrNoSuchNetwork(name)
  64. }
  65. if name == "" {
  66. name = c.Config().Daemon.DefaultNetwork
  67. }
  68. return c.NetworkByName(name)
  69. }
  70. // GetNetworksByID returns a list of networks whose ID partially matches zero or more networks
  71. func (daemon *Daemon) GetNetworksByID(partialID string) []libnetwork.Network {
  72. c := daemon.netController
  73. if c == nil {
  74. return nil
  75. }
  76. list := []libnetwork.Network{}
  77. l := func(nw libnetwork.Network) bool {
  78. if strings.HasPrefix(nw.ID(), partialID) {
  79. list = append(list, nw)
  80. }
  81. return false
  82. }
  83. c.WalkNetworks(l)
  84. return list
  85. }
  86. // getAllNetworks returns a list containing all networks
  87. func (daemon *Daemon) getAllNetworks() []libnetwork.Network {
  88. return daemon.netController.Networks()
  89. }
  90. type ingressJob struct {
  91. create *clustertypes.NetworkCreateRequest
  92. ip net.IP
  93. jobDone chan struct{}
  94. }
  95. var (
  96. ingressWorkerOnce sync.Once
  97. ingressJobsChannel chan *ingressJob
  98. ingressID string
  99. )
  100. func (daemon *Daemon) startIngressWorker() {
  101. ingressJobsChannel = make(chan *ingressJob, 100)
  102. go func() {
  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. return
  205. }
  206. // SetNetworkBootstrapKeys sets the bootstrap keys.
  207. func (daemon *Daemon) SetNetworkBootstrapKeys(keys []*networktypes.EncryptionKey) error {
  208. err := daemon.netController.SetKeys(keys)
  209. if err == nil {
  210. // Upon successful key setting dispatch the keys available event
  211. daemon.cluster.SendClusterEvent(lncluster.EventNetworkKeysAvailable)
  212. }
  213. return err
  214. }
  215. // UpdateAttachment notifies the attacher about the attachment config.
  216. func (daemon *Daemon) UpdateAttachment(networkName, networkID, containerID string, config *network.NetworkingConfig) error {
  217. if daemon.clusterProvider == nil {
  218. return fmt.Errorf("cluster provider is not initialized")
  219. }
  220. if err := daemon.clusterProvider.UpdateAttachment(networkName, containerID, config); err != nil {
  221. return daemon.clusterProvider.UpdateAttachment(networkID, containerID, config)
  222. }
  223. return nil
  224. }
  225. // WaitForDetachment makes the cluster manager wait for detachment of
  226. // the container from the network.
  227. func (daemon *Daemon) WaitForDetachment(ctx context.Context, networkName, networkID, taskID, containerID string) error {
  228. if daemon.clusterProvider == nil {
  229. return fmt.Errorf("cluster provider is not initialized")
  230. }
  231. return daemon.clusterProvider.WaitForDetachment(ctx, networkName, networkID, taskID, containerID)
  232. }
  233. // CreateManagedNetwork creates an agent network.
  234. func (daemon *Daemon) CreateManagedNetwork(create clustertypes.NetworkCreateRequest) error {
  235. _, err := daemon.createNetwork(create.NetworkCreateRequest, create.ID, true)
  236. return err
  237. }
  238. // CreateNetwork creates a network with the given name, driver and other optional parameters
  239. func (daemon *Daemon) CreateNetwork(create types.NetworkCreateRequest) (*types.NetworkCreateResponse, error) {
  240. resp, err := daemon.createNetwork(create, "", false)
  241. if err != nil {
  242. return nil, err
  243. }
  244. return resp, err
  245. }
  246. func (daemon *Daemon) createNetwork(create types.NetworkCreateRequest, id string, agent bool) (*types.NetworkCreateResponse, error) {
  247. if runconfig.IsPreDefinedNetwork(create.Name) && !agent {
  248. err := fmt.Errorf("%s is a pre-defined network and cannot be created", create.Name)
  249. return nil, apierrors.NewRequestForbiddenError(err)
  250. }
  251. var warning string
  252. nw, err := daemon.GetNetworkByName(create.Name)
  253. if err != nil {
  254. if _, ok := err.(libnetwork.ErrNoSuchNetwork); !ok {
  255. return nil, err
  256. }
  257. }
  258. if nw != nil {
  259. // check if user defined CheckDuplicate, if set true, return err
  260. // otherwise prepare a warning message
  261. if create.CheckDuplicate {
  262. return nil, libnetwork.NetworkNameError(create.Name)
  263. }
  264. warning = fmt.Sprintf("Network with name %s (id : %s) already exists", nw.Name(), nw.ID())
  265. }
  266. c := daemon.netController
  267. driver := create.Driver
  268. if driver == "" {
  269. driver = c.Config().Daemon.DefaultDriver
  270. }
  271. nwOptions := []libnetwork.NetworkOption{
  272. libnetwork.NetworkOptionEnableIPv6(create.EnableIPv6),
  273. libnetwork.NetworkOptionDriverOpts(create.Options),
  274. libnetwork.NetworkOptionLabels(create.Labels),
  275. libnetwork.NetworkOptionAttachable(create.Attachable),
  276. libnetwork.NetworkOptionIngress(create.Ingress),
  277. libnetwork.NetworkOptionScope(create.Scope),
  278. }
  279. if create.ConfigOnly {
  280. nwOptions = append(nwOptions, libnetwork.NetworkOptionConfigOnly())
  281. }
  282. if create.IPAM != nil {
  283. ipam := create.IPAM
  284. v4Conf, v6Conf, err := getIpamConfig(ipam.Config)
  285. if err != nil {
  286. return nil, err
  287. }
  288. nwOptions = append(nwOptions, libnetwork.NetworkOptionIpam(ipam.Driver, "", v4Conf, v6Conf, ipam.Options))
  289. }
  290. if create.Internal {
  291. nwOptions = append(nwOptions, libnetwork.NetworkOptionInternalNetwork())
  292. }
  293. if agent {
  294. nwOptions = append(nwOptions, libnetwork.NetworkOptionDynamic())
  295. nwOptions = append(nwOptions, libnetwork.NetworkOptionPersist(false))
  296. }
  297. if create.ConfigFrom != nil {
  298. nwOptions = append(nwOptions, libnetwork.NetworkOptionConfigFrom(create.ConfigFrom.Network))
  299. }
  300. n, err := c.NewNetwork(driver, create.Name, id, nwOptions...)
  301. if err != nil {
  302. if _, ok := err.(libnetwork.ErrDataStoreNotInitialized); ok {
  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 apierrors.NewRequestForbiddenError(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 apierrors.NewRequestForbiddenError(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. }