controller.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116
  1. /*
  2. Package libnetwork provides the basic functionality and extension points to
  3. create network namespaces and allocate interfaces for containers to use.
  4. networkType := "bridge"
  5. // Create a new controller instance
  6. driverOptions := options.Generic{}
  7. genericOption := make(map[string]interface{})
  8. genericOption[netlabel.GenericData] = driverOptions
  9. controller, err := libnetwork.New(config.OptionDriverConfig(networkType, genericOption))
  10. if err != nil {
  11. return
  12. }
  13. // Create a network for containers to join.
  14. // NewNetwork accepts Variadic optional arguments that libnetwork and Drivers can make use of
  15. network, err := controller.NewNetwork(networkType, "network1", "")
  16. if err != nil {
  17. return
  18. }
  19. // For each new container: allocate IP and interfaces. The returned network
  20. // settings will be used for container infos (inspect and such), as well as
  21. // iptables rules for port publishing. This info is contained or accessible
  22. // from the returned endpoint.
  23. ep, err := network.CreateEndpoint("Endpoint1")
  24. if err != nil {
  25. return
  26. }
  27. // Create the sandbox for the container.
  28. // NewSandbox accepts Variadic optional arguments which libnetwork can use.
  29. sbx, err := controller.NewSandbox("container1",
  30. libnetwork.OptionHostname("test"),
  31. libnetwork.OptionDomainname("example.com"))
  32. // A sandbox can join the endpoint via the join api.
  33. err = ep.Join(sbx)
  34. if err != nil {
  35. return
  36. }
  37. */
  38. package libnetwork
  39. import (
  40. "context"
  41. "fmt"
  42. "net"
  43. "path/filepath"
  44. "runtime"
  45. "strings"
  46. "sync"
  47. "time"
  48. "github.com/containerd/containerd/log"
  49. "github.com/docker/docker/libnetwork/cluster"
  50. "github.com/docker/docker/libnetwork/config"
  51. "github.com/docker/docker/libnetwork/datastore"
  52. "github.com/docker/docker/libnetwork/diagnostic"
  53. "github.com/docker/docker/libnetwork/discoverapi"
  54. "github.com/docker/docker/libnetwork/driverapi"
  55. remotedriver "github.com/docker/docker/libnetwork/drivers/remote"
  56. "github.com/docker/docker/libnetwork/drvregistry"
  57. "github.com/docker/docker/libnetwork/ipamapi"
  58. "github.com/docker/docker/libnetwork/netlabel"
  59. "github.com/docker/docker/libnetwork/osl"
  60. "github.com/docker/docker/libnetwork/scope"
  61. "github.com/docker/docker/libnetwork/types"
  62. "github.com/docker/docker/pkg/plugingetter"
  63. "github.com/docker/docker/pkg/plugins"
  64. "github.com/docker/docker/pkg/stringid"
  65. "github.com/moby/locker"
  66. "github.com/pkg/errors"
  67. )
  68. // NetworkWalker is a client provided function which will be used to walk the Networks.
  69. // When the function returns true, the walk will stop.
  70. type NetworkWalker func(nw *Network) bool
  71. // Controller manages networks.
  72. type Controller struct {
  73. id string
  74. drvRegistry drvregistry.Networks
  75. ipamRegistry drvregistry.IPAMs
  76. sandboxes map[string]*Sandbox
  77. cfg *config.Config
  78. store *datastore.Store
  79. extKeyListener net.Listener
  80. watchCh chan *Endpoint
  81. unWatchCh chan *Endpoint
  82. svcRecords map[string]*svcInfo
  83. nmap map[string]*netWatch
  84. serviceBindings map[serviceKey]*service
  85. defOsSbox osl.Sandbox
  86. ingressSandbox *Sandbox
  87. sboxOnce sync.Once
  88. agent *agent
  89. networkLocker *locker.Locker
  90. agentInitDone chan struct{}
  91. agentStopDone chan struct{}
  92. keys []*types.EncryptionKey
  93. DiagnosticServer *diagnostic.Server
  94. mu sync.Mutex
  95. }
  96. // New creates a new instance of network controller.
  97. func New(cfgOptions ...config.Option) (*Controller, error) {
  98. c := &Controller{
  99. id: stringid.GenerateRandomID(),
  100. cfg: config.New(cfgOptions...),
  101. sandboxes: map[string]*Sandbox{},
  102. svcRecords: make(map[string]*svcInfo),
  103. serviceBindings: make(map[serviceKey]*service),
  104. agentInitDone: make(chan struct{}),
  105. networkLocker: locker.New(),
  106. DiagnosticServer: diagnostic.New(),
  107. }
  108. c.DiagnosticServer.Init()
  109. if err := c.initStores(); err != nil {
  110. return nil, err
  111. }
  112. c.drvRegistry.Notify = c.RegisterDriver
  113. // External plugins don't need config passed through daemon. They can
  114. // bootstrap themselves.
  115. if err := remotedriver.Register(&c.drvRegistry, c.cfg.PluginGetter); err != nil {
  116. return nil, err
  117. }
  118. if err := registerNetworkDrivers(&c.drvRegistry, c.makeDriverConfig); err != nil {
  119. return nil, err
  120. }
  121. if err := initIPAMDrivers(&c.ipamRegistry, c.cfg.PluginGetter, c.cfg.DefaultAddressPool); err != nil {
  122. return nil, err
  123. }
  124. c.WalkNetworks(populateSpecial)
  125. // Reserve pools first before doing cleanup. Otherwise the
  126. // cleanups of endpoint/network and sandbox below will
  127. // generate many unnecessary warnings
  128. c.reservePools()
  129. // Cleanup resources
  130. c.sandboxCleanup(c.cfg.ActiveSandboxes)
  131. c.cleanupLocalEndpoints()
  132. c.networkCleanup()
  133. if err := c.startExternalKeyListener(); err != nil {
  134. return nil, err
  135. }
  136. setupArrangeUserFilterRule(c)
  137. return c, nil
  138. }
  139. // SetClusterProvider sets the cluster provider.
  140. func (c *Controller) SetClusterProvider(provider cluster.Provider) {
  141. var sameProvider bool
  142. c.mu.Lock()
  143. // Avoids to spawn multiple goroutine for the same cluster provider
  144. if c.cfg.ClusterProvider == provider {
  145. // If the cluster provider is already set, there is already a go routine spawned
  146. // that is listening for events, so nothing to do here
  147. sameProvider = true
  148. } else {
  149. c.cfg.ClusterProvider = provider
  150. }
  151. c.mu.Unlock()
  152. if provider == nil || sameProvider {
  153. return
  154. }
  155. // We don't want to spawn a new go routine if the previous one did not exit yet
  156. c.AgentStopWait()
  157. go c.clusterAgentInit()
  158. }
  159. // SetKeys configures the encryption key for gossip and overlay data path.
  160. func (c *Controller) SetKeys(keys []*types.EncryptionKey) error {
  161. // libnetwork side of agent depends on the keys. On the first receipt of
  162. // keys setup the agent. For subsequent key set handle the key change
  163. subsysKeys := make(map[string]int)
  164. for _, key := range keys {
  165. if key.Subsystem != subsysGossip &&
  166. key.Subsystem != subsysIPSec {
  167. return fmt.Errorf("key received for unrecognized subsystem")
  168. }
  169. subsysKeys[key.Subsystem]++
  170. }
  171. for s, count := range subsysKeys {
  172. if count != keyringSize {
  173. return fmt.Errorf("incorrect number of keys for subsystem %v", s)
  174. }
  175. }
  176. if c.getAgent() == nil {
  177. c.mu.Lock()
  178. c.keys = keys
  179. c.mu.Unlock()
  180. return nil
  181. }
  182. return c.handleKeyChange(keys)
  183. }
  184. func (c *Controller) getAgent() *agent {
  185. c.mu.Lock()
  186. defer c.mu.Unlock()
  187. return c.agent
  188. }
  189. func (c *Controller) clusterAgentInit() {
  190. clusterProvider := c.cfg.ClusterProvider
  191. var keysAvailable bool
  192. for {
  193. eventType := <-clusterProvider.ListenClusterEvents()
  194. // The events: EventSocketChange, EventNodeReady and EventNetworkKeysAvailable are not ordered
  195. // when all the condition for the agent initialization are met then proceed with it
  196. switch eventType {
  197. case cluster.EventNetworkKeysAvailable:
  198. // Validates that the keys are actually available before starting the initialization
  199. // This will handle old spurious messages left on the channel
  200. c.mu.Lock()
  201. keysAvailable = c.keys != nil
  202. c.mu.Unlock()
  203. fallthrough
  204. case cluster.EventSocketChange, cluster.EventNodeReady:
  205. if keysAvailable && !c.isDistributedControl() {
  206. c.agentOperationStart()
  207. if err := c.agentSetup(clusterProvider); err != nil {
  208. c.agentStopComplete()
  209. } else {
  210. c.agentInitComplete()
  211. }
  212. }
  213. case cluster.EventNodeLeave:
  214. c.agentOperationStart()
  215. c.mu.Lock()
  216. c.keys = nil
  217. c.mu.Unlock()
  218. // We are leaving the cluster. Make sure we
  219. // close the gossip so that we stop all
  220. // incoming gossip updates before cleaning up
  221. // any remaining service bindings. But before
  222. // deleting the networks since the networks
  223. // should still be present when cleaning up
  224. // service bindings
  225. c.agentClose()
  226. c.cleanupServiceDiscovery("")
  227. c.cleanupServiceBindings("")
  228. c.agentStopComplete()
  229. return
  230. }
  231. }
  232. }
  233. // AgentInitWait waits for agent initialization to be completed in the controller.
  234. func (c *Controller) AgentInitWait() {
  235. c.mu.Lock()
  236. agentInitDone := c.agentInitDone
  237. c.mu.Unlock()
  238. if agentInitDone != nil {
  239. <-agentInitDone
  240. }
  241. }
  242. // AgentStopWait waits for the Agent stop to be completed in the controller.
  243. func (c *Controller) AgentStopWait() {
  244. c.mu.Lock()
  245. agentStopDone := c.agentStopDone
  246. c.mu.Unlock()
  247. if agentStopDone != nil {
  248. <-agentStopDone
  249. }
  250. }
  251. // agentOperationStart marks the start of an Agent Init or Agent Stop
  252. func (c *Controller) agentOperationStart() {
  253. c.mu.Lock()
  254. if c.agentInitDone == nil {
  255. c.agentInitDone = make(chan struct{})
  256. }
  257. if c.agentStopDone == nil {
  258. c.agentStopDone = make(chan struct{})
  259. }
  260. c.mu.Unlock()
  261. }
  262. // agentInitComplete notifies the successful completion of the Agent initialization
  263. func (c *Controller) agentInitComplete() {
  264. c.mu.Lock()
  265. if c.agentInitDone != nil {
  266. close(c.agentInitDone)
  267. c.agentInitDone = nil
  268. }
  269. c.mu.Unlock()
  270. }
  271. // agentStopComplete notifies the successful completion of the Agent stop
  272. func (c *Controller) agentStopComplete() {
  273. c.mu.Lock()
  274. if c.agentStopDone != nil {
  275. close(c.agentStopDone)
  276. c.agentStopDone = nil
  277. }
  278. c.mu.Unlock()
  279. }
  280. func (c *Controller) makeDriverConfig(ntype string) map[string]interface{} {
  281. if c.cfg == nil {
  282. return nil
  283. }
  284. cfg := map[string]interface{}{}
  285. for _, label := range c.cfg.Labels {
  286. key, val, _ := strings.Cut(label, "=")
  287. if !strings.HasPrefix(key, netlabel.DriverPrefix+"."+ntype) {
  288. continue
  289. }
  290. cfg[key] = val
  291. }
  292. // Merge in the existing config for this driver.
  293. for k, v := range c.cfg.DriverConfig(ntype) {
  294. cfg[k] = v
  295. }
  296. if c.cfg.Scope.IsValid() {
  297. // FIXME: every driver instance constructs a new DataStore
  298. // instance against the same database. Yikes!
  299. cfg[netlabel.LocalKVClient] = discoverapi.DatastoreConfigData{
  300. Scope: scope.Local,
  301. Provider: c.cfg.Scope.Client.Provider,
  302. Address: c.cfg.Scope.Client.Address,
  303. Config: c.cfg.Scope.Client.Config,
  304. }
  305. }
  306. return cfg
  307. }
  308. // ID returns the controller's unique identity.
  309. func (c *Controller) ID() string {
  310. return c.id
  311. }
  312. // BuiltinDrivers returns the list of builtin network drivers.
  313. func (c *Controller) BuiltinDrivers() []string {
  314. drivers := []string{}
  315. c.drvRegistry.WalkDrivers(func(name string, driver driverapi.Driver, capability driverapi.Capability) bool {
  316. if driver.IsBuiltIn() {
  317. drivers = append(drivers, name)
  318. }
  319. return false
  320. })
  321. return drivers
  322. }
  323. // BuiltinIPAMDrivers returns the list of builtin ipam drivers.
  324. func (c *Controller) BuiltinIPAMDrivers() []string {
  325. drivers := []string{}
  326. c.ipamRegistry.WalkIPAMs(func(name string, driver ipamapi.Ipam, cap *ipamapi.Capability) bool {
  327. if driver.IsBuiltIn() {
  328. drivers = append(drivers, name)
  329. }
  330. return false
  331. })
  332. return drivers
  333. }
  334. func (c *Controller) processNodeDiscovery(nodes []net.IP, add bool) {
  335. c.drvRegistry.WalkDrivers(func(name string, driver driverapi.Driver, capability driverapi.Capability) bool {
  336. if d, ok := driver.(discoverapi.Discover); ok {
  337. c.pushNodeDiscovery(d, capability, nodes, add)
  338. }
  339. return false
  340. })
  341. }
  342. func (c *Controller) pushNodeDiscovery(d discoverapi.Discover, cap driverapi.Capability, nodes []net.IP, add bool) {
  343. var self net.IP
  344. // try swarm-mode config
  345. if agent := c.getAgent(); agent != nil {
  346. self = net.ParseIP(agent.advertiseAddr)
  347. }
  348. if d == nil || cap.ConnectivityScope != scope.Global || nodes == nil {
  349. return
  350. }
  351. for _, node := range nodes {
  352. nodeData := discoverapi.NodeDiscoveryData{Address: node.String(), Self: node.Equal(self)}
  353. var err error
  354. if add {
  355. err = d.DiscoverNew(discoverapi.NodeDiscovery, nodeData)
  356. } else {
  357. err = d.DiscoverDelete(discoverapi.NodeDiscovery, nodeData)
  358. }
  359. if err != nil {
  360. log.G(context.TODO()).Debugf("discovery notification error: %v", err)
  361. }
  362. }
  363. }
  364. // Config returns the bootup configuration for the controller.
  365. func (c *Controller) Config() config.Config {
  366. c.mu.Lock()
  367. defer c.mu.Unlock()
  368. if c.cfg == nil {
  369. return config.Config{}
  370. }
  371. return *c.cfg
  372. }
  373. func (c *Controller) isManager() bool {
  374. c.mu.Lock()
  375. defer c.mu.Unlock()
  376. if c.cfg == nil || c.cfg.ClusterProvider == nil {
  377. return false
  378. }
  379. return c.cfg.ClusterProvider.IsManager()
  380. }
  381. func (c *Controller) isAgent() bool {
  382. c.mu.Lock()
  383. defer c.mu.Unlock()
  384. if c.cfg == nil || c.cfg.ClusterProvider == nil {
  385. return false
  386. }
  387. return c.cfg.ClusterProvider.IsAgent()
  388. }
  389. func (c *Controller) isDistributedControl() bool {
  390. return !c.isManager() && !c.isAgent()
  391. }
  392. func (c *Controller) GetPluginGetter() plugingetter.PluginGetter {
  393. return c.cfg.PluginGetter
  394. }
  395. func (c *Controller) RegisterDriver(networkType string, driver driverapi.Driver, capability driverapi.Capability) error {
  396. if d, ok := driver.(discoverapi.Discover); ok {
  397. c.agentDriverNotify(d)
  398. }
  399. return nil
  400. }
  401. // XXX This should be made driver agnostic. See comment below.
  402. const overlayDSROptionString = "dsr"
  403. // NewNetwork creates a new network of the specified network type. The options
  404. // are network specific and modeled in a generic way.
  405. func (c *Controller) NewNetwork(networkType, name string, id string, options ...NetworkOption) (*Network, error) {
  406. var (
  407. caps driverapi.Capability
  408. err error
  409. t *Network
  410. skipCfgEpCount bool
  411. )
  412. if id != "" {
  413. c.networkLocker.Lock(id)
  414. defer c.networkLocker.Unlock(id) //nolint:errcheck
  415. if _, err = c.NetworkByID(id); err == nil {
  416. return nil, NetworkNameError(id)
  417. }
  418. }
  419. if strings.TrimSpace(name) == "" {
  420. return nil, ErrInvalidName(name)
  421. }
  422. if id == "" {
  423. id = stringid.GenerateRandomID()
  424. }
  425. defaultIpam := defaultIpamForNetworkType(networkType)
  426. // Construct the network object
  427. nw := &Network{
  428. name: name,
  429. networkType: networkType,
  430. generic: map[string]interface{}{netlabel.GenericData: make(map[string]string)},
  431. ipamType: defaultIpam,
  432. id: id,
  433. created: time.Now(),
  434. ctrlr: c,
  435. persist: true,
  436. drvOnce: &sync.Once{},
  437. loadBalancerMode: loadBalancerModeDefault,
  438. }
  439. nw.processOptions(options...)
  440. if err = nw.validateConfiguration(); err != nil {
  441. return nil, err
  442. }
  443. // Reset network types, force local scope and skip allocation and
  444. // plumbing for configuration networks. Reset of the config-only
  445. // network drivers is needed so that this special network is not
  446. // usable by old engine versions.
  447. if nw.configOnly {
  448. nw.scope = scope.Local
  449. nw.networkType = "null"
  450. goto addToStore
  451. }
  452. _, caps, err = nw.resolveDriver(nw.networkType, true)
  453. if err != nil {
  454. return nil, err
  455. }
  456. if nw.scope == scope.Local && caps.DataScope == scope.Global {
  457. return nil, types.ForbiddenErrorf("cannot downgrade network scope for %s networks", networkType)
  458. }
  459. if nw.ingress && caps.DataScope != scope.Global {
  460. return nil, types.ForbiddenErrorf("Ingress network can only be global scope network")
  461. }
  462. // At this point the network scope is still unknown if not set by user
  463. if (caps.DataScope == scope.Global || nw.scope == scope.Swarm) &&
  464. !c.isDistributedControl() && !nw.dynamic {
  465. if c.isManager() {
  466. // For non-distributed controlled environment, globalscoped non-dynamic networks are redirected to Manager
  467. return nil, ManagerRedirectError(name)
  468. }
  469. return nil, types.ForbiddenErrorf("Cannot create a multi-host network from a worker node. Please create the network from a manager node.")
  470. }
  471. if nw.scope == scope.Swarm && c.isDistributedControl() {
  472. return nil, types.ForbiddenErrorf("cannot create a swarm scoped network when swarm is not active")
  473. }
  474. // Make sure we have a driver available for this network type
  475. // before we allocate anything.
  476. if _, err := nw.driver(true); err != nil {
  477. return nil, err
  478. }
  479. // From this point on, we need the network specific configuration,
  480. // which may come from a configuration-only network
  481. if nw.configFrom != "" {
  482. t, err = c.getConfigNetwork(nw.configFrom)
  483. if err != nil {
  484. return nil, types.NotFoundErrorf("configuration network %q does not exist", nw.configFrom)
  485. }
  486. if err = t.applyConfigurationTo(nw); err != nil {
  487. return nil, types.InternalErrorf("Failed to apply configuration: %v", err)
  488. }
  489. nw.generic[netlabel.Internal] = nw.internal
  490. defer func() {
  491. if err == nil && !skipCfgEpCount {
  492. if err := t.getEpCnt().IncEndpointCnt(); err != nil {
  493. log.G(context.TODO()).Warnf("Failed to update reference count for configuration network %q on creation of network %q: %v",
  494. t.Name(), nw.Name(), err)
  495. }
  496. }
  497. }()
  498. }
  499. err = nw.ipamAllocate()
  500. if err != nil {
  501. return nil, err
  502. }
  503. defer func() {
  504. if err != nil {
  505. nw.ipamRelease()
  506. }
  507. }()
  508. err = c.addNetwork(nw)
  509. if err != nil {
  510. if _, ok := err.(types.MaskableError); ok { //nolint:gosimple
  511. // This error can be ignored and set this boolean
  512. // value to skip a refcount increment for configOnly networks
  513. skipCfgEpCount = true
  514. } else {
  515. return nil, err
  516. }
  517. }
  518. defer func() {
  519. if err != nil {
  520. if e := nw.deleteNetwork(); e != nil {
  521. log.G(context.TODO()).Warnf("couldn't roll back driver network on network %s creation failure: %v", nw.name, err)
  522. }
  523. }
  524. }()
  525. // XXX If the driver type is "overlay" check the options for DSR
  526. // being set. If so, set the network's load balancing mode to DSR.
  527. // This should really be done in a network option, but due to
  528. // time pressure to get this in without adding changes to moby,
  529. // swarm and CLI, it is being implemented as a driver-specific
  530. // option. Unfortunately, drivers can't influence the core
  531. // "libnetwork.Network" data type. Hence we need this hack code
  532. // to implement in this manner.
  533. if gval, ok := nw.generic[netlabel.GenericData]; ok && nw.networkType == "overlay" {
  534. optMap := gval.(map[string]string)
  535. if _, ok := optMap[overlayDSROptionString]; ok {
  536. nw.loadBalancerMode = loadBalancerModeDSR
  537. }
  538. }
  539. addToStore:
  540. // First store the endpoint count, then the network. To avoid to
  541. // end up with a datastore containing a network and not an epCnt,
  542. // in case of an ungraceful shutdown during this function call.
  543. epCnt := &endpointCnt{n: nw}
  544. if err = c.updateToStore(epCnt); err != nil {
  545. return nil, err
  546. }
  547. defer func() {
  548. if err != nil {
  549. if e := c.deleteFromStore(epCnt); e != nil {
  550. log.G(context.TODO()).Warnf("could not rollback from store, epCnt %v on failure (%v): %v", epCnt, err, e)
  551. }
  552. }
  553. }()
  554. nw.epCnt = epCnt
  555. if err = c.updateToStore(nw); err != nil {
  556. return nil, err
  557. }
  558. defer func() {
  559. if err != nil {
  560. if e := c.deleteFromStore(nw); e != nil {
  561. log.G(context.TODO()).Warnf("could not rollback from store, network %v on failure (%v): %v", nw, err, e)
  562. }
  563. }
  564. }()
  565. if nw.configOnly {
  566. return nw, nil
  567. }
  568. joinCluster(nw)
  569. defer func() {
  570. if err != nil {
  571. nw.cancelDriverWatches()
  572. if e := nw.leaveCluster(); e != nil {
  573. log.G(context.TODO()).Warnf("Failed to leave agent cluster on network %s on failure (%v): %v", nw.name, err, e)
  574. }
  575. }
  576. }()
  577. if nw.hasLoadBalancerEndpoint() {
  578. if err = nw.createLoadBalancerSandbox(); err != nil {
  579. return nil, err
  580. }
  581. }
  582. if !c.isDistributedControl() {
  583. c.mu.Lock()
  584. arrangeIngressFilterRule()
  585. c.mu.Unlock()
  586. }
  587. // Sets up the DOCKER-USER chain for each iptables version (IPv4, IPv6)
  588. // that's enabled in the controller's configuration.
  589. for _, ipVersion := range c.enabledIptablesVersions() {
  590. if err := setupUserChain(ipVersion); err != nil {
  591. log.G(context.TODO()).WithError(err).Warnf("Controller.NewNetwork %s:", name)
  592. }
  593. }
  594. return nw, nil
  595. }
  596. var joinCluster NetworkWalker = func(nw *Network) bool {
  597. if nw.configOnly {
  598. return false
  599. }
  600. if err := nw.joinCluster(); err != nil {
  601. log.G(context.TODO()).Errorf("Failed to join network %s (%s) into agent cluster: %v", nw.Name(), nw.ID(), err)
  602. }
  603. nw.addDriverWatches()
  604. return false
  605. }
  606. func (c *Controller) reservePools() {
  607. networks, err := c.getNetworks()
  608. if err != nil {
  609. log.G(context.TODO()).Warnf("Could not retrieve networks from local store during ipam allocation for existing networks: %v", err)
  610. return
  611. }
  612. for _, n := range networks {
  613. if n.configOnly {
  614. continue
  615. }
  616. if !doReplayPoolReserve(n) {
  617. continue
  618. }
  619. // Construct pseudo configs for the auto IP case
  620. autoIPv4 := (len(n.ipamV4Config) == 0 || (len(n.ipamV4Config) == 1 && n.ipamV4Config[0].PreferredPool == "")) && len(n.ipamV4Info) > 0
  621. autoIPv6 := (len(n.ipamV6Config) == 0 || (len(n.ipamV6Config) == 1 && n.ipamV6Config[0].PreferredPool == "")) && len(n.ipamV6Info) > 0
  622. if autoIPv4 {
  623. n.ipamV4Config = []*IpamConf{{PreferredPool: n.ipamV4Info[0].Pool.String()}}
  624. }
  625. if n.enableIPv6 && autoIPv6 {
  626. n.ipamV6Config = []*IpamConf{{PreferredPool: n.ipamV6Info[0].Pool.String()}}
  627. }
  628. // Account current network gateways
  629. for i, cfg := range n.ipamV4Config {
  630. if cfg.Gateway == "" && n.ipamV4Info[i].Gateway != nil {
  631. cfg.Gateway = n.ipamV4Info[i].Gateway.IP.String()
  632. }
  633. }
  634. if n.enableIPv6 {
  635. for i, cfg := range n.ipamV6Config {
  636. if cfg.Gateway == "" && n.ipamV6Info[i].Gateway != nil {
  637. cfg.Gateway = n.ipamV6Info[i].Gateway.IP.String()
  638. }
  639. }
  640. }
  641. // Reserve pools
  642. if err := n.ipamAllocate(); err != nil {
  643. log.G(context.TODO()).Warnf("Failed to allocate ipam pool(s) for network %q (%s): %v", n.Name(), n.ID(), err)
  644. }
  645. // Reserve existing endpoints' addresses
  646. ipam, _, err := n.getController().getIPAMDriver(n.ipamType)
  647. if err != nil {
  648. log.G(context.TODO()).Warnf("Failed to retrieve ipam driver for network %q (%s) during address reservation", n.Name(), n.ID())
  649. continue
  650. }
  651. epl, err := n.getEndpointsFromStore()
  652. if err != nil {
  653. log.G(context.TODO()).Warnf("Failed to retrieve list of current endpoints on network %q (%s)", n.Name(), n.ID())
  654. continue
  655. }
  656. for _, ep := range epl {
  657. if ep.Iface() == nil {
  658. log.G(context.TODO()).Warnf("endpoint interface is empty for %q (%s)", ep.Name(), ep.ID())
  659. continue
  660. }
  661. if err := ep.assignAddress(ipam, true, ep.Iface().AddressIPv6() != nil); err != nil {
  662. log.G(context.TODO()).Warnf("Failed to reserve current address for endpoint %q (%s) on network %q (%s)",
  663. ep.Name(), ep.ID(), n.Name(), n.ID())
  664. }
  665. }
  666. }
  667. }
  668. func doReplayPoolReserve(n *Network) bool {
  669. _, caps, err := n.getController().getIPAMDriver(n.ipamType)
  670. if err != nil {
  671. log.G(context.TODO()).Warnf("Failed to retrieve ipam driver for network %q (%s): %v", n.Name(), n.ID(), err)
  672. return false
  673. }
  674. return caps.RequiresRequestReplay
  675. }
  676. func (c *Controller) addNetwork(n *Network) error {
  677. d, err := n.driver(true)
  678. if err != nil {
  679. return err
  680. }
  681. // Create the network
  682. if err := d.CreateNetwork(n.id, n.generic, n, n.getIPData(4), n.getIPData(6)); err != nil {
  683. return err
  684. }
  685. n.startResolver()
  686. return nil
  687. }
  688. // Networks returns the list of Network(s) managed by this controller.
  689. func (c *Controller) Networks() []*Network {
  690. var list []*Network
  691. for _, n := range c.getNetworksFromStore() {
  692. if n.inDelete {
  693. continue
  694. }
  695. list = append(list, n)
  696. }
  697. return list
  698. }
  699. // WalkNetworks uses the provided function to walk the Network(s) managed by this controller.
  700. func (c *Controller) WalkNetworks(walker NetworkWalker) {
  701. for _, n := range c.Networks() {
  702. if walker(n) {
  703. return
  704. }
  705. }
  706. }
  707. // NetworkByName returns the Network which has the passed name.
  708. // If not found, the error [ErrNoSuchNetwork] is returned.
  709. func (c *Controller) NetworkByName(name string) (*Network, error) {
  710. if name == "" {
  711. return nil, ErrInvalidName(name)
  712. }
  713. var n *Network
  714. c.WalkNetworks(func(current *Network) bool {
  715. if current.Name() == name {
  716. n = current
  717. return true
  718. }
  719. return false
  720. })
  721. if n == nil {
  722. return nil, ErrNoSuchNetwork(name)
  723. }
  724. return n, nil
  725. }
  726. // NetworkByID returns the Network which has the passed id.
  727. // If not found, the error [ErrNoSuchNetwork] is returned.
  728. func (c *Controller) NetworkByID(id string) (*Network, error) {
  729. if id == "" {
  730. return nil, ErrInvalidID(id)
  731. }
  732. n, err := c.getNetworkFromStore(id)
  733. if err != nil {
  734. return nil, ErrNoSuchNetwork(id)
  735. }
  736. return n, nil
  737. }
  738. // NewSandbox creates a new sandbox for containerID.
  739. func (c *Controller) NewSandbox(containerID string, options ...SandboxOption) (*Sandbox, error) {
  740. if containerID == "" {
  741. return nil, types.InvalidParameterErrorf("invalid container ID")
  742. }
  743. var sb *Sandbox
  744. c.mu.Lock()
  745. for _, s := range c.sandboxes {
  746. if s.containerID == containerID {
  747. // If not a stub, then we already have a complete sandbox.
  748. if !s.isStub {
  749. sbID := s.ID()
  750. c.mu.Unlock()
  751. return nil, types.ForbiddenErrorf("container %s is already present in sandbox %s", containerID, sbID)
  752. }
  753. // We already have a stub sandbox from the
  754. // store. Make use of it so that we don't lose
  755. // the endpoints from store but reset the
  756. // isStub flag.
  757. sb = s
  758. sb.isStub = false
  759. break
  760. }
  761. }
  762. c.mu.Unlock()
  763. sandboxID := stringid.GenerateRandomID()
  764. if runtime.GOOS == "windows" {
  765. sandboxID = containerID
  766. }
  767. // Create sandbox and process options first. Key generation depends on an option
  768. if sb == nil {
  769. sb = &Sandbox{
  770. id: sandboxID,
  771. containerID: containerID,
  772. endpoints: []*Endpoint{},
  773. epPriority: map[string]int{},
  774. populatedEndpoints: map[string]struct{}{},
  775. config: containerConfig{},
  776. controller: c,
  777. extDNS: []extDNSEntry{},
  778. }
  779. }
  780. sb.processOptions(options...)
  781. c.mu.Lock()
  782. if sb.ingress && c.ingressSandbox != nil {
  783. c.mu.Unlock()
  784. return nil, types.ForbiddenErrorf("ingress sandbox already present")
  785. }
  786. if sb.ingress {
  787. c.ingressSandbox = sb
  788. sb.config.hostsPath = filepath.Join(c.cfg.DataDir, "/network/files/hosts")
  789. sb.config.resolvConfPath = filepath.Join(c.cfg.DataDir, "/network/files/resolv.conf")
  790. sb.id = "ingress_sbox"
  791. } else if sb.loadBalancerNID != "" {
  792. sb.id = "lb_" + sb.loadBalancerNID
  793. }
  794. c.mu.Unlock()
  795. var err error
  796. defer func() {
  797. if err != nil {
  798. c.mu.Lock()
  799. if sb.ingress {
  800. c.ingressSandbox = nil
  801. }
  802. c.mu.Unlock()
  803. }
  804. }()
  805. if err = sb.setupResolutionFiles(); err != nil {
  806. return nil, err
  807. }
  808. if sb.config.useDefaultSandBox {
  809. c.sboxOnce.Do(func() {
  810. c.defOsSbox, err = osl.NewSandbox(sb.Key(), false, false)
  811. })
  812. if err != nil {
  813. c.sboxOnce = sync.Once{}
  814. return nil, fmt.Errorf("failed to create default sandbox: %v", err)
  815. }
  816. sb.osSbox = c.defOsSbox
  817. }
  818. if sb.osSbox == nil && !sb.config.useExternalKey {
  819. if sb.osSbox, err = osl.NewSandbox(sb.Key(), !sb.config.useDefaultSandBox, false); err != nil {
  820. return nil, fmt.Errorf("failed to create new osl sandbox: %v", err)
  821. }
  822. }
  823. if sb.osSbox != nil {
  824. // Apply operating specific knobs on the load balancer sandbox
  825. err := sb.osSbox.InvokeFunc(func() {
  826. sb.osSbox.ApplyOSTweaks(sb.oslTypes)
  827. })
  828. if err != nil {
  829. log.G(context.TODO()).Errorf("Failed to apply performance tuning sysctls to the sandbox: %v", err)
  830. }
  831. // Keep this just so performance is not changed
  832. sb.osSbox.ApplyOSTweaks(sb.oslTypes)
  833. }
  834. c.mu.Lock()
  835. c.sandboxes[sb.id] = sb
  836. c.mu.Unlock()
  837. defer func() {
  838. if err != nil {
  839. c.mu.Lock()
  840. delete(c.sandboxes, sb.id)
  841. c.mu.Unlock()
  842. }
  843. }()
  844. err = sb.storeUpdate()
  845. if err != nil {
  846. return nil, fmt.Errorf("failed to update the store state of sandbox: %v", err)
  847. }
  848. return sb, nil
  849. }
  850. // GetSandbox returns the Sandbox which has the passed id.
  851. //
  852. // It returns an [ErrInvalidID] when passing an invalid ID, or an
  853. // [types.NotFoundError] if no Sandbox was found for the container.
  854. func (c *Controller) GetSandbox(containerID string) (*Sandbox, error) {
  855. if containerID == "" {
  856. return nil, ErrInvalidID("id is empty")
  857. }
  858. c.mu.Lock()
  859. defer c.mu.Unlock()
  860. if runtime.GOOS == "windows" {
  861. // fast-path for Windows, which uses the container ID as sandbox ID.
  862. if sb := c.sandboxes[containerID]; sb != nil && !sb.isStub {
  863. return sb, nil
  864. }
  865. } else {
  866. for _, sb := range c.sandboxes {
  867. if sb.containerID == containerID && !sb.isStub {
  868. return sb, nil
  869. }
  870. }
  871. }
  872. return nil, types.NotFoundErrorf("network sandbox for container %s not found", containerID)
  873. }
  874. // SandboxByID returns the Sandbox which has the passed id.
  875. // If not found, a [types.NotFoundError] is returned.
  876. func (c *Controller) SandboxByID(id string) (*Sandbox, error) {
  877. if id == "" {
  878. return nil, ErrInvalidID(id)
  879. }
  880. c.mu.Lock()
  881. s, ok := c.sandboxes[id]
  882. c.mu.Unlock()
  883. if !ok {
  884. return nil, types.NotFoundErrorf("sandbox %s not found", id)
  885. }
  886. return s, nil
  887. }
  888. // SandboxDestroy destroys a sandbox given a container ID.
  889. func (c *Controller) SandboxDestroy(id string) error {
  890. var sb *Sandbox
  891. c.mu.Lock()
  892. for _, s := range c.sandboxes {
  893. if s.containerID == id {
  894. sb = s
  895. break
  896. }
  897. }
  898. c.mu.Unlock()
  899. // It is not an error if sandbox is not available
  900. if sb == nil {
  901. return nil
  902. }
  903. return sb.Delete()
  904. }
  905. func (c *Controller) loadDriver(networkType string) error {
  906. var err error
  907. if pg := c.GetPluginGetter(); pg != nil {
  908. _, err = pg.Get(networkType, driverapi.NetworkPluginEndpointType, plugingetter.Lookup)
  909. } else {
  910. _, err = plugins.Get(networkType, driverapi.NetworkPluginEndpointType)
  911. }
  912. if err != nil {
  913. if errors.Cause(err) == plugins.ErrNotFound {
  914. return types.NotFoundErrorf(err.Error())
  915. }
  916. return err
  917. }
  918. return nil
  919. }
  920. func (c *Controller) loadIPAMDriver(name string) error {
  921. var err error
  922. if pg := c.GetPluginGetter(); pg != nil {
  923. _, err = pg.Get(name, ipamapi.PluginEndpointType, plugingetter.Lookup)
  924. } else {
  925. _, err = plugins.Get(name, ipamapi.PluginEndpointType)
  926. }
  927. if err != nil {
  928. if errors.Cause(err) == plugins.ErrNotFound {
  929. return types.NotFoundErrorf(err.Error())
  930. }
  931. return err
  932. }
  933. return nil
  934. }
  935. func (c *Controller) getIPAMDriver(name string) (ipamapi.Ipam, *ipamapi.Capability, error) {
  936. id, cap := c.ipamRegistry.IPAM(name)
  937. if id == nil {
  938. // Might be a plugin name. Try loading it
  939. if err := c.loadIPAMDriver(name); err != nil {
  940. return nil, nil, err
  941. }
  942. // Now that we resolved the plugin, try again looking up the registry
  943. id, cap = c.ipamRegistry.IPAM(name)
  944. if id == nil {
  945. return nil, nil, types.InvalidParameterErrorf("invalid ipam driver: %q", name)
  946. }
  947. }
  948. return id, cap, nil
  949. }
  950. // Stop stops the network controller.
  951. func (c *Controller) Stop() {
  952. c.closeStores()
  953. c.stopExternalKeyListener()
  954. osl.GC()
  955. }
  956. // StartDiagnostic starts the network diagnostic server listening on port.
  957. func (c *Controller) StartDiagnostic(port int) {
  958. c.mu.Lock()
  959. if !c.DiagnosticServer.IsDiagnosticEnabled() {
  960. c.DiagnosticServer.EnableDiagnostic("127.0.0.1", port)
  961. }
  962. c.mu.Unlock()
  963. }
  964. // StopDiagnostic stops the network diagnostic server.
  965. func (c *Controller) StopDiagnostic() {
  966. c.mu.Lock()
  967. if c.DiagnosticServer.IsDiagnosticEnabled() {
  968. c.DiagnosticServer.DisableDiagnostic()
  969. }
  970. c.mu.Unlock()
  971. }
  972. // IsDiagnosticEnabled returns true if the diagnostic server is running.
  973. func (c *Controller) IsDiagnosticEnabled() bool {
  974. c.mu.Lock()
  975. defer c.mu.Unlock()
  976. return c.DiagnosticServer.IsDiagnosticEnabled()
  977. }