endpoint.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  1. package libnetwork
  2. import (
  3. "container/heap"
  4. "encoding/json"
  5. "fmt"
  6. "net"
  7. "sync"
  8. log "github.com/Sirupsen/logrus"
  9. "github.com/docker/libnetwork/datastore"
  10. "github.com/docker/libnetwork/netlabel"
  11. "github.com/docker/libnetwork/types"
  12. )
  13. // Endpoint represents a logical connection between a network and a sandbox.
  14. type Endpoint interface {
  15. // A system generated id for this endpoint.
  16. ID() string
  17. // Name returns the name of this endpoint.
  18. Name() string
  19. // Network returns the name of the network to which this endpoint is attached.
  20. Network() string
  21. // Join joins the sandbox to the endpoint and populates into the sandbox
  22. // the network resources allocated for the endpoint.
  23. Join(sandbox Sandbox, options ...EndpointOption) error
  24. // Leave detaches the network resources populated in the sandbox.
  25. Leave(sandbox Sandbox, options ...EndpointOption) error
  26. // Return certain operational data belonging to this endpoint
  27. Info() EndpointInfo
  28. // DriverInfo returns a collection of driver operational data related to this endpoint retrieved from the driver
  29. DriverInfo() (map[string]interface{}, error)
  30. // Delete and detaches this endpoint from the network.
  31. Delete() error
  32. }
  33. // EndpointOption is a option setter function type used to pass varios options to Network
  34. // and Endpoint interfaces methods. The various setter functions of type EndpointOption are
  35. // provided by libnetwork, they look like <Create|Join|Leave>Option[...](...)
  36. type EndpointOption func(ep *endpoint)
  37. type endpoint struct {
  38. name string
  39. id string
  40. network *network
  41. iface *endpointInterface
  42. joinInfo *endpointJoinInfo
  43. sandboxID string
  44. exposedPorts []types.TransportPort
  45. generic map[string]interface{}
  46. joinLeaveDone chan struct{}
  47. dbIndex uint64
  48. dbExists bool
  49. sync.Mutex
  50. }
  51. func (ep *endpoint) MarshalJSON() ([]byte, error) {
  52. ep.Lock()
  53. defer ep.Unlock()
  54. epMap := make(map[string]interface{})
  55. epMap["name"] = ep.name
  56. epMap["id"] = ep.id
  57. epMap["ep_iface"] = ep.iface
  58. epMap["exposed_ports"] = ep.exposedPorts
  59. epMap["generic"] = ep.generic
  60. epMap["sandbox"] = ep.sandboxID
  61. return json.Marshal(epMap)
  62. }
  63. func (ep *endpoint) UnmarshalJSON(b []byte) (err error) {
  64. ep.Lock()
  65. defer ep.Unlock()
  66. var epMap map[string]interface{}
  67. if err := json.Unmarshal(b, &epMap); err != nil {
  68. return err
  69. }
  70. ep.name = epMap["name"].(string)
  71. ep.id = epMap["id"].(string)
  72. ib, _ := json.Marshal(epMap["ep_iface"])
  73. json.Unmarshal(ib, &ep.iface)
  74. tb, _ := json.Marshal(epMap["exposed_ports"])
  75. var tPorts []types.TransportPort
  76. json.Unmarshal(tb, &tPorts)
  77. ep.exposedPorts = tPorts
  78. cb, _ := json.Marshal(epMap["sandbox"])
  79. json.Unmarshal(cb, &ep.sandboxID)
  80. if epMap["generic"] != nil {
  81. ep.generic = epMap["generic"].(map[string]interface{})
  82. }
  83. return nil
  84. }
  85. func (ep *endpoint) ID() string {
  86. ep.Lock()
  87. defer ep.Unlock()
  88. return ep.id
  89. }
  90. func (ep *endpoint) Name() string {
  91. ep.Lock()
  92. defer ep.Unlock()
  93. return ep.name
  94. }
  95. func (ep *endpoint) Network() string {
  96. return ep.getNetwork().name
  97. }
  98. // endpoint Key structure : endpoint/network-id/endpoint-id
  99. func (ep *endpoint) Key() []string {
  100. return []string{datastore.EndpointKeyPrefix, ep.getNetwork().id, ep.id}
  101. }
  102. func (ep *endpoint) KeyPrefix() []string {
  103. return []string{datastore.EndpointKeyPrefix, ep.getNetwork().id}
  104. }
  105. func (ep *endpoint) networkIDFromKey(key []string) (string, error) {
  106. // endpoint Key structure : endpoint/network-id/endpoint-id
  107. // it's an invalid key if the key doesn't have all the 3 key elements above
  108. if key == nil || len(key) < 3 || key[0] != datastore.EndpointKeyPrefix {
  109. return "", fmt.Errorf("invalid endpoint key : %v", key)
  110. }
  111. // network-id is placed at index=1. pls refer to endpoint.Key() method
  112. return key[1], nil
  113. }
  114. func (ep *endpoint) Value() []byte {
  115. b, err := json.Marshal(ep)
  116. if err != nil {
  117. return nil
  118. }
  119. return b
  120. }
  121. func (ep *endpoint) SetValue(value []byte) error {
  122. return json.Unmarshal(value, ep)
  123. }
  124. func (ep *endpoint) Index() uint64 {
  125. ep.Lock()
  126. defer ep.Unlock()
  127. return ep.dbIndex
  128. }
  129. func (ep *endpoint) SetIndex(index uint64) {
  130. ep.Lock()
  131. defer ep.Unlock()
  132. ep.dbIndex = index
  133. ep.dbExists = true
  134. }
  135. func (ep *endpoint) Exists() bool {
  136. ep.Lock()
  137. defer ep.Unlock()
  138. return ep.dbExists
  139. }
  140. func (ep *endpoint) processOptions(options ...EndpointOption) {
  141. ep.Lock()
  142. defer ep.Unlock()
  143. for _, opt := range options {
  144. if opt != nil {
  145. opt(ep)
  146. }
  147. }
  148. }
  149. // joinLeaveStart waits to ensure there are no joins or leaves in progress and
  150. // marks this join/leave in progress without race
  151. func (ep *endpoint) joinLeaveStart() {
  152. ep.Lock()
  153. defer ep.Unlock()
  154. for ep.joinLeaveDone != nil {
  155. joinLeaveDone := ep.joinLeaveDone
  156. ep.Unlock()
  157. select {
  158. case <-joinLeaveDone:
  159. }
  160. ep.Lock()
  161. }
  162. ep.joinLeaveDone = make(chan struct{})
  163. }
  164. // joinLeaveEnd marks the end of this join/leave operation and
  165. // signals the same without race to other join and leave waiters
  166. func (ep *endpoint) joinLeaveEnd() {
  167. ep.Lock()
  168. defer ep.Unlock()
  169. if ep.joinLeaveDone != nil {
  170. close(ep.joinLeaveDone)
  171. ep.joinLeaveDone = nil
  172. }
  173. }
  174. func (ep *endpoint) Join(sbox Sandbox, options ...EndpointOption) error {
  175. var err error
  176. if sbox == nil {
  177. return types.BadRequestErrorf("endpoint cannot be joined by nil container")
  178. }
  179. sb, ok := sbox.(*sandbox)
  180. if !ok {
  181. return types.BadRequestErrorf("not a valid Sandbox interface")
  182. }
  183. ep.joinLeaveStart()
  184. defer ep.joinLeaveEnd()
  185. ep.Lock()
  186. if ep.sandboxID != "" {
  187. ep.Unlock()
  188. return types.ForbiddenErrorf("a sandbox has already joined the endpoint")
  189. }
  190. ep.sandboxID = sbox.ID()
  191. ep.joinInfo = &endpointJoinInfo{}
  192. network := ep.network
  193. epid := ep.id
  194. ep.Unlock()
  195. defer func() {
  196. if err != nil {
  197. ep.Lock()
  198. ep.sandboxID = ""
  199. ep.Unlock()
  200. }
  201. }()
  202. network.Lock()
  203. driver := network.driver
  204. nid := network.id
  205. network.Unlock()
  206. ep.processOptions(options...)
  207. err = driver.Join(nid, epid, sbox.Key(), ep, sbox.Labels())
  208. if err != nil {
  209. return err
  210. }
  211. defer func() {
  212. if err != nil {
  213. // Do not alter global err variable, it's needed by the previous defer
  214. if err := driver.Leave(nid, epid); err != nil {
  215. log.Warnf("driver leave failed while rolling back join: %v", err)
  216. }
  217. }
  218. }()
  219. address := ""
  220. if ip := ep.getFirstInterfaceAddress(); ip != nil {
  221. address = ip.String()
  222. }
  223. if err = sb.updateHostsFile(address, network.getSvcRecords()); err != nil {
  224. return err
  225. }
  226. if err = sb.updateDNS(ep.getNetwork().enableIPv6); err != nil {
  227. return err
  228. }
  229. if err = network.ctrlr.updateEndpointToStore(ep); err != nil {
  230. return err
  231. }
  232. sb.Lock()
  233. heap.Push(&sb.endpoints, ep)
  234. sb.Unlock()
  235. defer func() {
  236. if err != nil {
  237. for i, e := range sb.getConnectedEndpoints() {
  238. if e == ep {
  239. sb.Lock()
  240. heap.Remove(&sb.endpoints, i)
  241. sb.Unlock()
  242. return
  243. }
  244. }
  245. }
  246. }()
  247. if err = sb.populateNetworkResources(ep); err != nil {
  248. return err
  249. }
  250. if sb.needDefaultGW() {
  251. return sb.setupDefaultGW(ep)
  252. }
  253. return sb.clearDefaultGW()
  254. }
  255. func (ep *endpoint) hasInterface(iName string) bool {
  256. ep.Lock()
  257. defer ep.Unlock()
  258. return ep.iface != nil && ep.iface.srcName == iName
  259. }
  260. func (ep *endpoint) Leave(sbox Sandbox, options ...EndpointOption) error {
  261. ep.joinLeaveStart()
  262. defer ep.joinLeaveEnd()
  263. if sbox == nil || sbox.ID() == "" || sbox.Key() == "" {
  264. return types.BadRequestErrorf("invalid Sandbox passed to enpoint leave: %v", sbox)
  265. }
  266. sb, ok := sbox.(*sandbox)
  267. if !ok {
  268. return types.BadRequestErrorf("not a valid Sandbox interface")
  269. }
  270. ep.Lock()
  271. sid := ep.sandboxID
  272. ep.Unlock()
  273. if sid == "" {
  274. return types.ForbiddenErrorf("cannot leave endpoint with no attached sandbox")
  275. }
  276. if sid != sbox.ID() {
  277. return types.ForbiddenErrorf("unexpected sandbox ID in leave request. Expected %s. Got %s", ep.sandboxID, sbox.ID())
  278. }
  279. ep.processOptions(options...)
  280. ep.Lock()
  281. ep.sandboxID = ""
  282. n := ep.network
  283. ep.Unlock()
  284. n.Lock()
  285. c := n.ctrlr
  286. d := n.driver
  287. n.Unlock()
  288. if err := c.updateEndpointToStore(ep); err != nil {
  289. ep.Lock()
  290. ep.sandboxID = sid
  291. ep.Unlock()
  292. return err
  293. }
  294. if err := d.Leave(n.id, ep.id); err != nil {
  295. return err
  296. }
  297. if err := sb.clearNetworkResources(ep); err != nil {
  298. return err
  299. }
  300. if sb.needDefaultGW() {
  301. ep := sb.getEPwithoutGateway()
  302. if ep == nil {
  303. return fmt.Errorf("endpoint without GW expected, but not found")
  304. }
  305. return sb.setupDefaultGW(ep)
  306. }
  307. return sb.clearDefaultGW()
  308. }
  309. func (ep *endpoint) Delete() error {
  310. var err error
  311. ep.Lock()
  312. epid := ep.id
  313. name := ep.name
  314. n := ep.network
  315. if ep.sandboxID != "" {
  316. ep.Unlock()
  317. return &ActiveContainerError{name: name, id: epid}
  318. }
  319. n.Lock()
  320. ctrlr := n.ctrlr
  321. n.Unlock()
  322. ep.Unlock()
  323. if err = ctrlr.deleteEndpointFromStore(ep); err != nil {
  324. return err
  325. }
  326. defer func() {
  327. if err != nil {
  328. ep.SetIndex(0)
  329. if e := ctrlr.updateEndpointToStore(ep); e != nil {
  330. log.Warnf("failed to recreate endpoint in store %s : %v", name, err)
  331. }
  332. }
  333. }()
  334. // Update the endpoint count in network and update it in the datastore
  335. n.DecEndpointCnt()
  336. if err = ctrlr.updateNetworkToStore(n); err != nil {
  337. return err
  338. }
  339. defer func() {
  340. if err != nil {
  341. n.IncEndpointCnt()
  342. if e := ctrlr.updateNetworkToStore(n); e != nil {
  343. log.Warnf("failed to update network %s : %v", n.name, e)
  344. }
  345. }
  346. }()
  347. if err = ep.deleteEndpoint(); err != nil {
  348. return err
  349. }
  350. return nil
  351. }
  352. func (ep *endpoint) deleteEndpoint() error {
  353. ep.Lock()
  354. n := ep.network
  355. name := ep.name
  356. epid := ep.id
  357. ep.Unlock()
  358. n.Lock()
  359. _, ok := n.endpoints[epid]
  360. if !ok {
  361. n.Unlock()
  362. return nil
  363. }
  364. nid := n.id
  365. driver := n.driver
  366. delete(n.endpoints, epid)
  367. n.Unlock()
  368. if err := driver.DeleteEndpoint(nid, epid); err != nil {
  369. if _, ok := err.(types.ForbiddenError); ok {
  370. n.Lock()
  371. n.endpoints[epid] = ep
  372. n.Unlock()
  373. return err
  374. }
  375. log.Warnf("driver error deleting endpoint %s : %v", name, err)
  376. }
  377. n.updateSvcRecord(ep, false)
  378. return nil
  379. }
  380. func (ep *endpoint) getNetwork() *network {
  381. ep.Lock()
  382. defer ep.Unlock()
  383. return ep.network
  384. }
  385. func (ep *endpoint) getSandbox() (*sandbox, bool) {
  386. ep.Lock()
  387. c := ep.network.getController()
  388. sid := ep.sandboxID
  389. ep.Unlock()
  390. c.Lock()
  391. ps, ok := c.sandboxes[sid]
  392. c.Unlock()
  393. return ps, ok
  394. }
  395. func (ep *endpoint) getFirstInterfaceAddress() net.IP {
  396. ep.Lock()
  397. defer ep.Unlock()
  398. if ep.iface != nil {
  399. return ep.iface.addr.IP
  400. }
  401. return nil
  402. }
  403. // EndpointOptionGeneric function returns an option setter for a Generic option defined
  404. // in a Dictionary of Key-Value pair
  405. func EndpointOptionGeneric(generic map[string]interface{}) EndpointOption {
  406. return func(ep *endpoint) {
  407. for k, v := range generic {
  408. ep.generic[k] = v
  409. }
  410. }
  411. }
  412. // CreateOptionExposedPorts function returns an option setter for the container exposed
  413. // ports option to be passed to network.CreateEndpoint() method.
  414. func CreateOptionExposedPorts(exposedPorts []types.TransportPort) EndpointOption {
  415. return func(ep *endpoint) {
  416. // Defensive copy
  417. eps := make([]types.TransportPort, len(exposedPorts))
  418. copy(eps, exposedPorts)
  419. // Store endpoint label and in generic because driver needs it
  420. ep.exposedPorts = eps
  421. ep.generic[netlabel.ExposedPorts] = eps
  422. }
  423. }
  424. // CreateOptionPortMapping function returns an option setter for the mapping
  425. // ports option to be passed to network.CreateEndpoint() method.
  426. func CreateOptionPortMapping(portBindings []types.PortBinding) EndpointOption {
  427. return func(ep *endpoint) {
  428. // Store a copy of the bindings as generic data to pass to the driver
  429. pbs := make([]types.PortBinding, len(portBindings))
  430. copy(pbs, portBindings)
  431. ep.generic[netlabel.PortMap] = pbs
  432. }
  433. }
  434. // JoinOptionPriority function returns an option setter for priority option to
  435. // be passed to the endpoint.Join() method.
  436. func JoinOptionPriority(ep Endpoint, prio int) EndpointOption {
  437. return func(ep *endpoint) {
  438. // ep lock already acquired
  439. c := ep.network.getController()
  440. c.Lock()
  441. sb, ok := c.sandboxes[ep.sandboxID]
  442. c.Unlock()
  443. if !ok {
  444. log.Errorf("Could not set endpoint priority value during Join to endpoint %s: No sandbox id present in endpoint", ep.id)
  445. return
  446. }
  447. sb.epPriority[ep.id] = prio
  448. }
  449. }