controller.go 10.0 KB

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