network.go 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089
  1. package daemon // import "github.com/docker/docker/daemon"
  2. import (
  3. "context"
  4. "fmt"
  5. "net"
  6. "sort"
  7. "strconv"
  8. "strings"
  9. "sync"
  10. "github.com/docker/docker/api/types"
  11. containertypes "github.com/docker/docker/api/types/container"
  12. "github.com/docker/docker/api/types/filters"
  13. "github.com/docker/docker/api/types/network"
  14. "github.com/docker/docker/container"
  15. clustertypes "github.com/docker/docker/daemon/cluster/provider"
  16. internalnetwork "github.com/docker/docker/daemon/network"
  17. "github.com/docker/docker/errdefs"
  18. "github.com/docker/docker/libnetwork"
  19. lncluster "github.com/docker/docker/libnetwork/cluster"
  20. "github.com/docker/docker/libnetwork/driverapi"
  21. "github.com/docker/docker/libnetwork/ipamapi"
  22. "github.com/docker/docker/libnetwork/netlabel"
  23. "github.com/docker/docker/libnetwork/networkdb"
  24. "github.com/docker/docker/libnetwork/options"
  25. networktypes "github.com/docker/docker/libnetwork/types"
  26. "github.com/docker/docker/opts"
  27. "github.com/docker/docker/pkg/plugingetter"
  28. "github.com/docker/docker/runconfig"
  29. "github.com/docker/go-connections/nat"
  30. "github.com/pkg/errors"
  31. "github.com/sirupsen/logrus"
  32. )
  33. // PredefinedNetworkError is returned when user tries to create predefined network that already exists.
  34. type PredefinedNetworkError string
  35. func (pnr PredefinedNetworkError) Error() string {
  36. return fmt.Sprintf("operation is not permitted on predefined %s network ", string(pnr))
  37. }
  38. // Forbidden denotes the type of this error
  39. func (pnr PredefinedNetworkError) Forbidden() {}
  40. // NetworkControllerEnabled checks if the networking stack is enabled.
  41. // This feature depends on OS primitives and it's disabled in systems like Windows.
  42. func (daemon *Daemon) NetworkControllerEnabled() bool {
  43. return daemon.netController != nil
  44. }
  45. // NetworkController returns the network controller created by the daemon.
  46. func (daemon *Daemon) NetworkController() libnetwork.NetworkController {
  47. return daemon.netController
  48. }
  49. // FindNetwork returns a network based on:
  50. // 1. Full ID
  51. // 2. Full Name
  52. // 3. Partial ID
  53. // as long as there is no ambiguity
  54. func (daemon *Daemon) FindNetwork(term string) (libnetwork.Network, error) {
  55. listByFullName := []libnetwork.Network{}
  56. listByPartialID := []libnetwork.Network{}
  57. for _, nw := range daemon.getAllNetworks() {
  58. if nw.ID() == term {
  59. return nw, nil
  60. }
  61. if nw.Name() == term {
  62. listByFullName = append(listByFullName, nw)
  63. }
  64. if strings.HasPrefix(nw.ID(), term) {
  65. listByPartialID = append(listByPartialID, nw)
  66. }
  67. }
  68. switch {
  69. case len(listByFullName) == 1:
  70. return listByFullName[0], nil
  71. case len(listByFullName) > 1:
  72. return nil, errdefs.InvalidParameter(errors.Errorf("network %s is ambiguous (%d matches found on name)", term, len(listByFullName)))
  73. case len(listByPartialID) == 1:
  74. return listByPartialID[0], nil
  75. case len(listByPartialID) > 1:
  76. return nil, errdefs.InvalidParameter(errors.Errorf("network %s is ambiguous (%d matches found based on ID prefix)", term, len(listByPartialID)))
  77. }
  78. // Be very careful to change the error type here, the
  79. // libnetwork.ErrNoSuchNetwork error is used by the controller
  80. // to retry the creation of the network as managed through the swarm manager
  81. return nil, errdefs.NotFound(libnetwork.ErrNoSuchNetwork(term))
  82. }
  83. // GetNetworkByID function returns a network whose ID matches the given ID.
  84. // It fails with an error if no matching network is found.
  85. func (daemon *Daemon) GetNetworkByID(id string) (libnetwork.Network, error) {
  86. c := daemon.netController
  87. if c == nil {
  88. return nil, errors.Wrap(libnetwork.ErrNoSuchNetwork(id), "netcontroller is nil")
  89. }
  90. return c.NetworkByID(id)
  91. }
  92. // GetNetworkByName function returns a network for a given network name.
  93. // If no network name is given, the default network is returned.
  94. func (daemon *Daemon) GetNetworkByName(name string) (libnetwork.Network, error) {
  95. c := daemon.netController
  96. if c == nil {
  97. return nil, libnetwork.ErrNoSuchNetwork(name)
  98. }
  99. if name == "" {
  100. name = c.Config().Daemon.DefaultNetwork
  101. }
  102. return c.NetworkByName(name)
  103. }
  104. // GetNetworksByIDPrefix returns a list of networks whose ID partially matches zero or more networks
  105. func (daemon *Daemon) GetNetworksByIDPrefix(partialID string) []libnetwork.Network {
  106. c := daemon.netController
  107. if c == nil {
  108. return nil
  109. }
  110. list := []libnetwork.Network{}
  111. l := func(nw libnetwork.Network) bool {
  112. if strings.HasPrefix(nw.ID(), partialID) {
  113. list = append(list, nw)
  114. }
  115. return false
  116. }
  117. c.WalkNetworks(l)
  118. return list
  119. }
  120. // getAllNetworks returns a list containing all networks
  121. func (daemon *Daemon) getAllNetworks() []libnetwork.Network {
  122. c := daemon.netController
  123. if c == nil {
  124. return nil
  125. }
  126. return c.Networks()
  127. }
  128. type ingressJob struct {
  129. create *clustertypes.NetworkCreateRequest
  130. ip net.IP
  131. jobDone chan struct{}
  132. }
  133. var (
  134. ingressWorkerOnce sync.Once
  135. ingressJobsChannel chan *ingressJob
  136. ingressID string
  137. )
  138. func (daemon *Daemon) startIngressWorker() {
  139. ingressJobsChannel = make(chan *ingressJob, 100)
  140. go func() {
  141. //nolint: gosimple
  142. for {
  143. select {
  144. case r := <-ingressJobsChannel:
  145. if r.create != nil {
  146. daemon.setupIngress(r.create, r.ip, ingressID)
  147. ingressID = r.create.ID
  148. } else {
  149. daemon.releaseIngress(ingressID)
  150. ingressID = ""
  151. }
  152. close(r.jobDone)
  153. }
  154. }
  155. }()
  156. }
  157. // enqueueIngressJob adds a ingress add/rm request to the worker queue.
  158. // It guarantees the worker is started.
  159. func (daemon *Daemon) enqueueIngressJob(job *ingressJob) {
  160. ingressWorkerOnce.Do(daemon.startIngressWorker)
  161. ingressJobsChannel <- job
  162. }
  163. // SetupIngress setups ingress networking.
  164. // The function returns a channel which will signal the caller when the programming is completed.
  165. func (daemon *Daemon) SetupIngress(create clustertypes.NetworkCreateRequest, nodeIP string) (<-chan struct{}, error) {
  166. ip, _, err := net.ParseCIDR(nodeIP)
  167. if err != nil {
  168. return nil, err
  169. }
  170. done := make(chan struct{})
  171. daemon.enqueueIngressJob(&ingressJob{&create, ip, done})
  172. return done, nil
  173. }
  174. // ReleaseIngress releases the ingress networking.
  175. // The function returns a channel which will signal the caller when the programming is completed.
  176. func (daemon *Daemon) ReleaseIngress() (<-chan struct{}, error) {
  177. done := make(chan struct{})
  178. daemon.enqueueIngressJob(&ingressJob{nil, nil, done})
  179. return done, nil
  180. }
  181. func (daemon *Daemon) setupIngress(create *clustertypes.NetworkCreateRequest, ip net.IP, staleID string) {
  182. controller := daemon.netController
  183. controller.AgentInitWait()
  184. if staleID != "" && staleID != create.ID {
  185. daemon.releaseIngress(staleID)
  186. }
  187. if _, err := daemon.createNetwork(create.NetworkCreateRequest, create.ID, true); err != nil {
  188. // If it is any other error other than already
  189. // exists error log error and return.
  190. if _, ok := err.(libnetwork.NetworkNameError); !ok {
  191. logrus.Errorf("Failed creating ingress network: %v", err)
  192. return
  193. }
  194. // Otherwise continue down the call to create or recreate sandbox.
  195. }
  196. _, err := daemon.GetNetworkByID(create.ID)
  197. if err != nil {
  198. logrus.Errorf("Failed getting ingress network by id after creating: %v", err)
  199. }
  200. }
  201. func (daemon *Daemon) releaseIngress(id string) {
  202. controller := daemon.netController
  203. if id == "" {
  204. return
  205. }
  206. n, err := controller.NetworkByID(id)
  207. if err != nil {
  208. logrus.Errorf("failed to retrieve ingress network %s: %v", id, err)
  209. return
  210. }
  211. if err := n.Delete(libnetwork.NetworkDeleteOptionRemoveLB); err != nil {
  212. logrus.Errorf("Failed to delete ingress network %s: %v", n.ID(), err)
  213. return
  214. }
  215. }
  216. // SetNetworkBootstrapKeys sets the bootstrap keys.
  217. func (daemon *Daemon) SetNetworkBootstrapKeys(keys []*networktypes.EncryptionKey) error {
  218. err := daemon.netController.SetKeys(keys)
  219. if err == nil {
  220. // Upon successful key setting dispatch the keys available event
  221. daemon.cluster.SendClusterEvent(lncluster.EventNetworkKeysAvailable)
  222. }
  223. return err
  224. }
  225. // UpdateAttachment notifies the attacher about the attachment config.
  226. func (daemon *Daemon) UpdateAttachment(networkName, networkID, containerID string, config *network.NetworkingConfig) error {
  227. if daemon.clusterProvider == nil {
  228. return fmt.Errorf("cluster provider is not initialized")
  229. }
  230. if err := daemon.clusterProvider.UpdateAttachment(networkName, containerID, config); err != nil {
  231. return daemon.clusterProvider.UpdateAttachment(networkID, containerID, config)
  232. }
  233. return nil
  234. }
  235. // WaitForDetachment makes the cluster manager wait for detachment of
  236. // the container from the network.
  237. func (daemon *Daemon) WaitForDetachment(ctx context.Context, networkName, networkID, taskID, containerID string) error {
  238. if daemon.clusterProvider == nil {
  239. return fmt.Errorf("cluster provider is not initialized")
  240. }
  241. return daemon.clusterProvider.WaitForDetachment(ctx, networkName, networkID, taskID, containerID)
  242. }
  243. // CreateManagedNetwork creates an agent network.
  244. func (daemon *Daemon) CreateManagedNetwork(create clustertypes.NetworkCreateRequest) error {
  245. _, err := daemon.createNetwork(create.NetworkCreateRequest, create.ID, true)
  246. return err
  247. }
  248. // CreateNetwork creates a network with the given name, driver and other optional parameters
  249. func (daemon *Daemon) CreateNetwork(create types.NetworkCreateRequest) (*types.NetworkCreateResponse, error) {
  250. resp, err := daemon.createNetwork(create, "", false)
  251. if err != nil {
  252. return nil, err
  253. }
  254. return resp, err
  255. }
  256. func (daemon *Daemon) createNetwork(create types.NetworkCreateRequest, id string, agent bool) (*types.NetworkCreateResponse, error) {
  257. if runconfig.IsPreDefinedNetwork(create.Name) {
  258. return nil, PredefinedNetworkError(create.Name)
  259. }
  260. var warning string
  261. nw, err := daemon.GetNetworkByName(create.Name)
  262. if err != nil {
  263. if _, ok := err.(libnetwork.ErrNoSuchNetwork); !ok {
  264. return nil, err
  265. }
  266. }
  267. if nw != nil {
  268. // check if user defined CheckDuplicate, if set true, return err
  269. // otherwise prepare a warning message
  270. if create.CheckDuplicate {
  271. if !agent || nw.Info().Dynamic() {
  272. return nil, libnetwork.NetworkNameError(create.Name)
  273. }
  274. }
  275. warning = fmt.Sprintf("Network with name %s (id : %s) already exists", nw.Name(), nw.ID())
  276. }
  277. c := daemon.netController
  278. driver := create.Driver
  279. if driver == "" {
  280. driver = c.Config().Daemon.DefaultDriver
  281. }
  282. nwOptions := []libnetwork.NetworkOption{
  283. libnetwork.NetworkOptionEnableIPv6(create.EnableIPv6),
  284. libnetwork.NetworkOptionDriverOpts(create.Options),
  285. libnetwork.NetworkOptionLabels(create.Labels),
  286. libnetwork.NetworkOptionAttachable(create.Attachable),
  287. libnetwork.NetworkOptionIngress(create.Ingress),
  288. libnetwork.NetworkOptionScope(create.Scope),
  289. }
  290. if create.ConfigOnly {
  291. nwOptions = append(nwOptions, libnetwork.NetworkOptionConfigOnly())
  292. }
  293. if create.IPAM != nil {
  294. ipam := create.IPAM
  295. v4Conf, v6Conf, err := getIpamConfig(ipam.Config)
  296. if err != nil {
  297. return nil, err
  298. }
  299. nwOptions = append(nwOptions, libnetwork.NetworkOptionIpam(ipam.Driver, "", v4Conf, v6Conf, ipam.Options))
  300. }
  301. if create.Internal {
  302. nwOptions = append(nwOptions, libnetwork.NetworkOptionInternalNetwork())
  303. }
  304. if agent {
  305. nwOptions = append(nwOptions, libnetwork.NetworkOptionDynamic())
  306. nwOptions = append(nwOptions, libnetwork.NetworkOptionPersist(false))
  307. }
  308. if create.ConfigFrom != nil {
  309. nwOptions = append(nwOptions, libnetwork.NetworkOptionConfigFrom(create.ConfigFrom.Network))
  310. }
  311. if agent && driver == "overlay" {
  312. nodeIP, exists := daemon.GetAttachmentStore().GetIPForNetwork(id)
  313. if !exists {
  314. return nil, fmt.Errorf("Failed to find a load balancer IP to use for network: %v", id)
  315. }
  316. nwOptions = append(nwOptions, libnetwork.NetworkOptionLBEndpoint(nodeIP))
  317. }
  318. n, err := c.NewNetwork(driver, create.Name, id, nwOptions...)
  319. if err != nil {
  320. if _, ok := err.(libnetwork.ErrDataStoreNotInitialized); ok {
  321. //nolint: golint
  322. 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.")
  323. }
  324. return nil, err
  325. }
  326. daemon.pluginRefCount(driver, driverapi.NetworkPluginEndpointType, plugingetter.Acquire)
  327. if create.IPAM != nil {
  328. daemon.pluginRefCount(create.IPAM.Driver, ipamapi.PluginEndpointType, plugingetter.Acquire)
  329. }
  330. daemon.LogNetworkEvent(n, "create")
  331. return &types.NetworkCreateResponse{
  332. ID: n.ID(),
  333. Warning: warning,
  334. }, nil
  335. }
  336. func (daemon *Daemon) pluginRefCount(driver, capability string, mode int) {
  337. var builtinDrivers []string
  338. if capability == driverapi.NetworkPluginEndpointType {
  339. builtinDrivers = daemon.netController.BuiltinDrivers()
  340. } else if capability == ipamapi.PluginEndpointType {
  341. builtinDrivers = daemon.netController.BuiltinIPAMDrivers()
  342. }
  343. for _, d := range builtinDrivers {
  344. if d == driver {
  345. return
  346. }
  347. }
  348. if daemon.PluginStore != nil {
  349. _, err := daemon.PluginStore.Get(driver, capability, mode)
  350. if err != nil {
  351. logrus.WithError(err).WithFields(logrus.Fields{"mode": mode, "driver": driver}).Error("Error handling plugin refcount operation")
  352. }
  353. }
  354. }
  355. func getIpamConfig(data []network.IPAMConfig) ([]*libnetwork.IpamConf, []*libnetwork.IpamConf, error) {
  356. ipamV4Cfg := []*libnetwork.IpamConf{}
  357. ipamV6Cfg := []*libnetwork.IpamConf{}
  358. for _, d := range data {
  359. iCfg := libnetwork.IpamConf{}
  360. iCfg.PreferredPool = d.Subnet
  361. iCfg.SubPool = d.IPRange
  362. iCfg.Gateway = d.Gateway
  363. iCfg.AuxAddresses = d.AuxAddress
  364. ip, _, err := net.ParseCIDR(d.Subnet)
  365. if err != nil {
  366. return nil, nil, fmt.Errorf("Invalid subnet %s : %v", d.Subnet, err)
  367. }
  368. if ip.To4() != nil {
  369. ipamV4Cfg = append(ipamV4Cfg, &iCfg)
  370. } else {
  371. ipamV6Cfg = append(ipamV6Cfg, &iCfg)
  372. }
  373. }
  374. return ipamV4Cfg, ipamV6Cfg, nil
  375. }
  376. // UpdateContainerServiceConfig updates a service configuration.
  377. func (daemon *Daemon) UpdateContainerServiceConfig(containerName string, serviceConfig *clustertypes.ServiceConfig) error {
  378. ctr, err := daemon.GetContainer(containerName)
  379. if err != nil {
  380. return err
  381. }
  382. ctr.NetworkSettings.Service = serviceConfig
  383. return nil
  384. }
  385. // ConnectContainerToNetwork connects the given container to the given
  386. // network. If either cannot be found, an err is returned. If the
  387. // network cannot be set up, an err is returned.
  388. func (daemon *Daemon) ConnectContainerToNetwork(containerName, networkName string, endpointConfig *network.EndpointSettings) error {
  389. ctr, err := daemon.GetContainer(containerName)
  390. if err != nil {
  391. return err
  392. }
  393. return daemon.ConnectToNetwork(ctr, networkName, endpointConfig)
  394. }
  395. // DisconnectContainerFromNetwork disconnects the given container from
  396. // the given network. If either cannot be found, an err is returned.
  397. func (daemon *Daemon) DisconnectContainerFromNetwork(containerName string, networkName string, force bool) error {
  398. ctr, err := daemon.GetContainer(containerName)
  399. if err != nil {
  400. if force {
  401. return daemon.ForceEndpointDelete(containerName, networkName)
  402. }
  403. return err
  404. }
  405. return daemon.DisconnectFromNetwork(ctr, networkName, force)
  406. }
  407. // GetNetworkDriverList returns the list of plugins drivers
  408. // registered for network.
  409. func (daemon *Daemon) GetNetworkDriverList() []string {
  410. if !daemon.NetworkControllerEnabled() {
  411. return nil
  412. }
  413. pluginList := daemon.netController.BuiltinDrivers()
  414. managedPlugins := daemon.PluginStore.GetAllManagedPluginsByCap(driverapi.NetworkPluginEndpointType)
  415. for _, plugin := range managedPlugins {
  416. pluginList = append(pluginList, plugin.Name())
  417. }
  418. pluginMap := make(map[string]bool)
  419. for _, plugin := range pluginList {
  420. pluginMap[plugin] = true
  421. }
  422. networks := daemon.netController.Networks()
  423. for _, nw := range networks {
  424. if !pluginMap[nw.Type()] {
  425. pluginList = append(pluginList, nw.Type())
  426. pluginMap[nw.Type()] = true
  427. }
  428. }
  429. sort.Strings(pluginList)
  430. return pluginList
  431. }
  432. // DeleteManagedNetwork deletes an agent network.
  433. // The requirement of networkID is enforced.
  434. func (daemon *Daemon) DeleteManagedNetwork(networkID string) error {
  435. n, err := daemon.GetNetworkByID(networkID)
  436. if err != nil {
  437. return err
  438. }
  439. return daemon.deleteNetwork(n, true)
  440. }
  441. // DeleteNetwork destroys a network unless it's one of docker's predefined networks.
  442. func (daemon *Daemon) DeleteNetwork(networkID string) error {
  443. n, err := daemon.GetNetworkByID(networkID)
  444. if err != nil {
  445. return errors.Wrap(err, "could not find network by ID")
  446. }
  447. return daemon.deleteNetwork(n, false)
  448. }
  449. func (daemon *Daemon) deleteNetwork(nw libnetwork.Network, dynamic bool) error {
  450. if runconfig.IsPreDefinedNetwork(nw.Name()) && !dynamic {
  451. err := fmt.Errorf("%s is a pre-defined network and cannot be removed", nw.Name())
  452. return errdefs.Forbidden(err)
  453. }
  454. if dynamic && !nw.Info().Dynamic() {
  455. if runconfig.IsPreDefinedNetwork(nw.Name()) {
  456. // Predefined networks now support swarm services. Make this
  457. // a no-op when cluster requests to remove the predefined network.
  458. return nil
  459. }
  460. err := fmt.Errorf("%s is not a dynamic network", nw.Name())
  461. return errdefs.Forbidden(err)
  462. }
  463. if err := nw.Delete(); err != nil {
  464. return errors.Wrap(err, "error while removing network")
  465. }
  466. // If this is not a configuration only network, we need to
  467. // update the corresponding remote drivers' reference counts
  468. if !nw.Info().ConfigOnly() {
  469. daemon.pluginRefCount(nw.Type(), driverapi.NetworkPluginEndpointType, plugingetter.Release)
  470. ipamType, _, _, _ := nw.Info().IpamConfig()
  471. daemon.pluginRefCount(ipamType, ipamapi.PluginEndpointType, plugingetter.Release)
  472. daemon.LogNetworkEvent(nw, "destroy")
  473. }
  474. return nil
  475. }
  476. // GetNetworks returns a list of all networks
  477. func (daemon *Daemon) GetNetworks(filter filters.Args, config types.NetworkListConfig) ([]types.NetworkResource, error) {
  478. networks := daemon.getAllNetworks()
  479. list := make([]types.NetworkResource, 0, len(networks))
  480. var idx map[string]libnetwork.Network
  481. if config.Detailed {
  482. idx = make(map[string]libnetwork.Network)
  483. }
  484. for _, n := range networks {
  485. nr := buildNetworkResource(n)
  486. list = append(list, nr)
  487. if config.Detailed {
  488. idx[nr.ID] = n
  489. }
  490. }
  491. var err error
  492. list, err = internalnetwork.FilterNetworks(list, filter)
  493. if err != nil {
  494. return nil, err
  495. }
  496. if config.Detailed {
  497. for i := range list {
  498. np := &list[i]
  499. buildDetailedNetworkResources(np, idx[np.ID], config.Verbose)
  500. list[i] = *np
  501. }
  502. }
  503. return list, nil
  504. }
  505. func buildNetworkResource(nw libnetwork.Network) types.NetworkResource {
  506. r := types.NetworkResource{}
  507. if nw == nil {
  508. return r
  509. }
  510. info := nw.Info()
  511. r.Name = nw.Name()
  512. r.ID = nw.ID()
  513. r.Created = info.Created()
  514. r.Scope = info.Scope()
  515. r.Driver = nw.Type()
  516. r.EnableIPv6 = info.IPv6Enabled()
  517. r.Internal = info.Internal()
  518. r.Attachable = info.Attachable()
  519. r.Ingress = info.Ingress()
  520. r.Options = info.DriverOptions()
  521. r.Containers = make(map[string]types.EndpointResource)
  522. buildIpamResources(&r, info)
  523. r.Labels = info.Labels()
  524. r.ConfigOnly = info.ConfigOnly()
  525. if cn := info.ConfigFrom(); cn != "" {
  526. r.ConfigFrom = network.ConfigReference{Network: cn}
  527. }
  528. peers := info.Peers()
  529. if len(peers) != 0 {
  530. r.Peers = buildPeerInfoResources(peers)
  531. }
  532. return r
  533. }
  534. func buildDetailedNetworkResources(r *types.NetworkResource, nw libnetwork.Network, verbose bool) {
  535. if nw == nil {
  536. return
  537. }
  538. epl := nw.Endpoints()
  539. for _, e := range epl {
  540. ei := e.Info()
  541. if ei == nil {
  542. continue
  543. }
  544. sb := ei.Sandbox()
  545. tmpID := e.ID()
  546. key := "ep-" + tmpID
  547. if sb != nil {
  548. key = sb.ContainerID()
  549. }
  550. r.Containers[key] = buildEndpointResource(tmpID, e.Name(), ei)
  551. }
  552. if !verbose {
  553. return
  554. }
  555. services := nw.Info().Services()
  556. r.Services = make(map[string]network.ServiceInfo)
  557. for name, service := range services {
  558. tasks := []network.Task{}
  559. for _, t := range service.Tasks {
  560. tasks = append(tasks, network.Task{
  561. Name: t.Name,
  562. EndpointID: t.EndpointID,
  563. EndpointIP: t.EndpointIP,
  564. Info: t.Info,
  565. })
  566. }
  567. r.Services[name] = network.ServiceInfo{
  568. VIP: service.VIP,
  569. Ports: service.Ports,
  570. Tasks: tasks,
  571. LocalLBIndex: service.LocalLBIndex,
  572. }
  573. }
  574. }
  575. func buildPeerInfoResources(peers []networkdb.PeerInfo) []network.PeerInfo {
  576. peerInfo := make([]network.PeerInfo, 0, len(peers))
  577. for _, peer := range peers {
  578. peerInfo = append(peerInfo, network.PeerInfo{
  579. Name: peer.Name,
  580. IP: peer.IP,
  581. })
  582. }
  583. return peerInfo
  584. }
  585. func buildIpamResources(r *types.NetworkResource, nwInfo libnetwork.NetworkInfo) {
  586. id, opts, ipv4conf, ipv6conf := nwInfo.IpamConfig()
  587. ipv4Info, ipv6Info := nwInfo.IpamInfo()
  588. r.IPAM.Driver = id
  589. r.IPAM.Options = opts
  590. r.IPAM.Config = []network.IPAMConfig{}
  591. for _, ip4 := range ipv4conf {
  592. if ip4.PreferredPool == "" {
  593. continue
  594. }
  595. iData := network.IPAMConfig{}
  596. iData.Subnet = ip4.PreferredPool
  597. iData.IPRange = ip4.SubPool
  598. iData.Gateway = ip4.Gateway
  599. iData.AuxAddress = ip4.AuxAddresses
  600. r.IPAM.Config = append(r.IPAM.Config, iData)
  601. }
  602. if len(r.IPAM.Config) == 0 {
  603. for _, ip4Info := range ipv4Info {
  604. iData := network.IPAMConfig{}
  605. iData.Subnet = ip4Info.IPAMData.Pool.String()
  606. if ip4Info.IPAMData.Gateway != nil {
  607. iData.Gateway = ip4Info.IPAMData.Gateway.IP.String()
  608. }
  609. r.IPAM.Config = append(r.IPAM.Config, iData)
  610. }
  611. }
  612. hasIpv6Conf := false
  613. for _, ip6 := range ipv6conf {
  614. if ip6.PreferredPool == "" {
  615. continue
  616. }
  617. hasIpv6Conf = true
  618. iData := network.IPAMConfig{}
  619. iData.Subnet = ip6.PreferredPool
  620. iData.IPRange = ip6.SubPool
  621. iData.Gateway = ip6.Gateway
  622. iData.AuxAddress = ip6.AuxAddresses
  623. r.IPAM.Config = append(r.IPAM.Config, iData)
  624. }
  625. if !hasIpv6Conf {
  626. for _, ip6Info := range ipv6Info {
  627. if ip6Info.IPAMData.Pool == nil {
  628. continue
  629. }
  630. iData := network.IPAMConfig{}
  631. iData.Subnet = ip6Info.IPAMData.Pool.String()
  632. iData.Gateway = ip6Info.IPAMData.Gateway.String()
  633. r.IPAM.Config = append(r.IPAM.Config, iData)
  634. }
  635. }
  636. }
  637. func buildEndpointResource(id string, name string, info libnetwork.EndpointInfo) types.EndpointResource {
  638. er := types.EndpointResource{}
  639. er.EndpointID = id
  640. er.Name = name
  641. ei := info
  642. if ei == nil {
  643. return er
  644. }
  645. if iface := ei.Iface(); iface != nil {
  646. if mac := iface.MacAddress(); mac != nil {
  647. er.MacAddress = mac.String()
  648. }
  649. if ip := iface.Address(); ip != nil && len(ip.IP) > 0 {
  650. er.IPv4Address = ip.String()
  651. }
  652. if ipv6 := iface.AddressIPv6(); ipv6 != nil && len(ipv6.IP) > 0 {
  653. er.IPv6Address = ipv6.String()
  654. }
  655. }
  656. return er
  657. }
  658. // clearAttachableNetworks removes the attachable networks
  659. // after disconnecting any connected container
  660. func (daemon *Daemon) clearAttachableNetworks() {
  661. for _, n := range daemon.getAllNetworks() {
  662. if !n.Info().Attachable() {
  663. continue
  664. }
  665. for _, ep := range n.Endpoints() {
  666. epInfo := ep.Info()
  667. if epInfo == nil {
  668. continue
  669. }
  670. sb := epInfo.Sandbox()
  671. if sb == nil {
  672. continue
  673. }
  674. containerID := sb.ContainerID()
  675. if err := daemon.DisconnectContainerFromNetwork(containerID, n.ID(), true); err != nil {
  676. logrus.Warnf("Failed to disconnect container %s from swarm network %s on cluster leave: %v",
  677. containerID, n.Name(), err)
  678. }
  679. }
  680. if err := daemon.DeleteManagedNetwork(n.ID()); err != nil {
  681. logrus.Warnf("Failed to remove swarm network %s on cluster leave: %v", n.Name(), err)
  682. }
  683. }
  684. }
  685. // buildCreateEndpointOptions builds endpoint options from a given network.
  686. func buildCreateEndpointOptions(c *container.Container, n libnetwork.Network, epConfig *network.EndpointSettings, sb libnetwork.Sandbox, daemonDNS []string) ([]libnetwork.EndpointOption, error) {
  687. var (
  688. bindings = make(nat.PortMap)
  689. pbList []networktypes.PortBinding
  690. exposeList []networktypes.TransportPort
  691. createOptions []libnetwork.EndpointOption
  692. )
  693. defaultNetName := runconfig.DefaultDaemonNetworkMode().NetworkName()
  694. if (!serviceDiscoveryOnDefaultNetwork() && n.Name() == defaultNetName) ||
  695. c.NetworkSettings.IsAnonymousEndpoint {
  696. createOptions = append(createOptions, libnetwork.CreateOptionAnonymous())
  697. }
  698. if epConfig != nil {
  699. ipam := epConfig.IPAMConfig
  700. if ipam != nil {
  701. var (
  702. ipList []net.IP
  703. ip, ip6, linkip net.IP
  704. )
  705. for _, ips := range ipam.LinkLocalIPs {
  706. if linkip = net.ParseIP(ips); linkip == nil && ips != "" {
  707. return nil, errors.Errorf("Invalid link-local IP address: %s", ipam.LinkLocalIPs)
  708. }
  709. ipList = append(ipList, linkip)
  710. }
  711. if ip = net.ParseIP(ipam.IPv4Address); ip == nil && ipam.IPv4Address != "" {
  712. return nil, errors.Errorf("Invalid IPv4 address: %s)", ipam.IPv4Address)
  713. }
  714. if ip6 = net.ParseIP(ipam.IPv6Address); ip6 == nil && ipam.IPv6Address != "" {
  715. return nil, errors.Errorf("Invalid IPv6 address: %s)", ipam.IPv6Address)
  716. }
  717. createOptions = append(createOptions,
  718. libnetwork.CreateOptionIpam(ip, ip6, ipList, nil))
  719. }
  720. for _, alias := range epConfig.Aliases {
  721. createOptions = append(createOptions, libnetwork.CreateOptionMyAlias(alias))
  722. }
  723. for k, v := range epConfig.DriverOpts {
  724. createOptions = append(createOptions, libnetwork.EndpointOptionGeneric(options.Generic{k: v}))
  725. }
  726. }
  727. if c.NetworkSettings.Service != nil {
  728. svcCfg := c.NetworkSettings.Service
  729. var vip string
  730. if svcCfg.VirtualAddresses[n.ID()] != nil {
  731. vip = svcCfg.VirtualAddresses[n.ID()].IPv4
  732. }
  733. var portConfigs []*libnetwork.PortConfig
  734. for _, portConfig := range svcCfg.ExposedPorts {
  735. portConfigs = append(portConfigs, &libnetwork.PortConfig{
  736. Name: portConfig.Name,
  737. Protocol: libnetwork.PortConfig_Protocol(portConfig.Protocol),
  738. TargetPort: portConfig.TargetPort,
  739. PublishedPort: portConfig.PublishedPort,
  740. })
  741. }
  742. createOptions = append(createOptions, libnetwork.CreateOptionService(svcCfg.Name, svcCfg.ID, net.ParseIP(vip), portConfigs, svcCfg.Aliases[n.ID()]))
  743. }
  744. if !containertypes.NetworkMode(n.Name()).IsUserDefined() {
  745. createOptions = append(createOptions, libnetwork.CreateOptionDisableResolution())
  746. }
  747. // configs that are applicable only for the endpoint in the network
  748. // to which container was connected to on docker run.
  749. // Ideally all these network-specific endpoint configurations must be moved under
  750. // container.NetworkSettings.Networks[n.Name()]
  751. if n.Name() == c.HostConfig.NetworkMode.NetworkName() ||
  752. (n.Name() == defaultNetName && c.HostConfig.NetworkMode.IsDefault()) {
  753. if c.Config.MacAddress != "" {
  754. mac, err := net.ParseMAC(c.Config.MacAddress)
  755. if err != nil {
  756. return nil, err
  757. }
  758. genericOption := options.Generic{
  759. netlabel.MacAddress: mac,
  760. }
  761. createOptions = append(createOptions, libnetwork.EndpointOptionGeneric(genericOption))
  762. }
  763. }
  764. // Port-mapping rules belong to the container & applicable only to non-internal networks
  765. portmaps := getSandboxPortMapInfo(sb)
  766. if n.Info().Internal() || len(portmaps) > 0 {
  767. return createOptions, nil
  768. }
  769. if c.HostConfig.PortBindings != nil {
  770. for p, b := range c.HostConfig.PortBindings {
  771. bindings[p] = []nat.PortBinding{}
  772. for _, bb := range b {
  773. bindings[p] = append(bindings[p], nat.PortBinding{
  774. HostIP: bb.HostIP,
  775. HostPort: bb.HostPort,
  776. })
  777. }
  778. }
  779. }
  780. portSpecs := c.Config.ExposedPorts
  781. ports := make([]nat.Port, len(portSpecs))
  782. var i int
  783. for p := range portSpecs {
  784. ports[i] = p
  785. i++
  786. }
  787. nat.SortPortMap(ports, bindings)
  788. for _, port := range ports {
  789. expose := networktypes.TransportPort{}
  790. expose.Proto = networktypes.ParseProtocol(port.Proto())
  791. expose.Port = uint16(port.Int())
  792. exposeList = append(exposeList, expose)
  793. pb := networktypes.PortBinding{Port: expose.Port, Proto: expose.Proto}
  794. binding := bindings[port]
  795. for i := 0; i < len(binding); i++ {
  796. pbCopy := pb.GetCopy()
  797. newP, err := nat.NewPort(nat.SplitProtoPort(binding[i].HostPort))
  798. var portStart, portEnd int
  799. if err == nil {
  800. portStart, portEnd, err = newP.Range()
  801. }
  802. if err != nil {
  803. return nil, errors.Wrapf(err, "Error parsing HostPort value (%s)", binding[i].HostPort)
  804. }
  805. pbCopy.HostPort = uint16(portStart)
  806. pbCopy.HostPortEnd = uint16(portEnd)
  807. pbCopy.HostIP = net.ParseIP(binding[i].HostIP)
  808. pbList = append(pbList, pbCopy)
  809. }
  810. if c.HostConfig.PublishAllPorts && len(binding) == 0 {
  811. pbList = append(pbList, pb)
  812. }
  813. }
  814. var dns []string
  815. if len(c.HostConfig.DNS) > 0 {
  816. dns = c.HostConfig.DNS
  817. } else if len(daemonDNS) > 0 {
  818. dns = daemonDNS
  819. }
  820. if len(dns) > 0 {
  821. createOptions = append(createOptions,
  822. libnetwork.CreateOptionDNS(dns))
  823. }
  824. createOptions = append(createOptions,
  825. libnetwork.CreateOptionPortMapping(pbList),
  826. libnetwork.CreateOptionExposedPorts(exposeList))
  827. return createOptions, nil
  828. }
  829. // getSandboxPortMapInfo retrieves the current port-mapping programmed for the given sandbox
  830. func getSandboxPortMapInfo(sb libnetwork.Sandbox) nat.PortMap {
  831. pm := nat.PortMap{}
  832. if sb == nil {
  833. return pm
  834. }
  835. for _, ep := range sb.Endpoints() {
  836. pm, _ = getEndpointPortMapInfo(ep)
  837. if len(pm) > 0 {
  838. break
  839. }
  840. }
  841. return pm
  842. }
  843. func getEndpointPortMapInfo(ep libnetwork.Endpoint) (nat.PortMap, error) {
  844. pm := nat.PortMap{}
  845. driverInfo, err := ep.DriverInfo()
  846. if err != nil {
  847. return pm, err
  848. }
  849. if driverInfo == nil {
  850. // It is not an error for epInfo to be nil
  851. return pm, nil
  852. }
  853. if expData, ok := driverInfo[netlabel.ExposedPorts]; ok {
  854. if exposedPorts, ok := expData.([]networktypes.TransportPort); ok {
  855. for _, tp := range exposedPorts {
  856. natPort, err := nat.NewPort(tp.Proto.String(), strconv.Itoa(int(tp.Port)))
  857. if err != nil {
  858. return pm, fmt.Errorf("Error parsing Port value(%v):%v", tp.Port, err)
  859. }
  860. pm[natPort] = nil
  861. }
  862. }
  863. }
  864. mapData, ok := driverInfo[netlabel.PortMap]
  865. if !ok {
  866. return pm, nil
  867. }
  868. if portMapping, ok := mapData.([]networktypes.PortBinding); ok {
  869. for _, pp := range portMapping {
  870. natPort, err := nat.NewPort(pp.Proto.String(), strconv.Itoa(int(pp.Port)))
  871. if err != nil {
  872. return pm, err
  873. }
  874. natBndg := nat.PortBinding{HostIP: pp.HostIP.String(), HostPort: strconv.Itoa(int(pp.HostPort))}
  875. pm[natPort] = append(pm[natPort], natBndg)
  876. }
  877. }
  878. return pm, nil
  879. }
  880. // buildEndpointInfo sets endpoint-related fields on container.NetworkSettings based on the provided network and endpoint.
  881. func buildEndpointInfo(networkSettings *internalnetwork.Settings, n libnetwork.Network, ep libnetwork.Endpoint) error {
  882. if ep == nil {
  883. return errors.New("endpoint cannot be nil")
  884. }
  885. if networkSettings == nil {
  886. return errors.New("network cannot be nil")
  887. }
  888. epInfo := ep.Info()
  889. if epInfo == nil {
  890. // It is not an error to get an empty endpoint info
  891. return nil
  892. }
  893. if _, ok := networkSettings.Networks[n.Name()]; !ok {
  894. networkSettings.Networks[n.Name()] = &internalnetwork.EndpointSettings{
  895. EndpointSettings: &network.EndpointSettings{},
  896. }
  897. }
  898. networkSettings.Networks[n.Name()].NetworkID = n.ID()
  899. networkSettings.Networks[n.Name()].EndpointID = ep.ID()
  900. iface := epInfo.Iface()
  901. if iface == nil {
  902. return nil
  903. }
  904. if iface.MacAddress() != nil {
  905. networkSettings.Networks[n.Name()].MacAddress = iface.MacAddress().String()
  906. }
  907. if iface.Address() != nil {
  908. ones, _ := iface.Address().Mask.Size()
  909. networkSettings.Networks[n.Name()].IPAddress = iface.Address().IP.String()
  910. networkSettings.Networks[n.Name()].IPPrefixLen = ones
  911. }
  912. if iface.AddressIPv6() != nil && iface.AddressIPv6().IP.To16() != nil {
  913. onesv6, _ := iface.AddressIPv6().Mask.Size()
  914. networkSettings.Networks[n.Name()].GlobalIPv6Address = iface.AddressIPv6().IP.String()
  915. networkSettings.Networks[n.Name()].GlobalIPv6PrefixLen = onesv6
  916. }
  917. return nil
  918. }
  919. // buildJoinOptions builds endpoint Join options from a given network.
  920. func buildJoinOptions(networkSettings *internalnetwork.Settings, n interface {
  921. Name() string
  922. }) ([]libnetwork.EndpointOption, error) {
  923. var joinOptions []libnetwork.EndpointOption
  924. if epConfig, ok := networkSettings.Networks[n.Name()]; ok {
  925. for _, str := range epConfig.Links {
  926. name, alias, err := opts.ParseLink(str)
  927. if err != nil {
  928. return nil, err
  929. }
  930. joinOptions = append(joinOptions, libnetwork.CreateOptionAlias(name, alias))
  931. }
  932. for k, v := range epConfig.DriverOpts {
  933. joinOptions = append(joinOptions, libnetwork.EndpointOptionGeneric(options.Generic{k: v}))
  934. }
  935. }
  936. return joinOptions, nil
  937. }