controller.go 17 KB

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