controller.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  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. // ID provides an unique identity for the controller
  60. ID() string
  61. // ConfigureNetworkDriver applies the passed options to the driver instance for the specified network type
  62. ConfigureNetworkDriver(networkType string, options map[string]interface{}) error
  63. // Config method returns the bootup configuration for the controller
  64. Config() config.Config
  65. // Create a new network. The options parameter carries network specific options.
  66. // Labels support will be added in the near future.
  67. NewNetwork(networkType, name string, options ...NetworkOption) (Network, error)
  68. // Networks returns the list of Network(s) managed by this controller.
  69. Networks() []Network
  70. // WalkNetworks uses the provided function to walk the Network(s) managed by this controller.
  71. WalkNetworks(walker NetworkWalker)
  72. // NetworkByName returns the Network which has the passed name. If not found, the error ErrNoSuchNetwork is returned.
  73. NetworkByName(name string) (Network, error)
  74. // NetworkByID returns the Network which has the passed id. If not found, the error ErrNoSuchNetwork is returned.
  75. NetworkByID(id string) (Network, error)
  76. // NewSandbox cretes a new network sandbox for the passed container id
  77. NewSandbox(containerID string, options ...SandboxOption) (Sandbox, error)
  78. // Sandboxes returns the list of Sandbox(s) managed by this controller.
  79. Sandboxes() []Sandbox
  80. // WlakSandboxes uses the provided function to walk the Sandbox(s) managed by this controller.
  81. WalkSandboxes(walker SandboxWalker)
  82. // SandboxByID returns the Sandbox which has the passed id. If not found, a types.NotFoundError is returned.
  83. SandboxByID(id string) (Sandbox, error)
  84. // Stop network controller
  85. Stop()
  86. }
  87. // NetworkWalker is a client provided function which will be used to walk the Networks.
  88. // When the function returns true, the walk will stop.
  89. type NetworkWalker func(nw Network) bool
  90. // SandboxWalker is a client provided function which will be used to walk the Sandboxes.
  91. // When the function returns true, the walk will stop.
  92. type SandboxWalker func(sb Sandbox) bool
  93. type driverData struct {
  94. driver driverapi.Driver
  95. capability driverapi.Capability
  96. }
  97. type driverTable map[string]*driverData
  98. type networkTable map[string]*network
  99. type endpointTable map[string]*endpoint
  100. type sandboxTable map[string]*sandbox
  101. type controller struct {
  102. id string
  103. networks networkTable
  104. drivers driverTable
  105. sandboxes sandboxTable
  106. cfg *config.Config
  107. store datastore.DataStore
  108. extKeyListener net.Listener
  109. sync.Mutex
  110. }
  111. // New creates a new instance of network controller.
  112. func New(cfgOptions ...config.Option) (NetworkController, error) {
  113. var cfg *config.Config
  114. if len(cfgOptions) > 0 {
  115. cfg = &config.Config{}
  116. cfg.ProcessOptions(cfgOptions...)
  117. }
  118. c := &controller{
  119. id: stringid.GenerateRandomID(),
  120. cfg: cfg,
  121. networks: networkTable{},
  122. sandboxes: sandboxTable{},
  123. drivers: driverTable{}}
  124. if err := initDrivers(c); err != nil {
  125. return nil, err
  126. }
  127. if cfg != nil {
  128. if err := c.initDataStore(); err != nil {
  129. // Failing to initalize datastore is a bad situation to be in.
  130. // But it cannot fail creating the Controller
  131. log.Debugf("Failed to Initialize Datastore due to %v. Operating in non-clustered mode", err)
  132. }
  133. if err := c.initDiscovery(); err != nil {
  134. // Failing to initalize discovery is a bad situation to be in.
  135. // But it cannot fail creating the Controller
  136. log.Debugf("Failed to Initialize Discovery : %v", err)
  137. }
  138. }
  139. if err := c.startExternalKeyListener(); err != nil {
  140. return nil, err
  141. }
  142. return c, nil
  143. }
  144. func (c *controller) ID() string {
  145. return c.id
  146. }
  147. func (c *controller) validateHostDiscoveryConfig() bool {
  148. if c.cfg == nil || c.cfg.Cluster.Discovery == "" || c.cfg.Cluster.Address == "" {
  149. return false
  150. }
  151. return true
  152. }
  153. func (c *controller) initDiscovery() error {
  154. if c.cfg == nil {
  155. return fmt.Errorf("discovery initialization requires a valid configuration")
  156. }
  157. hostDiscovery := hostdiscovery.NewHostDiscovery()
  158. return hostDiscovery.StartDiscovery(&c.cfg.Cluster, c.hostJoinCallback, c.hostLeaveCallback)
  159. }
  160. func (c *controller) hostJoinCallback(hosts []net.IP) {
  161. }
  162. func (c *controller) hostLeaveCallback(hosts []net.IP) {
  163. }
  164. func (c *controller) Config() config.Config {
  165. c.Lock()
  166. defer c.Unlock()
  167. if c.cfg == nil {
  168. return config.Config{}
  169. }
  170. return *c.cfg
  171. }
  172. func (c *controller) ConfigureNetworkDriver(networkType string, options map[string]interface{}) error {
  173. c.Lock()
  174. dd, ok := c.drivers[networkType]
  175. c.Unlock()
  176. if !ok {
  177. return NetworkTypeError(networkType)
  178. }
  179. return dd.driver.Config(options)
  180. }
  181. func (c *controller) RegisterDriver(networkType string, driver driverapi.Driver, capability driverapi.Capability) error {
  182. if !config.IsValidName(networkType) {
  183. return ErrInvalidName(networkType)
  184. }
  185. c.Lock()
  186. if _, ok := c.drivers[networkType]; ok {
  187. c.Unlock()
  188. return driverapi.ErrActiveRegistration(networkType)
  189. }
  190. c.drivers[networkType] = &driverData{driver, capability}
  191. if c.cfg == nil {
  192. c.Unlock()
  193. return nil
  194. }
  195. opt := make(map[string]interface{})
  196. for _, label := range c.cfg.Daemon.Labels {
  197. if strings.HasPrefix(label, netlabel.DriverPrefix+"."+networkType) {
  198. opt[netlabel.Key(label)] = netlabel.Value(label)
  199. }
  200. }
  201. if capability.Scope == driverapi.GlobalScope && c.validateDatastoreConfig() {
  202. opt[netlabel.KVProvider] = c.cfg.Datastore.Client.Provider
  203. opt[netlabel.KVProviderURL] = c.cfg.Datastore.Client.Address
  204. }
  205. c.Unlock()
  206. if len(opt) != 0 {
  207. if err := driver.Config(opt); err != nil {
  208. return err
  209. }
  210. }
  211. return nil
  212. }
  213. // NewNetwork creates a new network of the specified network type. The options
  214. // are network specific and modeled in a generic way.
  215. func (c *controller) NewNetwork(networkType, name string, options ...NetworkOption) (Network, error) {
  216. if !config.IsValidName(name) {
  217. return nil, ErrInvalidName(name)
  218. }
  219. // Check if a network already exists with the specified network name
  220. c.Lock()
  221. for _, n := range c.networks {
  222. if n.name == name {
  223. c.Unlock()
  224. return nil, NetworkNameError(name)
  225. }
  226. }
  227. c.Unlock()
  228. // Construct the network object
  229. network := &network{
  230. name: name,
  231. networkType: networkType,
  232. id: stringid.GenerateRandomID(),
  233. ctrlr: c,
  234. endpoints: endpointTable{},
  235. }
  236. network.processOptions(options...)
  237. if err := c.addNetwork(network); err != nil {
  238. return nil, err
  239. }
  240. if err := c.updateNetworkToStore(network); err != nil {
  241. log.Warnf("couldnt create network %s: %v", network.name, err)
  242. if e := network.Delete(); e != nil {
  243. log.Warnf("couldnt cleanup network %s: %v", network.name, err)
  244. }
  245. return nil, err
  246. }
  247. return network, nil
  248. }
  249. func (c *controller) addNetwork(n *network) error {
  250. c.Lock()
  251. // Check if a driver for the specified network type is available
  252. dd, ok := c.drivers[n.networkType]
  253. c.Unlock()
  254. if !ok {
  255. var err error
  256. dd, err = c.loadDriver(n.networkType)
  257. if err != nil {
  258. return err
  259. }
  260. }
  261. n.Lock()
  262. n.svcRecords = svcMap{}
  263. n.driver = dd.driver
  264. d := n.driver
  265. n.Unlock()
  266. // Create the network
  267. if err := d.CreateNetwork(n.id, n.generic); err != nil {
  268. return err
  269. }
  270. if err := n.watchEndpoints(); err != nil {
  271. return err
  272. }
  273. c.Lock()
  274. c.networks[n.id] = n
  275. c.Unlock()
  276. return nil
  277. }
  278. func (c *controller) Networks() []Network {
  279. c.Lock()
  280. defer c.Unlock()
  281. list := make([]Network, 0, len(c.networks))
  282. for _, n := range c.networks {
  283. list = append(list, n)
  284. }
  285. return list
  286. }
  287. func (c *controller) WalkNetworks(walker NetworkWalker) {
  288. for _, n := range c.Networks() {
  289. if walker(n) {
  290. return
  291. }
  292. }
  293. }
  294. func (c *controller) NetworkByName(name string) (Network, error) {
  295. if name == "" {
  296. return nil, ErrInvalidName(name)
  297. }
  298. var n Network
  299. s := func(current Network) bool {
  300. if current.Name() == name {
  301. n = current
  302. return true
  303. }
  304. return false
  305. }
  306. c.WalkNetworks(s)
  307. if n == nil {
  308. return nil, ErrNoSuchNetwork(name)
  309. }
  310. return n, nil
  311. }
  312. func (c *controller) NetworkByID(id string) (Network, error) {
  313. if id == "" {
  314. return nil, ErrInvalidID(id)
  315. }
  316. c.Lock()
  317. defer c.Unlock()
  318. if n, ok := c.networks[id]; ok {
  319. return n, nil
  320. }
  321. return nil, ErrNoSuchNetwork(id)
  322. }
  323. // NewSandbox creates a new sandbox for the passed container id
  324. func (c *controller) NewSandbox(containerID string, options ...SandboxOption) (Sandbox, error) {
  325. var err error
  326. if containerID == "" {
  327. return nil, types.BadRequestErrorf("invalid container ID")
  328. }
  329. var existing Sandbox
  330. look := SandboxContainerWalker(&existing, containerID)
  331. c.WalkSandboxes(look)
  332. if existing != nil {
  333. return nil, types.BadRequestErrorf("container %s is already present: %v", containerID, existing)
  334. }
  335. // Create sandbox and process options first. Key generation depends on an option
  336. sb := &sandbox{
  337. id: stringid.GenerateRandomID(),
  338. containerID: containerID,
  339. endpoints: epHeap{},
  340. epPriority: map[string]int{},
  341. config: containerConfig{},
  342. controller: c,
  343. }
  344. // This sandbox may be using an existing osl sandbox, sharing it with another sandbox
  345. var peerSb Sandbox
  346. c.WalkSandboxes(SandboxKeyWalker(&peerSb, sb.Key()))
  347. if peerSb != nil {
  348. sb.osSbox = peerSb.(*sandbox).osSbox
  349. }
  350. heap.Init(&sb.endpoints)
  351. sb.processOptions(options...)
  352. if err = sb.setupResolutionFiles(); err != nil {
  353. return nil, err
  354. }
  355. if sb.osSbox == nil && !sb.config.useExternalKey {
  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) Stop() {
  444. c.stopExternalKeyListener()
  445. osl.GC()
  446. }