controller.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. /*
  2. Package libnetwork provides the basic functionality and extension points to
  3. create network namespaces and allocate interfaces for containers to use.
  4. // Create a new controller instance
  5. controller, _err := libnetwork.New(nil)
  6. // Select and configure the network driver
  7. networkType := "bridge"
  8. driverOptions := options.Generic{}
  9. genericOption := make(map[string]interface{})
  10. genericOption[netlabel.GenericData] = driverOptions
  11. err := controller.ConfigureNetworkDriver(networkType, genericOption)
  12. if err != nil {
  13. return
  14. }
  15. // Create a network for containers to join.
  16. // NewNetwork accepts Variadic optional arguments that libnetwork and Drivers can make of
  17. network, err := controller.NewNetwork(networkType, "network1")
  18. if err != nil {
  19. return
  20. }
  21. // For each new container: allocate IP and interfaces. The returned network
  22. // settings will be used for container infos (inspect and such), as well as
  23. // iptables rules for port publishing. This info is contained or accessible
  24. // from the returned endpoint.
  25. ep, err := network.CreateEndpoint("Endpoint1")
  26. if err != nil {
  27. return
  28. }
  29. // A container can join the endpoint by providing the container ID to the join
  30. // api.
  31. // Join accepts Variadic arguments which will be made use of by libnetwork and Drivers
  32. err = ep.Join("container1",
  33. libnetwork.JoinOptionHostname("test"),
  34. libnetwork.JoinOptionDomainname("docker.io"))
  35. if err != nil {
  36. return
  37. }
  38. */
  39. package libnetwork
  40. import (
  41. "container/heap"
  42. "fmt"
  43. "net"
  44. "strings"
  45. "sync"
  46. log "github.com/Sirupsen/logrus"
  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/netlabel"
  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. // ConfigureNetworkDriver applies the passed options to the driver instance for the specified network type
  61. ConfigureNetworkDriver(networkType string, options map[string]interface{}) error
  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. // GC triggers immediate garbage collection of resources which are garbage collected.
  84. GC()
  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 driverTable map[string]*driverData
  97. type networkTable map[string]*network
  98. type endpointTable map[string]*endpoint
  99. type sandboxTable map[string]*sandbox
  100. type controller struct {
  101. networks networkTable
  102. drivers driverTable
  103. sandboxes sandboxTable
  104. cfg *config.Config
  105. store datastore.DataStore
  106. sync.Mutex
  107. }
  108. // New creates a new instance of network controller.
  109. func New(cfgOptions ...config.Option) (NetworkController, error) {
  110. var cfg *config.Config
  111. if len(cfgOptions) > 0 {
  112. cfg = &config.Config{}
  113. cfg.ProcessOptions(cfgOptions...)
  114. }
  115. c := &controller{
  116. cfg: cfg,
  117. networks: networkTable{},
  118. sandboxes: sandboxTable{},
  119. drivers: driverTable{}}
  120. if err := initDrivers(c); err != nil {
  121. return nil, err
  122. }
  123. if cfg != nil {
  124. if err := c.initDataStore(); err != nil {
  125. // Failing to initalize datastore is a bad situation to be in.
  126. // But it cannot fail creating the Controller
  127. log.Debugf("Failed to Initialize Datastore due to %v. Operating in non-clustered mode", err)
  128. }
  129. if err := c.initDiscovery(); err != nil {
  130. // Failing to initalize discovery is a bad situation to be in.
  131. // But it cannot fail creating the Controller
  132. log.Debugf("Failed to Initialize Discovery : %v", err)
  133. }
  134. }
  135. return c, nil
  136. }
  137. func (c *controller) validateHostDiscoveryConfig() bool {
  138. if c.cfg == nil || c.cfg.Cluster.Discovery == "" || c.cfg.Cluster.Address == "" {
  139. return false
  140. }
  141. return true
  142. }
  143. func (c *controller) initDiscovery() error {
  144. if c.cfg == nil {
  145. return fmt.Errorf("discovery initialization requires a valid configuration")
  146. }
  147. hostDiscovery := hostdiscovery.NewHostDiscovery()
  148. return hostDiscovery.StartDiscovery(&c.cfg.Cluster, c.hostJoinCallback, c.hostLeaveCallback)
  149. }
  150. func (c *controller) hostJoinCallback(hosts []net.IP) {
  151. }
  152. func (c *controller) hostLeaveCallback(hosts []net.IP) {
  153. }
  154. func (c *controller) Config() config.Config {
  155. c.Lock()
  156. defer c.Unlock()
  157. if c.cfg == nil {
  158. return config.Config{}
  159. }
  160. return *c.cfg
  161. }
  162. func (c *controller) ConfigureNetworkDriver(networkType string, options map[string]interface{}) error {
  163. c.Lock()
  164. dd, ok := c.drivers[networkType]
  165. c.Unlock()
  166. if !ok {
  167. return NetworkTypeError(networkType)
  168. }
  169. return dd.driver.Config(options)
  170. }
  171. func (c *controller) RegisterDriver(networkType string, driver driverapi.Driver, capability driverapi.Capability) error {
  172. c.Lock()
  173. if !config.IsValidName(networkType) {
  174. c.Unlock()
  175. return ErrInvalidName(networkType)
  176. }
  177. if _, ok := c.drivers[networkType]; ok {
  178. c.Unlock()
  179. return driverapi.ErrActiveRegistration(networkType)
  180. }
  181. c.drivers[networkType] = &driverData{driver, capability}
  182. if c.cfg == nil {
  183. c.Unlock()
  184. return nil
  185. }
  186. opt := make(map[string]interface{})
  187. for _, label := range c.cfg.Daemon.Labels {
  188. if strings.HasPrefix(label, netlabel.DriverPrefix+"."+networkType) {
  189. opt[netlabel.Key(label)] = netlabel.Value(label)
  190. }
  191. }
  192. if capability.Scope == driverapi.GlobalScope && c.validateDatastoreConfig() {
  193. opt[netlabel.KVProvider] = c.cfg.Datastore.Client.Provider
  194. opt[netlabel.KVProviderURL] = c.cfg.Datastore.Client.Address
  195. }
  196. c.Unlock()
  197. if len(opt) != 0 {
  198. if err := driver.Config(opt); err != nil {
  199. return err
  200. }
  201. }
  202. return nil
  203. }
  204. // NewNetwork creates a new network of the specified network type. The options
  205. // are network specific and modeled in a generic way.
  206. func (c *controller) NewNetwork(networkType, name string, options ...NetworkOption) (Network, error) {
  207. if !config.IsValidName(name) {
  208. return nil, ErrInvalidName(name)
  209. }
  210. // Check if a network already exists with the specified network name
  211. c.Lock()
  212. for _, n := range c.networks {
  213. if n.name == name {
  214. c.Unlock()
  215. return nil, NetworkNameError(name)
  216. }
  217. }
  218. c.Unlock()
  219. // Construct the network object
  220. network := &network{
  221. name: name,
  222. networkType: networkType,
  223. id: stringid.GenerateRandomID(),
  224. ctrlr: c,
  225. endpoints: endpointTable{},
  226. }
  227. network.processOptions(options...)
  228. if err := c.addNetwork(network); err != nil {
  229. return nil, err
  230. }
  231. if err := c.updateNetworkToStore(network); err != nil {
  232. log.Warnf("couldnt create network %s: %v", network.name, err)
  233. if e := network.Delete(); e != nil {
  234. log.Warnf("couldnt cleanup network %s: %v", network.name, err)
  235. }
  236. return nil, err
  237. }
  238. return network, nil
  239. }
  240. func (c *controller) addNetwork(n *network) error {
  241. c.Lock()
  242. // Check if a driver for the specified network type is available
  243. dd, ok := c.drivers[n.networkType]
  244. c.Unlock()
  245. if !ok {
  246. var err error
  247. dd, err = c.loadDriver(n.networkType)
  248. if err != nil {
  249. return err
  250. }
  251. }
  252. n.Lock()
  253. n.svcRecords = svcMap{}
  254. n.driver = dd.driver
  255. d := n.driver
  256. n.Unlock()
  257. // Create the network
  258. if err := d.CreateNetwork(n.id, n.generic); err != nil {
  259. return err
  260. }
  261. if err := n.watchEndpoints(); err != nil {
  262. return err
  263. }
  264. c.Lock()
  265. c.networks[n.id] = n
  266. c.Unlock()
  267. return nil
  268. }
  269. func (c *controller) Networks() []Network {
  270. c.Lock()
  271. defer c.Unlock()
  272. list := make([]Network, 0, len(c.networks))
  273. for _, n := range c.networks {
  274. list = append(list, n)
  275. }
  276. return list
  277. }
  278. func (c *controller) WalkNetworks(walker NetworkWalker) {
  279. for _, n := range c.Networks() {
  280. if walker(n) {
  281. return
  282. }
  283. }
  284. }
  285. func (c *controller) NetworkByName(name string) (Network, error) {
  286. if name == "" {
  287. return nil, ErrInvalidName(name)
  288. }
  289. var n Network
  290. s := func(current Network) bool {
  291. if current.Name() == name {
  292. n = current
  293. return true
  294. }
  295. return false
  296. }
  297. c.WalkNetworks(s)
  298. if n == nil {
  299. return nil, ErrNoSuchNetwork(name)
  300. }
  301. return n, nil
  302. }
  303. func (c *controller) NetworkByID(id string) (Network, error) {
  304. if id == "" {
  305. return nil, ErrInvalidID(id)
  306. }
  307. c.Lock()
  308. defer c.Unlock()
  309. if n, ok := c.networks[id]; ok {
  310. return n, nil
  311. }
  312. return nil, ErrNoSuchNetwork(id)
  313. }
  314. // NewSandbox creates a new sandbox for the passed container id
  315. func (c *controller) NewSandbox(containerID string, options ...SandboxOption) (Sandbox, error) {
  316. var err error
  317. if containerID == "" {
  318. return nil, types.BadRequestErrorf("invalid container ID")
  319. }
  320. var existing Sandbox
  321. look := SandboxContainerWalker(&existing, containerID)
  322. c.WalkSandboxes(look)
  323. if existing != nil {
  324. return nil, types.BadRequestErrorf("container %s is already present: %v", containerID, existing)
  325. }
  326. // Create sandbox and process options first. Key generation depends on an option
  327. sb := &sandbox{
  328. id: stringid.GenerateRandomID(),
  329. containerID: containerID,
  330. endpoints: epHeap{},
  331. epPriority: map[string]int{},
  332. config: containerConfig{},
  333. controller: c,
  334. }
  335. // This sandbox may be using an existing osl sandbox, sharing it with another sandbox
  336. var peerSb Sandbox
  337. c.WalkSandboxes(SandboxKeyWalker(&peerSb, sb.Key()))
  338. if peerSb != nil {
  339. sb.osSbox = peerSb.(*sandbox).osSbox
  340. }
  341. heap.Init(&sb.endpoints)
  342. sb.processOptions(options...)
  343. err = sb.buildHostsFile()
  344. if err != nil {
  345. return nil, err
  346. }
  347. err = sb.updateParentHosts()
  348. if err != nil {
  349. return nil, err
  350. }
  351. err = sb.setupDNS()
  352. if err != nil {
  353. return nil, err
  354. }
  355. if sb.osSbox == nil {
  356. if sb.osSbox, err = osl.NewSandbox(sb.Key(), !sb.config.useDefaultSandBox); err != nil {
  357. return nil, fmt.Errorf("failed to create new osl sandbox: %v", err)
  358. }
  359. }
  360. c.Lock()
  361. c.sandboxes[sb.id] = sb
  362. c.Unlock()
  363. return sb, nil
  364. }
  365. func (c *controller) Sandboxes() []Sandbox {
  366. c.Lock()
  367. defer c.Unlock()
  368. list := make([]Sandbox, 0, len(c.sandboxes))
  369. for _, s := range c.sandboxes {
  370. list = append(list, s)
  371. }
  372. return list
  373. }
  374. func (c *controller) WalkSandboxes(walker SandboxWalker) {
  375. for _, sb := range c.Sandboxes() {
  376. if walker(sb) {
  377. return
  378. }
  379. }
  380. }
  381. func (c *controller) SandboxByID(id string) (Sandbox, error) {
  382. if id == "" {
  383. return nil, ErrInvalidID(id)
  384. }
  385. c.Lock()
  386. s, ok := c.sandboxes[id]
  387. c.Unlock()
  388. if !ok {
  389. return nil, types.NotFoundErrorf("sandbox %s not found", id)
  390. }
  391. return s, nil
  392. }
  393. // SandboxContainerWalker returns a Sandbox Walker function which looks for an existing Sandbox with the passed containerID
  394. func SandboxContainerWalker(out *Sandbox, containerID string) SandboxWalker {
  395. return func(sb Sandbox) bool {
  396. if sb.ContainerID() == containerID {
  397. *out = sb
  398. return true
  399. }
  400. return false
  401. }
  402. }
  403. // SandboxKeyWalker returns a Sandbox Walker function which looks for an existing Sandbox with the passed key
  404. func SandboxKeyWalker(out *Sandbox, key string) SandboxWalker {
  405. return func(sb Sandbox) bool {
  406. if sb.Key() == key {
  407. *out = sb
  408. return true
  409. }
  410. return false
  411. }
  412. }
  413. func (c *controller) loadDriver(networkType string) (*driverData, error) {
  414. // Plugins pkg performs lazy loading of plugins that acts as remote drivers.
  415. // As per the design, this Get call will result in remote driver discovery if there is a corresponding plugin available.
  416. _, err := plugins.Get(networkType, driverapi.NetworkPluginEndpointType)
  417. if err != nil {
  418. if err == plugins.ErrNotFound {
  419. return nil, types.NotFoundErrorf(err.Error())
  420. }
  421. return nil, err
  422. }
  423. c.Lock()
  424. defer c.Unlock()
  425. dd, ok := c.drivers[networkType]
  426. if !ok {
  427. return nil, ErrInvalidNetworkDriver(networkType)
  428. }
  429. return dd, nil
  430. }
  431. func (c *controller) isDriverGlobalScoped(networkType string) (bool, error) {
  432. c.Lock()
  433. dd, ok := c.drivers[networkType]
  434. c.Unlock()
  435. if !ok {
  436. return false, types.NotFoundErrorf("driver not found for %s", networkType)
  437. }
  438. if dd.capability.Scope == driverapi.GlobalScope {
  439. return true, nil
  440. }
  441. return false, nil
  442. }
  443. func (c *controller) GC() {
  444. osl.GC()
  445. }