controller.go 13 KB

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