controller.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657
  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. // Stop network controller
  84. Stop()
  85. }
  86. // NetworkWalker is a client provided function which will be used to walk the Networks.
  87. // When the function returns true, the walk will stop.
  88. type NetworkWalker func(nw Network) bool
  89. // SandboxWalker is a client provided function which will be used to walk the Sandboxes.
  90. // When the function returns true, the walk will stop.
  91. type SandboxWalker func(sb Sandbox) bool
  92. type driverData struct {
  93. driver driverapi.Driver
  94. capability driverapi.Capability
  95. }
  96. type ipamData struct {
  97. driver ipamapi.Ipam
  98. // default address spaces are provided by ipam driver at registration time
  99. defaultLocalAddressSpace, defaultGlobalAddressSpace string
  100. }
  101. type driverTable map[string]*driverData
  102. //type networkTable map[string]*network
  103. //type endpointTable map[string]*endpoint
  104. type ipamTable map[string]*ipamData
  105. type sandboxTable map[string]*sandbox
  106. type controller struct {
  107. id string
  108. //networks networkTable
  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]svcMap
  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]svcMap),
  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) 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 driverapi.ErrActiveRegistration(name)
  265. }
  266. locAS, glbAS, err := driver.GetDefaultAddressSpaces()
  267. if err != nil {
  268. return fmt.Errorf("ipam driver %s failed to return default address spaces: %v", name, err)
  269. }
  270. c.Lock()
  271. c.ipamDrivers[name] = &ipamData{driver: driver, defaultLocalAddressSpace: locAS, defaultGlobalAddressSpace: glbAS}
  272. c.Unlock()
  273. log.Debugf("Registering ipam provider: %s", name)
  274. return nil
  275. }
  276. // NewNetwork creates a new network of the specified network type. The options
  277. // are network specific and modeled in a generic way.
  278. func (c *controller) NewNetwork(networkType, name string, options ...NetworkOption) (Network, error) {
  279. if !config.IsValidName(name) {
  280. return nil, ErrInvalidName(name)
  281. }
  282. // Construct the network object
  283. network := &network{
  284. name: name,
  285. networkType: networkType,
  286. generic: map[string]interface{}{netlabel.GenericData: make(map[string]string)},
  287. ipamType: ipamapi.DefaultIPAM,
  288. id: stringid.GenerateRandomID(),
  289. ctrlr: c,
  290. persist: true,
  291. drvOnce: &sync.Once{},
  292. }
  293. network.processOptions(options...)
  294. // Make sure we have a driver available for this network type
  295. // before we allocate anything.
  296. if _, err := network.driver(); err != nil {
  297. return nil, err
  298. }
  299. err := network.ipamAllocate()
  300. if err != nil {
  301. return nil, err
  302. }
  303. defer func() {
  304. if err != nil {
  305. network.ipamRelease()
  306. }
  307. }()
  308. if err = c.addNetwork(network); err != nil {
  309. return nil, err
  310. }
  311. defer func() {
  312. if err != nil {
  313. if e := network.deleteNetwork(); e != nil {
  314. log.Warnf("couldn't roll back driver network on network %s creation failure: %v", network.name, err)
  315. }
  316. }
  317. }()
  318. if err = c.updateToStore(network); err != nil {
  319. return nil, err
  320. }
  321. defer func() {
  322. if err != nil {
  323. if e := c.deleteFromStore(network); e != nil {
  324. log.Warnf("couldnt rollback from store, network %s on failure (%v): %v", network.name, err, e)
  325. }
  326. }
  327. }()
  328. network.epCnt = &endpointCnt{n: network}
  329. if err = c.updateToStore(network.epCnt); err != nil {
  330. return nil, err
  331. }
  332. return network, nil
  333. }
  334. func (c *controller) addNetwork(n *network) error {
  335. d, err := n.driver()
  336. if err != nil {
  337. return err
  338. }
  339. // Create the network
  340. if err := d.CreateNetwork(n.id, n.generic, n.getIPData(4), n.getIPData(6)); err != nil {
  341. return err
  342. }
  343. return nil
  344. }
  345. func (c *controller) Networks() []Network {
  346. var list []Network
  347. networks, err := c.getNetworksFromStore()
  348. if err != nil {
  349. log.Error(err)
  350. }
  351. for _, n := range networks {
  352. list = append(list, n)
  353. }
  354. return list
  355. }
  356. func (c *controller) WalkNetworks(walker NetworkWalker) {
  357. for _, n := range c.Networks() {
  358. if walker(n) {
  359. return
  360. }
  361. }
  362. }
  363. func (c *controller) NetworkByName(name string) (Network, error) {
  364. if name == "" {
  365. return nil, ErrInvalidName(name)
  366. }
  367. var n Network
  368. s := func(current Network) bool {
  369. if current.Name() == name {
  370. n = current
  371. return true
  372. }
  373. return false
  374. }
  375. c.WalkNetworks(s)
  376. if n == nil {
  377. return nil, ErrNoSuchNetwork(name)
  378. }
  379. return n, nil
  380. }
  381. func (c *controller) NetworkByID(id string) (Network, error) {
  382. if id == "" {
  383. return nil, ErrInvalidID(id)
  384. }
  385. n, err := c.getNetworkFromStore(id)
  386. if err != nil {
  387. return nil, ErrNoSuchNetwork(id)
  388. }
  389. return n, nil
  390. }
  391. // NewSandbox creates a new sandbox for the passed container id
  392. func (c *controller) NewSandbox(containerID string, options ...SandboxOption) (Sandbox, error) {
  393. var err error
  394. if containerID == "" {
  395. return nil, types.BadRequestErrorf("invalid container ID")
  396. }
  397. var existing Sandbox
  398. look := SandboxContainerWalker(&existing, containerID)
  399. c.WalkSandboxes(look)
  400. if existing != nil {
  401. return nil, types.BadRequestErrorf("container %s is already present: %v", containerID, existing)
  402. }
  403. // Create sandbox and process options first. Key generation depends on an option
  404. sb := &sandbox{
  405. id: stringid.GenerateRandomID(),
  406. containerID: containerID,
  407. endpoints: epHeap{},
  408. epPriority: map[string]int{},
  409. config: containerConfig{},
  410. controller: c,
  411. }
  412. heap.Init(&sb.endpoints)
  413. sb.processOptions(options...)
  414. if err = sb.setupResolutionFiles(); err != nil {
  415. return nil, err
  416. }
  417. if sb.config.useDefaultSandBox {
  418. c.sboxOnce.Do(func() {
  419. c.defOsSbox, err = osl.NewSandbox(sb.Key(), false)
  420. })
  421. if err != nil {
  422. c.sboxOnce = sync.Once{}
  423. return nil, fmt.Errorf("failed to create default sandbox: %v", err)
  424. }
  425. sb.osSbox = c.defOsSbox
  426. }
  427. if sb.osSbox == nil && !sb.config.useExternalKey {
  428. if sb.osSbox, err = osl.NewSandbox(sb.Key(), !sb.config.useDefaultSandBox); err != nil {
  429. return nil, fmt.Errorf("failed to create new osl sandbox: %v", err)
  430. }
  431. }
  432. c.Lock()
  433. c.sandboxes[sb.id] = sb
  434. c.Unlock()
  435. defer func() {
  436. if err != nil {
  437. c.Lock()
  438. delete(c.sandboxes, sb.id)
  439. c.Unlock()
  440. }
  441. }()
  442. err = sb.storeUpdate()
  443. if err != nil {
  444. return nil, fmt.Errorf("updating the store state of sandbox failed: %v", err)
  445. }
  446. return sb, nil
  447. }
  448. func (c *controller) Sandboxes() []Sandbox {
  449. c.Lock()
  450. defer c.Unlock()
  451. list := make([]Sandbox, 0, len(c.sandboxes))
  452. for _, s := range c.sandboxes {
  453. list = append(list, s)
  454. }
  455. return list
  456. }
  457. func (c *controller) WalkSandboxes(walker SandboxWalker) {
  458. for _, sb := range c.Sandboxes() {
  459. if walker(sb) {
  460. return
  461. }
  462. }
  463. }
  464. func (c *controller) SandboxByID(id string) (Sandbox, error) {
  465. if id == "" {
  466. return nil, ErrInvalidID(id)
  467. }
  468. c.Lock()
  469. s, ok := c.sandboxes[id]
  470. c.Unlock()
  471. if !ok {
  472. return nil, types.NotFoundErrorf("sandbox %s not found", id)
  473. }
  474. return s, nil
  475. }
  476. // SandboxContainerWalker returns a Sandbox Walker function which looks for an existing Sandbox with the passed containerID
  477. func SandboxContainerWalker(out *Sandbox, containerID string) SandboxWalker {
  478. return func(sb Sandbox) bool {
  479. if sb.ContainerID() == containerID {
  480. *out = sb
  481. return true
  482. }
  483. return false
  484. }
  485. }
  486. // SandboxKeyWalker returns a Sandbox Walker function which looks for an existing Sandbox with the passed key
  487. func SandboxKeyWalker(out *Sandbox, key string) SandboxWalker {
  488. return func(sb Sandbox) bool {
  489. if sb.Key() == key {
  490. *out = sb
  491. return true
  492. }
  493. return false
  494. }
  495. }
  496. func (c *controller) loadDriver(networkType string) (*driverData, error) {
  497. // Plugins pkg performs lazy loading of plugins that acts as remote drivers.
  498. // As per the design, this Get call will result in remote driver discovery if there is a corresponding plugin available.
  499. _, err := plugins.Get(networkType, driverapi.NetworkPluginEndpointType)
  500. if err != nil {
  501. if err == plugins.ErrNotFound {
  502. return nil, types.NotFoundErrorf(err.Error())
  503. }
  504. return nil, err
  505. }
  506. c.Lock()
  507. defer c.Unlock()
  508. dd, ok := c.drivers[networkType]
  509. if !ok {
  510. return nil, ErrInvalidNetworkDriver(networkType)
  511. }
  512. return dd, nil
  513. }
  514. func (c *controller) loadIpamDriver(name string) (*ipamData, error) {
  515. if _, err := plugins.Get(name, ipamapi.PluginEndpointType); err != nil {
  516. if err == plugins.ErrNotFound {
  517. return nil, types.NotFoundErrorf(err.Error())
  518. }
  519. return nil, err
  520. }
  521. c.Lock()
  522. id, ok := c.ipamDrivers[name]
  523. c.Unlock()
  524. if !ok {
  525. return nil, ErrInvalidNetworkDriver(name)
  526. }
  527. return id, nil
  528. }
  529. func (c *controller) getIPAM(name string) (id *ipamData, err error) {
  530. var ok bool
  531. c.Lock()
  532. id, ok = c.ipamDrivers[name]
  533. c.Unlock()
  534. if !ok {
  535. id, err = c.loadIpamDriver(name)
  536. }
  537. return id, err
  538. }
  539. func (c *controller) getIpamDriver(name string) (ipamapi.Ipam, error) {
  540. id, err := c.getIPAM(name)
  541. if err != nil {
  542. return nil, err
  543. }
  544. return id.driver, nil
  545. }
  546. func (c *controller) Stop() {
  547. c.closeStores()
  548. c.stopExternalKeyListener()
  549. osl.GC()
  550. }