controller.go 16 KB

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