endpoint.go 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217
  1. package libnetwork
  2. import (
  3. "container/heap"
  4. "encoding/json"
  5. "fmt"
  6. "net"
  7. "strings"
  8. "sync"
  9. "github.com/docker/libnetwork/datastore"
  10. "github.com/docker/libnetwork/ipamapi"
  11. "github.com/docker/libnetwork/netlabel"
  12. "github.com/docker/libnetwork/options"
  13. "github.com/docker/libnetwork/types"
  14. "github.com/sirupsen/logrus"
  15. )
  16. // Endpoint represents a logical connection between a network and a sandbox.
  17. type Endpoint interface {
  18. // A system generated id for this endpoint.
  19. ID() string
  20. // Name returns the name of this endpoint.
  21. Name() string
  22. // Network returns the name of the network to which this endpoint is attached.
  23. Network() string
  24. // Join joins the sandbox to the endpoint and populates into the sandbox
  25. // the network resources allocated for the endpoint.
  26. Join(sandbox Sandbox, options ...EndpointOption) error
  27. // Leave detaches the network resources populated in the sandbox.
  28. Leave(sandbox Sandbox, options ...EndpointOption) error
  29. // Return certain operational data belonging to this endpoint
  30. Info() EndpointInfo
  31. // DriverInfo returns a collection of driver operational data related to this endpoint retrieved from the driver
  32. DriverInfo() (map[string]interface{}, error)
  33. // Delete and detaches this endpoint from the network.
  34. Delete(force bool) error
  35. }
  36. // EndpointOption is an option setter function type used to pass various options to Network
  37. // and Endpoint interfaces methods. The various setter functions of type EndpointOption are
  38. // provided by libnetwork, they look like <Create|Join|Leave>Option[...](...)
  39. type EndpointOption func(ep *endpoint)
  40. type endpoint struct {
  41. name string
  42. id string
  43. network *network
  44. iface *endpointInterface
  45. joinInfo *endpointJoinInfo
  46. sandboxID string
  47. locator string
  48. exposedPorts []types.TransportPort
  49. anonymous bool
  50. disableResolution bool
  51. generic map[string]interface{}
  52. joinLeaveDone chan struct{}
  53. prefAddress net.IP
  54. prefAddressV6 net.IP
  55. ipamOptions map[string]string
  56. aliases map[string]string
  57. myAliases []string
  58. svcID string
  59. svcName string
  60. virtualIP net.IP
  61. svcAliases []string
  62. ingressPorts []*PortConfig
  63. dbIndex uint64
  64. dbExists bool
  65. serviceEnabled bool
  66. loadBalancer bool
  67. sync.Mutex
  68. }
  69. func (ep *endpoint) MarshalJSON() ([]byte, error) {
  70. ep.Lock()
  71. defer ep.Unlock()
  72. epMap := make(map[string]interface{})
  73. epMap["name"] = ep.name
  74. epMap["id"] = ep.id
  75. epMap["ep_iface"] = ep.iface
  76. epMap["joinInfo"] = ep.joinInfo
  77. epMap["exposed_ports"] = ep.exposedPorts
  78. if ep.generic != nil {
  79. epMap["generic"] = ep.generic
  80. }
  81. epMap["sandbox"] = ep.sandboxID
  82. epMap["locator"] = ep.locator
  83. epMap["anonymous"] = ep.anonymous
  84. epMap["disableResolution"] = ep.disableResolution
  85. epMap["myAliases"] = ep.myAliases
  86. epMap["svcName"] = ep.svcName
  87. epMap["svcID"] = ep.svcID
  88. epMap["virtualIP"] = ep.virtualIP.String()
  89. epMap["ingressPorts"] = ep.ingressPorts
  90. epMap["svcAliases"] = ep.svcAliases
  91. epMap["loadBalancer"] = ep.loadBalancer
  92. return json.Marshal(epMap)
  93. }
  94. func (ep *endpoint) UnmarshalJSON(b []byte) (err error) {
  95. ep.Lock()
  96. defer ep.Unlock()
  97. var epMap map[string]interface{}
  98. if err := json.Unmarshal(b, &epMap); err != nil {
  99. return err
  100. }
  101. ep.name = epMap["name"].(string)
  102. ep.id = epMap["id"].(string)
  103. ib, _ := json.Marshal(epMap["ep_iface"])
  104. json.Unmarshal(ib, &ep.iface)
  105. jb, _ := json.Marshal(epMap["joinInfo"])
  106. json.Unmarshal(jb, &ep.joinInfo)
  107. tb, _ := json.Marshal(epMap["exposed_ports"])
  108. var tPorts []types.TransportPort
  109. json.Unmarshal(tb, &tPorts)
  110. ep.exposedPorts = tPorts
  111. cb, _ := json.Marshal(epMap["sandbox"])
  112. json.Unmarshal(cb, &ep.sandboxID)
  113. if v, ok := epMap["generic"]; ok {
  114. ep.generic = v.(map[string]interface{})
  115. if opt, ok := ep.generic[netlabel.PortMap]; ok {
  116. pblist := []types.PortBinding{}
  117. for i := 0; i < len(opt.([]interface{})); i++ {
  118. pb := types.PortBinding{}
  119. tmp := opt.([]interface{})[i].(map[string]interface{})
  120. bytes, err := json.Marshal(tmp)
  121. if err != nil {
  122. logrus.Error(err)
  123. break
  124. }
  125. err = json.Unmarshal(bytes, &pb)
  126. if err != nil {
  127. logrus.Error(err)
  128. break
  129. }
  130. pblist = append(pblist, pb)
  131. }
  132. ep.generic[netlabel.PortMap] = pblist
  133. }
  134. if opt, ok := ep.generic[netlabel.ExposedPorts]; ok {
  135. tplist := []types.TransportPort{}
  136. for i := 0; i < len(opt.([]interface{})); i++ {
  137. tp := types.TransportPort{}
  138. tmp := opt.([]interface{})[i].(map[string]interface{})
  139. bytes, err := json.Marshal(tmp)
  140. if err != nil {
  141. logrus.Error(err)
  142. break
  143. }
  144. err = json.Unmarshal(bytes, &tp)
  145. if err != nil {
  146. logrus.Error(err)
  147. break
  148. }
  149. tplist = append(tplist, tp)
  150. }
  151. ep.generic[netlabel.ExposedPorts] = tplist
  152. }
  153. }
  154. if v, ok := epMap["anonymous"]; ok {
  155. ep.anonymous = v.(bool)
  156. }
  157. if v, ok := epMap["disableResolution"]; ok {
  158. ep.disableResolution = v.(bool)
  159. }
  160. if l, ok := epMap["locator"]; ok {
  161. ep.locator = l.(string)
  162. }
  163. if sn, ok := epMap["svcName"]; ok {
  164. ep.svcName = sn.(string)
  165. }
  166. if si, ok := epMap["svcID"]; ok {
  167. ep.svcID = si.(string)
  168. }
  169. if vip, ok := epMap["virtualIP"]; ok {
  170. ep.virtualIP = net.ParseIP(vip.(string))
  171. }
  172. if v, ok := epMap["loadBalancer"]; ok {
  173. ep.loadBalancer = v.(bool)
  174. }
  175. sal, _ := json.Marshal(epMap["svcAliases"])
  176. var svcAliases []string
  177. json.Unmarshal(sal, &svcAliases)
  178. ep.svcAliases = svcAliases
  179. pc, _ := json.Marshal(epMap["ingressPorts"])
  180. var ingressPorts []*PortConfig
  181. json.Unmarshal(pc, &ingressPorts)
  182. ep.ingressPorts = ingressPorts
  183. ma, _ := json.Marshal(epMap["myAliases"])
  184. var myAliases []string
  185. json.Unmarshal(ma, &myAliases)
  186. ep.myAliases = myAliases
  187. return nil
  188. }
  189. func (ep *endpoint) New() datastore.KVObject {
  190. return &endpoint{network: ep.getNetwork()}
  191. }
  192. func (ep *endpoint) CopyTo(o datastore.KVObject) error {
  193. ep.Lock()
  194. defer ep.Unlock()
  195. dstEp := o.(*endpoint)
  196. dstEp.name = ep.name
  197. dstEp.id = ep.id
  198. dstEp.sandboxID = ep.sandboxID
  199. dstEp.locator = ep.locator
  200. dstEp.dbIndex = ep.dbIndex
  201. dstEp.dbExists = ep.dbExists
  202. dstEp.anonymous = ep.anonymous
  203. dstEp.disableResolution = ep.disableResolution
  204. dstEp.svcName = ep.svcName
  205. dstEp.svcID = ep.svcID
  206. dstEp.virtualIP = ep.virtualIP
  207. dstEp.loadBalancer = ep.loadBalancer
  208. dstEp.svcAliases = make([]string, len(ep.svcAliases))
  209. copy(dstEp.svcAliases, ep.svcAliases)
  210. dstEp.ingressPorts = make([]*PortConfig, len(ep.ingressPorts))
  211. copy(dstEp.ingressPorts, ep.ingressPorts)
  212. if ep.iface != nil {
  213. dstEp.iface = &endpointInterface{}
  214. ep.iface.CopyTo(dstEp.iface)
  215. }
  216. if ep.joinInfo != nil {
  217. dstEp.joinInfo = &endpointJoinInfo{}
  218. ep.joinInfo.CopyTo(dstEp.joinInfo)
  219. }
  220. dstEp.exposedPorts = make([]types.TransportPort, len(ep.exposedPorts))
  221. copy(dstEp.exposedPorts, ep.exposedPorts)
  222. dstEp.myAliases = make([]string, len(ep.myAliases))
  223. copy(dstEp.myAliases, ep.myAliases)
  224. dstEp.generic = options.Generic{}
  225. for k, v := range ep.generic {
  226. dstEp.generic[k] = v
  227. }
  228. return nil
  229. }
  230. func (ep *endpoint) ID() string {
  231. ep.Lock()
  232. defer ep.Unlock()
  233. return ep.id
  234. }
  235. func (ep *endpoint) Name() string {
  236. ep.Lock()
  237. defer ep.Unlock()
  238. return ep.name
  239. }
  240. func (ep *endpoint) MyAliases() []string {
  241. ep.Lock()
  242. defer ep.Unlock()
  243. return ep.myAliases
  244. }
  245. func (ep *endpoint) Network() string {
  246. if ep.network == nil {
  247. return ""
  248. }
  249. return ep.network.name
  250. }
  251. func (ep *endpoint) isAnonymous() bool {
  252. ep.Lock()
  253. defer ep.Unlock()
  254. return ep.anonymous
  255. }
  256. // isServiceEnabled check if service is enabled on the endpoint
  257. func (ep *endpoint) isServiceEnabled() bool {
  258. ep.Lock()
  259. defer ep.Unlock()
  260. return ep.serviceEnabled
  261. }
  262. // enableService sets service enabled on the endpoint
  263. func (ep *endpoint) enableService() {
  264. ep.Lock()
  265. defer ep.Unlock()
  266. ep.serviceEnabled = true
  267. }
  268. // disableService disables service on the endpoint
  269. func (ep *endpoint) disableService() {
  270. ep.Lock()
  271. defer ep.Unlock()
  272. ep.serviceEnabled = false
  273. }
  274. func (ep *endpoint) needResolver() bool {
  275. ep.Lock()
  276. defer ep.Unlock()
  277. return !ep.disableResolution
  278. }
  279. // endpoint Key structure : endpoint/network-id/endpoint-id
  280. func (ep *endpoint) Key() []string {
  281. if ep.network == nil {
  282. return nil
  283. }
  284. return []string{datastore.EndpointKeyPrefix, ep.network.id, ep.id}
  285. }
  286. func (ep *endpoint) KeyPrefix() []string {
  287. if ep.network == nil {
  288. return nil
  289. }
  290. return []string{datastore.EndpointKeyPrefix, ep.network.id}
  291. }
  292. func (ep *endpoint) networkIDFromKey(key string) (string, error) {
  293. // endpoint Key structure : docker/libnetwork/endpoint/${network-id}/${endpoint-id}
  294. // it's an invalid key if the key doesn't have all the 5 key elements above
  295. keyElements := strings.Split(key, "/")
  296. if !strings.HasPrefix(key, datastore.Key(datastore.EndpointKeyPrefix)) || len(keyElements) < 5 {
  297. return "", fmt.Errorf("invalid endpoint key : %v", key)
  298. }
  299. // network-id is placed at index=3. pls refer to endpoint.Key() method
  300. return strings.Split(key, "/")[3], nil
  301. }
  302. func (ep *endpoint) Value() []byte {
  303. b, err := json.Marshal(ep)
  304. if err != nil {
  305. return nil
  306. }
  307. return b
  308. }
  309. func (ep *endpoint) SetValue(value []byte) error {
  310. return json.Unmarshal(value, ep)
  311. }
  312. func (ep *endpoint) Index() uint64 {
  313. ep.Lock()
  314. defer ep.Unlock()
  315. return ep.dbIndex
  316. }
  317. func (ep *endpoint) SetIndex(index uint64) {
  318. ep.Lock()
  319. defer ep.Unlock()
  320. ep.dbIndex = index
  321. ep.dbExists = true
  322. }
  323. func (ep *endpoint) Exists() bool {
  324. ep.Lock()
  325. defer ep.Unlock()
  326. return ep.dbExists
  327. }
  328. func (ep *endpoint) Skip() bool {
  329. return ep.getNetwork().Skip()
  330. }
  331. func (ep *endpoint) processOptions(options ...EndpointOption) {
  332. ep.Lock()
  333. defer ep.Unlock()
  334. for _, opt := range options {
  335. if opt != nil {
  336. opt(ep)
  337. }
  338. }
  339. }
  340. func (ep *endpoint) getNetwork() *network {
  341. ep.Lock()
  342. defer ep.Unlock()
  343. return ep.network
  344. }
  345. func (ep *endpoint) getNetworkFromStore() (*network, error) {
  346. if ep.network == nil {
  347. return nil, fmt.Errorf("invalid network object in endpoint %s", ep.Name())
  348. }
  349. return ep.network.getController().getNetworkFromStore(ep.network.id)
  350. }
  351. func (ep *endpoint) Join(sbox Sandbox, options ...EndpointOption) error {
  352. if sbox == nil {
  353. return types.BadRequestErrorf("endpoint cannot be joined by nil container")
  354. }
  355. sb, ok := sbox.(*sandbox)
  356. if !ok {
  357. return types.BadRequestErrorf("not a valid Sandbox interface")
  358. }
  359. sb.joinLeaveStart()
  360. defer sb.joinLeaveEnd()
  361. return ep.sbJoin(sb, options...)
  362. }
  363. func (ep *endpoint) sbJoin(sb *sandbox, options ...EndpointOption) (err error) {
  364. n, err := ep.getNetworkFromStore()
  365. if err != nil {
  366. return fmt.Errorf("failed to get network from store during join: %v", err)
  367. }
  368. ep, err = n.getEndpointFromStore(ep.ID())
  369. if err != nil {
  370. return fmt.Errorf("failed to get endpoint from store during join: %v", err)
  371. }
  372. ep.Lock()
  373. if ep.sandboxID != "" {
  374. ep.Unlock()
  375. return types.ForbiddenErrorf("another container is attached to the same network endpoint")
  376. }
  377. ep.network = n
  378. ep.sandboxID = sb.ID()
  379. ep.joinInfo = &endpointJoinInfo{}
  380. epid := ep.id
  381. ep.Unlock()
  382. defer func() {
  383. if err != nil {
  384. ep.Lock()
  385. ep.sandboxID = ""
  386. ep.Unlock()
  387. }
  388. }()
  389. nid := n.ID()
  390. ep.processOptions(options...)
  391. d, err := n.driver(true)
  392. if err != nil {
  393. return fmt.Errorf("failed to get driver during join: %v", err)
  394. }
  395. err = d.Join(nid, epid, sb.Key(), ep, sb.Labels())
  396. if err != nil {
  397. return err
  398. }
  399. defer func() {
  400. if err != nil {
  401. if e := d.Leave(nid, epid); e != nil {
  402. logrus.Warnf("driver leave failed while rolling back join: %v", e)
  403. }
  404. }
  405. }()
  406. // Watch for service records
  407. if !n.getController().isAgent() {
  408. n.getController().watchSvcRecord(ep)
  409. }
  410. if doUpdateHostsFile(n, sb) {
  411. address := ""
  412. if ip := ep.getFirstInterfaceAddress(); ip != nil {
  413. address = ip.String()
  414. }
  415. if err = sb.updateHostsFile(address); err != nil {
  416. return err
  417. }
  418. }
  419. if err = sb.updateDNS(n.enableIPv6); err != nil {
  420. return err
  421. }
  422. // Current endpoint providing external connectivity for the sandbox
  423. extEp := sb.getGatewayEndpoint()
  424. sb.Lock()
  425. heap.Push(&sb.endpoints, ep)
  426. sb.Unlock()
  427. defer func() {
  428. if err != nil {
  429. sb.removeEndpoint(ep)
  430. }
  431. }()
  432. if err = sb.populateNetworkResources(ep); err != nil {
  433. return err
  434. }
  435. if err = n.getController().updateToStore(ep); err != nil {
  436. return err
  437. }
  438. if err = ep.addDriverInfoToCluster(); err != nil {
  439. return err
  440. }
  441. defer func() {
  442. if err != nil {
  443. if e := ep.deleteDriverInfoFromCluster(); e != nil {
  444. logrus.Errorf("Could not delete endpoint state for endpoint %s from cluster on join failure: %v", ep.Name(), e)
  445. }
  446. }
  447. }()
  448. if sb.needDefaultGW() && sb.getEndpointInGWNetwork() == nil {
  449. return sb.setupDefaultGW()
  450. }
  451. moveExtConn := sb.getGatewayEndpoint() != extEp
  452. if moveExtConn {
  453. if extEp != nil {
  454. logrus.Debugf("Revoking external connectivity on endpoint %s (%s)", extEp.Name(), extEp.ID())
  455. extN, err := extEp.getNetworkFromStore()
  456. if err != nil {
  457. return fmt.Errorf("failed to get network from store for revoking external connectivity during join: %v", err)
  458. }
  459. extD, err := extN.driver(true)
  460. if err != nil {
  461. return fmt.Errorf("failed to get driver for revoking external connectivity during join: %v", err)
  462. }
  463. if err = extD.RevokeExternalConnectivity(extEp.network.ID(), extEp.ID()); err != nil {
  464. return types.InternalErrorf(
  465. "driver failed revoking external connectivity on endpoint %s (%s): %v",
  466. extEp.Name(), extEp.ID(), err)
  467. }
  468. defer func() {
  469. if err != nil {
  470. if e := extD.ProgramExternalConnectivity(extEp.network.ID(), extEp.ID(), sb.Labels()); e != nil {
  471. logrus.Warnf("Failed to roll-back external connectivity on endpoint %s (%s): %v",
  472. extEp.Name(), extEp.ID(), e)
  473. }
  474. }
  475. }()
  476. }
  477. if !n.internal {
  478. logrus.Debugf("Programming external connectivity on endpoint %s (%s)", ep.Name(), ep.ID())
  479. if err = d.ProgramExternalConnectivity(n.ID(), ep.ID(), sb.Labels()); err != nil {
  480. return types.InternalErrorf(
  481. "driver failed programming external connectivity on endpoint %s (%s): %v",
  482. ep.Name(), ep.ID(), err)
  483. }
  484. }
  485. }
  486. if !sb.needDefaultGW() {
  487. if e := sb.clearDefaultGW(); e != nil {
  488. logrus.Warnf("Failure while disconnecting sandbox %s (%s) from gateway network: %v",
  489. sb.ID(), sb.ContainerID(), e)
  490. }
  491. }
  492. return nil
  493. }
  494. func doUpdateHostsFile(n *network, sb *sandbox) bool {
  495. return !n.ingress && n.Name() != libnGWNetwork
  496. }
  497. func (ep *endpoint) rename(name string) error {
  498. var (
  499. err error
  500. netWatch *netWatch
  501. ok bool
  502. )
  503. n := ep.getNetwork()
  504. if n == nil {
  505. return fmt.Errorf("network not connected for ep %q", ep.name)
  506. }
  507. c := n.getController()
  508. sb, ok := ep.getSandbox()
  509. if !ok {
  510. logrus.Warnf("rename for %s aborted, sandbox %s is not anymore present", ep.ID(), ep.sandboxID)
  511. return nil
  512. }
  513. if c.isAgent() {
  514. if err = ep.deleteServiceInfoFromCluster(sb, true, "rename"); err != nil {
  515. return types.InternalErrorf("Could not delete service state for endpoint %s from cluster on rename: %v", ep.Name(), err)
  516. }
  517. } else {
  518. c.Lock()
  519. netWatch, ok = c.nmap[n.ID()]
  520. c.Unlock()
  521. if !ok {
  522. return fmt.Errorf("watch null for network %q", n.Name())
  523. }
  524. n.updateSvcRecord(ep, c.getLocalEps(netWatch), false)
  525. }
  526. oldName := ep.name
  527. oldAnonymous := ep.anonymous
  528. ep.name = name
  529. ep.anonymous = false
  530. if c.isAgent() {
  531. if err = ep.addServiceInfoToCluster(sb); err != nil {
  532. return types.InternalErrorf("Could not add service state for endpoint %s to cluster on rename: %v", ep.Name(), err)
  533. }
  534. defer func() {
  535. if err != nil {
  536. ep.deleteServiceInfoFromCluster(sb, true, "rename")
  537. ep.name = oldName
  538. ep.anonymous = oldAnonymous
  539. ep.addServiceInfoToCluster(sb)
  540. }
  541. }()
  542. } else {
  543. n.updateSvcRecord(ep, c.getLocalEps(netWatch), true)
  544. defer func() {
  545. if err != nil {
  546. n.updateSvcRecord(ep, c.getLocalEps(netWatch), false)
  547. ep.name = oldName
  548. ep.anonymous = oldAnonymous
  549. n.updateSvcRecord(ep, c.getLocalEps(netWatch), true)
  550. }
  551. }()
  552. }
  553. // Update the store with the updated name
  554. if err = c.updateToStore(ep); err != nil {
  555. return err
  556. }
  557. // After the name change do a dummy endpoint count update to
  558. // trigger the service record update in the peer nodes
  559. // Ignore the error because updateStore fail for EpCnt is a
  560. // benign error. Besides there is no meaningful recovery that
  561. // we can do. When the cluster recovers subsequent EpCnt update
  562. // will force the peers to get the correct EP name.
  563. n.getEpCnt().updateStore()
  564. return err
  565. }
  566. func (ep *endpoint) hasInterface(iName string) bool {
  567. ep.Lock()
  568. defer ep.Unlock()
  569. return ep.iface != nil && ep.iface.srcName == iName
  570. }
  571. func (ep *endpoint) Leave(sbox Sandbox, options ...EndpointOption) error {
  572. if sbox == nil || sbox.ID() == "" || sbox.Key() == "" {
  573. return types.BadRequestErrorf("invalid Sandbox passed to endpoint leave: %v", sbox)
  574. }
  575. sb, ok := sbox.(*sandbox)
  576. if !ok {
  577. return types.BadRequestErrorf("not a valid Sandbox interface")
  578. }
  579. sb.joinLeaveStart()
  580. defer sb.joinLeaveEnd()
  581. return ep.sbLeave(sb, false, options...)
  582. }
  583. func (ep *endpoint) sbLeave(sb *sandbox, force bool, options ...EndpointOption) error {
  584. n, err := ep.getNetworkFromStore()
  585. if err != nil {
  586. return fmt.Errorf("failed to get network from store during leave: %v", err)
  587. }
  588. ep, err = n.getEndpointFromStore(ep.ID())
  589. if err != nil {
  590. return fmt.Errorf("failed to get endpoint from store during leave: %v", err)
  591. }
  592. ep.Lock()
  593. sid := ep.sandboxID
  594. ep.Unlock()
  595. if sid == "" {
  596. return types.ForbiddenErrorf("cannot leave endpoint with no attached sandbox")
  597. }
  598. if sid != sb.ID() {
  599. return types.ForbiddenErrorf("unexpected sandbox ID in leave request. Expected %s. Got %s", ep.sandboxID, sb.ID())
  600. }
  601. ep.processOptions(options...)
  602. d, err := n.driver(!force)
  603. if err != nil {
  604. return fmt.Errorf("failed to get driver during endpoint leave: %v", err)
  605. }
  606. ep.Lock()
  607. ep.sandboxID = ""
  608. ep.network = n
  609. ep.Unlock()
  610. // Current endpoint providing external connectivity to the sandbox
  611. extEp := sb.getGatewayEndpoint()
  612. moveExtConn := extEp != nil && (extEp.ID() == ep.ID())
  613. if d != nil {
  614. if moveExtConn {
  615. logrus.Debugf("Revoking external connectivity on endpoint %s (%s)", ep.Name(), ep.ID())
  616. if err := d.RevokeExternalConnectivity(n.id, ep.id); err != nil {
  617. logrus.Warnf("driver failed revoking external connectivity on endpoint %s (%s): %v",
  618. ep.Name(), ep.ID(), err)
  619. }
  620. }
  621. if err := d.Leave(n.id, ep.id); err != nil {
  622. if _, ok := err.(types.MaskableError); !ok {
  623. logrus.Warnf("driver error disconnecting container %s : %v", ep.name, err)
  624. }
  625. }
  626. }
  627. if ep.svcID != "" {
  628. if err := ep.deleteServiceInfoFromCluster(sb, true, "sbLeave"); err != nil {
  629. logrus.Warnf("Failed to clean up service info on container %s disconnect: %v", ep.name, err)
  630. }
  631. }
  632. if err := sb.clearNetworkResources(ep); err != nil {
  633. logrus.Warnf("Failed to clean up network resources on container %s disconnect: %v", ep.name, err)
  634. }
  635. // Update the store about the sandbox detach only after we
  636. // have completed sb.clearNetworkresources above to avoid
  637. // spurious logs when cleaning up the sandbox when the daemon
  638. // ungracefully exits and restarts before completing sandbox
  639. // detach but after store has been updated.
  640. if err := n.getController().updateToStore(ep); err != nil {
  641. return err
  642. }
  643. if e := ep.deleteDriverInfoFromCluster(); e != nil {
  644. logrus.Errorf("Failed to delete endpoint state for endpoint %s from cluster: %v", ep.Name(), e)
  645. }
  646. sb.deleteHostsEntries(n.getSvcRecords(ep))
  647. if !sb.inDelete && sb.needDefaultGW() && sb.getEndpointInGWNetwork() == nil {
  648. return sb.setupDefaultGW()
  649. }
  650. // New endpoint providing external connectivity for the sandbox
  651. extEp = sb.getGatewayEndpoint()
  652. if moveExtConn && extEp != nil {
  653. logrus.Debugf("Programming external connectivity on endpoint %s (%s)", extEp.Name(), extEp.ID())
  654. extN, err := extEp.getNetworkFromStore()
  655. if err != nil {
  656. return fmt.Errorf("failed to get network from store for programming external connectivity during leave: %v", err)
  657. }
  658. extD, err := extN.driver(true)
  659. if err != nil {
  660. return fmt.Errorf("failed to get driver for programming external connectivity during leave: %v", err)
  661. }
  662. if err := extD.ProgramExternalConnectivity(extEp.network.ID(), extEp.ID(), sb.Labels()); err != nil {
  663. logrus.Warnf("driver failed programming external connectivity on endpoint %s: (%s) %v",
  664. extEp.Name(), extEp.ID(), err)
  665. }
  666. }
  667. if !sb.needDefaultGW() {
  668. if err := sb.clearDefaultGW(); err != nil {
  669. logrus.Warnf("Failure while disconnecting sandbox %s (%s) from gateway network: %v",
  670. sb.ID(), sb.ContainerID(), err)
  671. }
  672. }
  673. return nil
  674. }
  675. func (ep *endpoint) Delete(force bool) error {
  676. var err error
  677. n, err := ep.getNetworkFromStore()
  678. if err != nil {
  679. return fmt.Errorf("failed to get network during Delete: %v", err)
  680. }
  681. ep, err = n.getEndpointFromStore(ep.ID())
  682. if err != nil {
  683. return fmt.Errorf("failed to get endpoint from store during Delete: %v", err)
  684. }
  685. ep.Lock()
  686. epid := ep.id
  687. name := ep.name
  688. sbid := ep.sandboxID
  689. ep.Unlock()
  690. sb, _ := n.getController().SandboxByID(sbid)
  691. if sb != nil && !force {
  692. return &ActiveContainerError{name: name, id: epid}
  693. }
  694. if sb != nil {
  695. if e := ep.sbLeave(sb.(*sandbox), force); e != nil {
  696. logrus.Warnf("failed to leave sandbox for endpoint %s : %v", name, e)
  697. }
  698. }
  699. if err = n.getController().deleteFromStore(ep); err != nil {
  700. return err
  701. }
  702. defer func() {
  703. if err != nil && !force {
  704. ep.dbExists = false
  705. if e := n.getController().updateToStore(ep); e != nil {
  706. logrus.Warnf("failed to recreate endpoint in store %s : %v", name, e)
  707. }
  708. }
  709. }()
  710. // unwatch for service records
  711. n.getController().unWatchSvcRecord(ep)
  712. if err = ep.deleteEndpoint(force); err != nil && !force {
  713. return err
  714. }
  715. ep.releaseAddress()
  716. if err := n.getEpCnt().DecEndpointCnt(); err != nil {
  717. logrus.Warnf("failed to decrement endpoint count for ep %s: %v", ep.ID(), err)
  718. }
  719. return nil
  720. }
  721. func (ep *endpoint) deleteEndpoint(force bool) error {
  722. ep.Lock()
  723. n := ep.network
  724. name := ep.name
  725. epid := ep.id
  726. ep.Unlock()
  727. driver, err := n.driver(!force)
  728. if err != nil {
  729. return fmt.Errorf("failed to delete endpoint: %v", err)
  730. }
  731. if driver == nil {
  732. return nil
  733. }
  734. if err := driver.DeleteEndpoint(n.id, epid); err != nil {
  735. if _, ok := err.(types.ForbiddenError); ok {
  736. return err
  737. }
  738. if _, ok := err.(types.MaskableError); !ok {
  739. logrus.Warnf("driver error deleting endpoint %s : %v", name, err)
  740. }
  741. }
  742. return nil
  743. }
  744. func (ep *endpoint) getSandbox() (*sandbox, bool) {
  745. c := ep.network.getController()
  746. ep.Lock()
  747. sid := ep.sandboxID
  748. ep.Unlock()
  749. c.Lock()
  750. ps, ok := c.sandboxes[sid]
  751. c.Unlock()
  752. return ps, ok
  753. }
  754. func (ep *endpoint) getFirstInterfaceAddress() net.IP {
  755. ep.Lock()
  756. defer ep.Unlock()
  757. if ep.iface.addr != nil {
  758. return ep.iface.addr.IP
  759. }
  760. return nil
  761. }
  762. // EndpointOptionGeneric function returns an option setter for a Generic option defined
  763. // in a Dictionary of Key-Value pair
  764. func EndpointOptionGeneric(generic map[string]interface{}) EndpointOption {
  765. return func(ep *endpoint) {
  766. for k, v := range generic {
  767. ep.generic[k] = v
  768. }
  769. }
  770. }
  771. var (
  772. linkLocalMask = net.CIDRMask(16, 32)
  773. linkLocalMaskIPv6 = net.CIDRMask(64, 128)
  774. )
  775. // CreateOptionIpam function returns an option setter for the ipam configuration for this endpoint
  776. func CreateOptionIpam(ipV4, ipV6 net.IP, llIPs []net.IP, ipamOptions map[string]string) EndpointOption {
  777. return func(ep *endpoint) {
  778. ep.prefAddress = ipV4
  779. ep.prefAddressV6 = ipV6
  780. if len(llIPs) != 0 {
  781. for _, ip := range llIPs {
  782. nw := &net.IPNet{IP: ip, Mask: linkLocalMask}
  783. if ip.To4() == nil {
  784. nw.Mask = linkLocalMaskIPv6
  785. }
  786. ep.iface.llAddrs = append(ep.iface.llAddrs, nw)
  787. }
  788. }
  789. ep.ipamOptions = ipamOptions
  790. }
  791. }
  792. // CreateOptionExposedPorts function returns an option setter for the container exposed
  793. // ports option to be passed to network.CreateEndpoint() method.
  794. func CreateOptionExposedPorts(exposedPorts []types.TransportPort) EndpointOption {
  795. return func(ep *endpoint) {
  796. // Defensive copy
  797. eps := make([]types.TransportPort, len(exposedPorts))
  798. copy(eps, exposedPorts)
  799. // Store endpoint label and in generic because driver needs it
  800. ep.exposedPorts = eps
  801. ep.generic[netlabel.ExposedPorts] = eps
  802. }
  803. }
  804. // CreateOptionPortMapping function returns an option setter for the mapping
  805. // ports option to be passed to network.CreateEndpoint() method.
  806. func CreateOptionPortMapping(portBindings []types.PortBinding) EndpointOption {
  807. return func(ep *endpoint) {
  808. // Store a copy of the bindings as generic data to pass to the driver
  809. pbs := make([]types.PortBinding, len(portBindings))
  810. copy(pbs, portBindings)
  811. ep.generic[netlabel.PortMap] = pbs
  812. }
  813. }
  814. // CreateOptionDNS function returns an option setter for dns entry option to
  815. // be passed to container Create method.
  816. func CreateOptionDNS(dns []string) EndpointOption {
  817. return func(ep *endpoint) {
  818. ep.generic[netlabel.DNSServers] = dns
  819. }
  820. }
  821. // CreateOptionAnonymous function returns an option setter for setting
  822. // this endpoint as anonymous
  823. func CreateOptionAnonymous() EndpointOption {
  824. return func(ep *endpoint) {
  825. ep.anonymous = true
  826. }
  827. }
  828. // CreateOptionDisableResolution function returns an option setter to indicate
  829. // this endpoint doesn't want embedded DNS server functionality
  830. func CreateOptionDisableResolution() EndpointOption {
  831. return func(ep *endpoint) {
  832. ep.disableResolution = true
  833. }
  834. }
  835. // CreateOptionAlias function returns an option setter for setting endpoint alias
  836. func CreateOptionAlias(name string, alias string) EndpointOption {
  837. return func(ep *endpoint) {
  838. if ep.aliases == nil {
  839. ep.aliases = make(map[string]string)
  840. }
  841. ep.aliases[alias] = name
  842. }
  843. }
  844. // CreateOptionService function returns an option setter for setting service binding configuration
  845. func CreateOptionService(name, id string, vip net.IP, ingressPorts []*PortConfig, aliases []string) EndpointOption {
  846. return func(ep *endpoint) {
  847. ep.svcName = name
  848. ep.svcID = id
  849. ep.virtualIP = vip
  850. ep.ingressPorts = ingressPorts
  851. ep.svcAliases = aliases
  852. }
  853. }
  854. // CreateOptionMyAlias function returns an option setter for setting endpoint's self alias
  855. func CreateOptionMyAlias(alias string) EndpointOption {
  856. return func(ep *endpoint) {
  857. ep.myAliases = append(ep.myAliases, alias)
  858. }
  859. }
  860. // CreateOptionLoadBalancer function returns an option setter for denoting the endpoint is a load balancer for a network
  861. func CreateOptionLoadBalancer() EndpointOption {
  862. return func(ep *endpoint) {
  863. ep.loadBalancer = true
  864. }
  865. }
  866. // JoinOptionPriority function returns an option setter for priority option to
  867. // be passed to the endpoint.Join() method.
  868. func JoinOptionPriority(ep Endpoint, prio int) EndpointOption {
  869. return func(ep *endpoint) {
  870. // ep lock already acquired
  871. c := ep.network.getController()
  872. c.Lock()
  873. sb, ok := c.sandboxes[ep.sandboxID]
  874. c.Unlock()
  875. if !ok {
  876. logrus.Errorf("Could not set endpoint priority value during Join to endpoint %s: No sandbox id present in endpoint", ep.id)
  877. return
  878. }
  879. sb.epPriority[ep.id] = prio
  880. }
  881. }
  882. func (ep *endpoint) DataScope() string {
  883. return ep.getNetwork().DataScope()
  884. }
  885. func (ep *endpoint) assignAddress(ipam ipamapi.Ipam, assignIPv4, assignIPv6 bool) error {
  886. var err error
  887. n := ep.getNetwork()
  888. if n.hasSpecialDriver() {
  889. return nil
  890. }
  891. logrus.Debugf("Assigning addresses for endpoint %s's interface on network %s", ep.Name(), n.Name())
  892. if assignIPv4 {
  893. if err = ep.assignAddressVersion(4, ipam); err != nil {
  894. return err
  895. }
  896. }
  897. if assignIPv6 {
  898. err = ep.assignAddressVersion(6, ipam)
  899. }
  900. return err
  901. }
  902. func (ep *endpoint) assignAddressVersion(ipVer int, ipam ipamapi.Ipam) error {
  903. var (
  904. poolID *string
  905. address **net.IPNet
  906. prefAdd net.IP
  907. progAdd net.IP
  908. )
  909. n := ep.getNetwork()
  910. switch ipVer {
  911. case 4:
  912. poolID = &ep.iface.v4PoolID
  913. address = &ep.iface.addr
  914. prefAdd = ep.prefAddress
  915. case 6:
  916. poolID = &ep.iface.v6PoolID
  917. address = &ep.iface.addrv6
  918. prefAdd = ep.prefAddressV6
  919. default:
  920. return types.InternalErrorf("incorrect ip version number passed: %d", ipVer)
  921. }
  922. ipInfo := n.getIPInfo(ipVer)
  923. // ipv6 address is not mandatory
  924. if len(ipInfo) == 0 && ipVer == 6 {
  925. return nil
  926. }
  927. // The address to program may be chosen by the user or by the network driver in one specific
  928. // case to support backward compatibility with `docker daemon --fixed-cidrv6` use case
  929. if prefAdd != nil {
  930. progAdd = prefAdd
  931. } else if *address != nil {
  932. progAdd = (*address).IP
  933. }
  934. for _, d := range ipInfo {
  935. if progAdd != nil && !d.Pool.Contains(progAdd) {
  936. continue
  937. }
  938. addr, _, err := ipam.RequestAddress(d.PoolID, progAdd, ep.ipamOptions)
  939. if err == nil {
  940. ep.Lock()
  941. *address = addr
  942. *poolID = d.PoolID
  943. ep.Unlock()
  944. return nil
  945. }
  946. if err != ipamapi.ErrNoAvailableIPs || progAdd != nil {
  947. return err
  948. }
  949. }
  950. if progAdd != nil {
  951. return types.BadRequestErrorf("Invalid address %s: It does not belong to any of this network's subnets", prefAdd)
  952. }
  953. return fmt.Errorf("no available IPv%d addresses on this network's address pools: %s (%s)", ipVer, n.Name(), n.ID())
  954. }
  955. func (ep *endpoint) releaseAddress() {
  956. n := ep.getNetwork()
  957. if n.hasSpecialDriver() {
  958. return
  959. }
  960. logrus.Debugf("Releasing addresses for endpoint %s's interface on network %s", ep.Name(), n.Name())
  961. ipam, _, err := n.getController().getIPAMDriver(n.ipamType)
  962. if err != nil {
  963. logrus.Warnf("Failed to retrieve ipam driver to release interface address on delete of endpoint %s (%s): %v", ep.Name(), ep.ID(), err)
  964. return
  965. }
  966. if ep.iface.addr != nil {
  967. if err := ipam.ReleaseAddress(ep.iface.v4PoolID, ep.iface.addr.IP); err != nil {
  968. logrus.Warnf("Failed to release ip address %s on delete of endpoint %s (%s): %v", ep.iface.addr.IP, ep.Name(), ep.ID(), err)
  969. }
  970. }
  971. if ep.iface.addrv6 != nil && ep.iface.addrv6.IP.IsGlobalUnicast() {
  972. if err := ipam.ReleaseAddress(ep.iface.v6PoolID, ep.iface.addrv6.IP); err != nil {
  973. logrus.Warnf("Failed to release ip address %s on delete of endpoint %s (%s): %v", ep.iface.addrv6.IP, ep.Name(), ep.ID(), err)
  974. }
  975. }
  976. }
  977. func (c *controller) cleanupLocalEndpoints() {
  978. // Get used endpoints
  979. eps := make(map[string]interface{})
  980. for _, sb := range c.sandboxes {
  981. for _, ep := range sb.endpoints {
  982. eps[ep.id] = true
  983. }
  984. }
  985. nl, err := c.getNetworksForScope(datastore.LocalScope)
  986. if err != nil {
  987. logrus.Warnf("Could not get list of networks during endpoint cleanup: %v", err)
  988. return
  989. }
  990. for _, n := range nl {
  991. if n.ConfigOnly() {
  992. continue
  993. }
  994. epl, err := n.getEndpointsFromStore()
  995. if err != nil {
  996. logrus.Warnf("Could not get list of endpoints in network %s during endpoint cleanup: %v", n.name, err)
  997. continue
  998. }
  999. for _, ep := range epl {
  1000. if _, ok := eps[ep.id]; ok {
  1001. continue
  1002. }
  1003. logrus.Infof("Removing stale endpoint %s (%s)", ep.name, ep.id)
  1004. if err := ep.Delete(true); err != nil {
  1005. logrus.Warnf("Could not delete local endpoint %s during endpoint cleanup: %v", ep.name, err)
  1006. }
  1007. }
  1008. epl, err = n.getEndpointsFromStore()
  1009. if err != nil {
  1010. logrus.Warnf("Could not get list of endpoints in network %s for count update: %v", n.name, err)
  1011. continue
  1012. }
  1013. epCnt := n.getEpCnt().EndpointCnt()
  1014. if epCnt != uint64(len(epl)) {
  1015. logrus.Infof("Fixing inconsistent endpoint_cnt for network %s. Expected=%d, Actual=%d", n.name, len(epl), epCnt)
  1016. n.getEpCnt().setCnt(uint64(len(epl)))
  1017. }
  1018. }
  1019. }