controller.go 18 KB

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