controller.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  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. "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. }
  211. network.processOptions(options...)
  212. if err := c.addNetwork(network); err != nil {
  213. return nil, err
  214. }
  215. if err := c.updateNetworkToStore(network); err != nil {
  216. log.Warnf("couldnt create network %s: %v", network.name, err)
  217. if e := network.Delete(); e != nil {
  218. log.Warnf("couldnt cleanup network %s: %v", network.name, err)
  219. }
  220. return nil, err
  221. }
  222. return network, nil
  223. }
  224. func (c *controller) addNetwork(n *network) error {
  225. c.Lock()
  226. // Check if a driver for the specified network type is available
  227. dd, ok := c.drivers[n.networkType]
  228. c.Unlock()
  229. if !ok {
  230. var err error
  231. dd, err = c.loadDriver(n.networkType)
  232. if err != nil {
  233. return err
  234. }
  235. }
  236. n.Lock()
  237. n.svcRecords = svcMap{}
  238. n.driver = dd.driver
  239. n.dataScope = dd.capability.DataScope
  240. d := n.driver
  241. n.Unlock()
  242. // Create the network
  243. if err := d.CreateNetwork(n.id, n.generic); err != nil {
  244. return err
  245. }
  246. if err := n.watchEndpoints(); err != nil {
  247. return err
  248. }
  249. c.Lock()
  250. c.networks[n.id] = n
  251. c.Unlock()
  252. return nil
  253. }
  254. func (c *controller) Networks() []Network {
  255. c.Lock()
  256. defer c.Unlock()
  257. list := make([]Network, 0, len(c.networks))
  258. for _, n := range c.networks {
  259. list = append(list, n)
  260. }
  261. return list
  262. }
  263. func (c *controller) WalkNetworks(walker NetworkWalker) {
  264. for _, n := range c.Networks() {
  265. if walker(n) {
  266. return
  267. }
  268. }
  269. }
  270. func (c *controller) NetworkByName(name string) (Network, error) {
  271. if name == "" {
  272. return nil, ErrInvalidName(name)
  273. }
  274. var n Network
  275. s := func(current Network) bool {
  276. if current.Name() == name {
  277. n = current
  278. return true
  279. }
  280. return false
  281. }
  282. c.WalkNetworks(s)
  283. if n == nil {
  284. return nil, ErrNoSuchNetwork(name)
  285. }
  286. return n, nil
  287. }
  288. func (c *controller) NetworkByID(id string) (Network, error) {
  289. if id == "" {
  290. return nil, ErrInvalidID(id)
  291. }
  292. c.Lock()
  293. defer c.Unlock()
  294. if n, ok := c.networks[id]; ok {
  295. return n, nil
  296. }
  297. return nil, ErrNoSuchNetwork(id)
  298. }
  299. // NewSandbox creates a new sandbox for the passed container id
  300. func (c *controller) NewSandbox(containerID string, options ...SandboxOption) (Sandbox, error) {
  301. var err error
  302. if containerID == "" {
  303. return nil, types.BadRequestErrorf("invalid container ID")
  304. }
  305. var existing Sandbox
  306. look := SandboxContainerWalker(&existing, containerID)
  307. c.WalkSandboxes(look)
  308. if existing != nil {
  309. return nil, types.BadRequestErrorf("container %s is already present: %v", containerID, existing)
  310. }
  311. // Create sandbox and process options first. Key generation depends on an option
  312. sb := &sandbox{
  313. id: stringid.GenerateRandomID(),
  314. containerID: containerID,
  315. endpoints: epHeap{},
  316. epPriority: map[string]int{},
  317. config: containerConfig{},
  318. controller: c,
  319. }
  320. // This sandbox may be using an existing osl sandbox, sharing it with another sandbox
  321. var peerSb Sandbox
  322. c.WalkSandboxes(SandboxKeyWalker(&peerSb, sb.Key()))
  323. if peerSb != nil {
  324. sb.osSbox = peerSb.(*sandbox).osSbox
  325. }
  326. heap.Init(&sb.endpoints)
  327. sb.processOptions(options...)
  328. if err = sb.setupResolutionFiles(); err != nil {
  329. return nil, err
  330. }
  331. if sb.osSbox == nil && !sb.config.useExternalKey {
  332. if sb.osSbox, err = osl.NewSandbox(sb.Key(), !sb.config.useDefaultSandBox); err != nil {
  333. return nil, fmt.Errorf("failed to create new osl sandbox: %v", err)
  334. }
  335. }
  336. c.Lock()
  337. c.sandboxes[sb.id] = sb
  338. c.Unlock()
  339. return sb, nil
  340. }
  341. func (c *controller) Sandboxes() []Sandbox {
  342. c.Lock()
  343. defer c.Unlock()
  344. list := make([]Sandbox, 0, len(c.sandboxes))
  345. for _, s := range c.sandboxes {
  346. list = append(list, s)
  347. }
  348. return list
  349. }
  350. func (c *controller) WalkSandboxes(walker SandboxWalker) {
  351. for _, sb := range c.Sandboxes() {
  352. if walker(sb) {
  353. return
  354. }
  355. }
  356. }
  357. func (c *controller) SandboxByID(id string) (Sandbox, error) {
  358. if id == "" {
  359. return nil, ErrInvalidID(id)
  360. }
  361. c.Lock()
  362. s, ok := c.sandboxes[id]
  363. c.Unlock()
  364. if !ok {
  365. return nil, types.NotFoundErrorf("sandbox %s not found", id)
  366. }
  367. return s, nil
  368. }
  369. // SandboxContainerWalker returns a Sandbox Walker function which looks for an existing Sandbox with the passed containerID
  370. func SandboxContainerWalker(out *Sandbox, containerID string) SandboxWalker {
  371. return func(sb Sandbox) bool {
  372. if sb.ContainerID() == containerID {
  373. *out = sb
  374. return true
  375. }
  376. return false
  377. }
  378. }
  379. // SandboxKeyWalker returns a Sandbox Walker function which looks for an existing Sandbox with the passed key
  380. func SandboxKeyWalker(out *Sandbox, key string) SandboxWalker {
  381. return func(sb Sandbox) bool {
  382. if sb.Key() == key {
  383. *out = sb
  384. return true
  385. }
  386. return false
  387. }
  388. }
  389. func (c *controller) loadDriver(networkType string) (*driverData, error) {
  390. // Plugins pkg performs lazy loading of plugins that acts as remote drivers.
  391. // As per the design, this Get call will result in remote driver discovery if there is a corresponding plugin available.
  392. _, err := plugins.Get(networkType, driverapi.NetworkPluginEndpointType)
  393. if err != nil {
  394. if err == plugins.ErrNotFound {
  395. return nil, types.NotFoundErrorf(err.Error())
  396. }
  397. return nil, err
  398. }
  399. c.Lock()
  400. defer c.Unlock()
  401. dd, ok := c.drivers[networkType]
  402. if !ok {
  403. return nil, ErrInvalidNetworkDriver(networkType)
  404. }
  405. return dd, nil
  406. }
  407. func (c *controller) Stop() {
  408. c.stopExternalKeyListener()
  409. osl.GC()
  410. }