controller.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  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. // addNetwork can be called for local scope network lazily when
  298. // an endpoint is created after a restart and the network was
  299. // created in previous life. Make sure you wrap around the driver
  300. // notification of network creation in once call so that the driver
  301. // invoked only once in case both the network and endpoint creation
  302. // happens in the same lifetime.
  303. network.drvOnce.Do(func() {
  304. err = c.addNetwork(network)
  305. })
  306. if err != nil {
  307. return nil, err
  308. }
  309. if err = c.updateToStore(network); err != nil {
  310. log.Warnf("couldnt create network %s: %v", network.name, err)
  311. if e := network.Delete(); e != nil {
  312. log.Warnf("couldnt cleanup network %s on network create failure (%v): %v", network.name, err, e)
  313. }
  314. return nil, err
  315. }
  316. return network, nil
  317. }
  318. func (c *controller) addNetwork(n *network) error {
  319. d, err := n.driver()
  320. if err != nil {
  321. return err
  322. }
  323. // Create the network
  324. if err := d.CreateNetwork(n.id, n.generic, n.getIPData(4), n.getIPData(6)); err != nil {
  325. return err
  326. }
  327. return nil
  328. }
  329. func (c *controller) Networks() []Network {
  330. var list []Network
  331. networks, err := c.getNetworksFromStore()
  332. if err != nil {
  333. log.Error(err)
  334. }
  335. for _, n := range networks {
  336. list = append(list, n)
  337. }
  338. return list
  339. }
  340. func (c *controller) WalkNetworks(walker NetworkWalker) {
  341. for _, n := range c.Networks() {
  342. if walker(n) {
  343. return
  344. }
  345. }
  346. }
  347. func (c *controller) NetworkByName(name string) (Network, error) {
  348. if name == "" {
  349. return nil, ErrInvalidName(name)
  350. }
  351. var n Network
  352. s := func(current Network) bool {
  353. if current.Name() == name {
  354. n = current
  355. return true
  356. }
  357. return false
  358. }
  359. c.WalkNetworks(s)
  360. if n == nil {
  361. return nil, ErrNoSuchNetwork(name)
  362. }
  363. return n, nil
  364. }
  365. func (c *controller) NetworkByID(id string) (Network, error) {
  366. if id == "" {
  367. return nil, ErrInvalidID(id)
  368. }
  369. n, err := c.getNetworkFromStore(id)
  370. if err != nil {
  371. return nil, ErrNoSuchNetwork(id)
  372. }
  373. return n, nil
  374. }
  375. // NewSandbox creates a new sandbox for the passed container id
  376. func (c *controller) NewSandbox(containerID string, options ...SandboxOption) (Sandbox, error) {
  377. var err error
  378. if containerID == "" {
  379. return nil, types.BadRequestErrorf("invalid container ID")
  380. }
  381. var existing Sandbox
  382. look := SandboxContainerWalker(&existing, containerID)
  383. c.WalkSandboxes(look)
  384. if existing != nil {
  385. return nil, types.BadRequestErrorf("container %s is already present: %v", containerID, existing)
  386. }
  387. // Create sandbox and process options first. Key generation depends on an option
  388. sb := &sandbox{
  389. id: stringid.GenerateRandomID(),
  390. containerID: containerID,
  391. endpoints: epHeap{},
  392. epPriority: map[string]int{},
  393. config: containerConfig{},
  394. controller: c,
  395. }
  396. // This sandbox may be using an existing osl sandbox, sharing it with another sandbox
  397. var peerSb Sandbox
  398. c.WalkSandboxes(SandboxKeyWalker(&peerSb, sb.Key()))
  399. if peerSb != nil {
  400. sb.osSbox = peerSb.(*sandbox).osSbox
  401. }
  402. heap.Init(&sb.endpoints)
  403. sb.processOptions(options...)
  404. if err = sb.setupResolutionFiles(); err != nil {
  405. return nil, err
  406. }
  407. if sb.osSbox == nil && !sb.config.useExternalKey {
  408. if sb.osSbox, err = osl.NewSandbox(sb.Key(), !sb.config.useDefaultSandBox); err != nil {
  409. return nil, fmt.Errorf("failed to create new osl sandbox: %v", err)
  410. }
  411. }
  412. c.Lock()
  413. c.sandboxes[sb.id] = sb
  414. c.Unlock()
  415. defer func() {
  416. if err != nil {
  417. c.Lock()
  418. delete(c.sandboxes, sb.id)
  419. c.Unlock()
  420. }
  421. }()
  422. err = sb.storeUpdate()
  423. if err != nil {
  424. return nil, fmt.Errorf("updating the store state of sandbox failed: %v", err)
  425. }
  426. return sb, nil
  427. }
  428. func (c *controller) Sandboxes() []Sandbox {
  429. c.Lock()
  430. defer c.Unlock()
  431. list := make([]Sandbox, 0, len(c.sandboxes))
  432. for _, s := range c.sandboxes {
  433. list = append(list, s)
  434. }
  435. return list
  436. }
  437. func (c *controller) WalkSandboxes(walker SandboxWalker) {
  438. for _, sb := range c.Sandboxes() {
  439. if walker(sb) {
  440. return
  441. }
  442. }
  443. }
  444. func (c *controller) SandboxByID(id string) (Sandbox, error) {
  445. if id == "" {
  446. return nil, ErrInvalidID(id)
  447. }
  448. c.Lock()
  449. s, ok := c.sandboxes[id]
  450. c.Unlock()
  451. if !ok {
  452. return nil, types.NotFoundErrorf("sandbox %s not found", id)
  453. }
  454. return s, nil
  455. }
  456. // SandboxContainerWalker returns a Sandbox Walker function which looks for an existing Sandbox with the passed containerID
  457. func SandboxContainerWalker(out *Sandbox, containerID string) SandboxWalker {
  458. return func(sb Sandbox) bool {
  459. if sb.ContainerID() == containerID {
  460. *out = sb
  461. return true
  462. }
  463. return false
  464. }
  465. }
  466. // SandboxKeyWalker returns a Sandbox Walker function which looks for an existing Sandbox with the passed key
  467. func SandboxKeyWalker(out *Sandbox, key string) SandboxWalker {
  468. return func(sb Sandbox) bool {
  469. if sb.Key() == key {
  470. *out = sb
  471. return true
  472. }
  473. return false
  474. }
  475. }
  476. func (c *controller) loadDriver(networkType string) (*driverData, error) {
  477. // Plugins pkg performs lazy loading of plugins that acts as remote drivers.
  478. // As per the design, this Get call will result in remote driver discovery if there is a corresponding plugin available.
  479. _, err := plugins.Get(networkType, driverapi.NetworkPluginEndpointType)
  480. if err != nil {
  481. if err == plugins.ErrNotFound {
  482. return nil, types.NotFoundErrorf(err.Error())
  483. }
  484. return nil, err
  485. }
  486. c.Lock()
  487. defer c.Unlock()
  488. dd, ok := c.drivers[networkType]
  489. if !ok {
  490. return nil, ErrInvalidNetworkDriver(networkType)
  491. }
  492. return dd, nil
  493. }
  494. func (c *controller) loadIpamDriver(name string) (*ipamData, error) {
  495. if _, err := plugins.Get(name, ipamapi.PluginEndpointType); err != nil {
  496. if err == plugins.ErrNotFound {
  497. return nil, types.NotFoundErrorf(err.Error())
  498. }
  499. return nil, err
  500. }
  501. c.Lock()
  502. id, ok := c.ipamDrivers[name]
  503. c.Unlock()
  504. if !ok {
  505. return nil, ErrInvalidNetworkDriver(name)
  506. }
  507. return id, nil
  508. }
  509. func (c *controller) getIPAM(name string) (id *ipamData, err error) {
  510. var ok bool
  511. c.Lock()
  512. id, ok = c.ipamDrivers[name]
  513. c.Unlock()
  514. if !ok {
  515. id, err = c.loadIpamDriver(name)
  516. }
  517. return id, err
  518. }
  519. func (c *controller) getIpamDriver(name string) (ipamapi.Ipam, error) {
  520. id, err := c.getIPAM(name)
  521. if err != nil {
  522. return nil, err
  523. }
  524. return id.driver, nil
  525. }
  526. func (c *controller) Stop() {
  527. c.closeStores()
  528. c.stopExternalKeyListener()
  529. osl.GC()
  530. }