controller.go 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362
  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("docker.io"))
  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. "fmt"
  41. "net"
  42. "path/filepath"
  43. "runtime"
  44. "strings"
  45. "sync"
  46. "time"
  47. "github.com/docker/docker/libnetwork/cluster"
  48. "github.com/docker/docker/libnetwork/config"
  49. "github.com/docker/docker/libnetwork/datastore"
  50. "github.com/docker/docker/libnetwork/diagnostic"
  51. "github.com/docker/docker/libnetwork/discoverapi"
  52. "github.com/docker/docker/libnetwork/driverapi"
  53. "github.com/docker/docker/libnetwork/drvregistry"
  54. "github.com/docker/docker/libnetwork/hostdiscovery"
  55. "github.com/docker/docker/libnetwork/ipamapi"
  56. "github.com/docker/docker/libnetwork/netlabel"
  57. "github.com/docker/docker/libnetwork/options"
  58. "github.com/docker/docker/libnetwork/osl"
  59. "github.com/docker/docker/libnetwork/types"
  60. "github.com/docker/docker/pkg/discovery"
  61. "github.com/docker/docker/pkg/plugingetter"
  62. "github.com/docker/docker/pkg/plugins"
  63. "github.com/docker/docker/pkg/stringid"
  64. "github.com/moby/locker"
  65. "github.com/pkg/errors"
  66. "github.com/sirupsen/logrus"
  67. )
  68. // NetworkController provides the interface for controller instance which manages
  69. // networks.
  70. type NetworkController interface {
  71. // ID provides a unique identity for the controller
  72. ID() string
  73. // BuiltinDrivers returns list of builtin drivers
  74. BuiltinDrivers() []string
  75. // BuiltinIPAMDrivers returns list of builtin ipam drivers
  76. BuiltinIPAMDrivers() []string
  77. // Config method returns the bootup configuration for the controller
  78. Config() config.Config
  79. // Create a new network. The options parameter carries network specific options.
  80. NewNetwork(networkType, name string, id string, options ...NetworkOption) (Network, error)
  81. // Networks returns the list of Network(s) managed by this controller.
  82. Networks() []Network
  83. // WalkNetworks uses the provided function to walk the Network(s) managed by this controller.
  84. WalkNetworks(walker NetworkWalker)
  85. // NetworkByName returns the Network which has the passed name. If not found, the error ErrNoSuchNetwork is returned.
  86. NetworkByName(name string) (Network, error)
  87. // NetworkByID returns the Network which has the passed id. If not found, the error ErrNoSuchNetwork is returned.
  88. NetworkByID(id string) (Network, error)
  89. // NewSandbox creates a new network sandbox for the passed container id
  90. NewSandbox(containerID string, options ...SandboxOption) (Sandbox, error)
  91. // Sandboxes returns the list of Sandbox(s) managed by this controller.
  92. Sandboxes() []Sandbox
  93. // WalkSandboxes uses the provided function to walk the Sandbox(s) managed by this controller.
  94. WalkSandboxes(walker SandboxWalker)
  95. // SandboxByID returns the Sandbox which has the passed id. If not found, a types.NotFoundError is returned.
  96. SandboxByID(id string) (Sandbox, error)
  97. // SandboxDestroy destroys a sandbox given a container ID
  98. SandboxDestroy(id string) error
  99. // Stop network controller
  100. Stop()
  101. // ReloadConfiguration updates the controller configuration
  102. ReloadConfiguration(cfgOptions ...config.Option) error
  103. // SetClusterProvider sets cluster provider
  104. SetClusterProvider(provider cluster.Provider)
  105. // Wait for agent initialization complete in libnetwork controller
  106. AgentInitWait()
  107. // Wait for agent to stop if running
  108. AgentStopWait()
  109. // SetKeys configures the encryption key for gossip and overlay data path
  110. SetKeys(keys []*types.EncryptionKey) error
  111. // StartDiagnostic start the network diagnostic mode
  112. StartDiagnostic(port int)
  113. // StopDiagnostic start the network diagnostic mode
  114. StopDiagnostic()
  115. // IsDiagnosticEnabled returns true if the diagnostic is enabled
  116. IsDiagnosticEnabled() bool
  117. }
  118. // NetworkWalker is a client provided function which will be used to walk the Networks.
  119. // When the function returns true, the walk will stop.
  120. type NetworkWalker func(nw Network) bool
  121. // SandboxWalker is a client provided function which will be used to walk the Sandboxes.
  122. // When the function returns true, the walk will stop.
  123. type SandboxWalker func(sb Sandbox) bool
  124. type sandboxTable map[string]*sandbox
  125. type controller struct {
  126. id string
  127. drvRegistry *drvregistry.DrvRegistry
  128. sandboxes sandboxTable
  129. cfg *config.Config
  130. stores []datastore.DataStore
  131. discovery hostdiscovery.HostDiscovery
  132. extKeyListener net.Listener
  133. watchCh chan *endpoint
  134. unWatchCh chan *endpoint
  135. svcRecords map[string]svcInfo
  136. nmap map[string]*netWatch
  137. serviceBindings map[serviceKey]*service
  138. defOsSbox osl.Sandbox
  139. ingressSandbox *sandbox
  140. sboxOnce sync.Once
  141. agent *agent
  142. networkLocker *locker.Locker
  143. agentInitDone chan struct{}
  144. agentStopDone chan struct{}
  145. keys []*types.EncryptionKey
  146. DiagnosticServer *diagnostic.Server
  147. sync.Mutex
  148. }
  149. type initializer struct {
  150. fn drvregistry.InitFunc
  151. ntype string
  152. }
  153. // New creates a new instance of network controller.
  154. func New(cfgOptions ...config.Option) (NetworkController, error) {
  155. c := &controller{
  156. id: stringid.GenerateRandomID(),
  157. cfg: config.ParseConfigOptions(cfgOptions...),
  158. sandboxes: sandboxTable{},
  159. svcRecords: make(map[string]svcInfo),
  160. serviceBindings: make(map[serviceKey]*service),
  161. agentInitDone: make(chan struct{}),
  162. networkLocker: locker.New(),
  163. DiagnosticServer: diagnostic.New(),
  164. }
  165. c.DiagnosticServer.Init()
  166. if err := c.initStores(); err != nil {
  167. return nil, err
  168. }
  169. drvRegistry, err := drvregistry.New(c.getStore(datastore.LocalScope), c.getStore(datastore.GlobalScope), c.RegisterDriver, nil, c.cfg.PluginGetter)
  170. if err != nil {
  171. return nil, err
  172. }
  173. for _, i := range getInitializers(c.cfg.Daemon.Experimental) {
  174. var dcfg map[string]interface{}
  175. // External plugins don't need config passed through daemon. They can
  176. // bootstrap themselves
  177. if i.ntype != "remote" {
  178. dcfg = c.makeDriverConfig(i.ntype)
  179. }
  180. if err := drvRegistry.AddDriver(i.ntype, i.fn, dcfg); err != nil {
  181. return nil, err
  182. }
  183. }
  184. if err = initIPAMDrivers(drvRegistry, nil, c.getStore(datastore.GlobalScope), c.cfg.Daemon.DefaultAddressPool); err != nil {
  185. return nil, err
  186. }
  187. c.drvRegistry = drvRegistry
  188. if c.cfg != nil && c.cfg.Cluster.Watcher != nil {
  189. if err := c.initDiscovery(c.cfg.Cluster.Watcher); err != nil {
  190. // Failing to initialize discovery is a bad situation to be in.
  191. // But it cannot fail creating the Controller
  192. logrus.Errorf("Failed to Initialize Discovery : %v", err)
  193. }
  194. }
  195. c.WalkNetworks(populateSpecial)
  196. // Reserve pools first before doing cleanup. Otherwise the
  197. // cleanups of endpoint/network and sandbox below will
  198. // generate many unnecessary warnings
  199. c.reservePools()
  200. // Cleanup resources
  201. c.sandboxCleanup(c.cfg.ActiveSandboxes)
  202. c.cleanupLocalEndpoints()
  203. c.networkCleanup()
  204. if err := c.startExternalKeyListener(); err != nil {
  205. return nil, err
  206. }
  207. setupArrangeUserFilterRule(c)
  208. return c, nil
  209. }
  210. func (c *controller) SetClusterProvider(provider cluster.Provider) {
  211. var sameProvider bool
  212. c.Lock()
  213. // Avoids to spawn multiple goroutine for the same cluster provider
  214. if c.cfg.Daemon.ClusterProvider == provider {
  215. // If the cluster provider is already set, there is already a go routine spawned
  216. // that is listening for events, so nothing to do here
  217. sameProvider = true
  218. } else {
  219. c.cfg.Daemon.ClusterProvider = provider
  220. }
  221. c.Unlock()
  222. if provider == nil || sameProvider {
  223. return
  224. }
  225. // We don't want to spawn a new go routine if the previous one did not exit yet
  226. c.AgentStopWait()
  227. go c.clusterAgentInit()
  228. }
  229. // libnetwork side of agent depends on the keys. On the first receipt of
  230. // keys setup the agent. For subsequent key set handle the key change
  231. func (c *controller) SetKeys(keys []*types.EncryptionKey) error {
  232. subsysKeys := make(map[string]int)
  233. for _, key := range keys {
  234. if key.Subsystem != subsysGossip &&
  235. key.Subsystem != subsysIPSec {
  236. return fmt.Errorf("key received for unrecognized subsystem")
  237. }
  238. subsysKeys[key.Subsystem]++
  239. }
  240. for s, count := range subsysKeys {
  241. if count != keyringSize {
  242. return fmt.Errorf("incorrect number of keys for subsystem %v", s)
  243. }
  244. }
  245. agent := c.getAgent()
  246. if agent == nil {
  247. c.Lock()
  248. c.keys = keys
  249. c.Unlock()
  250. return nil
  251. }
  252. return c.handleKeyChange(keys)
  253. }
  254. func (c *controller) getAgent() *agent {
  255. c.Lock()
  256. defer c.Unlock()
  257. return c.agent
  258. }
  259. func (c *controller) clusterAgentInit() {
  260. clusterProvider := c.cfg.Daemon.ClusterProvider
  261. var keysAvailable bool
  262. for {
  263. eventType := <-clusterProvider.ListenClusterEvents()
  264. // The events: EventSocketChange, EventNodeReady and EventNetworkKeysAvailable are not ordered
  265. // when all the condition for the agent initialization are met then proceed with it
  266. switch eventType {
  267. case cluster.EventNetworkKeysAvailable:
  268. // Validates that the keys are actually available before starting the initialization
  269. // This will handle old spurious messages left on the channel
  270. c.Lock()
  271. keysAvailable = c.keys != nil
  272. c.Unlock()
  273. fallthrough
  274. case cluster.EventSocketChange, cluster.EventNodeReady:
  275. if keysAvailable && !c.isDistributedControl() {
  276. c.agentOperationStart()
  277. if err := c.agentSetup(clusterProvider); err != nil {
  278. c.agentStopComplete()
  279. } else {
  280. c.agentInitComplete()
  281. }
  282. }
  283. case cluster.EventNodeLeave:
  284. c.agentOperationStart()
  285. c.Lock()
  286. c.keys = nil
  287. c.Unlock()
  288. // We are leaving the cluster. Make sure we
  289. // close the gossip so that we stop all
  290. // incoming gossip updates before cleaning up
  291. // any remaining service bindings. But before
  292. // deleting the networks since the networks
  293. // should still be present when cleaning up
  294. // service bindings
  295. c.agentClose()
  296. c.cleanupServiceDiscovery("")
  297. c.cleanupServiceBindings("")
  298. c.agentStopComplete()
  299. return
  300. }
  301. }
  302. }
  303. // AgentInitWait waits for agent initialization to be completed in the controller.
  304. func (c *controller) AgentInitWait() {
  305. c.Lock()
  306. agentInitDone := c.agentInitDone
  307. c.Unlock()
  308. if agentInitDone != nil {
  309. <-agentInitDone
  310. }
  311. }
  312. // AgentStopWait waits for the Agent stop to be completed in the controller
  313. func (c *controller) AgentStopWait() {
  314. c.Lock()
  315. agentStopDone := c.agentStopDone
  316. c.Unlock()
  317. if agentStopDone != nil {
  318. <-agentStopDone
  319. }
  320. }
  321. // agentOperationStart marks the start of an Agent Init or Agent Stop
  322. func (c *controller) agentOperationStart() {
  323. c.Lock()
  324. if c.agentInitDone == nil {
  325. c.agentInitDone = make(chan struct{})
  326. }
  327. if c.agentStopDone == nil {
  328. c.agentStopDone = make(chan struct{})
  329. }
  330. c.Unlock()
  331. }
  332. // agentInitComplete notifies the successful completion of the Agent initialization
  333. func (c *controller) agentInitComplete() {
  334. c.Lock()
  335. if c.agentInitDone != nil {
  336. close(c.agentInitDone)
  337. c.agentInitDone = nil
  338. }
  339. c.Unlock()
  340. }
  341. // agentStopComplete notifies the successful completion of the Agent stop
  342. func (c *controller) agentStopComplete() {
  343. c.Lock()
  344. if c.agentStopDone != nil {
  345. close(c.agentStopDone)
  346. c.agentStopDone = nil
  347. }
  348. c.Unlock()
  349. }
  350. func (c *controller) makeDriverConfig(ntype string) map[string]interface{} {
  351. if c.cfg == nil {
  352. return nil
  353. }
  354. config := make(map[string]interface{})
  355. for _, label := range c.cfg.Daemon.Labels {
  356. if !strings.HasPrefix(netlabel.Key(label), netlabel.DriverPrefix+"."+ntype) {
  357. continue
  358. }
  359. config[netlabel.Key(label)] = netlabel.Value(label)
  360. }
  361. drvCfg, ok := c.cfg.Daemon.DriverCfg[ntype]
  362. if ok {
  363. for k, v := range drvCfg.(map[string]interface{}) {
  364. config[k] = v
  365. }
  366. }
  367. for k, v := range c.cfg.Scopes {
  368. if !v.IsValid() {
  369. continue
  370. }
  371. config[netlabel.MakeKVClient(k)] = discoverapi.DatastoreConfigData{
  372. Scope: k,
  373. Provider: v.Client.Provider,
  374. Address: v.Client.Address,
  375. Config: v.Client.Config,
  376. }
  377. }
  378. return config
  379. }
  380. var procReloadConfig = make(chan (bool), 1)
  381. func (c *controller) ReloadConfiguration(cfgOptions ...config.Option) error {
  382. procReloadConfig <- true
  383. defer func() { <-procReloadConfig }()
  384. // For now we accept the configuration reload only as a mean to provide a global store config after boot.
  385. // Refuse the configuration if it alters an existing datastore client configuration.
  386. update := false
  387. cfg := config.ParseConfigOptions(cfgOptions...)
  388. for s := range c.cfg.Scopes {
  389. if _, ok := cfg.Scopes[s]; !ok {
  390. return types.ForbiddenErrorf("cannot accept new configuration because it removes an existing datastore client")
  391. }
  392. }
  393. for s, nSCfg := range cfg.Scopes {
  394. if eSCfg, ok := c.cfg.Scopes[s]; ok {
  395. if eSCfg.Client.Provider != nSCfg.Client.Provider ||
  396. eSCfg.Client.Address != nSCfg.Client.Address {
  397. return types.ForbiddenErrorf("cannot accept new configuration because it modifies an existing datastore client")
  398. }
  399. } else {
  400. if err := c.initScopedStore(s, nSCfg); err != nil {
  401. return err
  402. }
  403. update = true
  404. }
  405. }
  406. if !update {
  407. return nil
  408. }
  409. c.Lock()
  410. c.cfg = cfg
  411. c.Unlock()
  412. var dsConfig *discoverapi.DatastoreConfigData
  413. for scope, sCfg := range cfg.Scopes {
  414. if scope == datastore.LocalScope || !sCfg.IsValid() {
  415. continue
  416. }
  417. dsConfig = &discoverapi.DatastoreConfigData{
  418. Scope: scope,
  419. Provider: sCfg.Client.Provider,
  420. Address: sCfg.Client.Address,
  421. Config: sCfg.Client.Config,
  422. }
  423. break
  424. }
  425. if dsConfig == nil {
  426. return nil
  427. }
  428. c.drvRegistry.WalkIPAMs(func(name string, driver ipamapi.Ipam, cap *ipamapi.Capability) bool {
  429. err := driver.DiscoverNew(discoverapi.DatastoreConfig, *dsConfig)
  430. if err != nil {
  431. logrus.Errorf("Failed to set datastore in driver %s: %v", name, err)
  432. }
  433. return false
  434. })
  435. c.drvRegistry.WalkDrivers(func(name string, driver driverapi.Driver, capability driverapi.Capability) bool {
  436. err := driver.DiscoverNew(discoverapi.DatastoreConfig, *dsConfig)
  437. if err != nil {
  438. logrus.Errorf("Failed to set datastore in driver %s: %v", name, err)
  439. }
  440. return false
  441. })
  442. if c.discovery == nil && c.cfg.Cluster.Watcher != nil {
  443. if err := c.initDiscovery(c.cfg.Cluster.Watcher); err != nil {
  444. logrus.Errorf("Failed to Initialize Discovery after configuration update: %v", err)
  445. }
  446. }
  447. return nil
  448. }
  449. func (c *controller) ID() string {
  450. return c.id
  451. }
  452. func (c *controller) BuiltinDrivers() []string {
  453. drivers := []string{}
  454. c.drvRegistry.WalkDrivers(func(name string, driver driverapi.Driver, capability driverapi.Capability) bool {
  455. if driver.IsBuiltIn() {
  456. drivers = append(drivers, name)
  457. }
  458. return false
  459. })
  460. return drivers
  461. }
  462. func (c *controller) BuiltinIPAMDrivers() []string {
  463. drivers := []string{}
  464. c.drvRegistry.WalkIPAMs(func(name string, driver ipamapi.Ipam, cap *ipamapi.Capability) bool {
  465. if driver.IsBuiltIn() {
  466. drivers = append(drivers, name)
  467. }
  468. return false
  469. })
  470. return drivers
  471. }
  472. func (c *controller) clusterHostID() string {
  473. c.Lock()
  474. defer c.Unlock()
  475. if c.cfg == nil || c.cfg.Cluster.Address == "" {
  476. return ""
  477. }
  478. addr := strings.Split(c.cfg.Cluster.Address, ":")
  479. return addr[0]
  480. }
  481. func (c *controller) initDiscovery(watcher discovery.Watcher) error {
  482. if c.cfg == nil {
  483. return fmt.Errorf("discovery initialization requires a valid configuration")
  484. }
  485. c.discovery = hostdiscovery.NewHostDiscovery(watcher)
  486. return c.discovery.Watch(c.activeCallback, c.hostJoinCallback, c.hostLeaveCallback)
  487. }
  488. func (c *controller) activeCallback() {
  489. ds := c.getStore(datastore.GlobalScope)
  490. if ds != nil && !ds.Active() {
  491. ds.RestartWatch()
  492. }
  493. }
  494. func (c *controller) hostJoinCallback(nodes []net.IP) {
  495. c.processNodeDiscovery(nodes, true)
  496. }
  497. func (c *controller) hostLeaveCallback(nodes []net.IP) {
  498. c.processNodeDiscovery(nodes, false)
  499. }
  500. func (c *controller) processNodeDiscovery(nodes []net.IP, add bool) {
  501. c.drvRegistry.WalkDrivers(func(name string, driver driverapi.Driver, capability driverapi.Capability) bool {
  502. c.pushNodeDiscovery(driver, capability, nodes, add)
  503. return false
  504. })
  505. }
  506. func (c *controller) pushNodeDiscovery(d driverapi.Driver, cap driverapi.Capability, nodes []net.IP, add bool) {
  507. var self net.IP
  508. if c.cfg != nil {
  509. addr := strings.Split(c.cfg.Cluster.Address, ":")
  510. self = net.ParseIP(addr[0])
  511. // if external kvstore is not configured, try swarm-mode config
  512. if self == nil {
  513. if agent := c.getAgent(); agent != nil {
  514. self = net.ParseIP(agent.advertiseAddr)
  515. }
  516. }
  517. }
  518. if d == nil || cap.ConnectivityScope != datastore.GlobalScope || nodes == nil {
  519. return
  520. }
  521. for _, node := range nodes {
  522. nodeData := discoverapi.NodeDiscoveryData{Address: node.String(), Self: node.Equal(self)}
  523. var err error
  524. if add {
  525. err = d.DiscoverNew(discoverapi.NodeDiscovery, nodeData)
  526. } else {
  527. err = d.DiscoverDelete(discoverapi.NodeDiscovery, nodeData)
  528. }
  529. if err != nil {
  530. logrus.Debugf("discovery notification error: %v", err)
  531. }
  532. }
  533. }
  534. func (c *controller) Config() config.Config {
  535. c.Lock()
  536. defer c.Unlock()
  537. if c.cfg == nil {
  538. return config.Config{}
  539. }
  540. return *c.cfg
  541. }
  542. func (c *controller) isManager() bool {
  543. c.Lock()
  544. defer c.Unlock()
  545. if c.cfg == nil || c.cfg.Daemon.ClusterProvider == nil {
  546. return false
  547. }
  548. return c.cfg.Daemon.ClusterProvider.IsManager()
  549. }
  550. func (c *controller) isAgent() bool {
  551. c.Lock()
  552. defer c.Unlock()
  553. if c.cfg == nil || c.cfg.Daemon.ClusterProvider == nil {
  554. return false
  555. }
  556. return c.cfg.Daemon.ClusterProvider.IsAgent()
  557. }
  558. func (c *controller) isDistributedControl() bool {
  559. return !c.isManager() && !c.isAgent()
  560. }
  561. func (c *controller) GetPluginGetter() plugingetter.PluginGetter {
  562. return c.drvRegistry.GetPluginGetter()
  563. }
  564. func (c *controller) RegisterDriver(networkType string, driver driverapi.Driver, capability driverapi.Capability) error {
  565. c.Lock()
  566. hd := c.discovery
  567. c.Unlock()
  568. if hd != nil {
  569. c.pushNodeDiscovery(driver, capability, hd.Fetch(), true)
  570. }
  571. c.agentDriverNotify(driver)
  572. return nil
  573. }
  574. // XXX This should be made driver agnostic. See comment below.
  575. const overlayDSROptionString = "dsr"
  576. // NewNetwork creates a new network of the specified network type. The options
  577. // are network specific and modeled in a generic way.
  578. func (c *controller) NewNetwork(networkType, name string, id string, options ...NetworkOption) (Network, error) {
  579. var (
  580. cap *driverapi.Capability
  581. err error
  582. t *network
  583. skipCfgEpCount bool
  584. )
  585. if id != "" {
  586. c.networkLocker.Lock(id)
  587. defer c.networkLocker.Unlock(id) // nolint:errcheck
  588. if _, err = c.NetworkByID(id); err == nil {
  589. return nil, NetworkNameError(id)
  590. }
  591. }
  592. if !config.IsValidName(name) {
  593. return nil, ErrInvalidName(name)
  594. }
  595. if id == "" {
  596. id = stringid.GenerateRandomID()
  597. }
  598. defaultIpam := defaultIpamForNetworkType(networkType)
  599. // Construct the network object
  600. network := &network{
  601. name: name,
  602. networkType: networkType,
  603. generic: map[string]interface{}{netlabel.GenericData: make(map[string]string)},
  604. ipamType: defaultIpam,
  605. id: id,
  606. created: time.Now(),
  607. ctrlr: c,
  608. persist: true,
  609. drvOnce: &sync.Once{},
  610. loadBalancerMode: loadBalancerModeDefault,
  611. }
  612. network.processOptions(options...)
  613. if err = network.validateConfiguration(); err != nil {
  614. return nil, err
  615. }
  616. // Reset network types, force local scope and skip allocation and
  617. // plumbing for configuration networks. Reset of the config-only
  618. // network drivers is needed so that this special network is not
  619. // usable by old engine versions.
  620. if network.configOnly {
  621. network.scope = datastore.LocalScope
  622. network.networkType = "null"
  623. goto addToStore
  624. }
  625. _, cap, err = network.resolveDriver(network.networkType, true)
  626. if err != nil {
  627. return nil, err
  628. }
  629. if network.scope == datastore.LocalScope && cap.DataScope == datastore.GlobalScope {
  630. return nil, types.ForbiddenErrorf("cannot downgrade network scope for %s networks", networkType)
  631. }
  632. if network.ingress && cap.DataScope != datastore.GlobalScope {
  633. return nil, types.ForbiddenErrorf("Ingress network can only be global scope network")
  634. }
  635. // At this point the network scope is still unknown if not set by user
  636. if (cap.DataScope == datastore.GlobalScope || network.scope == datastore.SwarmScope) &&
  637. !c.isDistributedControl() && !network.dynamic {
  638. if c.isManager() {
  639. // For non-distributed controlled environment, globalscoped non-dynamic networks are redirected to Manager
  640. return nil, ManagerRedirectError(name)
  641. }
  642. return nil, types.ForbiddenErrorf("Cannot create a multi-host network from a worker node. Please create the network from a manager node.")
  643. }
  644. if network.scope == datastore.SwarmScope && c.isDistributedControl() {
  645. return nil, types.ForbiddenErrorf("cannot create a swarm scoped network when swarm is not active")
  646. }
  647. // Make sure we have a driver available for this network type
  648. // before we allocate anything.
  649. if _, err := network.driver(true); err != nil {
  650. return nil, err
  651. }
  652. // From this point on, we need the network specific configuration,
  653. // which may come from a configuration-only network
  654. if network.configFrom != "" {
  655. t, err = c.getConfigNetwork(network.configFrom)
  656. if err != nil {
  657. return nil, types.NotFoundErrorf("configuration network %q does not exist", network.configFrom)
  658. }
  659. if err = t.applyConfigurationTo(network); err != nil {
  660. return nil, types.InternalErrorf("Failed to apply configuration: %v", err)
  661. }
  662. network.generic[netlabel.Internal] = network.internal
  663. defer func() {
  664. if err == nil && !skipCfgEpCount {
  665. if err := t.getEpCnt().IncEndpointCnt(); err != nil {
  666. logrus.Warnf("Failed to update reference count for configuration network %q on creation of network %q: %v",
  667. t.Name(), network.Name(), err)
  668. }
  669. }
  670. }()
  671. }
  672. err = network.ipamAllocate()
  673. if err != nil {
  674. return nil, err
  675. }
  676. defer func() {
  677. if err != nil {
  678. network.ipamRelease()
  679. }
  680. }()
  681. err = c.addNetwork(network)
  682. if err != nil {
  683. if _, ok := err.(types.MaskableError); ok { // nolint:gosimple
  684. // This error can be ignored and set this boolean
  685. // value to skip a refcount increment for configOnly networks
  686. skipCfgEpCount = true
  687. } else {
  688. return nil, err
  689. }
  690. }
  691. defer func() {
  692. if err != nil {
  693. if e := network.deleteNetwork(); e != nil {
  694. logrus.Warnf("couldn't roll back driver network on network %s creation failure: %v", network.name, err)
  695. }
  696. }
  697. }()
  698. // XXX If the driver type is "overlay" check the options for DSR
  699. // being set. If so, set the network's load balancing mode to DSR.
  700. // This should really be done in a network option, but due to
  701. // time pressure to get this in without adding changes to moby,
  702. // swarm and CLI, it is being implemented as a driver-specific
  703. // option. Unfortunately, drivers can't influence the core
  704. // "libnetwork.network" data type. Hence we need this hack code
  705. // to implement in this manner.
  706. if gval, ok := network.generic[netlabel.GenericData]; ok && network.networkType == "overlay" {
  707. optMap := gval.(map[string]string)
  708. if _, ok := optMap[overlayDSROptionString]; ok {
  709. network.loadBalancerMode = loadBalancerModeDSR
  710. }
  711. }
  712. addToStore:
  713. // First store the endpoint count, then the network. To avoid to
  714. // end up with a datastore containing a network and not an epCnt,
  715. // in case of an ungraceful shutdown during this function call.
  716. epCnt := &endpointCnt{n: network}
  717. if err = c.updateToStore(epCnt); err != nil {
  718. return nil, err
  719. }
  720. defer func() {
  721. if err != nil {
  722. if e := c.deleteFromStore(epCnt); e != nil {
  723. logrus.Warnf("could not rollback from store, epCnt %v on failure (%v): %v", epCnt, err, e)
  724. }
  725. }
  726. }()
  727. network.epCnt = epCnt
  728. if err = c.updateToStore(network); err != nil {
  729. return nil, err
  730. }
  731. defer func() {
  732. if err != nil {
  733. if e := c.deleteFromStore(network); e != nil {
  734. logrus.Warnf("could not rollback from store, network %v on failure (%v): %v", network, err, e)
  735. }
  736. }
  737. }()
  738. if network.configOnly {
  739. return network, nil
  740. }
  741. joinCluster(network)
  742. defer func() {
  743. if err != nil {
  744. network.cancelDriverWatches()
  745. if e := network.leaveCluster(); e != nil {
  746. logrus.Warnf("Failed to leave agent cluster on network %s on failure (%v): %v", network.name, err, e)
  747. }
  748. }
  749. }()
  750. if network.hasLoadBalancerEndpoint() {
  751. if err = network.createLoadBalancerSandbox(); err != nil {
  752. return nil, err
  753. }
  754. }
  755. if !c.isDistributedControl() {
  756. c.Lock()
  757. arrangeIngressFilterRule()
  758. c.Unlock()
  759. }
  760. arrangeUserFilterRule()
  761. return network, nil
  762. }
  763. var joinCluster NetworkWalker = func(nw Network) bool {
  764. n := nw.(*network)
  765. if n.configOnly {
  766. return false
  767. }
  768. if err := n.joinCluster(); err != nil {
  769. logrus.Errorf("Failed to join network %s (%s) into agent cluster: %v", n.Name(), n.ID(), err)
  770. }
  771. n.addDriverWatches()
  772. return false
  773. }
  774. func (c *controller) reservePools() {
  775. networks, err := c.getNetworksForScope(datastore.LocalScope)
  776. if err != nil {
  777. logrus.Warnf("Could not retrieve networks from local store during ipam allocation for existing networks: %v", err)
  778. return
  779. }
  780. for _, n := range networks {
  781. if n.configOnly {
  782. continue
  783. }
  784. if !doReplayPoolReserve(n) {
  785. continue
  786. }
  787. // Construct pseudo configs for the auto IP case
  788. autoIPv4 := (len(n.ipamV4Config) == 0 || (len(n.ipamV4Config) == 1 && n.ipamV4Config[0].PreferredPool == "")) && len(n.ipamV4Info) > 0
  789. autoIPv6 := (len(n.ipamV6Config) == 0 || (len(n.ipamV6Config) == 1 && n.ipamV6Config[0].PreferredPool == "")) && len(n.ipamV6Info) > 0
  790. if autoIPv4 {
  791. n.ipamV4Config = []*IpamConf{{PreferredPool: n.ipamV4Info[0].Pool.String()}}
  792. }
  793. if n.enableIPv6 && autoIPv6 {
  794. n.ipamV6Config = []*IpamConf{{PreferredPool: n.ipamV6Info[0].Pool.String()}}
  795. }
  796. // Account current network gateways
  797. for i, c := range n.ipamV4Config {
  798. if c.Gateway == "" && n.ipamV4Info[i].Gateway != nil {
  799. c.Gateway = n.ipamV4Info[i].Gateway.IP.String()
  800. }
  801. }
  802. if n.enableIPv6 {
  803. for i, c := range n.ipamV6Config {
  804. if c.Gateway == "" && n.ipamV6Info[i].Gateway != nil {
  805. c.Gateway = n.ipamV6Info[i].Gateway.IP.String()
  806. }
  807. }
  808. }
  809. // Reserve pools
  810. if err := n.ipamAllocate(); err != nil {
  811. logrus.Warnf("Failed to allocate ipam pool(s) for network %q (%s): %v", n.Name(), n.ID(), err)
  812. }
  813. // Reserve existing endpoints' addresses
  814. ipam, _, err := n.getController().getIPAMDriver(n.ipamType)
  815. if err != nil {
  816. logrus.Warnf("Failed to retrieve ipam driver for network %q (%s) during address reservation", n.Name(), n.ID())
  817. continue
  818. }
  819. epl, err := n.getEndpointsFromStore()
  820. if err != nil {
  821. logrus.Warnf("Failed to retrieve list of current endpoints on network %q (%s)", n.Name(), n.ID())
  822. continue
  823. }
  824. for _, ep := range epl {
  825. if ep.Iface() == nil {
  826. logrus.Warnf("endpoint interface is empty for %q (%s)", ep.Name(), ep.ID())
  827. continue
  828. }
  829. if err := ep.assignAddress(ipam, true, ep.Iface().AddressIPv6() != nil); err != nil {
  830. logrus.Warnf("Failed to reserve current address for endpoint %q (%s) on network %q (%s)",
  831. ep.Name(), ep.ID(), n.Name(), n.ID())
  832. }
  833. }
  834. }
  835. }
  836. func doReplayPoolReserve(n *network) bool {
  837. _, caps, err := n.getController().getIPAMDriver(n.ipamType)
  838. if err != nil {
  839. logrus.Warnf("Failed to retrieve ipam driver for network %q (%s): %v", n.Name(), n.ID(), err)
  840. return false
  841. }
  842. return caps.RequiresRequestReplay
  843. }
  844. func (c *controller) addNetwork(n *network) error {
  845. d, err := n.driver(true)
  846. if err != nil {
  847. return err
  848. }
  849. // Create the network
  850. if err := d.CreateNetwork(n.id, n.generic, n, n.getIPData(4), n.getIPData(6)); err != nil {
  851. return err
  852. }
  853. n.startResolver()
  854. return nil
  855. }
  856. func (c *controller) Networks() []Network {
  857. var list []Network
  858. for _, n := range c.getNetworksFromStore() {
  859. if n.inDelete {
  860. continue
  861. }
  862. list = append(list, n)
  863. }
  864. return list
  865. }
  866. func (c *controller) WalkNetworks(walker NetworkWalker) {
  867. for _, n := range c.Networks() {
  868. if walker(n) {
  869. return
  870. }
  871. }
  872. }
  873. func (c *controller) NetworkByName(name string) (Network, error) {
  874. if name == "" {
  875. return nil, ErrInvalidName(name)
  876. }
  877. var n Network
  878. s := func(current Network) bool {
  879. if current.Name() == name {
  880. n = current
  881. return true
  882. }
  883. return false
  884. }
  885. c.WalkNetworks(s)
  886. if n == nil {
  887. return nil, ErrNoSuchNetwork(name)
  888. }
  889. return n, nil
  890. }
  891. func (c *controller) NetworkByID(id string) (Network, error) {
  892. if id == "" {
  893. return nil, ErrInvalidID(id)
  894. }
  895. n, err := c.getNetworkFromStore(id)
  896. if err != nil {
  897. return nil, ErrNoSuchNetwork(id)
  898. }
  899. return n, nil
  900. }
  901. // NewSandbox creates a new sandbox for the passed container id
  902. func (c *controller) NewSandbox(containerID string, options ...SandboxOption) (Sandbox, error) {
  903. if containerID == "" {
  904. return nil, types.BadRequestErrorf("invalid container ID")
  905. }
  906. var sb *sandbox
  907. c.Lock()
  908. for _, s := range c.sandboxes {
  909. if s.containerID == containerID {
  910. // If not a stub, then we already have a complete sandbox.
  911. if !s.isStub {
  912. sbID := s.ID()
  913. c.Unlock()
  914. return nil, types.ForbiddenErrorf("container %s is already present in sandbox %s", containerID, sbID)
  915. }
  916. // We already have a stub sandbox from the
  917. // store. Make use of it so that we don't lose
  918. // the endpoints from store but reset the
  919. // isStub flag.
  920. sb = s
  921. sb.isStub = false
  922. break
  923. }
  924. }
  925. c.Unlock()
  926. sandboxID := stringid.GenerateRandomID()
  927. if runtime.GOOS == "windows" {
  928. sandboxID = containerID
  929. }
  930. // Create sandbox and process options first. Key generation depends on an option
  931. if sb == nil {
  932. sb = &sandbox{
  933. id: sandboxID,
  934. containerID: containerID,
  935. endpoints: []*endpoint{},
  936. epPriority: map[string]int{},
  937. populatedEndpoints: map[string]struct{}{},
  938. config: containerConfig{},
  939. controller: c,
  940. extDNS: []extDNSEntry{},
  941. }
  942. }
  943. sb.processOptions(options...)
  944. c.Lock()
  945. if sb.ingress && c.ingressSandbox != nil {
  946. c.Unlock()
  947. return nil, types.ForbiddenErrorf("ingress sandbox already present")
  948. }
  949. if sb.ingress {
  950. c.ingressSandbox = sb
  951. sb.config.hostsPath = filepath.Join(c.cfg.Daemon.DataDir, "/network/files/hosts")
  952. sb.config.resolvConfPath = filepath.Join(c.cfg.Daemon.DataDir, "/network/files/resolv.conf")
  953. sb.id = "ingress_sbox"
  954. } else if sb.loadBalancerNID != "" {
  955. sb.id = "lb_" + sb.loadBalancerNID
  956. }
  957. c.Unlock()
  958. var err error
  959. defer func() {
  960. if err != nil {
  961. c.Lock()
  962. if sb.ingress {
  963. c.ingressSandbox = nil
  964. }
  965. c.Unlock()
  966. }
  967. }()
  968. if err = sb.setupResolutionFiles(); err != nil {
  969. return nil, err
  970. }
  971. if sb.config.useDefaultSandBox {
  972. c.sboxOnce.Do(func() {
  973. c.defOsSbox, err = osl.NewSandbox(sb.Key(), false, false)
  974. })
  975. if err != nil {
  976. c.sboxOnce = sync.Once{}
  977. return nil, fmt.Errorf("failed to create default sandbox: %v", err)
  978. }
  979. sb.osSbox = c.defOsSbox
  980. }
  981. if sb.osSbox == nil && !sb.config.useExternalKey {
  982. if sb.osSbox, err = osl.NewSandbox(sb.Key(), !sb.config.useDefaultSandBox, false); err != nil {
  983. return nil, fmt.Errorf("failed to create new osl sandbox: %v", err)
  984. }
  985. }
  986. if sb.osSbox != nil {
  987. // Apply operating specific knobs on the load balancer sandbox
  988. sb.osSbox.ApplyOSTweaks(sb.oslTypes)
  989. }
  990. c.Lock()
  991. c.sandboxes[sb.id] = sb
  992. c.Unlock()
  993. defer func() {
  994. if err != nil {
  995. c.Lock()
  996. delete(c.sandboxes, sb.id)
  997. c.Unlock()
  998. }
  999. }()
  1000. err = sb.storeUpdate()
  1001. if err != nil {
  1002. return nil, fmt.Errorf("failed to update the store state of sandbox: %v", err)
  1003. }
  1004. return sb, nil
  1005. }
  1006. func (c *controller) Sandboxes() []Sandbox {
  1007. c.Lock()
  1008. defer c.Unlock()
  1009. list := make([]Sandbox, 0, len(c.sandboxes))
  1010. for _, s := range c.sandboxes {
  1011. // Hide stub sandboxes from libnetwork users
  1012. if s.isStub {
  1013. continue
  1014. }
  1015. list = append(list, s)
  1016. }
  1017. return list
  1018. }
  1019. func (c *controller) WalkSandboxes(walker SandboxWalker) {
  1020. for _, sb := range c.Sandboxes() {
  1021. if walker(sb) {
  1022. return
  1023. }
  1024. }
  1025. }
  1026. func (c *controller) SandboxByID(id string) (Sandbox, error) {
  1027. if id == "" {
  1028. return nil, ErrInvalidID(id)
  1029. }
  1030. c.Lock()
  1031. s, ok := c.sandboxes[id]
  1032. c.Unlock()
  1033. if !ok {
  1034. return nil, types.NotFoundErrorf("sandbox %s not found", id)
  1035. }
  1036. return s, nil
  1037. }
  1038. // SandboxDestroy destroys a sandbox given a container ID
  1039. func (c *controller) SandboxDestroy(id string) error {
  1040. var sb *sandbox
  1041. c.Lock()
  1042. for _, s := range c.sandboxes {
  1043. if s.containerID == id {
  1044. sb = s
  1045. break
  1046. }
  1047. }
  1048. c.Unlock()
  1049. // It is not an error if sandbox is not available
  1050. if sb == nil {
  1051. return nil
  1052. }
  1053. return sb.Delete()
  1054. }
  1055. // SandboxContainerWalker returns a Sandbox Walker function which looks for an existing Sandbox with the passed containerID
  1056. func SandboxContainerWalker(out *Sandbox, containerID string) SandboxWalker {
  1057. return func(sb Sandbox) bool {
  1058. if sb.ContainerID() == containerID {
  1059. *out = sb
  1060. return true
  1061. }
  1062. return false
  1063. }
  1064. }
  1065. // SandboxKeyWalker returns a Sandbox Walker function which looks for an existing Sandbox with the passed key
  1066. func SandboxKeyWalker(out *Sandbox, key string) SandboxWalker {
  1067. return func(sb Sandbox) bool {
  1068. if sb.Key() == key {
  1069. *out = sb
  1070. return true
  1071. }
  1072. return false
  1073. }
  1074. }
  1075. func (c *controller) loadDriver(networkType string) error {
  1076. var err error
  1077. if pg := c.GetPluginGetter(); pg != nil {
  1078. _, err = pg.Get(networkType, driverapi.NetworkPluginEndpointType, plugingetter.Lookup)
  1079. } else {
  1080. _, err = plugins.Get(networkType, driverapi.NetworkPluginEndpointType)
  1081. }
  1082. if err != nil {
  1083. if errors.Cause(err) == plugins.ErrNotFound {
  1084. return types.NotFoundErrorf(err.Error())
  1085. }
  1086. return err
  1087. }
  1088. return nil
  1089. }
  1090. func (c *controller) loadIPAMDriver(name string) error {
  1091. var err error
  1092. if pg := c.GetPluginGetter(); pg != nil {
  1093. _, err = pg.Get(name, ipamapi.PluginEndpointType, plugingetter.Lookup)
  1094. } else {
  1095. _, err = plugins.Get(name, ipamapi.PluginEndpointType)
  1096. }
  1097. if err != nil {
  1098. if errors.Cause(err) == plugins.ErrNotFound {
  1099. return types.NotFoundErrorf(err.Error())
  1100. }
  1101. return err
  1102. }
  1103. return nil
  1104. }
  1105. func (c *controller) getIPAMDriver(name string) (ipamapi.Ipam, *ipamapi.Capability, error) {
  1106. id, cap := c.drvRegistry.IPAM(name)
  1107. if id == nil {
  1108. // Might be a plugin name. Try loading it
  1109. if err := c.loadIPAMDriver(name); err != nil {
  1110. return nil, nil, err
  1111. }
  1112. // Now that we resolved the plugin, try again looking up the registry
  1113. id, cap = c.drvRegistry.IPAM(name)
  1114. if id == nil {
  1115. return nil, nil, types.BadRequestErrorf("invalid ipam driver: %q", name)
  1116. }
  1117. }
  1118. return id, cap, nil
  1119. }
  1120. func (c *controller) Stop() {
  1121. c.closeStores()
  1122. c.stopExternalKeyListener()
  1123. osl.GC()
  1124. }
  1125. // StartDiagnostic start the network dias mode
  1126. func (c *controller) StartDiagnostic(port int) {
  1127. c.Lock()
  1128. if !c.DiagnosticServer.IsDiagnosticEnabled() {
  1129. c.DiagnosticServer.EnableDiagnostic("127.0.0.1", port)
  1130. }
  1131. c.Unlock()
  1132. }
  1133. // StopDiagnostic start the network dias mode
  1134. func (c *controller) StopDiagnostic() {
  1135. c.Lock()
  1136. if c.DiagnosticServer.IsDiagnosticEnabled() {
  1137. c.DiagnosticServer.DisableDiagnostic()
  1138. }
  1139. c.Unlock()
  1140. }
  1141. // IsDiagnosticEnabled returns true if the dias is enabled
  1142. func (c *controller) IsDiagnosticEnabled() bool {
  1143. c.Lock()
  1144. defer c.Unlock()
  1145. return c.DiagnosticServer.IsDiagnosticEnabled()
  1146. }
  1147. func (c *controller) iptablesEnabled() bool {
  1148. c.Lock()
  1149. defer c.Unlock()
  1150. if c.cfg == nil {
  1151. return false
  1152. }
  1153. // parse map cfg["bridge"]["generic"]["EnableIPTable"]
  1154. cfgBridge, ok := c.cfg.Daemon.DriverCfg["bridge"].(map[string]interface{})
  1155. if !ok {
  1156. return false
  1157. }
  1158. cfgGeneric, ok := cfgBridge[netlabel.GenericData].(options.Generic)
  1159. if !ok {
  1160. return false
  1161. }
  1162. enabled, ok := cfgGeneric["EnableIPTables"].(bool)
  1163. if !ok {
  1164. // unless user explicitly stated, assume iptable is enabled
  1165. enabled = true
  1166. }
  1167. return enabled
  1168. }