controller.go 16 KB

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