controller.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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 acceps 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. "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/sandbox"
  52. "github.com/docker/libnetwork/types"
  53. )
  54. // NetworkController provides the interface for controller instance which manages
  55. // networks.
  56. type NetworkController interface {
  57. // ConfigureNetworkDriver applies the passed options to the driver instance for the specified network type
  58. ConfigureNetworkDriver(networkType string, options map[string]interface{}) error
  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. // GC triggers immediate garbage collection of resources which are garbage collected.
  73. GC()
  74. }
  75. // NetworkWalker is a client provided function which will be used to walk the Networks.
  76. // When the function returns true, the walk will stop.
  77. type NetworkWalker func(nw Network) bool
  78. type driverData struct {
  79. driver driverapi.Driver
  80. capability driverapi.Capability
  81. }
  82. type driverTable map[string]*driverData
  83. type networkTable map[types.UUID]*network
  84. type endpointTable map[types.UUID]*endpoint
  85. type sandboxTable map[string]*sandboxData
  86. type controller struct {
  87. networks networkTable
  88. drivers driverTable
  89. sandboxes sandboxTable
  90. cfg *config.Config
  91. store datastore.DataStore
  92. sync.Mutex
  93. }
  94. // New creates a new instance of network controller.
  95. func New(cfgOptions ...config.Option) (NetworkController, error) {
  96. var cfg *config.Config
  97. if len(cfgOptions) > 0 {
  98. cfg = &config.Config{}
  99. cfg.ProcessOptions(cfgOptions...)
  100. }
  101. c := &controller{
  102. cfg: cfg,
  103. networks: networkTable{},
  104. sandboxes: sandboxTable{},
  105. drivers: driverTable{}}
  106. if err := initDrivers(c); err != nil {
  107. return nil, err
  108. }
  109. if cfg != nil {
  110. if err := c.initDataStore(); err != nil {
  111. // Failing to initalize datastore is a bad situation to be in.
  112. // But it cannot fail creating the Controller
  113. log.Debugf("Failed to Initialize Datastore due to %v. Operating in non-clustered mode", err)
  114. }
  115. if err := c.initDiscovery(); err != nil {
  116. // Failing to initalize discovery is a bad situation to be in.
  117. // But it cannot fail creating the Controller
  118. log.Debugf("Failed to Initialize Discovery : %v", err)
  119. }
  120. }
  121. return c, nil
  122. }
  123. func (c *controller) validateHostDiscoveryConfig() bool {
  124. if c.cfg == nil || c.cfg.Cluster.Discovery == "" || c.cfg.Cluster.Address == "" {
  125. return false
  126. }
  127. return true
  128. }
  129. func (c *controller) initDiscovery() error {
  130. if c.cfg == nil {
  131. return fmt.Errorf("discovery initialization requires a valid configuration")
  132. }
  133. hostDiscovery := hostdiscovery.NewHostDiscovery()
  134. return hostDiscovery.StartDiscovery(&c.cfg.Cluster, c.hostJoinCallback, c.hostLeaveCallback)
  135. }
  136. func (c *controller) hostJoinCallback(hosts []net.IP) {
  137. }
  138. func (c *controller) hostLeaveCallback(hosts []net.IP) {
  139. }
  140. func (c *controller) Config() config.Config {
  141. c.Lock()
  142. defer c.Unlock()
  143. if c.cfg == nil {
  144. return config.Config{}
  145. }
  146. return *c.cfg
  147. }
  148. func (c *controller) ConfigureNetworkDriver(networkType string, options map[string]interface{}) error {
  149. c.Lock()
  150. dd, ok := c.drivers[networkType]
  151. c.Unlock()
  152. if !ok {
  153. return NetworkTypeError(networkType)
  154. }
  155. return dd.driver.Config(options)
  156. }
  157. func (c *controller) RegisterDriver(networkType string, driver driverapi.Driver, capability driverapi.Capability) error {
  158. c.Lock()
  159. defer c.Unlock()
  160. if _, ok := c.drivers[networkType]; ok {
  161. return driverapi.ErrActiveRegistration(networkType)
  162. }
  163. c.drivers[networkType] = &driverData{driver, capability}
  164. return nil
  165. }
  166. // NewNetwork creates a new network of the specified network type. The options
  167. // are network specific and modeled in a generic way.
  168. func (c *controller) NewNetwork(networkType, name string, options ...NetworkOption) (Network, error) {
  169. if name == "" {
  170. return nil, ErrInvalidName(name)
  171. }
  172. // Check if a network already exists with the specified network name
  173. c.Lock()
  174. for _, n := range c.networks {
  175. if n.name == name {
  176. c.Unlock()
  177. return nil, NetworkNameError(name)
  178. }
  179. }
  180. c.Unlock()
  181. // Construct the network object
  182. network := &network{
  183. name: name,
  184. networkType: networkType,
  185. id: types.UUID(stringid.GenerateRandomID()),
  186. ctrlr: c,
  187. endpoints: endpointTable{},
  188. }
  189. network.processOptions(options...)
  190. if err := c.addNetwork(network); err != nil {
  191. return nil, err
  192. }
  193. if err := c.updateNetworkToStore(network); err != nil {
  194. if e := network.Delete(); e != nil {
  195. log.Warnf("couldnt cleanup network %s: %v", network.name, err)
  196. }
  197. return nil, err
  198. }
  199. return network, nil
  200. }
  201. func (c *controller) addNetwork(n *network) error {
  202. c.Lock()
  203. // Check if a driver for the specified network type is available
  204. dd, ok := c.drivers[n.networkType]
  205. c.Unlock()
  206. if !ok {
  207. var err error
  208. dd, err = c.loadDriver(n.networkType)
  209. if err != nil {
  210. return err
  211. }
  212. }
  213. n.Lock()
  214. n.driver = dd.driver
  215. d := n.driver
  216. n.Unlock()
  217. // Create the network
  218. if err := d.CreateNetwork(n.id, n.generic); err != nil {
  219. return err
  220. }
  221. c.Lock()
  222. c.networks[n.id] = n
  223. c.Unlock()
  224. return nil
  225. }
  226. func (c *controller) Networks() []Network {
  227. c.Lock()
  228. defer c.Unlock()
  229. list := make([]Network, 0, len(c.networks))
  230. for _, n := range c.networks {
  231. list = append(list, n)
  232. }
  233. return list
  234. }
  235. func (c *controller) WalkNetworks(walker NetworkWalker) {
  236. for _, n := range c.Networks() {
  237. if walker(n) {
  238. return
  239. }
  240. }
  241. }
  242. func (c *controller) NetworkByName(name string) (Network, error) {
  243. if name == "" {
  244. return nil, ErrInvalidName(name)
  245. }
  246. var n Network
  247. s := func(current Network) bool {
  248. if current.Name() == name {
  249. n = current
  250. return true
  251. }
  252. return false
  253. }
  254. c.WalkNetworks(s)
  255. if n == nil {
  256. return nil, ErrNoSuchNetwork(name)
  257. }
  258. return n, nil
  259. }
  260. func (c *controller) NetworkByID(id string) (Network, error) {
  261. if id == "" {
  262. return nil, ErrInvalidID(id)
  263. }
  264. c.Lock()
  265. defer c.Unlock()
  266. if n, ok := c.networks[types.UUID(id)]; ok {
  267. return n, nil
  268. }
  269. return nil, ErrNoSuchNetwork(id)
  270. }
  271. func (c *controller) loadDriver(networkType string) (*driverData, error) {
  272. // Plugins pkg performs lazy loading of plugins that acts as remote drivers.
  273. // As per the design, this Get call will result in remote driver discovery if there is a corresponding plugin available.
  274. _, err := plugins.Get(networkType, driverapi.NetworkPluginEndpointType)
  275. if err != nil {
  276. if err == plugins.ErrNotFound {
  277. return nil, types.NotFoundErrorf(err.Error())
  278. }
  279. return nil, err
  280. }
  281. c.Lock()
  282. defer c.Unlock()
  283. dd, ok := c.drivers[networkType]
  284. if !ok {
  285. return nil, ErrInvalidNetworkDriver(networkType)
  286. }
  287. return dd, nil
  288. }
  289. func (c *controller) isDriverGlobalScoped(networkType string) (bool, error) {
  290. c.Lock()
  291. dd, ok := c.drivers[networkType]
  292. c.Unlock()
  293. if !ok {
  294. return false, types.NotFoundErrorf("driver not found for %s", networkType)
  295. }
  296. if dd.capability.Scope == driverapi.GlobalScope {
  297. return true, nil
  298. }
  299. return false, nil
  300. }
  301. func (c *controller) GC() {
  302. sandbox.GC()
  303. }