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