controller.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  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. if _, ok := c.ipamDrivers[name]; ok {
  257. c.Unlock()
  258. return driverapi.ErrActiveRegistration(name)
  259. }
  260. l, g, err := driver.GetDefaultAddressSpaces()
  261. if err != nil {
  262. return fmt.Errorf("ipam driver %s failed to return default address spaces: %v", name, err)
  263. }
  264. c.ipamDrivers[name] = &ipamData{driver: driver, defaultLocalAddressSpace: l, defaultGlobalAddressSpace: g}
  265. c.Unlock()
  266. log.Debugf("Registering ipam provider: %s", name)
  267. return nil
  268. }
  269. // NewNetwork creates a new network of the specified network type. The options
  270. // are network specific and modeled in a generic way.
  271. func (c *controller) NewNetwork(networkType, name string, options ...NetworkOption) (Network, error) {
  272. if !config.IsValidName(name) {
  273. return nil, ErrInvalidName(name)
  274. }
  275. // Check if a network already exists with the specified network name
  276. c.Lock()
  277. for _, n := range c.networks {
  278. if n.name == name {
  279. c.Unlock()
  280. return nil, NetworkNameError(name)
  281. }
  282. }
  283. c.Unlock()
  284. // Construct the network object
  285. network := &network{
  286. name: name,
  287. networkType: networkType,
  288. ipamType: ipamapi.DefaultIPAM,
  289. id: stringid.GenerateRandomID(),
  290. ctrlr: c,
  291. endpoints: endpointTable{},
  292. persist: true,
  293. }
  294. network.processOptions(options...)
  295. if err := c.addNetwork(network); err != nil {
  296. return nil, err
  297. }
  298. if err := c.updateToStore(network); err != nil {
  299. log.Warnf("couldnt create network %s: %v", network.name, err)
  300. if e := network.Delete(); e != nil {
  301. log.Warnf("couldnt cleanup network %s: %v", network.name, err)
  302. }
  303. return nil, err
  304. }
  305. return network, nil
  306. }
  307. func (c *controller) addNetwork(n *network) error {
  308. c.Lock()
  309. // Check if a driver for the specified network type is available
  310. dd, ok := c.drivers[n.networkType]
  311. c.Unlock()
  312. if !ok {
  313. var err error
  314. dd, err = c.loadDriver(n.networkType)
  315. if err != nil {
  316. return err
  317. }
  318. }
  319. n.Lock()
  320. n.svcRecords = svcMap{}
  321. n.driver = dd.driver
  322. n.dataScope = dd.capability.DataScope
  323. d := n.driver
  324. n.Unlock()
  325. // Create the network
  326. if err := d.CreateNetwork(n.id, n.generic); err != nil {
  327. return err
  328. }
  329. if n.isGlobalScoped() {
  330. if err := n.watchEndpoints(); err != nil {
  331. return err
  332. }
  333. }
  334. c.Lock()
  335. c.networks[n.id] = n
  336. c.Unlock()
  337. return nil
  338. }
  339. func (c *controller) Networks() []Network {
  340. c.Lock()
  341. defer c.Unlock()
  342. list := make([]Network, 0, len(c.networks))
  343. for _, n := range c.networks {
  344. list = append(list, n)
  345. }
  346. return list
  347. }
  348. func (c *controller) WalkNetworks(walker NetworkWalker) {
  349. for _, n := range c.Networks() {
  350. if walker(n) {
  351. return
  352. }
  353. }
  354. }
  355. func (c *controller) NetworkByName(name string) (Network, error) {
  356. if name == "" {
  357. return nil, ErrInvalidName(name)
  358. }
  359. var n Network
  360. s := func(current Network) bool {
  361. if current.Name() == name {
  362. n = current
  363. return true
  364. }
  365. return false
  366. }
  367. c.WalkNetworks(s)
  368. if n == nil {
  369. return nil, ErrNoSuchNetwork(name)
  370. }
  371. return n, nil
  372. }
  373. func (c *controller) NetworkByID(id string) (Network, error) {
  374. if id == "" {
  375. return nil, ErrInvalidID(id)
  376. }
  377. c.Lock()
  378. defer c.Unlock()
  379. if n, ok := c.networks[id]; ok {
  380. return n, nil
  381. }
  382. return nil, ErrNoSuchNetwork(id)
  383. }
  384. // NewSandbox creates a new sandbox for the passed container id
  385. func (c *controller) NewSandbox(containerID string, options ...SandboxOption) (Sandbox, error) {
  386. var err error
  387. if containerID == "" {
  388. return nil, types.BadRequestErrorf("invalid container ID")
  389. }
  390. var existing Sandbox
  391. look := SandboxContainerWalker(&existing, containerID)
  392. c.WalkSandboxes(look)
  393. if existing != nil {
  394. return nil, types.BadRequestErrorf("container %s is already present: %v", containerID, existing)
  395. }
  396. // Create sandbox and process options first. Key generation depends on an option
  397. sb := &sandbox{
  398. id: stringid.GenerateRandomID(),
  399. containerID: containerID,
  400. endpoints: epHeap{},
  401. epPriority: map[string]int{},
  402. config: containerConfig{},
  403. controller: c,
  404. }
  405. // This sandbox may be using an existing osl sandbox, sharing it with another sandbox
  406. var peerSb Sandbox
  407. c.WalkSandboxes(SandboxKeyWalker(&peerSb, sb.Key()))
  408. if peerSb != nil {
  409. sb.osSbox = peerSb.(*sandbox).osSbox
  410. }
  411. heap.Init(&sb.endpoints)
  412. sb.processOptions(options...)
  413. if err = sb.setupResolutionFiles(); err != nil {
  414. return nil, err
  415. }
  416. if sb.osSbox == nil && !sb.config.useExternalKey {
  417. if sb.osSbox, err = osl.NewSandbox(sb.Key(), !sb.config.useDefaultSandBox); err != nil {
  418. return nil, fmt.Errorf("failed to create new osl sandbox: %v", err)
  419. }
  420. }
  421. c.Lock()
  422. c.sandboxes[sb.id] = sb
  423. c.Unlock()
  424. return sb, nil
  425. }
  426. func (c *controller) Sandboxes() []Sandbox {
  427. c.Lock()
  428. defer c.Unlock()
  429. list := make([]Sandbox, 0, len(c.sandboxes))
  430. for _, s := range c.sandboxes {
  431. list = append(list, s)
  432. }
  433. return list
  434. }
  435. func (c *controller) WalkSandboxes(walker SandboxWalker) {
  436. for _, sb := range c.Sandboxes() {
  437. if walker(sb) {
  438. return
  439. }
  440. }
  441. }
  442. func (c *controller) SandboxByID(id string) (Sandbox, error) {
  443. if id == "" {
  444. return nil, ErrInvalidID(id)
  445. }
  446. c.Lock()
  447. s, ok := c.sandboxes[id]
  448. c.Unlock()
  449. if !ok {
  450. return nil, types.NotFoundErrorf("sandbox %s not found", id)
  451. }
  452. return s, nil
  453. }
  454. // SandboxContainerWalker returns a Sandbox Walker function which looks for an existing Sandbox with the passed containerID
  455. func SandboxContainerWalker(out *Sandbox, containerID string) SandboxWalker {
  456. return func(sb Sandbox) bool {
  457. if sb.ContainerID() == containerID {
  458. *out = sb
  459. return true
  460. }
  461. return false
  462. }
  463. }
  464. // SandboxKeyWalker returns a Sandbox Walker function which looks for an existing Sandbox with the passed key
  465. func SandboxKeyWalker(out *Sandbox, key string) SandboxWalker {
  466. return func(sb Sandbox) bool {
  467. if sb.Key() == key {
  468. *out = sb
  469. return true
  470. }
  471. return false
  472. }
  473. }
  474. func (c *controller) loadDriver(networkType string) (*driverData, error) {
  475. // Plugins pkg performs lazy loading of plugins that acts as remote drivers.
  476. // As per the design, this Get call will result in remote driver discovery if there is a corresponding plugin available.
  477. _, err := plugins.Get(networkType, driverapi.NetworkPluginEndpointType)
  478. if err != nil {
  479. if err == plugins.ErrNotFound {
  480. return nil, types.NotFoundErrorf(err.Error())
  481. }
  482. return nil, err
  483. }
  484. c.Lock()
  485. defer c.Unlock()
  486. dd, ok := c.drivers[networkType]
  487. if !ok {
  488. return nil, ErrInvalidNetworkDriver(networkType)
  489. }
  490. return dd, nil
  491. }
  492. func (c *controller) loadIpamDriver(name string) (*ipamData, error) {
  493. if _, err := plugins.Get(name, ipamapi.PluginEndpointType); err != nil {
  494. if err == plugins.ErrNotFound {
  495. return nil, types.NotFoundErrorf(err.Error())
  496. }
  497. return nil, err
  498. }
  499. c.Lock()
  500. id, ok := c.ipamDrivers[name]
  501. c.Unlock()
  502. if !ok {
  503. return nil, ErrInvalidNetworkDriver(name)
  504. }
  505. return id, nil
  506. }
  507. func (c *controller) getIPAM(name string) (id *ipamData, err error) {
  508. var ok bool
  509. c.Lock()
  510. id, ok = c.ipamDrivers[name]
  511. c.Unlock()
  512. if !ok {
  513. id, err = c.loadIpamDriver(name)
  514. }
  515. return id, err
  516. }
  517. func (c *controller) getIpamDriver(name string) (ipamapi.Ipam, error) {
  518. id, err := c.getIPAM(name)
  519. if err != nil {
  520. return nil, err
  521. }
  522. return id.driver, nil
  523. }
  524. func (c *controller) Stop() {
  525. if c.localStore != nil {
  526. c.localStore.KVStore().Close()
  527. }
  528. c.stopExternalKeyListener()
  529. osl.GC()
  530. }