endpoint.go 32 KB

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