controller.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701
  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. "container/heap"
  41. "fmt"
  42. "net"
  43. "strings"
  44. "sync"
  45. log "github.com/Sirupsen/logrus"
  46. "github.com/docker/docker/pkg/discovery"
  47. "github.com/docker/docker/pkg/plugins"
  48. "github.com/docker/docker/pkg/stringid"
  49. "github.com/docker/libnetwork/config"
  50. "github.com/docker/libnetwork/datastore"
  51. "github.com/docker/libnetwork/driverapi"
  52. "github.com/docker/libnetwork/hostdiscovery"
  53. "github.com/docker/libnetwork/ipamapi"
  54. "github.com/docker/libnetwork/netlabel"
  55. "github.com/docker/libnetwork/osl"
  56. "github.com/docker/libnetwork/types"
  57. )
  58. // NetworkController provides the interface for controller instance which manages
  59. // networks.
  60. type NetworkController interface {
  61. // ID provides an unique identity for the controller
  62. ID() string
  63. // Config method returns the bootup configuration for the controller
  64. Config() config.Config
  65. // Create a new network. The options parameter carries network specific options.
  66. NewNetwork(networkType, name string, options ...NetworkOption) (Network, error)
  67. // Networks returns the list of Network(s) managed by this controller.
  68. Networks() []Network
  69. // WalkNetworks uses the provided function to walk the Network(s) managed by this controller.
  70. WalkNetworks(walker NetworkWalker)
  71. // NetworkByName returns the Network which has the passed name. If not found, the error ErrNoSuchNetwork is returned.
  72. NetworkByName(name string) (Network, error)
  73. // NetworkByID returns the Network which has the passed id. If not found, the error ErrNoSuchNetwork is returned.
  74. NetworkByID(id string) (Network, error)
  75. // NewSandbox cretes a new network sandbox for the passed container id
  76. NewSandbox(containerID string, options ...SandboxOption) (Sandbox, error)
  77. // Sandboxes returns the list of Sandbox(s) managed by this controller.
  78. Sandboxes() []Sandbox
  79. // WlakSandboxes uses the provided function to walk the Sandbox(s) managed by this controller.
  80. WalkSandboxes(walker SandboxWalker)
  81. // SandboxByID returns the Sandbox which has the passed id. If not found, a types.NotFoundError is returned.
  82. SandboxByID(id string) (Sandbox, error)
  83. // SandboxDestroy destroys a sandbox given a container ID
  84. SandboxDestroy(id string) error
  85. // Stop network controller
  86. Stop()
  87. }
  88. // NetworkWalker is a client provided function which will be used to walk the Networks.
  89. // When the function returns true, the walk will stop.
  90. type NetworkWalker func(nw Network) bool
  91. // SandboxWalker is a client provided function which will be used to walk the Sandboxes.
  92. // When the function returns true, the walk will stop.
  93. type SandboxWalker func(sb Sandbox) bool
  94. type driverData struct {
  95. driver driverapi.Driver
  96. capability driverapi.Capability
  97. }
  98. type ipamData struct {
  99. driver ipamapi.Ipam
  100. // default address spaces are provided by ipam driver at registration time
  101. defaultLocalAddressSpace, defaultGlobalAddressSpace string
  102. }
  103. type driverTable map[string]*driverData
  104. //type networkTable map[string]*network
  105. //type endpointTable map[string]*endpoint
  106. type ipamTable map[string]*ipamData
  107. type sandboxTable map[string]*sandbox
  108. type controller struct {
  109. id string
  110. //networks networkTable
  111. drivers driverTable
  112. ipamDrivers ipamTable
  113. sandboxes sandboxTable
  114. cfg *config.Config
  115. stores []datastore.DataStore
  116. discovery hostdiscovery.HostDiscovery
  117. extKeyListener net.Listener
  118. watchCh chan *endpoint
  119. unWatchCh chan *endpoint
  120. svcDb map[string]svcMap
  121. nmap map[string]*netWatch
  122. defOsSbox osl.Sandbox
  123. sboxOnce sync.Once
  124. sync.Mutex
  125. }
  126. // New creates a new instance of network controller.
  127. func New(cfgOptions ...config.Option) (NetworkController, error) {
  128. var cfg *config.Config
  129. cfg = &config.Config{
  130. Daemon: config.DaemonCfg{
  131. DriverCfg: make(map[string]interface{}),
  132. },
  133. Scopes: make(map[string]*datastore.ScopeCfg),
  134. }
  135. if len(cfgOptions) > 0 {
  136. cfg.ProcessOptions(cfgOptions...)
  137. }
  138. cfg.LoadDefaultScopes(cfg.Daemon.DataDir)
  139. c := &controller{
  140. id: stringid.GenerateRandomID(),
  141. cfg: cfg,
  142. sandboxes: sandboxTable{},
  143. drivers: driverTable{},
  144. ipamDrivers: ipamTable{},
  145. svcDb: make(map[string]svcMap),
  146. }
  147. if err := c.initStores(); err != nil {
  148. return nil, err
  149. }
  150. if cfg != nil && cfg.Cluster.Watcher != nil {
  151. if err := c.initDiscovery(cfg.Cluster.Watcher); err != nil {
  152. // Failing to initalize discovery is a bad situation to be in.
  153. // But it cannot fail creating the Controller
  154. log.Errorf("Failed to Initialize Discovery : %v", err)
  155. }
  156. }
  157. if err := initDrivers(c); err != nil {
  158. return nil, err
  159. }
  160. if err := initIpams(c, c.getStore(datastore.LocalScope),
  161. c.getStore(datastore.GlobalScope)); err != nil {
  162. return nil, err
  163. }
  164. c.sandboxCleanup()
  165. c.cleanupLocalEndpoints()
  166. if err := c.startExternalKeyListener(); err != nil {
  167. return nil, err
  168. }
  169. return c, nil
  170. }
  171. func (c *controller) ID() string {
  172. return c.id
  173. }
  174. func (c *controller) validateHostDiscoveryConfig() bool {
  175. if c.cfg == nil || c.cfg.Cluster.Discovery == "" || c.cfg.Cluster.Address == "" {
  176. return false
  177. }
  178. return true
  179. }
  180. func (c *controller) initDiscovery(watcher discovery.Watcher) error {
  181. if c.cfg == nil {
  182. return fmt.Errorf("discovery initialization requires a valid configuration")
  183. }
  184. c.discovery = hostdiscovery.NewHostDiscovery(watcher)
  185. return c.discovery.Watch(c.activeCallback, c.hostJoinCallback, c.hostLeaveCallback)
  186. }
  187. func (c *controller) activeCallback() {
  188. ds := c.getStore(datastore.GlobalScope)
  189. if ds != nil && !ds.Active() {
  190. ds.RestartWatch()
  191. }
  192. }
  193. func (c *controller) hostJoinCallback(nodes []net.IP) {
  194. c.processNodeDiscovery(nodes, true)
  195. }
  196. func (c *controller) hostLeaveCallback(nodes []net.IP) {
  197. c.processNodeDiscovery(nodes, false)
  198. }
  199. func (c *controller) processNodeDiscovery(nodes []net.IP, add bool) {
  200. c.Lock()
  201. drivers := []*driverData{}
  202. for _, d := range c.drivers {
  203. drivers = append(drivers, d)
  204. }
  205. c.Unlock()
  206. for _, d := range drivers {
  207. c.pushNodeDiscovery(d, nodes, add)
  208. }
  209. }
  210. func (c *controller) pushNodeDiscovery(d *driverData, nodes []net.IP, add bool) {
  211. var self net.IP
  212. if c.cfg != nil {
  213. addr := strings.Split(c.cfg.Cluster.Address, ":")
  214. self = net.ParseIP(addr[0])
  215. }
  216. if d == nil || d.capability.DataScope != datastore.GlobalScope || nodes == nil {
  217. return
  218. }
  219. for _, node := range nodes {
  220. nodeData := driverapi.NodeDiscoveryData{Address: node.String(), Self: node.Equal(self)}
  221. var err error
  222. if add {
  223. err = d.driver.DiscoverNew(driverapi.NodeDiscovery, nodeData)
  224. } else {
  225. err = d.driver.DiscoverDelete(driverapi.NodeDiscovery, nodeData)
  226. }
  227. if err != nil {
  228. log.Debugf("discovery notification error : %v", err)
  229. }
  230. }
  231. }
  232. func (c *controller) Config() config.Config {
  233. c.Lock()
  234. defer c.Unlock()
  235. if c.cfg == nil {
  236. return config.Config{}
  237. }
  238. return *c.cfg
  239. }
  240. func (c *controller) RegisterDriver(networkType string, driver driverapi.Driver, capability driverapi.Capability) error {
  241. if !config.IsValidName(networkType) {
  242. return ErrInvalidName(networkType)
  243. }
  244. c.Lock()
  245. if _, ok := c.drivers[networkType]; ok {
  246. c.Unlock()
  247. return driverapi.ErrActiveRegistration(networkType)
  248. }
  249. dData := &driverData{driver, capability}
  250. c.drivers[networkType] = dData
  251. hd := c.discovery
  252. c.Unlock()
  253. if hd != nil {
  254. c.pushNodeDiscovery(dData, hd.Fetch(), true)
  255. }
  256. return nil
  257. }
  258. func (c *controller) RegisterIpamDriver(name string, driver ipamapi.Ipam) error {
  259. if !config.IsValidName(name) {
  260. return ErrInvalidName(name)
  261. }
  262. c.Lock()
  263. _, ok := c.ipamDrivers[name]
  264. c.Unlock()
  265. if ok {
  266. return driverapi.ErrActiveRegistration(name)
  267. }
  268. locAS, glbAS, err := driver.GetDefaultAddressSpaces()
  269. if err != nil {
  270. return fmt.Errorf("ipam driver %s failed to return default address spaces: %v", name, err)
  271. }
  272. c.Lock()
  273. c.ipamDrivers[name] = &ipamData{driver: driver, defaultLocalAddressSpace: locAS, defaultGlobalAddressSpace: glbAS}
  274. c.Unlock()
  275. log.Debugf("Registering ipam provider: %s", name)
  276. return nil
  277. }
  278. // NewNetwork creates a new network of the specified network type. The options
  279. // are network specific and modeled in a generic way.
  280. func (c *controller) NewNetwork(networkType, name string, options ...NetworkOption) (Network, error) {
  281. if !config.IsValidName(name) {
  282. return nil, ErrInvalidName(name)
  283. }
  284. // Construct the network object
  285. network := &network{
  286. name: name,
  287. networkType: networkType,
  288. generic: map[string]interface{}{netlabel.GenericData: make(map[string]string)},
  289. ipamType: ipamapi.DefaultIPAM,
  290. id: stringid.GenerateRandomID(),
  291. ctrlr: c,
  292. persist: true,
  293. drvOnce: &sync.Once{},
  294. }
  295. network.processOptions(options...)
  296. // Make sure we have a driver available for this network type
  297. // before we allocate anything.
  298. if _, err := network.driver(); err != nil {
  299. return nil, err
  300. }
  301. err := network.ipamAllocate()
  302. if err != nil {
  303. return nil, err
  304. }
  305. defer func() {
  306. if err != nil {
  307. network.ipamRelease()
  308. }
  309. }()
  310. if err = c.addNetwork(network); err != nil {
  311. return nil, err
  312. }
  313. defer func() {
  314. if err != nil {
  315. if e := network.deleteNetwork(); e != nil {
  316. log.Warnf("couldn't roll back driver network on network %s creation failure: %v", network.name, err)
  317. }
  318. }
  319. }()
  320. if err = c.updateToStore(network); err != nil {
  321. return nil, err
  322. }
  323. defer func() {
  324. if err != nil {
  325. if e := c.deleteFromStore(network); e != nil {
  326. log.Warnf("couldnt rollback from store, network %s on failure (%v): %v", network.name, err, e)
  327. }
  328. }
  329. }()
  330. network.epCnt = &endpointCnt{n: network}
  331. if err = c.updateToStore(network.epCnt); err != nil {
  332. return nil, err
  333. }
  334. return network, nil
  335. }
  336. func (c *controller) addNetwork(n *network) error {
  337. d, err := n.driver()
  338. if err != nil {
  339. return err
  340. }
  341. // Create the network
  342. if err := d.CreateNetwork(n.id, n.generic, n.getIPData(4), n.getIPData(6)); err != nil {
  343. return err
  344. }
  345. return nil
  346. }
  347. func (c *controller) Networks() []Network {
  348. var list []Network
  349. networks, err := c.getNetworksFromStore()
  350. if err != nil {
  351. log.Error(err)
  352. }
  353. for _, n := range networks {
  354. list = append(list, n)
  355. }
  356. return list
  357. }
  358. func (c *controller) WalkNetworks(walker NetworkWalker) {
  359. for _, n := range c.Networks() {
  360. if walker(n) {
  361. return
  362. }
  363. }
  364. }
  365. func (c *controller) NetworkByName(name string) (Network, error) {
  366. if name == "" {
  367. return nil, ErrInvalidName(name)
  368. }
  369. var n Network
  370. s := func(current Network) bool {
  371. if current.Name() == name {
  372. n = current
  373. return true
  374. }
  375. return false
  376. }
  377. c.WalkNetworks(s)
  378. if n == nil {
  379. return nil, ErrNoSuchNetwork(name)
  380. }
  381. return n, nil
  382. }
  383. func (c *controller) NetworkByID(id string) (Network, error) {
  384. if id == "" {
  385. return nil, ErrInvalidID(id)
  386. }
  387. n, err := c.getNetworkFromStore(id)
  388. if err != nil {
  389. return nil, ErrNoSuchNetwork(id)
  390. }
  391. return n, nil
  392. }
  393. // NewSandbox creates a new sandbox for the passed container id
  394. func (c *controller) NewSandbox(containerID string, options ...SandboxOption) (Sandbox, error) {
  395. var err error
  396. if containerID == "" {
  397. return nil, types.BadRequestErrorf("invalid container ID")
  398. }
  399. var sb *sandbox
  400. c.Lock()
  401. for _, s := range c.sandboxes {
  402. if s.containerID == containerID {
  403. // If not a stub, then we already have a complete sandbox.
  404. if !s.isStub {
  405. c.Unlock()
  406. return nil, types.BadRequestErrorf("container %s is already present: %v", containerID, s)
  407. }
  408. // We already have a stub sandbox from the
  409. // store. Make use of it so that we don't lose
  410. // the endpoints from store but reset the
  411. // isStub flag.
  412. sb = s
  413. sb.isStub = false
  414. break
  415. }
  416. }
  417. c.Unlock()
  418. // Create sandbox and process options first. Key generation depends on an option
  419. if sb == nil {
  420. sb = &sandbox{
  421. id: stringid.GenerateRandomID(),
  422. containerID: containerID,
  423. endpoints: epHeap{},
  424. epPriority: map[string]int{},
  425. config: containerConfig{},
  426. controller: c,
  427. }
  428. }
  429. heap.Init(&sb.endpoints)
  430. sb.processOptions(options...)
  431. if err = sb.setupResolutionFiles(); err != nil {
  432. return nil, err
  433. }
  434. if sb.config.useDefaultSandBox {
  435. c.sboxOnce.Do(func() {
  436. c.defOsSbox, err = osl.NewSandbox(sb.Key(), false)
  437. })
  438. if err != nil {
  439. c.sboxOnce = sync.Once{}
  440. return nil, fmt.Errorf("failed to create default sandbox: %v", err)
  441. }
  442. sb.osSbox = c.defOsSbox
  443. }
  444. if sb.osSbox == nil && !sb.config.useExternalKey {
  445. if sb.osSbox, err = osl.NewSandbox(sb.Key(), !sb.config.useDefaultSandBox); err != nil {
  446. return nil, fmt.Errorf("failed to create new osl sandbox: %v", err)
  447. }
  448. }
  449. c.Lock()
  450. c.sandboxes[sb.id] = sb
  451. c.Unlock()
  452. defer func() {
  453. if err != nil {
  454. c.Lock()
  455. delete(c.sandboxes, sb.id)
  456. c.Unlock()
  457. }
  458. }()
  459. err = sb.storeUpdate()
  460. if err != nil {
  461. return nil, fmt.Errorf("updating the store state of sandbox failed: %v", err)
  462. }
  463. return sb, nil
  464. }
  465. func (c *controller) Sandboxes() []Sandbox {
  466. c.Lock()
  467. defer c.Unlock()
  468. list := make([]Sandbox, 0, len(c.sandboxes))
  469. for _, s := range c.sandboxes {
  470. // Hide stub sandboxes from libnetwork users
  471. if s.isStub {
  472. continue
  473. }
  474. list = append(list, s)
  475. }
  476. return list
  477. }
  478. func (c *controller) WalkSandboxes(walker SandboxWalker) {
  479. for _, sb := range c.Sandboxes() {
  480. if walker(sb) {
  481. return
  482. }
  483. }
  484. }
  485. func (c *controller) SandboxByID(id string) (Sandbox, error) {
  486. if id == "" {
  487. return nil, ErrInvalidID(id)
  488. }
  489. c.Lock()
  490. s, ok := c.sandboxes[id]
  491. c.Unlock()
  492. if !ok {
  493. return nil, types.NotFoundErrorf("sandbox %s not found", id)
  494. }
  495. return s, nil
  496. }
  497. // SandboxDestroy destroys a sandbox given a container ID
  498. func (c *controller) SandboxDestroy(id string) error {
  499. var sb *sandbox
  500. c.Lock()
  501. for _, s := range c.sandboxes {
  502. if s.containerID == id {
  503. sb = s
  504. break
  505. }
  506. }
  507. c.Unlock()
  508. // It is not an error if sandbox is not available
  509. if sb == nil {
  510. return nil
  511. }
  512. return sb.Delete()
  513. }
  514. // SandboxContainerWalker returns a Sandbox Walker function which looks for an existing Sandbox with the passed containerID
  515. func SandboxContainerWalker(out *Sandbox, containerID string) SandboxWalker {
  516. return func(sb Sandbox) bool {
  517. if sb.ContainerID() == containerID {
  518. *out = sb
  519. return true
  520. }
  521. return false
  522. }
  523. }
  524. // SandboxKeyWalker returns a Sandbox Walker function which looks for an existing Sandbox with the passed key
  525. func SandboxKeyWalker(out *Sandbox, key string) SandboxWalker {
  526. return func(sb Sandbox) bool {
  527. if sb.Key() == key {
  528. *out = sb
  529. return true
  530. }
  531. return false
  532. }
  533. }
  534. func (c *controller) loadDriver(networkType string) (*driverData, error) {
  535. // Plugins pkg performs lazy loading of plugins that acts as remote drivers.
  536. // As per the design, this Get call will result in remote driver discovery if there is a corresponding plugin available.
  537. _, err := plugins.Get(networkType, driverapi.NetworkPluginEndpointType)
  538. if err != nil {
  539. if err == plugins.ErrNotFound {
  540. return nil, types.NotFoundErrorf(err.Error())
  541. }
  542. return nil, err
  543. }
  544. c.Lock()
  545. defer c.Unlock()
  546. dd, ok := c.drivers[networkType]
  547. if !ok {
  548. return nil, ErrInvalidNetworkDriver(networkType)
  549. }
  550. return dd, nil
  551. }
  552. func (c *controller) loadIpamDriver(name string) (*ipamData, error) {
  553. if _, err := plugins.Get(name, ipamapi.PluginEndpointType); err != nil {
  554. if err == plugins.ErrNotFound {
  555. return nil, types.NotFoundErrorf(err.Error())
  556. }
  557. return nil, err
  558. }
  559. c.Lock()
  560. id, ok := c.ipamDrivers[name]
  561. c.Unlock()
  562. if !ok {
  563. return nil, ErrInvalidNetworkDriver(name)
  564. }
  565. return id, nil
  566. }
  567. func (c *controller) getIPAM(name string) (id *ipamData, err error) {
  568. var ok bool
  569. c.Lock()
  570. id, ok = c.ipamDrivers[name]
  571. c.Unlock()
  572. if !ok {
  573. id, err = c.loadIpamDriver(name)
  574. }
  575. return id, err
  576. }
  577. func (c *controller) getIpamDriver(name string) (ipamapi.Ipam, error) {
  578. id, err := c.getIPAM(name)
  579. if err != nil {
  580. return nil, err
  581. }
  582. return id.driver, nil
  583. }
  584. func (c *controller) Stop() {
  585. c.closeStores()
  586. c.stopExternalKeyListener()
  587. osl.GC()
  588. }