controller.go 16 KB

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