endpoint.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878
  1. package libnetwork
  2. import (
  3. "container/heap"
  4. "encoding/json"
  5. "fmt"
  6. "net"
  7. "strings"
  8. "sync"
  9. log "github.com/Sirupsen/logrus"
  10. "github.com/docker/libnetwork/datastore"
  11. "github.com/docker/libnetwork/ipamapi"
  12. "github.com/docker/libnetwork/netlabel"
  13. "github.com/docker/libnetwork/options"
  14. "github.com/docker/libnetwork/types"
  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() error
  35. }
  36. // EndpointOption is a option setter function type used to pass varios 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. exposedPorts []types.TransportPort
  48. anonymous bool
  49. generic map[string]interface{}
  50. joinLeaveDone chan struct{}
  51. prefAddress net.IP
  52. prefAddressV6 net.IP
  53. ipamOptions map[string]string
  54. dbIndex uint64
  55. dbExists bool
  56. sync.Mutex
  57. }
  58. func (ep *endpoint) MarshalJSON() ([]byte, error) {
  59. ep.Lock()
  60. defer ep.Unlock()
  61. epMap := make(map[string]interface{})
  62. epMap["name"] = ep.name
  63. epMap["id"] = ep.id
  64. epMap["ep_iface"] = ep.iface
  65. epMap["exposed_ports"] = ep.exposedPorts
  66. if ep.generic != nil {
  67. epMap["generic"] = ep.generic
  68. }
  69. epMap["sandbox"] = ep.sandboxID
  70. epMap["anonymous"] = ep.anonymous
  71. return json.Marshal(epMap)
  72. }
  73. func (ep *endpoint) UnmarshalJSON(b []byte) (err error) {
  74. ep.Lock()
  75. defer ep.Unlock()
  76. var epMap map[string]interface{}
  77. if err := json.Unmarshal(b, &epMap); err != nil {
  78. return err
  79. }
  80. ep.name = epMap["name"].(string)
  81. ep.id = epMap["id"].(string)
  82. ib, _ := json.Marshal(epMap["ep_iface"])
  83. json.Unmarshal(ib, &ep.iface)
  84. tb, _ := json.Marshal(epMap["exposed_ports"])
  85. var tPorts []types.TransportPort
  86. json.Unmarshal(tb, &tPorts)
  87. ep.exposedPorts = tPorts
  88. cb, _ := json.Marshal(epMap["sandbox"])
  89. json.Unmarshal(cb, &ep.sandboxID)
  90. if v, ok := epMap["generic"]; ok {
  91. ep.generic = v.(map[string]interface{})
  92. if opt, ok := ep.generic[netlabel.PortMap]; ok {
  93. pblist := []types.PortBinding{}
  94. for i := 0; i < len(opt.([]interface{})); i++ {
  95. pb := types.PortBinding{}
  96. tmp := opt.([]interface{})[i].(map[string]interface{})
  97. bytes, err := json.Marshal(tmp)
  98. if err != nil {
  99. log.Error(err)
  100. break
  101. }
  102. err = json.Unmarshal(bytes, &pb)
  103. if err != nil {
  104. log.Error(err)
  105. break
  106. }
  107. pblist = append(pblist, pb)
  108. }
  109. ep.generic[netlabel.PortMap] = pblist
  110. }
  111. if opt, ok := ep.generic[netlabel.ExposedPorts]; ok {
  112. tplist := []types.TransportPort{}
  113. for i := 0; i < len(opt.([]interface{})); i++ {
  114. tp := types.TransportPort{}
  115. tmp := opt.([]interface{})[i].(map[string]interface{})
  116. bytes, err := json.Marshal(tmp)
  117. if err != nil {
  118. log.Error(err)
  119. break
  120. }
  121. err = json.Unmarshal(bytes, &tp)
  122. if err != nil {
  123. log.Error(err)
  124. break
  125. }
  126. tplist = append(tplist, tp)
  127. }
  128. ep.generic[netlabel.ExposedPorts] = tplist
  129. }
  130. }
  131. if v, ok := epMap["anonymous"]; ok {
  132. ep.anonymous = v.(bool)
  133. }
  134. return nil
  135. }
  136. func (ep *endpoint) New() datastore.KVObject {
  137. return &endpoint{network: ep.getNetwork()}
  138. }
  139. func (ep *endpoint) CopyTo(o datastore.KVObject) error {
  140. ep.Lock()
  141. defer ep.Unlock()
  142. dstEp := o.(*endpoint)
  143. dstEp.name = ep.name
  144. dstEp.id = ep.id
  145. dstEp.sandboxID = ep.sandboxID
  146. dstEp.dbIndex = ep.dbIndex
  147. dstEp.dbExists = ep.dbExists
  148. dstEp.anonymous = ep.anonymous
  149. if ep.iface != nil {
  150. dstEp.iface = &endpointInterface{}
  151. ep.iface.CopyTo(dstEp.iface)
  152. }
  153. dstEp.exposedPorts = make([]types.TransportPort, len(ep.exposedPorts))
  154. copy(dstEp.exposedPorts, ep.exposedPorts)
  155. dstEp.generic = options.Generic{}
  156. for k, v := range ep.generic {
  157. dstEp.generic[k] = v
  158. }
  159. return nil
  160. }
  161. func (ep *endpoint) ID() string {
  162. ep.Lock()
  163. defer ep.Unlock()
  164. return ep.id
  165. }
  166. func (ep *endpoint) Name() string {
  167. ep.Lock()
  168. defer ep.Unlock()
  169. return ep.name
  170. }
  171. func (ep *endpoint) Network() string {
  172. if ep.network == nil {
  173. return ""
  174. }
  175. return ep.network.name
  176. }
  177. func (ep *endpoint) isAnonymous() bool {
  178. ep.Lock()
  179. defer ep.Unlock()
  180. return ep.anonymous
  181. }
  182. // endpoint Key structure : endpoint/network-id/endpoint-id
  183. func (ep *endpoint) Key() []string {
  184. if ep.network == nil {
  185. return nil
  186. }
  187. return []string{datastore.EndpointKeyPrefix, ep.network.id, ep.id}
  188. }
  189. func (ep *endpoint) KeyPrefix() []string {
  190. if ep.network == nil {
  191. return nil
  192. }
  193. return []string{datastore.EndpointKeyPrefix, ep.network.id}
  194. }
  195. func (ep *endpoint) networkIDFromKey(key string) (string, error) {
  196. // endpoint Key structure : docker/libnetwork/endpoint/${network-id}/${endpoint-id}
  197. // it's an invalid key if the key doesn't have all the 5 key elements above
  198. keyElements := strings.Split(key, "/")
  199. if !strings.HasPrefix(key, datastore.Key(datastore.EndpointKeyPrefix)) || len(keyElements) < 5 {
  200. return "", fmt.Errorf("invalid endpoint key : %v", key)
  201. }
  202. // network-id is placed at index=3. pls refer to endpoint.Key() method
  203. return strings.Split(key, "/")[3], nil
  204. }
  205. func (ep *endpoint) Value() []byte {
  206. b, err := json.Marshal(ep)
  207. if err != nil {
  208. return nil
  209. }
  210. return b
  211. }
  212. func (ep *endpoint) SetValue(value []byte) error {
  213. return json.Unmarshal(value, ep)
  214. }
  215. func (ep *endpoint) Index() uint64 {
  216. ep.Lock()
  217. defer ep.Unlock()
  218. return ep.dbIndex
  219. }
  220. func (ep *endpoint) SetIndex(index uint64) {
  221. ep.Lock()
  222. defer ep.Unlock()
  223. ep.dbIndex = index
  224. ep.dbExists = true
  225. }
  226. func (ep *endpoint) Exists() bool {
  227. ep.Lock()
  228. defer ep.Unlock()
  229. return ep.dbExists
  230. }
  231. func (ep *endpoint) Skip() bool {
  232. return ep.getNetwork().Skip()
  233. }
  234. func (ep *endpoint) processOptions(options ...EndpointOption) {
  235. ep.Lock()
  236. defer ep.Unlock()
  237. for _, opt := range options {
  238. if opt != nil {
  239. opt(ep)
  240. }
  241. }
  242. }
  243. func (ep *endpoint) getNetwork() *network {
  244. ep.Lock()
  245. defer ep.Unlock()
  246. return ep.network
  247. }
  248. func (ep *endpoint) getNetworkFromStore() (*network, error) {
  249. if ep.network == nil {
  250. return nil, fmt.Errorf("invalid network object in endpoint %s", ep.Name())
  251. }
  252. return ep.network.ctrlr.getNetworkFromStore(ep.network.id)
  253. }
  254. func (ep *endpoint) Join(sbox Sandbox, options ...EndpointOption) error {
  255. if sbox == nil {
  256. return types.BadRequestErrorf("endpoint cannot be joined by nil container")
  257. }
  258. sb, ok := sbox.(*sandbox)
  259. if !ok {
  260. return types.BadRequestErrorf("not a valid Sandbox interface")
  261. }
  262. sb.joinLeaveStart()
  263. defer sb.joinLeaveEnd()
  264. return ep.sbJoin(sbox, options...)
  265. }
  266. func (ep *endpoint) sbJoin(sbox Sandbox, options ...EndpointOption) error {
  267. var err error
  268. sb, ok := sbox.(*sandbox)
  269. if !ok {
  270. return types.BadRequestErrorf("not a valid Sandbox interface")
  271. }
  272. network, err := ep.getNetworkFromStore()
  273. if err != nil {
  274. return fmt.Errorf("failed to get network from store during join: %v", err)
  275. }
  276. ep, err = network.getEndpointFromStore(ep.ID())
  277. if err != nil {
  278. return fmt.Errorf("failed to get endpoint from store during join: %v", err)
  279. }
  280. ep.Lock()
  281. if ep.sandboxID != "" {
  282. ep.Unlock()
  283. return types.ForbiddenErrorf("another container is attached to the same network endpoint")
  284. }
  285. ep.Unlock()
  286. ep.Lock()
  287. ep.network = network
  288. ep.sandboxID = sbox.ID()
  289. ep.joinInfo = &endpointJoinInfo{}
  290. epid := ep.id
  291. ep.Unlock()
  292. defer func() {
  293. if err != nil {
  294. ep.Lock()
  295. ep.sandboxID = ""
  296. ep.Unlock()
  297. }
  298. }()
  299. network.Lock()
  300. nid := network.id
  301. network.Unlock()
  302. ep.processOptions(options...)
  303. driver, err := network.driver()
  304. if err != nil {
  305. return fmt.Errorf("failed to join endpoint: %v", err)
  306. }
  307. err = driver.Join(nid, epid, sbox.Key(), ep, sbox.Labels())
  308. if err != nil {
  309. return err
  310. }
  311. defer func() {
  312. if err != nil {
  313. // Do not alter global err variable, it's needed by the previous defer
  314. if err := driver.Leave(nid, epid); err != nil {
  315. log.Warnf("driver leave failed while rolling back join: %v", err)
  316. }
  317. }
  318. }()
  319. // Watch for service records
  320. network.getController().watchSvcRecord(ep)
  321. address := ""
  322. if ip := ep.getFirstInterfaceAddress(); ip != nil {
  323. address = ip.String()
  324. }
  325. if err = sb.updateHostsFile(address, network.getSvcRecords(ep)); err != nil {
  326. return err
  327. }
  328. if err = sb.updateDNS(network.enableIPv6); err != nil {
  329. return err
  330. }
  331. if err = network.getController().updateToStore(ep); err != nil {
  332. return err
  333. }
  334. sb.Lock()
  335. heap.Push(&sb.endpoints, ep)
  336. sb.Unlock()
  337. defer func() {
  338. if err != nil {
  339. for i, e := range sb.getConnectedEndpoints() {
  340. if e == ep {
  341. sb.Lock()
  342. heap.Remove(&sb.endpoints, i)
  343. sb.Unlock()
  344. return
  345. }
  346. }
  347. }
  348. }()
  349. if err = sb.populateNetworkResources(ep); err != nil {
  350. return err
  351. }
  352. if sb.needDefaultGW() {
  353. return sb.setupDefaultGW(ep)
  354. }
  355. return sb.clearDefaultGW()
  356. }
  357. func (ep *endpoint) rename(name string) error {
  358. var err error
  359. n := ep.getNetwork()
  360. if n == nil {
  361. return fmt.Errorf("network not connected for ep %q", ep.name)
  362. }
  363. n.getController().Lock()
  364. netWatch, ok := n.getController().nmap[n.ID()]
  365. n.getController().Unlock()
  366. if !ok {
  367. return fmt.Errorf("watch null for network %q", n.Name())
  368. }
  369. n.updateSvcRecord(ep, n.getController().getLocalEps(netWatch), false)
  370. oldName := ep.name
  371. ep.name = name
  372. n.updateSvcRecord(ep, n.getController().getLocalEps(netWatch), true)
  373. defer func() {
  374. if err != nil {
  375. n.updateSvcRecord(ep, n.getController().getLocalEps(netWatch), false)
  376. ep.name = oldName
  377. n.updateSvcRecord(ep, n.getController().getLocalEps(netWatch), true)
  378. }
  379. }()
  380. // Update the store with the updated name
  381. if err = n.getController().updateToStore(ep); err != nil {
  382. return err
  383. }
  384. // After the name change do a dummy endpoint count update to
  385. // trigger the service record update in the peer nodes
  386. // Ignore the error because updateStore fail for EpCnt is a
  387. // benign error. Besides there is no meaningful recovery that
  388. // we can do. When the cluster recovers subsequent EpCnt update
  389. // will force the peers to get the correct EP name.
  390. n.getEpCnt().updateStore()
  391. return err
  392. }
  393. func (ep *endpoint) hasInterface(iName string) bool {
  394. ep.Lock()
  395. defer ep.Unlock()
  396. return ep.iface != nil && ep.iface.srcName == iName
  397. }
  398. func (ep *endpoint) Leave(sbox Sandbox, options ...EndpointOption) error {
  399. if sbox == nil || sbox.ID() == "" || sbox.Key() == "" {
  400. return types.BadRequestErrorf("invalid Sandbox passed to enpoint leave: %v", sbox)
  401. }
  402. sb, ok := sbox.(*sandbox)
  403. if !ok {
  404. return types.BadRequestErrorf("not a valid Sandbox interface")
  405. }
  406. sb.joinLeaveStart()
  407. defer sb.joinLeaveEnd()
  408. return ep.sbLeave(sbox, options...)
  409. }
  410. func (ep *endpoint) sbLeave(sbox Sandbox, options ...EndpointOption) error {
  411. sb, ok := sbox.(*sandbox)
  412. if !ok {
  413. return types.BadRequestErrorf("not a valid Sandbox interface")
  414. }
  415. n, err := ep.getNetworkFromStore()
  416. if err != nil {
  417. return fmt.Errorf("failed to get network from store during leave: %v", err)
  418. }
  419. ep, err = n.getEndpointFromStore(ep.ID())
  420. if err != nil {
  421. return fmt.Errorf("failed to get endpoint from store during leave: %v", err)
  422. }
  423. ep.Lock()
  424. sid := ep.sandboxID
  425. ep.Unlock()
  426. if sid == "" {
  427. return types.ForbiddenErrorf("cannot leave endpoint with no attached sandbox")
  428. }
  429. if sid != sbox.ID() {
  430. return types.ForbiddenErrorf("unexpected sandbox ID in leave request. Expected %s. Got %s", ep.sandboxID, sbox.ID())
  431. }
  432. ep.processOptions(options...)
  433. d, err := n.driver()
  434. if err != nil {
  435. return fmt.Errorf("failed to leave endpoint: %v", err)
  436. }
  437. ep.Lock()
  438. ep.sandboxID = ""
  439. ep.network = n
  440. ep.Unlock()
  441. if err := d.Leave(n.id, ep.id); err != nil {
  442. if _, ok := err.(types.MaskableError); !ok {
  443. log.Warnf("driver error disconnecting container %s : %v", ep.name, err)
  444. }
  445. }
  446. if err := sb.clearNetworkResources(ep); err != nil {
  447. log.Warnf("Could not cleanup network resources on container %s disconnect: %v", ep.name, err)
  448. }
  449. // Update the store about the sandbox detach only after we
  450. // have completed sb.clearNetworkresources above to avoid
  451. // spurious logs when cleaning up the sandbox when the daemon
  452. // ungracefully exits and restarts before completing sandbox
  453. // detach but after store has been updated.
  454. if err := n.getController().updateToStore(ep); err != nil {
  455. return err
  456. }
  457. sb.deleteHostsEntries(n.getSvcRecords(ep))
  458. if !sb.inDelete && sb.needDefaultGW() {
  459. ep := sb.getEPwithoutGateway()
  460. if ep == nil {
  461. return fmt.Errorf("endpoint without GW expected, but not found")
  462. }
  463. return sb.setupDefaultGW(ep)
  464. }
  465. return sb.clearDefaultGW()
  466. }
  467. func (ep *endpoint) Delete() error {
  468. var err error
  469. n, err := ep.getNetworkFromStore()
  470. if err != nil {
  471. return fmt.Errorf("failed to get network during Delete: %v", err)
  472. }
  473. ep, err = n.getEndpointFromStore(ep.ID())
  474. if err != nil {
  475. return fmt.Errorf("failed to get endpoint from store during Delete: %v", err)
  476. }
  477. ep.Lock()
  478. epid := ep.id
  479. name := ep.name
  480. sb, _ := n.getController().SandboxByID(ep.sandboxID)
  481. if sb != nil {
  482. ep.Unlock()
  483. return &ActiveContainerError{name: name, id: epid}
  484. }
  485. ep.Unlock()
  486. if err = n.getController().deleteFromStore(ep); err != nil {
  487. return err
  488. }
  489. defer func() {
  490. if err != nil {
  491. ep.dbExists = false
  492. if e := n.getController().updateToStore(ep); e != nil {
  493. log.Warnf("failed to recreate endpoint in store %s : %v", name, e)
  494. }
  495. }
  496. }()
  497. if err = n.getEpCnt().DecEndpointCnt(); err != nil {
  498. return err
  499. }
  500. defer func() {
  501. if err != nil {
  502. if e := n.getEpCnt().IncEndpointCnt(); e != nil {
  503. log.Warnf("failed to update network %s : %v", n.name, e)
  504. }
  505. }
  506. }()
  507. // unwatch for service records
  508. n.getController().unWatchSvcRecord(ep)
  509. if err = ep.deleteEndpoint(); err != nil {
  510. return err
  511. }
  512. ep.releaseAddress()
  513. return nil
  514. }
  515. func (ep *endpoint) deleteEndpoint() error {
  516. ep.Lock()
  517. n := ep.network
  518. name := ep.name
  519. epid := ep.id
  520. ep.Unlock()
  521. driver, err := n.driver()
  522. if err != nil {
  523. return fmt.Errorf("failed to delete endpoint: %v", err)
  524. }
  525. if err := driver.DeleteEndpoint(n.id, epid); err != nil {
  526. if _, ok := err.(types.ForbiddenError); ok {
  527. return err
  528. }
  529. if _, ok := err.(types.MaskableError); !ok {
  530. log.Warnf("driver error deleting endpoint %s : %v", name, err)
  531. }
  532. }
  533. return nil
  534. }
  535. func (ep *endpoint) getSandbox() (*sandbox, bool) {
  536. ep.Lock()
  537. c := ep.network.getController()
  538. sid := ep.sandboxID
  539. ep.Unlock()
  540. c.Lock()
  541. ps, ok := c.sandboxes[sid]
  542. c.Unlock()
  543. return ps, ok
  544. }
  545. func (ep *endpoint) getFirstInterfaceAddress() net.IP {
  546. ep.Lock()
  547. defer ep.Unlock()
  548. if ep.iface.addr != nil {
  549. return ep.iface.addr.IP
  550. }
  551. return nil
  552. }
  553. // EndpointOptionGeneric function returns an option setter for a Generic option defined
  554. // in a Dictionary of Key-Value pair
  555. func EndpointOptionGeneric(generic map[string]interface{}) EndpointOption {
  556. return func(ep *endpoint) {
  557. for k, v := range generic {
  558. ep.generic[k] = v
  559. }
  560. }
  561. }
  562. // CreateOptionIpam function returns an option setter for the ipam configuration for this endpoint
  563. func CreateOptionIpam(ipV4, ipV6 net.IP, ipamOptions map[string]string) EndpointOption {
  564. return func(ep *endpoint) {
  565. ep.prefAddress = ipV4
  566. ep.prefAddressV6 = ipV6
  567. ep.ipamOptions = ipamOptions
  568. }
  569. }
  570. // CreateOptionExposedPorts function returns an option setter for the container exposed
  571. // ports option to be passed to network.CreateEndpoint() method.
  572. func CreateOptionExposedPorts(exposedPorts []types.TransportPort) EndpointOption {
  573. return func(ep *endpoint) {
  574. // Defensive copy
  575. eps := make([]types.TransportPort, len(exposedPorts))
  576. copy(eps, exposedPorts)
  577. // Store endpoint label and in generic because driver needs it
  578. ep.exposedPorts = eps
  579. ep.generic[netlabel.ExposedPorts] = eps
  580. }
  581. }
  582. // CreateOptionPortMapping function returns an option setter for the mapping
  583. // ports option to be passed to network.CreateEndpoint() method.
  584. func CreateOptionPortMapping(portBindings []types.PortBinding) EndpointOption {
  585. return func(ep *endpoint) {
  586. // Store a copy of the bindings as generic data to pass to the driver
  587. pbs := make([]types.PortBinding, len(portBindings))
  588. copy(pbs, portBindings)
  589. ep.generic[netlabel.PortMap] = pbs
  590. }
  591. }
  592. // CreateOptionAnonymous function returns an option setter for setting
  593. // this endpoint as anonymous
  594. func CreateOptionAnonymous() EndpointOption {
  595. return func(ep *endpoint) {
  596. ep.anonymous = true
  597. }
  598. }
  599. // JoinOptionPriority function returns an option setter for priority option to
  600. // be passed to the endpoint.Join() method.
  601. func JoinOptionPriority(ep Endpoint, prio int) EndpointOption {
  602. return func(ep *endpoint) {
  603. // ep lock already acquired
  604. c := ep.network.getController()
  605. c.Lock()
  606. sb, ok := c.sandboxes[ep.sandboxID]
  607. c.Unlock()
  608. if !ok {
  609. log.Errorf("Could not set endpoint priority value during Join to endpoint %s: No sandbox id present in endpoint", ep.id)
  610. return
  611. }
  612. sb.epPriority[ep.id] = prio
  613. }
  614. }
  615. func (ep *endpoint) DataScope() string {
  616. return ep.getNetwork().DataScope()
  617. }
  618. func (ep *endpoint) assignAddress(ipam ipamapi.Ipam, assignIPv4, assignIPv6 bool) error {
  619. var err error
  620. n := ep.getNetwork()
  621. if n.Type() == "host" || n.Type() == "null" {
  622. return nil
  623. }
  624. log.Debugf("Assigning addresses for endpoint %s's interface on network %s", ep.Name(), n.Name())
  625. if assignIPv4 {
  626. if err = ep.assignAddressVersion(4, ipam); err != nil {
  627. return err
  628. }
  629. }
  630. if assignIPv6 {
  631. err = ep.assignAddressVersion(6, ipam)
  632. }
  633. return err
  634. }
  635. func (ep *endpoint) assignAddressVersion(ipVer int, ipam ipamapi.Ipam) error {
  636. var (
  637. poolID *string
  638. address **net.IPNet
  639. prefAdd net.IP
  640. progAdd net.IP
  641. )
  642. n := ep.getNetwork()
  643. switch ipVer {
  644. case 4:
  645. poolID = &ep.iface.v4PoolID
  646. address = &ep.iface.addr
  647. prefAdd = ep.prefAddress
  648. case 6:
  649. poolID = &ep.iface.v6PoolID
  650. address = &ep.iface.addrv6
  651. prefAdd = ep.prefAddressV6
  652. default:
  653. return types.InternalErrorf("incorrect ip version number passed: %d", ipVer)
  654. }
  655. ipInfo := n.getIPInfo(ipVer)
  656. // ipv6 address is not mandatory
  657. if len(ipInfo) == 0 && ipVer == 6 {
  658. return nil
  659. }
  660. // The address to program may be chosen by the user or by the network driver in one specific
  661. // case to support backward compatibility with `docker daemon --fixed-cidrv6` use case
  662. if prefAdd != nil {
  663. progAdd = prefAdd
  664. } else if *address != nil {
  665. progAdd = (*address).IP
  666. }
  667. for _, d := range ipInfo {
  668. if progAdd != nil && !d.Pool.Contains(progAdd) {
  669. continue
  670. }
  671. addr, _, err := ipam.RequestAddress(d.PoolID, progAdd, ep.ipamOptions)
  672. if err == nil {
  673. ep.Lock()
  674. *address = addr
  675. *poolID = d.PoolID
  676. ep.Unlock()
  677. return nil
  678. }
  679. if err != ipamapi.ErrNoAvailableIPs || progAdd != nil {
  680. return err
  681. }
  682. }
  683. if progAdd != nil {
  684. return types.BadRequestErrorf("Invalid preferred address %s: It does not belong to any of this network's subnets")
  685. }
  686. return fmt.Errorf("no available IPv%d addresses on this network's address pools: %s (%s)", ipVer, n.Name(), n.ID())
  687. }
  688. func (ep *endpoint) releaseAddress() {
  689. n := ep.getNetwork()
  690. if n.Type() == "host" || n.Type() == "null" {
  691. return
  692. }
  693. log.Debugf("Releasing addresses for endpoint %s's interface on network %s", ep.Name(), n.Name())
  694. ipam, err := n.getController().getIpamDriver(n.ipamType)
  695. if err != nil {
  696. log.Warnf("Failed to retrieve ipam driver to release interface address on delete of endpoint %s (%s): %v", ep.Name(), ep.ID(), err)
  697. return
  698. }
  699. if err := ipam.ReleaseAddress(ep.iface.v4PoolID, ep.iface.addr.IP); err != nil {
  700. log.Warnf("Failed to release ip address %s on delete of endpoint %s (%s): %v", ep.iface.addr.IP, ep.Name(), ep.ID(), err)
  701. }
  702. if ep.iface.addrv6 != nil && ep.iface.addrv6.IP.IsGlobalUnicast() {
  703. if err := ipam.ReleaseAddress(ep.iface.v6PoolID, ep.iface.addrv6.IP); err != nil {
  704. log.Warnf("Failed to release ip address %s on delete of endpoint %s (%s): %v", ep.iface.addrv6.IP, ep.Name(), ep.ID(), err)
  705. }
  706. }
  707. }
  708. func (c *controller) cleanupLocalEndpoints() {
  709. nl, err := c.getNetworksForScope(datastore.LocalScope)
  710. if err != nil {
  711. log.Warnf("Could not get list of networks during endpoint cleanup: %v", err)
  712. return
  713. }
  714. for _, n := range nl {
  715. epl, err := n.getEndpointsFromStore()
  716. if err != nil {
  717. log.Warnf("Could not get list of endpoints in network %s during endpoint cleanup: %v", n.name, err)
  718. continue
  719. }
  720. for _, ep := range epl {
  721. if err := ep.Delete(); err != nil {
  722. log.Warnf("Could not delete local endpoint %s during endpoint cleanup: %v", ep.name, err)
  723. }
  724. }
  725. }
  726. }