controller.go 13 KB

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