controller.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  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. "encoding/json"
  42. "fmt"
  43. "net"
  44. "os"
  45. "strings"
  46. "sync"
  47. log "github.com/Sirupsen/logrus"
  48. "github.com/docker/docker/pkg/plugins"
  49. "github.com/docker/docker/pkg/stringid"
  50. "github.com/docker/libnetwork/config"
  51. "github.com/docker/libnetwork/datastore"
  52. "github.com/docker/libnetwork/driverapi"
  53. "github.com/docker/libnetwork/hostdiscovery"
  54. "github.com/docker/libnetwork/sandbox"
  55. "github.com/docker/libnetwork/types"
  56. "github.com/docker/swarm/pkg/store"
  57. )
  58. // NetworkController provides the interface for controller instance which manages
  59. // networks.
  60. type NetworkController interface {
  61. // ConfigureNetworkDriver applies the passed options to the driver instance for the specified network type
  62. ConfigureNetworkDriver(networkType string, options map[string]interface{}) error
  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. }
  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 sandboxData struct {
  79. sandbox sandbox.Sandbox
  80. refCnt int
  81. }
  82. type networkTable map[types.UUID]*network
  83. type endpointTable map[types.UUID]*endpoint
  84. type sandboxTable map[string]*sandboxData
  85. type controller struct {
  86. networks networkTable
  87. drivers driverTable
  88. sandboxes sandboxTable
  89. cfg *config.Config
  90. store datastore.DataStore
  91. sync.Mutex
  92. }
  93. // New creates a new instance of network controller.
  94. func New(configFile string) (NetworkController, error) {
  95. c := &controller{
  96. networks: networkTable{},
  97. sandboxes: sandboxTable{},
  98. drivers: driverTable{}}
  99. if err := initDrivers(c); err != nil {
  100. return nil, err
  101. }
  102. if err := c.initConfig(configFile); err == nil {
  103. if err := c.initDataStore(); err != nil {
  104. // Failing to initalize datastore is a bad situation to be in.
  105. // But it cannot fail creating the Controller
  106. log.Warnf("Failed to Initialize Datastore due to %v. Operating in non-clustered mode", err)
  107. }
  108. if err := c.initDiscovery(); err != nil {
  109. // Failing to initalize discovery is a bad situation to be in.
  110. // But it cannot fail creating the Controller
  111. log.Warnf("Failed to Initialize Discovery : %v", err)
  112. }
  113. } else {
  114. // Missing Configuration file is not a failure scenario
  115. // But without that, datastore cannot be initialized.
  116. log.Debugf("Unable to Parse LibNetwork Config file : %v", err)
  117. }
  118. return c, nil
  119. }
  120. const (
  121. cfgFileEnv = "LIBNETWORK_CFG"
  122. defaultCfgFile = "/etc/default/libnetwork.toml"
  123. )
  124. func (c *controller) initConfig(configFile string) error {
  125. cfgFile := configFile
  126. if strings.Trim(cfgFile, " ") == "" {
  127. cfgFile = os.Getenv(cfgFileEnv)
  128. if strings.Trim(cfgFile, " ") == "" {
  129. cfgFile = defaultCfgFile
  130. }
  131. }
  132. cfg, err := config.ParseConfig(cfgFile)
  133. if err != nil {
  134. return ErrInvalidConfigFile(cfgFile)
  135. }
  136. c.Lock()
  137. c.cfg = cfg
  138. c.Unlock()
  139. return nil
  140. }
  141. func (c *controller) initDataStore() error {
  142. if c.cfg == nil {
  143. return fmt.Errorf("datastore initialization requires a valid configuration")
  144. }
  145. store, err := datastore.NewDataStore(&c.cfg.Datastore)
  146. if err != nil {
  147. return err
  148. }
  149. c.Lock()
  150. c.store = store
  151. c.Unlock()
  152. go c.watchNewNetworks()
  153. return nil
  154. }
  155. func (c *controller) initDiscovery() error {
  156. if c.cfg == nil {
  157. return fmt.Errorf("discovery initialization requires a valid configuration")
  158. }
  159. hostDiscovery := hostdiscovery.NewHostDiscovery()
  160. return hostDiscovery.StartDiscovery(&c.cfg.Cluster, c.hostJoinCallback, c.hostLeaveCallback)
  161. }
  162. func (c *controller) hostJoinCallback(hosts []net.IP) {
  163. }
  164. func (c *controller) hostLeaveCallback(hosts []net.IP) {
  165. }
  166. func (c *controller) ConfigureNetworkDriver(networkType string, options map[string]interface{}) error {
  167. c.Lock()
  168. d, ok := c.drivers[networkType]
  169. c.Unlock()
  170. if !ok {
  171. return NetworkTypeError(networkType)
  172. }
  173. return d.Config(options)
  174. }
  175. func (c *controller) RegisterDriver(networkType string, driver driverapi.Driver) error {
  176. c.Lock()
  177. defer c.Unlock()
  178. if _, ok := c.drivers[networkType]; ok {
  179. return driverapi.ErrActiveRegistration(networkType)
  180. }
  181. c.drivers[networkType] = driver
  182. return nil
  183. }
  184. // NewNetwork creates a new network of the specified network type. The options
  185. // are network specific and modeled in a generic way.
  186. func (c *controller) NewNetwork(networkType, name string, options ...NetworkOption) (Network, error) {
  187. if name == "" {
  188. return nil, ErrInvalidName(name)
  189. }
  190. // Check if a driver for the specified network type is available
  191. c.Lock()
  192. d, ok := c.drivers[networkType]
  193. c.Unlock()
  194. if !ok {
  195. var err error
  196. d, err = c.loadDriver(networkType)
  197. if err != nil {
  198. return nil, err
  199. }
  200. }
  201. // Check if a network already exists with the specified network name
  202. c.Lock()
  203. for _, n := range c.networks {
  204. if n.name == name {
  205. c.Unlock()
  206. return nil, NetworkNameError(name)
  207. }
  208. }
  209. c.Unlock()
  210. // Construct the network object
  211. network := &network{
  212. name: name,
  213. id: types.UUID(stringid.GenerateRandomID()),
  214. ctrlr: c,
  215. driver: d,
  216. endpoints: endpointTable{},
  217. }
  218. network.processOptions(options...)
  219. if err := c.addNetworkToStore(network); err != nil {
  220. return nil, err
  221. }
  222. // Create the network
  223. if err := d.CreateNetwork(network.id, network.generic); err != nil {
  224. return nil, err
  225. }
  226. // Store the network handler in controller
  227. c.Lock()
  228. c.networks[network.id] = network
  229. c.Unlock()
  230. return network, nil
  231. }
  232. func (c *controller) newNetworkFromStore(n *network) {
  233. c.Lock()
  234. defer c.Unlock()
  235. if _, ok := c.drivers[n.networkType]; !ok {
  236. log.Warnf("Network driver unavailable for type=%s. ignoring network updates for %s", n.Type(), n.Name())
  237. return
  238. }
  239. n.ctrlr = c
  240. n.driver = c.drivers[n.networkType]
  241. c.networks[n.id] = n
  242. // TODO : Populate n.endpoints back from endpoint dbstore
  243. }
  244. func (c *controller) addNetworkToStore(n *network) error {
  245. if isReservedNetwork(n.Name()) {
  246. return nil
  247. }
  248. c.Lock()
  249. cs := c.store
  250. c.Unlock()
  251. if cs == nil {
  252. log.Debugf("datastore not initialized. Network %s is not added to the store", n.Name())
  253. return nil
  254. }
  255. return cs.PutObjectAtomic(n)
  256. }
  257. func (c *controller) watchNewNetworks() {
  258. c.Lock()
  259. cs := c.store
  260. c.Unlock()
  261. cs.KVStore().WatchRange(datastore.Key(datastore.NetworkKeyPrefix), "", 0, func(kvi []store.KVEntry) {
  262. for _, kve := range kvi {
  263. var n network
  264. err := json.Unmarshal(kve.Value(), &n)
  265. if err != nil {
  266. log.Error(err)
  267. continue
  268. }
  269. n.dbIndex = kve.LastIndex()
  270. c.Lock()
  271. existing, ok := c.networks[n.id]
  272. c.Unlock()
  273. if ok && existing.dbIndex == n.dbIndex {
  274. // Skip any watch notification for a network that has not changed
  275. continue
  276. } else if ok {
  277. // Received an update for an existing network object
  278. log.Debugf("Skipping network update for %s (%s)", n.name, n.id)
  279. continue
  280. }
  281. c.newNetworkFromStore(&n)
  282. }
  283. })
  284. }
  285. func (c *controller) Networks() []Network {
  286. c.Lock()
  287. defer c.Unlock()
  288. list := make([]Network, 0, len(c.networks))
  289. for _, n := range c.networks {
  290. list = append(list, n)
  291. }
  292. return list
  293. }
  294. func (c *controller) WalkNetworks(walker NetworkWalker) {
  295. for _, n := range c.Networks() {
  296. if walker(n) {
  297. return
  298. }
  299. }
  300. }
  301. func (c *controller) NetworkByName(name string) (Network, error) {
  302. if name == "" {
  303. return nil, ErrInvalidName(name)
  304. }
  305. var n Network
  306. s := func(current Network) bool {
  307. if current.Name() == name {
  308. n = current
  309. return true
  310. }
  311. return false
  312. }
  313. c.WalkNetworks(s)
  314. if n == nil {
  315. return nil, ErrNoSuchNetwork(name)
  316. }
  317. return n, nil
  318. }
  319. func (c *controller) NetworkByID(id string) (Network, error) {
  320. if id == "" {
  321. return nil, ErrInvalidID(id)
  322. }
  323. c.Lock()
  324. defer c.Unlock()
  325. if n, ok := c.networks[types.UUID(id)]; ok {
  326. return n, nil
  327. }
  328. return nil, ErrNoSuchNetwork(id)
  329. }
  330. func (c *controller) sandboxAdd(key string, create bool) (sandbox.Sandbox, error) {
  331. c.Lock()
  332. defer c.Unlock()
  333. sData, ok := c.sandboxes[key]
  334. if !ok {
  335. sb, err := sandbox.NewSandbox(key, create)
  336. if err != nil {
  337. return nil, err
  338. }
  339. sData = &sandboxData{sandbox: sb, refCnt: 1}
  340. c.sandboxes[key] = sData
  341. return sData.sandbox, nil
  342. }
  343. sData.refCnt++
  344. return sData.sandbox, nil
  345. }
  346. func (c *controller) sandboxRm(key string) {
  347. c.Lock()
  348. defer c.Unlock()
  349. sData := c.sandboxes[key]
  350. sData.refCnt--
  351. if sData.refCnt == 0 {
  352. sData.sandbox.Destroy()
  353. delete(c.sandboxes, key)
  354. }
  355. }
  356. func (c *controller) sandboxGet(key string) sandbox.Sandbox {
  357. c.Lock()
  358. defer c.Unlock()
  359. sData, ok := c.sandboxes[key]
  360. if !ok {
  361. return nil
  362. }
  363. return sData.sandbox
  364. }
  365. func (c *controller) loadDriver(networkType string) (driverapi.Driver, error) {
  366. // Plugins pkg performs lazy loading of plugins that acts as remote drivers.
  367. // As per the design, this Get call will result in remote driver discovery if there is a corresponding plugin available.
  368. _, err := plugins.Get(networkType, driverapi.NetworkPluginEndpointType)
  369. if err != nil {
  370. if err == plugins.ErrNotFound {
  371. return nil, types.NotFoundErrorf(err.Error())
  372. }
  373. return nil, err
  374. }
  375. c.Lock()
  376. defer c.Unlock()
  377. d, ok := c.drivers[networkType]
  378. if !ok {
  379. return nil, ErrInvalidNetworkDriver(networkType)
  380. }
  381. return d, nil
  382. }