controller.go 16 KB

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