network.go 25 KB

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