controller.go 9.6 KB

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