network.go 27 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166
  1. package libnetwork
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net"
  6. "strconv"
  7. "strings"
  8. "sync"
  9. log "github.com/Sirupsen/logrus"
  10. "github.com/docker/docker/pkg/stringid"
  11. "github.com/docker/libnetwork/config"
  12. "github.com/docker/libnetwork/datastore"
  13. "github.com/docker/libnetwork/driverapi"
  14. "github.com/docker/libnetwork/etchosts"
  15. "github.com/docker/libnetwork/ipamapi"
  16. "github.com/docker/libnetwork/netlabel"
  17. "github.com/docker/libnetwork/netutils"
  18. "github.com/docker/libnetwork/options"
  19. "github.com/docker/libnetwork/types"
  20. )
  21. // A Network represents a logical connectivity zone that containers may
  22. // join using the Link method. A Network is managed by a specific driver.
  23. type Network interface {
  24. // A user chosen name for this network.
  25. Name() string
  26. // A system generated id for this network.
  27. ID() string
  28. // The type of network, which corresponds to its managing driver.
  29. Type() string
  30. // Create a new endpoint to this network symbolically identified by the
  31. // specified unique name. The options parameter carry driver specific options.
  32. CreateEndpoint(name string, options ...EndpointOption) (Endpoint, error)
  33. // Delete the network.
  34. Delete() error
  35. // Endpoints returns the list of Endpoint(s) in this network.
  36. Endpoints() []Endpoint
  37. // WalkEndpoints uses the provided function to walk the Endpoints
  38. WalkEndpoints(walker EndpointWalker)
  39. // EndpointByName returns the Endpoint which has the passed name. If not found, the error ErrNoSuchEndpoint is returned.
  40. EndpointByName(name string) (Endpoint, error)
  41. // EndpointByID returns the Endpoint which has the passed id. If not found, the error ErrNoSuchEndpoint is returned.
  42. EndpointByID(id string) (Endpoint, error)
  43. // Return certain operational data belonging to this network
  44. Info() NetworkInfo
  45. }
  46. // NetworkInfo returns some configuration and operational information about the network
  47. type NetworkInfo interface {
  48. IpamConfig() (string, []*IpamConf, []*IpamConf)
  49. DriverOptions() map[string]string
  50. Scope() string
  51. }
  52. // EndpointWalker is a client provided function which will be used to walk the Endpoints.
  53. // When the function returns true, the walk will stop.
  54. type EndpointWalker func(ep Endpoint) bool
  55. type svcMap map[string]net.IP
  56. // IpamConf contains all the ipam related configurations for a network
  57. type IpamConf struct {
  58. // The master address pool for containers and network interfaces
  59. PreferredPool string
  60. // A subset of the master pool. If specified,
  61. // this becomes the container pool
  62. SubPool string
  63. // Input options for IPAM Driver (optional)
  64. Options map[string]string
  65. // Preferred Network Gateway address (optional)
  66. Gateway string
  67. // Auxiliary addresses for network driver. Must be within the master pool.
  68. // libnetwork will reserve them if they fall into the container pool
  69. AuxAddresses map[string]string
  70. }
  71. // Validate checks whether the configuration is valid
  72. func (c *IpamConf) Validate() error {
  73. if c.Gateway != "" && nil == net.ParseIP(c.Gateway) {
  74. return types.BadRequestErrorf("invalid gateway address %s in Ipam configuration", c.Gateway)
  75. }
  76. return nil
  77. }
  78. // IpamInfo contains all the ipam related operational info for a network
  79. type IpamInfo struct {
  80. PoolID string
  81. Meta map[string]string
  82. driverapi.IPAMData
  83. }
  84. // MarshalJSON encodes IpamInfo into json message
  85. func (i *IpamInfo) MarshalJSON() ([]byte, error) {
  86. m := map[string]interface{}{
  87. "PoolID": i.PoolID,
  88. }
  89. v, err := json.Marshal(&i.IPAMData)
  90. if err != nil {
  91. return nil, err
  92. }
  93. m["IPAMData"] = string(v)
  94. if i.Meta != nil {
  95. m["Meta"] = i.Meta
  96. }
  97. return json.Marshal(m)
  98. }
  99. // UnmarshalJSON decodes json message into PoolData
  100. func (i *IpamInfo) UnmarshalJSON(data []byte) error {
  101. var (
  102. m map[string]interface{}
  103. err error
  104. )
  105. if err = json.Unmarshal(data, &m); err != nil {
  106. return err
  107. }
  108. i.PoolID = m["PoolID"].(string)
  109. if v, ok := m["Meta"]; ok {
  110. b, _ := json.Marshal(v)
  111. if err = json.Unmarshal(b, &i.Meta); err != nil {
  112. return err
  113. }
  114. }
  115. if v, ok := m["IPAMData"]; ok {
  116. if err = json.Unmarshal([]byte(v.(string)), &i.IPAMData); err != nil {
  117. return err
  118. }
  119. }
  120. return nil
  121. }
  122. type network struct {
  123. ctrlr *controller
  124. name string
  125. networkType string
  126. id string
  127. ipamType string
  128. addrSpace string
  129. ipamV4Config []*IpamConf
  130. ipamV6Config []*IpamConf
  131. ipamV4Info []*IpamInfo
  132. ipamV6Info []*IpamInfo
  133. enableIPv6 bool
  134. postIPv6 bool
  135. epCnt *endpointCnt
  136. generic options.Generic
  137. dbIndex uint64
  138. svcRecords svcMap
  139. dbExists bool
  140. persist bool
  141. stopWatchCh chan struct{}
  142. drvOnce *sync.Once
  143. sync.Mutex
  144. }
  145. func (n *network) Name() string {
  146. n.Lock()
  147. defer n.Unlock()
  148. return n.name
  149. }
  150. func (n *network) ID() string {
  151. n.Lock()
  152. defer n.Unlock()
  153. return n.id
  154. }
  155. func (n *network) Type() string {
  156. n.Lock()
  157. defer n.Unlock()
  158. return n.networkType
  159. }
  160. func (n *network) Key() []string {
  161. n.Lock()
  162. defer n.Unlock()
  163. return []string{datastore.NetworkKeyPrefix, n.id}
  164. }
  165. func (n *network) KeyPrefix() []string {
  166. return []string{datastore.NetworkKeyPrefix}
  167. }
  168. func (n *network) Value() []byte {
  169. n.Lock()
  170. defer n.Unlock()
  171. b, err := json.Marshal(n)
  172. if err != nil {
  173. return nil
  174. }
  175. return b
  176. }
  177. func (n *network) SetValue(value []byte) error {
  178. return json.Unmarshal(value, n)
  179. }
  180. func (n *network) Index() uint64 {
  181. n.Lock()
  182. defer n.Unlock()
  183. return n.dbIndex
  184. }
  185. func (n *network) SetIndex(index uint64) {
  186. n.Lock()
  187. n.dbIndex = index
  188. n.dbExists = true
  189. n.Unlock()
  190. }
  191. func (n *network) Exists() bool {
  192. n.Lock()
  193. defer n.Unlock()
  194. return n.dbExists
  195. }
  196. func (n *network) Skip() bool {
  197. n.Lock()
  198. defer n.Unlock()
  199. return !n.persist
  200. }
  201. func (n *network) New() datastore.KVObject {
  202. n.Lock()
  203. defer n.Unlock()
  204. return &network{
  205. ctrlr: n.ctrlr,
  206. drvOnce: &sync.Once{},
  207. }
  208. }
  209. // CopyTo deep copies to the destination IpamConfig
  210. func (c *IpamConf) CopyTo(dstC *IpamConf) error {
  211. dstC.PreferredPool = c.PreferredPool
  212. dstC.SubPool = c.SubPool
  213. dstC.Gateway = c.Gateway
  214. if c.Options != nil {
  215. dstC.Options = make(map[string]string, len(c.Options))
  216. for k, v := range c.Options {
  217. dstC.Options[k] = v
  218. }
  219. }
  220. if c.AuxAddresses != nil {
  221. dstC.AuxAddresses = make(map[string]string, len(c.AuxAddresses))
  222. for k, v := range c.AuxAddresses {
  223. dstC.AuxAddresses[k] = v
  224. }
  225. }
  226. return nil
  227. }
  228. // CopyTo deep copies to the destination IpamInfo
  229. func (i *IpamInfo) CopyTo(dstI *IpamInfo) error {
  230. dstI.PoolID = i.PoolID
  231. if i.Meta != nil {
  232. dstI.Meta = make(map[string]string)
  233. for k, v := range i.Meta {
  234. dstI.Meta[k] = v
  235. }
  236. }
  237. dstI.AddressSpace = i.AddressSpace
  238. dstI.Pool = types.GetIPNetCopy(i.Pool)
  239. dstI.Gateway = types.GetIPNetCopy(i.Gateway)
  240. if i.AuxAddresses != nil {
  241. dstI.AuxAddresses = make(map[string]*net.IPNet)
  242. for k, v := range i.AuxAddresses {
  243. dstI.AuxAddresses[k] = types.GetIPNetCopy(v)
  244. }
  245. }
  246. return nil
  247. }
  248. func (n *network) CopyTo(o datastore.KVObject) error {
  249. n.Lock()
  250. defer n.Unlock()
  251. dstN := o.(*network)
  252. dstN.name = n.name
  253. dstN.id = n.id
  254. dstN.networkType = n.networkType
  255. dstN.ipamType = n.ipamType
  256. dstN.enableIPv6 = n.enableIPv6
  257. dstN.persist = n.persist
  258. dstN.postIPv6 = n.postIPv6
  259. dstN.dbIndex = n.dbIndex
  260. dstN.dbExists = n.dbExists
  261. dstN.drvOnce = n.drvOnce
  262. for _, v4conf := range n.ipamV4Config {
  263. dstV4Conf := &IpamConf{}
  264. v4conf.CopyTo(dstV4Conf)
  265. dstN.ipamV4Config = append(dstN.ipamV4Config, dstV4Conf)
  266. }
  267. for _, v4info := range n.ipamV4Info {
  268. dstV4Info := &IpamInfo{}
  269. v4info.CopyTo(dstV4Info)
  270. dstN.ipamV4Info = append(dstN.ipamV4Info, dstV4Info)
  271. }
  272. for _, v6conf := range n.ipamV6Config {
  273. dstV6Conf := &IpamConf{}
  274. v6conf.CopyTo(dstV6Conf)
  275. dstN.ipamV6Config = append(dstN.ipamV6Config, dstV6Conf)
  276. }
  277. for _, v6info := range n.ipamV6Info {
  278. dstV6Info := &IpamInfo{}
  279. v6info.CopyTo(dstV6Info)
  280. dstN.ipamV6Info = append(dstN.ipamV6Info, dstV6Info)
  281. }
  282. dstN.generic = options.Generic{}
  283. for k, v := range n.generic {
  284. dstN.generic[k] = v
  285. }
  286. return nil
  287. }
  288. func (n *network) DataScope() string {
  289. return n.driverScope()
  290. }
  291. func (n *network) getEpCnt() *endpointCnt {
  292. n.Lock()
  293. defer n.Unlock()
  294. return n.epCnt
  295. }
  296. // TODO : Can be made much more generic with the help of reflection (but has some golang limitations)
  297. func (n *network) MarshalJSON() ([]byte, error) {
  298. netMap := make(map[string]interface{})
  299. netMap["name"] = n.name
  300. netMap["id"] = n.id
  301. netMap["networkType"] = n.networkType
  302. netMap["ipamType"] = n.ipamType
  303. netMap["addrSpace"] = n.addrSpace
  304. netMap["enableIPv6"] = n.enableIPv6
  305. if n.generic != nil {
  306. netMap["generic"] = n.generic
  307. }
  308. netMap["persist"] = n.persist
  309. netMap["postIPv6"] = n.postIPv6
  310. if len(n.ipamV4Config) > 0 {
  311. ics, err := json.Marshal(n.ipamV4Config)
  312. if err != nil {
  313. return nil, err
  314. }
  315. netMap["ipamV4Config"] = string(ics)
  316. }
  317. if len(n.ipamV4Info) > 0 {
  318. iis, err := json.Marshal(n.ipamV4Info)
  319. if err != nil {
  320. return nil, err
  321. }
  322. netMap["ipamV4Info"] = string(iis)
  323. }
  324. if len(n.ipamV6Config) > 0 {
  325. ics, err := json.Marshal(n.ipamV6Config)
  326. if err != nil {
  327. return nil, err
  328. }
  329. netMap["ipamV6Config"] = string(ics)
  330. }
  331. if len(n.ipamV6Info) > 0 {
  332. iis, err := json.Marshal(n.ipamV6Info)
  333. if err != nil {
  334. return nil, err
  335. }
  336. netMap["ipamV6Info"] = string(iis)
  337. }
  338. return json.Marshal(netMap)
  339. }
  340. // TODO : Can be made much more generic with the help of reflection (but has some golang limitations)
  341. func (n *network) UnmarshalJSON(b []byte) (err error) {
  342. var netMap map[string]interface{}
  343. if err := json.Unmarshal(b, &netMap); err != nil {
  344. return err
  345. }
  346. n.name = netMap["name"].(string)
  347. n.id = netMap["id"].(string)
  348. n.networkType = netMap["networkType"].(string)
  349. n.enableIPv6 = netMap["enableIPv6"].(bool)
  350. if v, ok := netMap["generic"]; ok {
  351. n.generic = v.(map[string]interface{})
  352. // Restore opts in their map[string]string form
  353. if v, ok := n.generic[netlabel.GenericData]; ok {
  354. var lmap map[string]string
  355. ba, err := json.Marshal(v)
  356. if err != nil {
  357. return err
  358. }
  359. if err := json.Unmarshal(ba, &lmap); err != nil {
  360. return err
  361. }
  362. n.generic[netlabel.GenericData] = lmap
  363. }
  364. }
  365. if v, ok := netMap["persist"]; ok {
  366. n.persist = v.(bool)
  367. }
  368. if v, ok := netMap["postIPv6"]; ok {
  369. n.postIPv6 = v.(bool)
  370. }
  371. if v, ok := netMap["ipamType"]; ok {
  372. n.ipamType = v.(string)
  373. } else {
  374. n.ipamType = ipamapi.DefaultIPAM
  375. }
  376. if v, ok := netMap["addrSpace"]; ok {
  377. n.addrSpace = v.(string)
  378. }
  379. if v, ok := netMap["ipamV4Config"]; ok {
  380. if err := json.Unmarshal([]byte(v.(string)), &n.ipamV4Config); err != nil {
  381. return err
  382. }
  383. }
  384. if v, ok := netMap["ipamV4Info"]; ok {
  385. if err := json.Unmarshal([]byte(v.(string)), &n.ipamV4Info); err != nil {
  386. return err
  387. }
  388. }
  389. if v, ok := netMap["ipamV6Config"]; ok {
  390. if err := json.Unmarshal([]byte(v.(string)), &n.ipamV6Config); err != nil {
  391. return err
  392. }
  393. }
  394. if v, ok := netMap["ipamV6Info"]; ok {
  395. if err := json.Unmarshal([]byte(v.(string)), &n.ipamV6Info); err != nil {
  396. return err
  397. }
  398. }
  399. return nil
  400. }
  401. // NetworkOption is a option setter function type used to pass varios options to
  402. // NewNetwork method. The various setter functions of type NetworkOption are
  403. // provided by libnetwork, they look like NetworkOptionXXXX(...)
  404. type NetworkOption func(n *network)
  405. // NetworkOptionGeneric function returns an option setter for a Generic option defined
  406. // in a Dictionary of Key-Value pair
  407. func NetworkOptionGeneric(generic map[string]interface{}) NetworkOption {
  408. return func(n *network) {
  409. n.generic = generic
  410. if _, ok := generic[netlabel.EnableIPv6]; ok {
  411. n.enableIPv6 = generic[netlabel.EnableIPv6].(bool)
  412. }
  413. }
  414. }
  415. // NetworkOptionPersist returns an option setter to set persistence policy for a network
  416. func NetworkOptionPersist(persist bool) NetworkOption {
  417. return func(n *network) {
  418. n.persist = persist
  419. }
  420. }
  421. // NetworkOptionIpam function returns an option setter for the ipam configuration for this network
  422. func NetworkOptionIpam(ipamDriver string, addrSpace string, ipV4 []*IpamConf, ipV6 []*IpamConf) NetworkOption {
  423. return func(n *network) {
  424. if ipamDriver != "" {
  425. n.ipamType = ipamDriver
  426. }
  427. n.addrSpace = addrSpace
  428. n.ipamV4Config = ipV4
  429. n.ipamV6Config = ipV6
  430. }
  431. }
  432. // NetworkOptionDriverOpts function returns an option setter for any parameter described by a map
  433. func NetworkOptionDriverOpts(opts map[string]string) NetworkOption {
  434. return func(n *network) {
  435. if n.generic == nil {
  436. n.generic = make(map[string]interface{})
  437. }
  438. if opts == nil {
  439. opts = make(map[string]string)
  440. }
  441. // Store the options
  442. n.generic[netlabel.GenericData] = opts
  443. // Decode and store the endpoint options of libnetwork interest
  444. if val, ok := opts[netlabel.EnableIPv6]; ok {
  445. var err error
  446. if n.enableIPv6, err = strconv.ParseBool(val); err != nil {
  447. log.Warnf("Failed to parse %s' value: %s (%s)", netlabel.EnableIPv6, val, err.Error())
  448. }
  449. }
  450. }
  451. }
  452. // NetworkOptionDeferIPv6Alloc instructs the network to defer the IPV6 address allocation until after the endpoint has been created
  453. // It is being provided to support the specific docker daemon flags where user can deterministically assign an IPv6 address
  454. // to a container as combination of fixed-cidr-v6 + mac-address
  455. // TODO: Remove this option setter once we support endpoint ipam options
  456. func NetworkOptionDeferIPv6Alloc(enable bool) NetworkOption {
  457. return func(n *network) {
  458. n.postIPv6 = enable
  459. }
  460. }
  461. func (n *network) processOptions(options ...NetworkOption) {
  462. for _, opt := range options {
  463. if opt != nil {
  464. opt(n)
  465. }
  466. }
  467. }
  468. func (n *network) driverScope() string {
  469. c := n.getController()
  470. c.Lock()
  471. // Check if a driver for the specified network type is available
  472. dd, ok := c.drivers[n.networkType]
  473. c.Unlock()
  474. if !ok {
  475. var err error
  476. dd, err = c.loadDriver(n.networkType)
  477. if err != nil {
  478. // If driver could not be resolved simply return an empty string
  479. return ""
  480. }
  481. }
  482. return dd.capability.DataScope
  483. }
  484. func (n *network) driver() (driverapi.Driver, error) {
  485. c := n.getController()
  486. c.Lock()
  487. // Check if a driver for the specified network type is available
  488. dd, ok := c.drivers[n.networkType]
  489. c.Unlock()
  490. if !ok {
  491. var err error
  492. dd, err = c.loadDriver(n.networkType)
  493. if err != nil {
  494. return nil, err
  495. }
  496. }
  497. return dd.driver, nil
  498. }
  499. func (n *network) Delete() error {
  500. n.Lock()
  501. c := n.ctrlr
  502. name := n.name
  503. id := n.id
  504. n.Unlock()
  505. n, err := c.getNetworkFromStore(id)
  506. if err != nil {
  507. return &UnknownNetworkError{name: name, id: id}
  508. }
  509. numEps := n.getEpCnt().EndpointCnt()
  510. if numEps != 0 {
  511. return &ActiveEndpointsError{name: n.name, id: n.id}
  512. }
  513. if err = n.deleteNetwork(); err != nil {
  514. return err
  515. }
  516. defer func() {
  517. if err != nil {
  518. if e := c.addNetwork(n); e != nil {
  519. log.Warnf("failed to rollback deleteNetwork for network %s: %v",
  520. n.Name(), err)
  521. }
  522. }
  523. }()
  524. // deleteFromStore performs an atomic delete operation and the
  525. // network.epCnt will help prevent any possible
  526. // race between endpoint join and network delete
  527. if err = n.getController().deleteFromStore(n.getEpCnt()); err != nil {
  528. return fmt.Errorf("error deleting network endpoint count from store: %v", err)
  529. }
  530. n.ipamRelease()
  531. if err = n.getController().deleteFromStore(n); err != nil {
  532. return fmt.Errorf("error deleting network from store: %v", err)
  533. }
  534. return nil
  535. }
  536. func (n *network) deleteNetwork() error {
  537. d, err := n.driver()
  538. if err != nil {
  539. return fmt.Errorf("failed deleting network: %v", err)
  540. }
  541. if err := d.DeleteNetwork(n.ID()); err != nil {
  542. // Forbidden Errors should be honored
  543. if _, ok := err.(types.ForbiddenError); ok {
  544. return err
  545. }
  546. if _, ok := err.(types.MaskableError); !ok {
  547. log.Warnf("driver error deleting network %s : %v", n.name, err)
  548. }
  549. }
  550. return nil
  551. }
  552. func (n *network) addEndpoint(ep *endpoint) error {
  553. d, err := n.driver()
  554. if err != nil {
  555. return fmt.Errorf("failed to add endpoint: %v", err)
  556. }
  557. err = d.CreateEndpoint(n.id, ep.id, ep.Interface(), ep.generic)
  558. if err != nil {
  559. return types.InternalErrorf("failed to create endpoint %s on network %s: %v",
  560. ep.Name(), n.Name(), err)
  561. }
  562. return nil
  563. }
  564. func (n *network) CreateEndpoint(name string, options ...EndpointOption) (Endpoint, error) {
  565. var err error
  566. if !config.IsValidName(name) {
  567. return nil, ErrInvalidName(name)
  568. }
  569. if _, err = n.EndpointByName(name); err == nil {
  570. return nil, types.ForbiddenErrorf("service endpoint with name %s already exists", name)
  571. }
  572. ep := &endpoint{name: name, generic: make(map[string]interface{}), iface: &endpointInterface{}}
  573. ep.id = stringid.GenerateRandomID()
  574. // Initialize ep.network with a possibly stale copy of n. We need this to get network from
  575. // store. But once we get it from store we will have the most uptodate copy possible.
  576. ep.network = n
  577. ep.network, err = ep.getNetworkFromStore()
  578. if err != nil {
  579. return nil, fmt.Errorf("failed to get network during CreateEndpoint: %v", err)
  580. }
  581. n = ep.network
  582. ep.processOptions(options...)
  583. if opt, ok := ep.generic[netlabel.MacAddress]; ok {
  584. if mac, ok := opt.(net.HardwareAddr); ok {
  585. ep.iface.mac = mac
  586. }
  587. }
  588. ipam, err := n.getController().getIPAM(n.ipamType)
  589. if err != nil {
  590. return nil, err
  591. }
  592. if ipam.capability.RequiresMACAddress {
  593. if ep.iface.mac == nil {
  594. ep.iface.mac = netutils.GenerateRandomMAC()
  595. }
  596. if ep.ipamOptions == nil {
  597. ep.ipamOptions = make(map[string]string)
  598. }
  599. ep.ipamOptions[netlabel.MacAddress] = ep.iface.mac.String()
  600. }
  601. if err = ep.assignAddress(ipam.driver, true, !n.postIPv6); err != nil {
  602. return nil, err
  603. }
  604. defer func() {
  605. if err != nil {
  606. ep.releaseAddress()
  607. }
  608. }()
  609. if err = n.addEndpoint(ep); err != nil {
  610. return nil, err
  611. }
  612. defer func() {
  613. if err != nil {
  614. if e := ep.deleteEndpoint(); e != nil {
  615. log.Warnf("cleaning up endpoint failed %s : %v", name, e)
  616. }
  617. }
  618. }()
  619. if err = ep.assignAddress(ipam.driver, false, n.postIPv6); err != nil {
  620. return nil, err
  621. }
  622. if err = n.getController().updateToStore(ep); err != nil {
  623. return nil, err
  624. }
  625. defer func() {
  626. if err != nil {
  627. if e := n.getController().deleteFromStore(ep); e != nil {
  628. log.Warnf("error rolling back endpoint %s from store: %v", name, e)
  629. }
  630. }
  631. }()
  632. // Watch for service records
  633. n.getController().watchSvcRecord(ep)
  634. defer func() {
  635. if err != nil {
  636. n.getController().unWatchSvcRecord(ep)
  637. }
  638. }()
  639. // Increment endpoint count to indicate completion of endpoint addition
  640. if err = n.getEpCnt().IncEndpointCnt(); err != nil {
  641. return nil, err
  642. }
  643. return ep, nil
  644. }
  645. func (n *network) Endpoints() []Endpoint {
  646. var list []Endpoint
  647. endpoints, err := n.getEndpointsFromStore()
  648. if err != nil {
  649. log.Error(err)
  650. }
  651. for _, ep := range endpoints {
  652. list = append(list, ep)
  653. }
  654. return list
  655. }
  656. func (n *network) WalkEndpoints(walker EndpointWalker) {
  657. for _, e := range n.Endpoints() {
  658. if walker(e) {
  659. return
  660. }
  661. }
  662. }
  663. func (n *network) EndpointByName(name string) (Endpoint, error) {
  664. if name == "" {
  665. return nil, ErrInvalidName(name)
  666. }
  667. var e Endpoint
  668. s := func(current Endpoint) bool {
  669. if current.Name() == name {
  670. e = current
  671. return true
  672. }
  673. return false
  674. }
  675. n.WalkEndpoints(s)
  676. if e == nil {
  677. return nil, ErrNoSuchEndpoint(name)
  678. }
  679. return e, nil
  680. }
  681. func (n *network) EndpointByID(id string) (Endpoint, error) {
  682. if id == "" {
  683. return nil, ErrInvalidID(id)
  684. }
  685. ep, err := n.getEndpointFromStore(id)
  686. if err != nil {
  687. return nil, ErrNoSuchEndpoint(id)
  688. }
  689. return ep, nil
  690. }
  691. func (n *network) updateSvcRecord(ep *endpoint, localEps []*endpoint, isAdd bool) {
  692. if ep.isAnonymous() {
  693. return
  694. }
  695. c := n.getController()
  696. sr, ok := c.svcDb[n.ID()]
  697. if !ok {
  698. c.svcDb[n.ID()] = svcMap{}
  699. sr = c.svcDb[n.ID()]
  700. }
  701. n.Lock()
  702. var recs []etchosts.Record
  703. if iface := ep.Iface(); iface.Address() != nil {
  704. if isAdd {
  705. // If we already have this endpoint in service db just return
  706. if _, ok := sr[ep.Name()]; ok {
  707. n.Unlock()
  708. return
  709. }
  710. sr[ep.Name()] = iface.Address().IP
  711. sr[ep.Name()+"."+n.name] = iface.Address().IP
  712. } else {
  713. delete(sr, ep.Name())
  714. delete(sr, ep.Name()+"."+n.name)
  715. }
  716. recs = append(recs, etchosts.Record{
  717. Hosts: ep.Name(),
  718. IP: iface.Address().IP.String(),
  719. })
  720. recs = append(recs, etchosts.Record{
  721. Hosts: ep.Name() + "." + n.name,
  722. IP: iface.Address().IP.String(),
  723. })
  724. }
  725. n.Unlock()
  726. // If there are no records to add or delete then simply return here
  727. if len(recs) == 0 {
  728. return
  729. }
  730. var sbList []*sandbox
  731. for _, lEp := range localEps {
  732. if ep.ID() == lEp.ID() {
  733. continue
  734. }
  735. if sb, hasSandbox := lEp.getSandbox(); hasSandbox {
  736. sbList = append(sbList, sb)
  737. }
  738. }
  739. for _, sb := range sbList {
  740. if isAdd {
  741. sb.addHostsEntries(recs)
  742. } else {
  743. sb.deleteHostsEntries(recs)
  744. }
  745. }
  746. }
  747. func (n *network) getSvcRecords(ep *endpoint) []etchosts.Record {
  748. n.Lock()
  749. defer n.Unlock()
  750. var recs []etchosts.Record
  751. sr, _ := n.ctrlr.svcDb[n.id]
  752. for h, ip := range sr {
  753. if ep != nil && strings.Split(h, ".")[0] == ep.Name() {
  754. continue
  755. }
  756. recs = append(recs, etchosts.Record{
  757. Hosts: h,
  758. IP: ip.String(),
  759. })
  760. }
  761. return recs
  762. }
  763. func (n *network) getController() *controller {
  764. n.Lock()
  765. defer n.Unlock()
  766. return n.ctrlr
  767. }
  768. func (n *network) ipamAllocate() error {
  769. // For now also exclude bridge from using new ipam
  770. if n.Type() == "host" || n.Type() == "null" {
  771. return nil
  772. }
  773. ipam, err := n.getController().getIpamDriver(n.ipamType)
  774. if err != nil {
  775. return err
  776. }
  777. if n.addrSpace == "" {
  778. if n.addrSpace, err = n.deriveAddressSpace(); err != nil {
  779. return err
  780. }
  781. }
  782. err = n.ipamAllocateVersion(4, ipam)
  783. if err != nil {
  784. return err
  785. }
  786. defer func() {
  787. if err != nil {
  788. n.ipamReleaseVersion(4, ipam)
  789. }
  790. }()
  791. return n.ipamAllocateVersion(6, ipam)
  792. }
  793. func (n *network) ipamAllocateVersion(ipVer int, ipam ipamapi.Ipam) error {
  794. var (
  795. cfgList *[]*IpamConf
  796. infoList *[]*IpamInfo
  797. err error
  798. )
  799. switch ipVer {
  800. case 4:
  801. cfgList = &n.ipamV4Config
  802. infoList = &n.ipamV4Info
  803. case 6:
  804. cfgList = &n.ipamV6Config
  805. infoList = &n.ipamV6Info
  806. default:
  807. return types.InternalErrorf("incorrect ip version passed to ipam allocate: %d", ipVer)
  808. }
  809. if len(*cfgList) == 0 {
  810. if ipVer == 6 {
  811. return nil
  812. }
  813. *cfgList = []*IpamConf{&IpamConf{}}
  814. }
  815. *infoList = make([]*IpamInfo, len(*cfgList))
  816. log.Debugf("Allocating IPv%d pools for network %s (%s)", ipVer, n.Name(), n.ID())
  817. for i, cfg := range *cfgList {
  818. if err = cfg.Validate(); err != nil {
  819. return err
  820. }
  821. d := &IpamInfo{}
  822. (*infoList)[i] = d
  823. d.PoolID, d.Pool, d.Meta, err = ipam.RequestPool(n.addrSpace, cfg.PreferredPool, cfg.SubPool, cfg.Options, ipVer == 6)
  824. if err != nil {
  825. return err
  826. }
  827. defer func() {
  828. if err != nil {
  829. if err := ipam.ReleasePool(d.PoolID); err != nil {
  830. log.Warnf("Failed to release address pool %s after failure to create network %s (%s)", d.PoolID, n.Name(), n.ID())
  831. }
  832. }
  833. }()
  834. if gws, ok := d.Meta[netlabel.Gateway]; ok {
  835. if d.Gateway, err = types.ParseCIDR(gws); err != nil {
  836. return types.BadRequestErrorf("failed to parse gateway address (%v) returned by ipam driver: %v", gws, err)
  837. }
  838. }
  839. // If user requested a specific gateway, libnetwork will allocate it
  840. // irrespective of whether ipam driver returned a gateway already.
  841. // If none of the above is true, libnetwork will allocate one.
  842. if cfg.Gateway != "" || d.Gateway == nil {
  843. var gatewayOpts = map[string]string{
  844. ipamapi.RequestAddressType: netlabel.Gateway,
  845. }
  846. if d.Gateway, _, err = ipam.RequestAddress(d.PoolID, net.ParseIP(cfg.Gateway), gatewayOpts); err != nil {
  847. return types.InternalErrorf("failed to allocate gateway (%v): %v", cfg.Gateway, err)
  848. }
  849. }
  850. // Auxiliary addresses must be part of the master address pool
  851. // If they fall into the container addressable pool, libnetwork will reserve them
  852. if cfg.AuxAddresses != nil {
  853. var ip net.IP
  854. d.IPAMData.AuxAddresses = make(map[string]*net.IPNet, len(cfg.AuxAddresses))
  855. for k, v := range cfg.AuxAddresses {
  856. if ip = net.ParseIP(v); ip == nil {
  857. return types.BadRequestErrorf("non parsable secondary ip address (%s:%s) passed for network %s", k, v, n.Name())
  858. }
  859. if !d.Pool.Contains(ip) {
  860. return types.ForbiddenErrorf("auxilairy address: (%s:%s) must belong to the master pool: %s", k, v, d.Pool)
  861. }
  862. // Attempt reservation in the container addressable pool, silent the error if address does not belong to that pool
  863. if d.IPAMData.AuxAddresses[k], _, err = ipam.RequestAddress(d.PoolID, ip, nil); err != nil && err != ipamapi.ErrIPOutOfRange {
  864. return types.InternalErrorf("failed to allocate secondary ip address (%s:%s): %v", k, v, err)
  865. }
  866. }
  867. }
  868. }
  869. return nil
  870. }
  871. func (n *network) ipamRelease() {
  872. // For now exclude host and null
  873. if n.Type() == "host" || n.Type() == "null" {
  874. return
  875. }
  876. ipam, err := n.getController().getIpamDriver(n.ipamType)
  877. if err != nil {
  878. log.Warnf("Failed to retrieve ipam driver to release address pool(s) on delete of network %s (%s): %v", n.Name(), n.ID(), err)
  879. return
  880. }
  881. n.ipamReleaseVersion(4, ipam)
  882. n.ipamReleaseVersion(6, ipam)
  883. }
  884. func (n *network) ipamReleaseVersion(ipVer int, ipam ipamapi.Ipam) {
  885. var infoList []*IpamInfo
  886. switch ipVer {
  887. case 4:
  888. infoList = n.ipamV4Info
  889. case 6:
  890. infoList = n.ipamV6Info
  891. default:
  892. log.Warnf("incorrect ip version passed to ipam release: %d", ipVer)
  893. return
  894. }
  895. if infoList == nil {
  896. return
  897. }
  898. log.Debugf("releasing IPv%d pools from network %s (%s)", ipVer, n.Name(), n.ID())
  899. for _, d := range infoList {
  900. if d.Gateway != nil {
  901. if err := ipam.ReleaseAddress(d.PoolID, d.Gateway.IP); err != nil {
  902. log.Warnf("Failed to release gateway ip address %s on delete of network %s (%s): %v", d.Gateway.IP, n.Name(), n.ID(), err)
  903. }
  904. }
  905. if d.IPAMData.AuxAddresses != nil {
  906. for k, nw := range d.IPAMData.AuxAddresses {
  907. if d.Pool.Contains(nw.IP) {
  908. if err := ipam.ReleaseAddress(d.PoolID, nw.IP); err != nil && err != ipamapi.ErrIPOutOfRange {
  909. log.Warnf("Failed to release secondary ip address %s (%v) on delete of network %s (%s): %v", k, nw.IP, n.Name(), n.ID(), err)
  910. }
  911. }
  912. }
  913. }
  914. if err := ipam.ReleasePool(d.PoolID); err != nil {
  915. log.Warnf("Failed to release address pool %s on delete of network %s (%s): %v", d.PoolID, n.Name(), n.ID(), err)
  916. }
  917. }
  918. }
  919. func (n *network) getIPInfo(ipVer int) []*IpamInfo {
  920. var info []*IpamInfo
  921. switch ipVer {
  922. case 4:
  923. info = n.ipamV4Info
  924. case 6:
  925. info = n.ipamV6Info
  926. default:
  927. return nil
  928. }
  929. l := make([]*IpamInfo, 0, len(info))
  930. n.Lock()
  931. for _, d := range info {
  932. l = append(l, d)
  933. }
  934. n.Unlock()
  935. return l
  936. }
  937. func (n *network) getIPData(ipVer int) []driverapi.IPAMData {
  938. var info []*IpamInfo
  939. switch ipVer {
  940. case 4:
  941. info = n.ipamV4Info
  942. case 6:
  943. info = n.ipamV6Info
  944. default:
  945. return nil
  946. }
  947. l := make([]driverapi.IPAMData, 0, len(info))
  948. n.Lock()
  949. for _, d := range info {
  950. l = append(l, d.IPAMData)
  951. }
  952. n.Unlock()
  953. return l
  954. }
  955. func (n *network) deriveAddressSpace() (string, error) {
  956. c := n.getController()
  957. c.Lock()
  958. ipd, ok := c.ipamDrivers[n.ipamType]
  959. c.Unlock()
  960. if !ok {
  961. return "", types.NotFoundErrorf("could not find ipam driver %s to get default address space", n.ipamType)
  962. }
  963. if n.DataScope() == datastore.GlobalScope {
  964. return ipd.defaultGlobalAddressSpace, nil
  965. }
  966. return ipd.defaultLocalAddressSpace, nil
  967. }
  968. func (n *network) Info() NetworkInfo {
  969. return n
  970. }
  971. func (n *network) DriverOptions() map[string]string {
  972. n.Lock()
  973. defer n.Unlock()
  974. if n.generic != nil {
  975. if m, ok := n.generic[netlabel.GenericData]; ok {
  976. return m.(map[string]string)
  977. }
  978. }
  979. return map[string]string{}
  980. }
  981. func (n *network) Scope() string {
  982. return n.driverScope()
  983. }
  984. func (n *network) IpamConfig() (string, []*IpamConf, []*IpamConf) {
  985. n.Lock()
  986. defer n.Unlock()
  987. v4L := make([]*IpamConf, len(n.ipamV4Config))
  988. v6L := make([]*IpamConf, len(n.ipamV6Config))
  989. for i, c := range n.ipamV4Config {
  990. cc := &IpamConf{}
  991. c.CopyTo(cc)
  992. v4L[i] = cc
  993. }
  994. for i, c := range n.ipamV6Config {
  995. cc := &IpamConf{}
  996. c.CopyTo(cc)
  997. v6L[i] = cc
  998. }
  999. return n.ipamType, v4L, v6L
  1000. }