network.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. package daemon
  2. import (
  3. "fmt"
  4. "net"
  5. "runtime"
  6. "sort"
  7. "strings"
  8. "github.com/Sirupsen/logrus"
  9. apierrors "github.com/docker/docker/api/errors"
  10. "github.com/docker/docker/api/types"
  11. "github.com/docker/docker/api/types/network"
  12. clustertypes "github.com/docker/docker/daemon/cluster/provider"
  13. "github.com/docker/docker/pkg/plugingetter"
  14. "github.com/docker/docker/runconfig"
  15. "github.com/docker/libnetwork"
  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. "golang.org/x/net/context"
  21. )
  22. // NetworkControllerEnabled checks if the networking stack is enabled.
  23. // This feature depends on OS primitives and it's disabled in systems like Windows.
  24. func (daemon *Daemon) NetworkControllerEnabled() bool {
  25. return daemon.netController != nil
  26. }
  27. // FindNetwork function finds a network for a given string that can represent network name or id
  28. func (daemon *Daemon) FindNetwork(idName string) (libnetwork.Network, error) {
  29. // Find by Name
  30. n, err := daemon.GetNetworkByName(idName)
  31. if err != nil && !isNoSuchNetworkError(err) {
  32. return nil, err
  33. }
  34. if n != nil {
  35. return n, nil
  36. }
  37. // Find by id
  38. return daemon.GetNetworkByID(idName)
  39. }
  40. func isNoSuchNetworkError(err error) bool {
  41. _, ok := err.(libnetwork.ErrNoSuchNetwork)
  42. return ok
  43. }
  44. // GetNetworkByID function returns a network whose ID begins with the given prefix.
  45. // It fails with an error if no matching, or more than one matching, networks are found.
  46. func (daemon *Daemon) GetNetworkByID(partialID string) (libnetwork.Network, error) {
  47. list := daemon.GetNetworksByID(partialID)
  48. if len(list) == 0 {
  49. return nil, libnetwork.ErrNoSuchNetwork(partialID)
  50. }
  51. if len(list) > 1 {
  52. return nil, libnetwork.ErrInvalidID(partialID)
  53. }
  54. return list[0], nil
  55. }
  56. // GetNetworkByName function returns a network for a given network name.
  57. // If no network name is given, the default network is returned.
  58. func (daemon *Daemon) GetNetworkByName(name string) (libnetwork.Network, error) {
  59. c := daemon.netController
  60. if c == nil {
  61. return nil, libnetwork.ErrNoSuchNetwork(name)
  62. }
  63. if name == "" {
  64. name = c.Config().Daemon.DefaultNetwork
  65. }
  66. return c.NetworkByName(name)
  67. }
  68. // GetNetworksByID returns a list of networks whose ID partially matches zero or more networks
  69. func (daemon *Daemon) GetNetworksByID(partialID string) []libnetwork.Network {
  70. c := daemon.netController
  71. if c == nil {
  72. return nil
  73. }
  74. list := []libnetwork.Network{}
  75. l := func(nw libnetwork.Network) bool {
  76. if strings.HasPrefix(nw.ID(), partialID) {
  77. list = append(list, nw)
  78. }
  79. return false
  80. }
  81. c.WalkNetworks(l)
  82. return list
  83. }
  84. // getAllNetworks returns a list containing all networks
  85. func (daemon *Daemon) getAllNetworks() []libnetwork.Network {
  86. return daemon.netController.Networks()
  87. }
  88. func isIngressNetwork(name string) bool {
  89. return name == "ingress"
  90. }
  91. var ingressChan = make(chan struct{}, 1)
  92. func ingressWait() func() {
  93. ingressChan <- struct{}{}
  94. return func() { <-ingressChan }
  95. }
  96. // SetupIngress setups ingress networking.
  97. func (daemon *Daemon) SetupIngress(create clustertypes.NetworkCreateRequest, nodeIP string) error {
  98. ip, _, err := net.ParseCIDR(nodeIP)
  99. if err != nil {
  100. return err
  101. }
  102. go func() {
  103. controller := daemon.netController
  104. controller.AgentInitWait()
  105. if n, err := daemon.GetNetworkByName(create.Name); err == nil && n != nil && n.ID() != create.ID {
  106. if err := controller.SandboxDestroy("ingress-sbox"); err != nil {
  107. logrus.Errorf("Failed to delete stale ingress sandbox: %v", err)
  108. return
  109. }
  110. // Cleanup any stale endpoints that might be left over during previous iterations
  111. epList := n.Endpoints()
  112. for _, ep := range epList {
  113. if err := ep.Delete(true); err != nil {
  114. logrus.Errorf("Failed to delete endpoint %s (%s): %v", ep.Name(), ep.ID(), err)
  115. }
  116. }
  117. if err := n.Delete(); err != nil {
  118. logrus.Errorf("Failed to delete stale ingress network %s: %v", n.ID(), err)
  119. return
  120. }
  121. }
  122. if _, err := daemon.createNetwork(create.NetworkCreateRequest, create.ID, true); err != nil {
  123. // If it is any other error other than already
  124. // exists error log error and return.
  125. if _, ok := err.(libnetwork.NetworkNameError); !ok {
  126. logrus.Errorf("Failed creating ingress network: %v", err)
  127. return
  128. }
  129. // Otherwise continue down the call to create or recreate sandbox.
  130. }
  131. n, err := daemon.GetNetworkByID(create.ID)
  132. if err != nil {
  133. logrus.Errorf("Failed getting ingress network by id after creating: %v", err)
  134. return
  135. }
  136. sb, err := controller.NewSandbox("ingress-sbox", libnetwork.OptionIngress())
  137. if err != nil {
  138. if _, ok := err.(networktypes.ForbiddenError); !ok {
  139. logrus.Errorf("Failed creating ingress sandbox: %v", err)
  140. }
  141. return
  142. }
  143. ep, err := n.CreateEndpoint("ingress-endpoint", libnetwork.CreateOptionIpam(ip, nil, nil, nil))
  144. if err != nil {
  145. logrus.Errorf("Failed creating ingress endpoint: %v", err)
  146. return
  147. }
  148. if err := ep.Join(sb, nil); err != nil {
  149. logrus.Errorf("Failed joining ingress sandbox to ingress endpoint: %v", err)
  150. }
  151. if err := sb.EnableService(); err != nil {
  152. logrus.WithError(err).Error("Failed enabling service for ingress sandbox")
  153. }
  154. }()
  155. return nil
  156. }
  157. // SetNetworkBootstrapKeys sets the bootstrap keys.
  158. func (daemon *Daemon) SetNetworkBootstrapKeys(keys []*networktypes.EncryptionKey) error {
  159. return daemon.netController.SetKeys(keys)
  160. }
  161. // UpdateAttachment notifies the attacher about the attachment config.
  162. func (daemon *Daemon) UpdateAttachment(networkName, networkID, containerID string, config *network.NetworkingConfig) error {
  163. if daemon.clusterProvider == nil {
  164. return fmt.Errorf("cluster provider is not initialized")
  165. }
  166. if err := daemon.clusterProvider.UpdateAttachment(networkName, containerID, config); err != nil {
  167. return daemon.clusterProvider.UpdateAttachment(networkID, containerID, config)
  168. }
  169. return nil
  170. }
  171. // WaitForDetachment makes the cluster manager wait for detachment of
  172. // the container from the network.
  173. func (daemon *Daemon) WaitForDetachment(ctx context.Context, networkName, networkID, taskID, containerID string) error {
  174. if daemon.clusterProvider == nil {
  175. return fmt.Errorf("cluster provider is not initialized")
  176. }
  177. return daemon.clusterProvider.WaitForDetachment(ctx, networkName, networkID, taskID, containerID)
  178. }
  179. // CreateManagedNetwork creates an agent network.
  180. func (daemon *Daemon) CreateManagedNetwork(create clustertypes.NetworkCreateRequest) error {
  181. _, err := daemon.createNetwork(create.NetworkCreateRequest, create.ID, true)
  182. return err
  183. }
  184. // CreateNetwork creates a network with the given name, driver and other optional parameters
  185. func (daemon *Daemon) CreateNetwork(create types.NetworkCreateRequest) (*types.NetworkCreateResponse, error) {
  186. resp, err := daemon.createNetwork(create, "", false)
  187. if err != nil {
  188. return nil, err
  189. }
  190. return resp, err
  191. }
  192. func (daemon *Daemon) createNetwork(create types.NetworkCreateRequest, id string, agent bool) (*types.NetworkCreateResponse, error) {
  193. // If there is a pending ingress network creation wait here
  194. // since ingress network creation can happen via node download
  195. // from manager or task download.
  196. if isIngressNetwork(create.Name) {
  197. defer ingressWait()()
  198. }
  199. if runconfig.IsPreDefinedNetwork(create.Name) && !agent {
  200. err := fmt.Errorf("%s is a pre-defined network and cannot be created", create.Name)
  201. return nil, apierrors.NewRequestForbiddenError(err)
  202. }
  203. var warning string
  204. nw, err := daemon.GetNetworkByName(create.Name)
  205. if err != nil {
  206. if _, ok := err.(libnetwork.ErrNoSuchNetwork); !ok {
  207. return nil, err
  208. }
  209. }
  210. if nw != nil {
  211. if create.CheckDuplicate {
  212. return nil, libnetwork.NetworkNameError(create.Name)
  213. }
  214. warning = fmt.Sprintf("Network with name %s (id : %s) already exists", nw.Name(), nw.ID())
  215. }
  216. c := daemon.netController
  217. driver := create.Driver
  218. if driver == "" {
  219. driver = c.Config().Daemon.DefaultDriver
  220. }
  221. nwOptions := []libnetwork.NetworkOption{
  222. libnetwork.NetworkOptionEnableIPv6(create.EnableIPv6),
  223. libnetwork.NetworkOptionDriverOpts(create.Options),
  224. libnetwork.NetworkOptionLabels(create.Labels),
  225. libnetwork.NetworkOptionAttachable(create.Attachable),
  226. }
  227. if create.IPAM != nil {
  228. ipam := create.IPAM
  229. v4Conf, v6Conf, err := getIpamConfig(ipam.Config)
  230. if err != nil {
  231. return nil, err
  232. }
  233. nwOptions = append(nwOptions, libnetwork.NetworkOptionIpam(ipam.Driver, "", v4Conf, v6Conf, ipam.Options))
  234. }
  235. if create.Internal {
  236. nwOptions = append(nwOptions, libnetwork.NetworkOptionInternalNetwork())
  237. }
  238. if agent {
  239. nwOptions = append(nwOptions, libnetwork.NetworkOptionDynamic())
  240. nwOptions = append(nwOptions, libnetwork.NetworkOptionPersist(false))
  241. }
  242. if isIngressNetwork(create.Name) {
  243. nwOptions = append(nwOptions, libnetwork.NetworkOptionIngress())
  244. }
  245. n, err := c.NewNetwork(driver, create.Name, id, nwOptions...)
  246. if err != nil {
  247. return nil, err
  248. }
  249. daemon.pluginRefCount(driver, driverapi.NetworkPluginEndpointType, plugingetter.Acquire)
  250. if create.IPAM != nil {
  251. daemon.pluginRefCount(create.IPAM.Driver, ipamapi.PluginEndpointType, plugingetter.Acquire)
  252. }
  253. daemon.LogNetworkEvent(n, "create")
  254. return &types.NetworkCreateResponse{
  255. ID: n.ID(),
  256. Warning: warning,
  257. }, nil
  258. }
  259. func (daemon *Daemon) pluginRefCount(driver, capability string, mode int) {
  260. var builtinDrivers []string
  261. if capability == driverapi.NetworkPluginEndpointType {
  262. builtinDrivers = daemon.netController.BuiltinDrivers()
  263. } else if capability == ipamapi.PluginEndpointType {
  264. builtinDrivers = daemon.netController.BuiltinIPAMDrivers()
  265. }
  266. for _, d := range builtinDrivers {
  267. if d == driver {
  268. return
  269. }
  270. }
  271. if daemon.PluginStore != nil {
  272. _, err := daemon.PluginStore.Get(driver, capability, mode)
  273. if err != nil {
  274. logrus.WithError(err).WithFields(logrus.Fields{"mode": mode, "driver": driver}).Error("Error handling plugin refcount operation")
  275. }
  276. }
  277. }
  278. func getIpamConfig(data []network.IPAMConfig) ([]*libnetwork.IpamConf, []*libnetwork.IpamConf, error) {
  279. ipamV4Cfg := []*libnetwork.IpamConf{}
  280. ipamV6Cfg := []*libnetwork.IpamConf{}
  281. for _, d := range data {
  282. iCfg := libnetwork.IpamConf{}
  283. iCfg.PreferredPool = d.Subnet
  284. iCfg.SubPool = d.IPRange
  285. iCfg.Gateway = d.Gateway
  286. iCfg.AuxAddresses = d.AuxAddress
  287. ip, _, err := net.ParseCIDR(d.Subnet)
  288. if err != nil {
  289. return nil, nil, fmt.Errorf("Invalid subnet %s : %v", d.Subnet, err)
  290. }
  291. if ip.To4() != nil {
  292. ipamV4Cfg = append(ipamV4Cfg, &iCfg)
  293. } else {
  294. ipamV6Cfg = append(ipamV6Cfg, &iCfg)
  295. }
  296. }
  297. return ipamV4Cfg, ipamV6Cfg, nil
  298. }
  299. // UpdateContainerServiceConfig updates a service configuration.
  300. func (daemon *Daemon) UpdateContainerServiceConfig(containerName string, serviceConfig *clustertypes.ServiceConfig) error {
  301. container, err := daemon.GetContainer(containerName)
  302. if err != nil {
  303. return err
  304. }
  305. container.NetworkSettings.Service = serviceConfig
  306. return nil
  307. }
  308. // ConnectContainerToNetwork connects the given container to the given
  309. // network. If either cannot be found, an err is returned. If the
  310. // network cannot be set up, an err is returned.
  311. func (daemon *Daemon) ConnectContainerToNetwork(containerName, networkName string, endpointConfig *network.EndpointSettings) error {
  312. if runtime.GOOS == "solaris" {
  313. return errors.New("docker network connect is unsupported on Solaris platform")
  314. }
  315. container, err := daemon.GetContainer(containerName)
  316. if err != nil {
  317. return err
  318. }
  319. return daemon.ConnectToNetwork(container, networkName, endpointConfig)
  320. }
  321. // DisconnectContainerFromNetwork disconnects the given container from
  322. // the given network. If either cannot be found, an err is returned.
  323. func (daemon *Daemon) DisconnectContainerFromNetwork(containerName string, networkName string, force bool) error {
  324. if runtime.GOOS == "solaris" {
  325. return errors.New("docker network disconnect is unsupported on Solaris platform")
  326. }
  327. container, err := daemon.GetContainer(containerName)
  328. if err != nil {
  329. if force {
  330. return daemon.ForceEndpointDelete(containerName, networkName)
  331. }
  332. return err
  333. }
  334. return daemon.DisconnectFromNetwork(container, networkName, force)
  335. }
  336. // GetNetworkDriverList returns the list of plugins drivers
  337. // registered for network.
  338. func (daemon *Daemon) GetNetworkDriverList() []string {
  339. if !daemon.NetworkControllerEnabled() {
  340. return nil
  341. }
  342. pluginList := daemon.netController.BuiltinDrivers()
  343. managedPlugins := daemon.PluginStore.GetAllManagedPluginsByCap(driverapi.NetworkPluginEndpointType)
  344. for _, plugin := range managedPlugins {
  345. pluginList = append(pluginList, plugin.Name())
  346. }
  347. pluginMap := make(map[string]bool)
  348. for _, plugin := range pluginList {
  349. pluginMap[plugin] = true
  350. }
  351. networks := daemon.netController.Networks()
  352. for _, network := range networks {
  353. if !pluginMap[network.Type()] {
  354. pluginList = append(pluginList, network.Type())
  355. pluginMap[network.Type()] = true
  356. }
  357. }
  358. sort.Strings(pluginList)
  359. return pluginList
  360. }
  361. // DeleteManagedNetwork deletes an agent network.
  362. func (daemon *Daemon) DeleteManagedNetwork(networkID string) error {
  363. return daemon.deleteNetwork(networkID, true)
  364. }
  365. // DeleteNetwork destroys a network unless it's one of docker's predefined networks.
  366. func (daemon *Daemon) DeleteNetwork(networkID string) error {
  367. return daemon.deleteNetwork(networkID, false)
  368. }
  369. func (daemon *Daemon) deleteNetwork(networkID string, dynamic bool) error {
  370. nw, err := daemon.FindNetwork(networkID)
  371. if err != nil {
  372. return err
  373. }
  374. if runconfig.IsPreDefinedNetwork(nw.Name()) && !dynamic {
  375. err := fmt.Errorf("%s is a pre-defined network and cannot be removed", nw.Name())
  376. return apierrors.NewRequestForbiddenError(err)
  377. }
  378. if err := nw.Delete(); err != nil {
  379. return err
  380. }
  381. daemon.pluginRefCount(nw.Type(), driverapi.NetworkPluginEndpointType, plugingetter.Release)
  382. ipamType, _, _, _ := nw.Info().IpamConfig()
  383. daemon.pluginRefCount(ipamType, ipamapi.PluginEndpointType, plugingetter.Release)
  384. daemon.LogNetworkEvent(nw, "destroy")
  385. return nil
  386. }
  387. // GetNetworks returns a list of all networks
  388. func (daemon *Daemon) GetNetworks() []libnetwork.Network {
  389. return daemon.getAllNetworks()
  390. }
  391. // clearAttachableNetworks removes the attachable networks
  392. // after disconnecting any connected container
  393. func (daemon *Daemon) clearAttachableNetworks() {
  394. for _, n := range daemon.GetNetworks() {
  395. if !n.Info().Attachable() {
  396. continue
  397. }
  398. for _, ep := range n.Endpoints() {
  399. epInfo := ep.Info()
  400. if epInfo == nil {
  401. continue
  402. }
  403. sb := epInfo.Sandbox()
  404. if sb == nil {
  405. continue
  406. }
  407. containerID := sb.ContainerID()
  408. if err := daemon.DisconnectContainerFromNetwork(containerID, n.ID(), true); err != nil {
  409. logrus.Warnf("Failed to disconnect container %s from swarm network %s on cluster leave: %v",
  410. containerID, n.Name(), err)
  411. }
  412. }
  413. if err := daemon.DeleteManagedNetwork(n.ID()); err != nil {
  414. logrus.Warnf("Failed to remove swarm network %s on cluster leave: %v", n.Name(), err)
  415. }
  416. }
  417. }