controller.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  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/osl"
  54. "github.com/docker/libnetwork/types"
  55. )
  56. // NetworkController provides the interface for controller instance which manages
  57. // networks.
  58. type NetworkController interface {
  59. // ID provides an unique identity for the controller
  60. ID() string
  61. // Config method returns the bootup configuration for the controller
  62. Config() config.Config
  63. // Create a new network. The options parameter carries network specific options.
  64. // Labels support will be added in the near future.
  65. NewNetwork(networkType, name string, options ...NetworkOption) (Network, error)
  66. // Networks returns the list of Network(s) managed by this controller.
  67. Networks() []Network
  68. // WalkNetworks uses the provided function to walk the Network(s) managed by this controller.
  69. WalkNetworks(walker NetworkWalker)
  70. // NetworkByName returns the Network which has the passed name. If not found, the error ErrNoSuchNetwork is returned.
  71. NetworkByName(name string) (Network, error)
  72. // NetworkByID returns the Network which has the passed id. If not found, the error ErrNoSuchNetwork is returned.
  73. NetworkByID(id string) (Network, error)
  74. // NewSandbox cretes a new network sandbox for the passed container id
  75. NewSandbox(containerID string, options ...SandboxOption) (Sandbox, error)
  76. // Sandboxes returns the list of Sandbox(s) managed by this controller.
  77. Sandboxes() []Sandbox
  78. // WlakSandboxes uses the provided function to walk the Sandbox(s) managed by this controller.
  79. WalkSandboxes(walker SandboxWalker)
  80. // SandboxByID returns the Sandbox which has the passed id. If not found, a types.NotFoundError is returned.
  81. SandboxByID(id string) (Sandbox, error)
  82. // Stop network controller
  83. Stop()
  84. }
  85. // NetworkWalker is a client provided function which will be used to walk the Networks.
  86. // When the function returns true, the walk will stop.
  87. type NetworkWalker func(nw Network) bool
  88. // SandboxWalker is a client provided function which will be used to walk the Sandboxes.
  89. // When the function returns true, the walk will stop.
  90. type SandboxWalker func(sb Sandbox) bool
  91. type driverData struct {
  92. driver driverapi.Driver
  93. capability driverapi.Capability
  94. }
  95. type driverTable map[string]*driverData
  96. type networkTable map[string]*network
  97. type endpointTable map[string]*endpoint
  98. type sandboxTable map[string]*sandbox
  99. type controller struct {
  100. id string
  101. networks networkTable
  102. drivers driverTable
  103. sandboxes sandboxTable
  104. cfg *config.Config
  105. globalStore, localStore datastore.DataStore
  106. discovery hostdiscovery.HostDiscovery
  107. extKeyListener net.Listener
  108. sync.Mutex
  109. }
  110. // New creates a new instance of network controller.
  111. func New(cfgOptions ...config.Option) (NetworkController, error) {
  112. var cfg *config.Config
  113. if len(cfgOptions) > 0 {
  114. cfg = &config.Config{
  115. Daemon: config.DaemonCfg{
  116. DriverCfg: make(map[string]interface{}),
  117. },
  118. }
  119. cfg.ProcessOptions(cfgOptions...)
  120. }
  121. c := &controller{
  122. id: stringid.GenerateRandomID(),
  123. cfg: cfg,
  124. networks: networkTable{},
  125. sandboxes: sandboxTable{},
  126. drivers: driverTable{}}
  127. if err := initDrivers(c); err != nil {
  128. return nil, err
  129. }
  130. if cfg != nil {
  131. if err := c.initGlobalStore(); err != nil {
  132. // Failing to initalize datastore is a bad situation to be in.
  133. // But it cannot fail creating the Controller
  134. log.Debugf("Failed to Initialize Datastore due to %v. Operating in non-clustered mode", err)
  135. }
  136. if err := c.initDiscovery(cfg.Cluster.Watcher); err != nil {
  137. // Failing to initalize discovery is a bad situation to be in.
  138. // But it cannot fail creating the Controller
  139. log.Debugf("Failed to Initialize Discovery : %v", err)
  140. }
  141. if err := c.initLocalStore(); err != nil {
  142. log.Debugf("Failed to Initialize LocalDatastore due to %v.", err)
  143. }
  144. }
  145. if err := c.startExternalKeyListener(); err != nil {
  146. return nil, err
  147. }
  148. return c, nil
  149. }
  150. func (c *controller) ID() string {
  151. return c.id
  152. }
  153. func (c *controller) validateHostDiscoveryConfig() bool {
  154. if c.cfg == nil || c.cfg.Cluster.Discovery == "" || c.cfg.Cluster.Address == "" {
  155. return false
  156. }
  157. return true
  158. }
  159. func (c *controller) initDiscovery(watcher discovery.Watcher) error {
  160. if c.cfg == nil {
  161. return fmt.Errorf("discovery initialization requires a valid configuration")
  162. }
  163. c.discovery = hostdiscovery.NewHostDiscovery(watcher)
  164. return c.discovery.Watch(c.hostJoinCallback, c.hostLeaveCallback)
  165. }
  166. func (c *controller) hostJoinCallback(nodes []net.IP) {
  167. c.processNodeDiscovery(nodes, true)
  168. }
  169. func (c *controller) hostLeaveCallback(nodes []net.IP) {
  170. c.processNodeDiscovery(nodes, false)
  171. }
  172. func (c *controller) processNodeDiscovery(nodes []net.IP, add bool) {
  173. c.Lock()
  174. drivers := []*driverData{}
  175. for _, d := range c.drivers {
  176. drivers = append(drivers, d)
  177. }
  178. c.Unlock()
  179. for _, d := range drivers {
  180. c.pushNodeDiscovery(d, nodes, add)
  181. }
  182. }
  183. func (c *controller) pushNodeDiscovery(d *driverData, nodes []net.IP, add bool) {
  184. var self net.IP
  185. if c.cfg != nil {
  186. addr := strings.Split(c.cfg.Cluster.Address, ":")
  187. self = net.ParseIP(addr[0])
  188. }
  189. if d == nil || d.capability.DataScope != datastore.GlobalScope || nodes == nil {
  190. return
  191. }
  192. for _, node := range nodes {
  193. nodeData := driverapi.NodeDiscoveryData{Address: node.String(), Self: node.Equal(self)}
  194. var err error
  195. if add {
  196. err = d.driver.DiscoverNew(driverapi.NodeDiscovery, nodeData)
  197. } else {
  198. err = d.driver.DiscoverDelete(driverapi.NodeDiscovery, nodeData)
  199. }
  200. if err != nil {
  201. log.Debugf("discovery notification error : %v", err)
  202. }
  203. }
  204. }
  205. func (c *controller) Config() config.Config {
  206. c.Lock()
  207. defer c.Unlock()
  208. if c.cfg == nil {
  209. return config.Config{}
  210. }
  211. return *c.cfg
  212. }
  213. func (c *controller) RegisterDriver(networkType string, driver driverapi.Driver, capability driverapi.Capability) error {
  214. if !config.IsValidName(networkType) {
  215. return ErrInvalidName(networkType)
  216. }
  217. c.Lock()
  218. if _, ok := c.drivers[networkType]; ok {
  219. c.Unlock()
  220. return driverapi.ErrActiveRegistration(networkType)
  221. }
  222. dData := &driverData{driver, capability}
  223. c.drivers[networkType] = dData
  224. hd := c.discovery
  225. c.Unlock()
  226. if hd != nil {
  227. c.pushNodeDiscovery(dData, hd.Fetch(), true)
  228. }
  229. return nil
  230. }
  231. // NewNetwork creates a new network of the specified network type. The options
  232. // are network specific and modeled in a generic way.
  233. func (c *controller) NewNetwork(networkType, name string, options ...NetworkOption) (Network, error) {
  234. if !config.IsValidName(name) {
  235. return nil, ErrInvalidName(name)
  236. }
  237. // Check if a network already exists with the specified network name
  238. c.Lock()
  239. for _, n := range c.networks {
  240. if n.name == name {
  241. c.Unlock()
  242. return nil, NetworkNameError(name)
  243. }
  244. }
  245. c.Unlock()
  246. // Construct the network object
  247. network := &network{
  248. name: name,
  249. networkType: networkType,
  250. id: stringid.GenerateRandomID(),
  251. ctrlr: c,
  252. endpoints: endpointTable{},
  253. persist: true,
  254. }
  255. network.processOptions(options...)
  256. if err := c.addNetwork(network); err != nil {
  257. return nil, err
  258. }
  259. if err := c.updateToStore(network); err != nil {
  260. log.Warnf("couldnt create network %s: %v", network.name, err)
  261. if e := network.Delete(); e != nil {
  262. log.Warnf("couldnt cleanup network %s: %v", network.name, err)
  263. }
  264. return nil, err
  265. }
  266. return network, nil
  267. }
  268. func (c *controller) addNetwork(n *network) error {
  269. c.Lock()
  270. // Check if a driver for the specified network type is available
  271. dd, ok := c.drivers[n.networkType]
  272. c.Unlock()
  273. if !ok {
  274. var err error
  275. dd, err = c.loadDriver(n.networkType)
  276. if err != nil {
  277. return err
  278. }
  279. }
  280. n.Lock()
  281. n.svcRecords = svcMap{}
  282. n.driver = dd.driver
  283. n.dataScope = dd.capability.DataScope
  284. d := n.driver
  285. n.Unlock()
  286. // Create the network
  287. if err := d.CreateNetwork(n.id, n.generic); err != nil {
  288. return err
  289. }
  290. if n.isGlobalScoped() {
  291. if err := n.watchEndpoints(); err != nil {
  292. return err
  293. }
  294. }
  295. c.Lock()
  296. c.networks[n.id] = n
  297. c.Unlock()
  298. return nil
  299. }
  300. func (c *controller) Networks() []Network {
  301. c.Lock()
  302. defer c.Unlock()
  303. list := make([]Network, 0, len(c.networks))
  304. for _, n := range c.networks {
  305. list = append(list, n)
  306. }
  307. return list
  308. }
  309. func (c *controller) WalkNetworks(walker NetworkWalker) {
  310. for _, n := range c.Networks() {
  311. if walker(n) {
  312. return
  313. }
  314. }
  315. }
  316. func (c *controller) NetworkByName(name string) (Network, error) {
  317. if name == "" {
  318. return nil, ErrInvalidName(name)
  319. }
  320. var n Network
  321. s := func(current Network) bool {
  322. if current.Name() == name {
  323. n = current
  324. return true
  325. }
  326. return false
  327. }
  328. c.WalkNetworks(s)
  329. if n == nil {
  330. return nil, ErrNoSuchNetwork(name)
  331. }
  332. return n, nil
  333. }
  334. func (c *controller) NetworkByID(id string) (Network, error) {
  335. if id == "" {
  336. return nil, ErrInvalidID(id)
  337. }
  338. c.Lock()
  339. defer c.Unlock()
  340. if n, ok := c.networks[id]; ok {
  341. return n, nil
  342. }
  343. return nil, ErrNoSuchNetwork(id)
  344. }
  345. // NewSandbox creates a new sandbox for the passed container id
  346. func (c *controller) NewSandbox(containerID string, options ...SandboxOption) (Sandbox, error) {
  347. var err error
  348. if containerID == "" {
  349. return nil, types.BadRequestErrorf("invalid container ID")
  350. }
  351. var existing Sandbox
  352. look := SandboxContainerWalker(&existing, containerID)
  353. c.WalkSandboxes(look)
  354. if existing != nil {
  355. return nil, types.BadRequestErrorf("container %s is already present: %v", containerID, existing)
  356. }
  357. // Create sandbox and process options first. Key generation depends on an option
  358. sb := &sandbox{
  359. id: stringid.GenerateRandomID(),
  360. containerID: containerID,
  361. endpoints: epHeap{},
  362. epPriority: map[string]int{},
  363. config: containerConfig{},
  364. controller: c,
  365. }
  366. // This sandbox may be using an existing osl sandbox, sharing it with another sandbox
  367. var peerSb Sandbox
  368. c.WalkSandboxes(SandboxKeyWalker(&peerSb, sb.Key()))
  369. if peerSb != nil {
  370. sb.osSbox = peerSb.(*sandbox).osSbox
  371. }
  372. heap.Init(&sb.endpoints)
  373. sb.processOptions(options...)
  374. if err = sb.setupResolutionFiles(); err != nil {
  375. return nil, err
  376. }
  377. if sb.osSbox == nil && !sb.config.useExternalKey {
  378. if sb.osSbox, err = osl.NewSandbox(sb.Key(), !sb.config.useDefaultSandBox); err != nil {
  379. return nil, fmt.Errorf("failed to create new osl sandbox: %v", err)
  380. }
  381. }
  382. c.Lock()
  383. c.sandboxes[sb.id] = sb
  384. c.Unlock()
  385. return sb, nil
  386. }
  387. func (c *controller) Sandboxes() []Sandbox {
  388. c.Lock()
  389. defer c.Unlock()
  390. list := make([]Sandbox, 0, len(c.sandboxes))
  391. for _, s := range c.sandboxes {
  392. list = append(list, s)
  393. }
  394. return list
  395. }
  396. func (c *controller) WalkSandboxes(walker SandboxWalker) {
  397. for _, sb := range c.Sandboxes() {
  398. if walker(sb) {
  399. return
  400. }
  401. }
  402. }
  403. func (c *controller) SandboxByID(id string) (Sandbox, error) {
  404. if id == "" {
  405. return nil, ErrInvalidID(id)
  406. }
  407. c.Lock()
  408. s, ok := c.sandboxes[id]
  409. c.Unlock()
  410. if !ok {
  411. return nil, types.NotFoundErrorf("sandbox %s not found", id)
  412. }
  413. return s, nil
  414. }
  415. // SandboxContainerWalker returns a Sandbox Walker function which looks for an existing Sandbox with the passed containerID
  416. func SandboxContainerWalker(out *Sandbox, containerID string) SandboxWalker {
  417. return func(sb Sandbox) bool {
  418. if sb.ContainerID() == containerID {
  419. *out = sb
  420. return true
  421. }
  422. return false
  423. }
  424. }
  425. // SandboxKeyWalker returns a Sandbox Walker function which looks for an existing Sandbox with the passed key
  426. func SandboxKeyWalker(out *Sandbox, key string) SandboxWalker {
  427. return func(sb Sandbox) bool {
  428. if sb.Key() == key {
  429. *out = sb
  430. return true
  431. }
  432. return false
  433. }
  434. }
  435. func (c *controller) loadDriver(networkType string) (*driverData, error) {
  436. // Plugins pkg performs lazy loading of plugins that acts as remote drivers.
  437. // As per the design, this Get call will result in remote driver discovery if there is a corresponding plugin available.
  438. _, err := plugins.Get(networkType, driverapi.NetworkPluginEndpointType)
  439. if err != nil {
  440. if err == plugins.ErrNotFound {
  441. return nil, types.NotFoundErrorf(err.Error())
  442. }
  443. return nil, err
  444. }
  445. c.Lock()
  446. defer c.Unlock()
  447. dd, ok := c.drivers[networkType]
  448. if !ok {
  449. return nil, ErrInvalidNetworkDriver(networkType)
  450. }
  451. return dd, nil
  452. }
  453. func (c *controller) getDriver(networkType string) (*driverData, error) {
  454. c.Lock()
  455. defer c.Unlock()
  456. dd, ok := c.drivers[networkType]
  457. if !ok {
  458. return nil, types.NotFoundErrorf("driver %s not found", networkType)
  459. }
  460. return dd, nil
  461. }
  462. func (c *controller) Stop() {
  463. if c.localStore != nil {
  464. c.localStore.KVStore().Close()
  465. }
  466. c.stopExternalKeyListener()
  467. osl.GC()
  468. }