controller.go 17 KB

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