controller.go 10 KB

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