sandbox.go 24 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015
  1. package libnetwork
  2. import (
  3. "container/heap"
  4. "encoding/json"
  5. "fmt"
  6. "net"
  7. "strings"
  8. "sync"
  9. "time"
  10. log "github.com/Sirupsen/logrus"
  11. "github.com/docker/libnetwork/etchosts"
  12. "github.com/docker/libnetwork/netlabel"
  13. "github.com/docker/libnetwork/osl"
  14. "github.com/docker/libnetwork/types"
  15. )
  16. // Sandbox provides the control over the network container entity. It is a one to one mapping with the container.
  17. type Sandbox interface {
  18. // ID returns the ID of the sandbox
  19. ID() string
  20. // Key returns the sandbox's key
  21. Key() string
  22. // ContainerID returns the container id associated to this sandbox
  23. ContainerID() string
  24. // Labels returns the sandbox's labels
  25. Labels() map[string]interface{}
  26. // Statistics retrieves the interfaces' statistics for the sandbox
  27. Statistics() (map[string]*types.InterfaceStatistics, error)
  28. // Refresh leaves all the endpoints, resets and re-apply the options,
  29. // re-joins all the endpoints without destroying the osl sandbox
  30. Refresh(options ...SandboxOption) error
  31. // SetKey updates the Sandbox Key
  32. SetKey(key string) error
  33. // Rename changes the name of all attached Endpoints
  34. Rename(name string) error
  35. // Delete destroys this container after detaching it from all connected endpoints.
  36. Delete() error
  37. // ResolveName resolves a service name to an IPv4 or IPv6 address by searching
  38. // the networks the sandbox is connected to. For IPv6 queries, second return
  39. // value will be true if the name exists in docker domain but doesn't have an
  40. // IPv6 address. Such queries shouldn't be forwarded to external nameservers.
  41. ResolveName(name string, iplen int) ([]net.IP, bool)
  42. // ResolveIP returns the service name for the passed in IP. IP is in reverse dotted
  43. // notation; the format used for DNS PTR records
  44. ResolveIP(name string) string
  45. // Endpoints returns all the endpoints connected to the sandbox
  46. Endpoints() []Endpoint
  47. }
  48. // SandboxOption is an option setter function type used to pass various options to
  49. // NewNetContainer method. The various setter functions of type SandboxOption are
  50. // provided by libnetwork, they look like ContainerOptionXXXX(...)
  51. type SandboxOption func(sb *sandbox)
  52. func (sb *sandbox) processOptions(options ...SandboxOption) {
  53. for _, opt := range options {
  54. if opt != nil {
  55. opt(sb)
  56. }
  57. }
  58. }
  59. type epHeap []*endpoint
  60. type sandbox struct {
  61. id string
  62. containerID string
  63. config containerConfig
  64. extDNS []string
  65. osSbox osl.Sandbox
  66. controller *controller
  67. resolver Resolver
  68. resolverOnce sync.Once
  69. refCnt int
  70. endpoints epHeap
  71. epPriority map[string]int
  72. joinLeaveDone chan struct{}
  73. dbIndex uint64
  74. dbExists bool
  75. isStub bool
  76. inDelete bool
  77. sync.Mutex
  78. }
  79. // These are the container configs used to customize container /etc/hosts file.
  80. type hostsPathConfig struct {
  81. hostName string
  82. domainName string
  83. hostsPath string
  84. originHostsPath string
  85. extraHosts []extraHost
  86. parentUpdates []parentUpdate
  87. }
  88. type parentUpdate struct {
  89. cid string
  90. name string
  91. ip string
  92. }
  93. type extraHost struct {
  94. name string
  95. IP string
  96. }
  97. // These are the container configs used to customize container /etc/resolv.conf file.
  98. type resolvConfPathConfig struct {
  99. resolvConfPath string
  100. originResolvConfPath string
  101. resolvConfHashFile string
  102. dnsList []string
  103. dnsSearchList []string
  104. dnsOptionsList []string
  105. }
  106. type containerConfig struct {
  107. hostsPathConfig
  108. resolvConfPathConfig
  109. generic map[string]interface{}
  110. useDefaultSandBox bool
  111. useExternalKey bool
  112. prio int // higher the value, more the priority
  113. exposedPorts []types.TransportPort
  114. }
  115. func (sb *sandbox) ID() string {
  116. return sb.id
  117. }
  118. func (sb *sandbox) ContainerID() string {
  119. return sb.containerID
  120. }
  121. func (sb *sandbox) Key() string {
  122. if sb.config.useDefaultSandBox {
  123. return osl.GenerateKey("default")
  124. }
  125. return osl.GenerateKey(sb.id)
  126. }
  127. func (sb *sandbox) Labels() map[string]interface{} {
  128. sb.Lock()
  129. sb.Unlock()
  130. opts := make(map[string]interface{}, len(sb.config.generic))
  131. for k, v := range sb.config.generic {
  132. opts[k] = v
  133. }
  134. return opts
  135. }
  136. func (sb *sandbox) Statistics() (map[string]*types.InterfaceStatistics, error) {
  137. m := make(map[string]*types.InterfaceStatistics)
  138. sb.Lock()
  139. osb := sb.osSbox
  140. sb.Unlock()
  141. if osb == nil {
  142. return m, nil
  143. }
  144. var err error
  145. for _, i := range osb.Info().Interfaces() {
  146. if m[i.DstName()], err = i.Statistics(); err != nil {
  147. return m, err
  148. }
  149. }
  150. return m, nil
  151. }
  152. func (sb *sandbox) Delete() error {
  153. return sb.delete(false)
  154. }
  155. func (sb *sandbox) delete(force bool) error {
  156. sb.Lock()
  157. if sb.inDelete {
  158. sb.Unlock()
  159. return types.ForbiddenErrorf("another sandbox delete in progress")
  160. }
  161. // Set the inDelete flag. This will ensure that we don't
  162. // update the store until we have completed all the endpoint
  163. // leaves and deletes. And when endpoint leaves and deletes
  164. // are completed then we can finally delete the sandbox object
  165. // altogether from the data store. If the daemon exits
  166. // ungracefully in the middle of a sandbox delete this way we
  167. // will have all the references to the endpoints in the
  168. // sandbox so that we can clean them up when we restart
  169. sb.inDelete = true
  170. sb.Unlock()
  171. c := sb.controller
  172. // Detach from all endpoints
  173. retain := false
  174. for _, ep := range sb.getConnectedEndpoints() {
  175. // gw network endpoint detach and removal are automatic
  176. if ep.endpointInGWNetwork() {
  177. continue
  178. }
  179. // Retain the sanbdox if we can't obtain the network from store.
  180. if _, err := c.getNetworkFromStore(ep.getNetwork().ID()); err != nil {
  181. retain = true
  182. log.Warnf("Failed getting network for ep %s during sandbox %s delete: %v", ep.ID(), sb.ID(), err)
  183. continue
  184. }
  185. if !force {
  186. if err := ep.Leave(sb); err != nil {
  187. log.Warnf("Failed detaching sandbox %s from endpoint %s: %v\n", sb.ID(), ep.ID(), err)
  188. }
  189. }
  190. if err := ep.Delete(force); err != nil {
  191. log.Warnf("Failed deleting endpoint %s: %v\n", ep.ID(), err)
  192. }
  193. }
  194. if retain {
  195. sb.Lock()
  196. sb.inDelete = false
  197. sb.Unlock()
  198. return fmt.Errorf("could not cleanup all the endpoints in container %s / sandbox %s", sb.containerID, sb.id)
  199. }
  200. // Container is going away. Path cache in etchosts is most
  201. // likely not required any more. Drop it.
  202. etchosts.Drop(sb.config.hostsPath)
  203. if sb.resolver != nil {
  204. sb.resolver.Stop()
  205. }
  206. if sb.osSbox != nil && !sb.config.useDefaultSandBox {
  207. sb.osSbox.Destroy()
  208. }
  209. if err := sb.storeDelete(); err != nil {
  210. log.Warnf("Failed to delete sandbox %s from store: %v", sb.ID(), err)
  211. }
  212. c.Lock()
  213. delete(c.sandboxes, sb.ID())
  214. c.Unlock()
  215. return nil
  216. }
  217. func (sb *sandbox) Rename(name string) error {
  218. var err error
  219. for _, ep := range sb.getConnectedEndpoints() {
  220. if ep.endpointInGWNetwork() {
  221. continue
  222. }
  223. oldName := ep.Name()
  224. lEp := ep
  225. if err = ep.rename(name); err != nil {
  226. break
  227. }
  228. defer func() {
  229. if err != nil {
  230. lEp.rename(oldName)
  231. }
  232. }()
  233. }
  234. return err
  235. }
  236. func (sb *sandbox) Refresh(options ...SandboxOption) error {
  237. // Store connected endpoints
  238. epList := sb.getConnectedEndpoints()
  239. // Detach from all endpoints
  240. for _, ep := range epList {
  241. if err := ep.Leave(sb); err != nil {
  242. log.Warnf("Failed detaching sandbox %s from endpoint %s: %v\n", sb.ID(), ep.ID(), err)
  243. }
  244. }
  245. // Re-apply options
  246. sb.config = containerConfig{}
  247. sb.processOptions(options...)
  248. // Setup discovery files
  249. if err := sb.setupResolutionFiles(); err != nil {
  250. return err
  251. }
  252. // Re -connect to all endpoints
  253. for _, ep := range epList {
  254. if err := ep.Join(sb); err != nil {
  255. log.Warnf("Failed attach sandbox %s to endpoint %s: %v\n", sb.ID(), ep.ID(), err)
  256. }
  257. }
  258. return nil
  259. }
  260. func (sb *sandbox) MarshalJSON() ([]byte, error) {
  261. sb.Lock()
  262. defer sb.Unlock()
  263. // We are just interested in the container ID. This can be expanded to include all of containerInfo if there is a need
  264. return json.Marshal(sb.id)
  265. }
  266. func (sb *sandbox) UnmarshalJSON(b []byte) (err error) {
  267. sb.Lock()
  268. defer sb.Unlock()
  269. var id string
  270. if err := json.Unmarshal(b, &id); err != nil {
  271. return err
  272. }
  273. sb.id = id
  274. return nil
  275. }
  276. func (sb *sandbox) Endpoints() []Endpoint {
  277. sb.Lock()
  278. defer sb.Unlock()
  279. endpoints := make([]Endpoint, len(sb.endpoints))
  280. for i, ep := range sb.endpoints {
  281. endpoints[i] = ep
  282. }
  283. return endpoints
  284. }
  285. func (sb *sandbox) getConnectedEndpoints() []*endpoint {
  286. sb.Lock()
  287. defer sb.Unlock()
  288. eps := make([]*endpoint, len(sb.endpoints))
  289. for i, ep := range sb.endpoints {
  290. eps[i] = ep
  291. }
  292. return eps
  293. }
  294. func (sb *sandbox) removeEndpoint(ep *endpoint) {
  295. sb.Lock()
  296. defer sb.Unlock()
  297. for i, e := range sb.endpoints {
  298. if e == ep {
  299. heap.Remove(&sb.endpoints, i)
  300. return
  301. }
  302. }
  303. }
  304. func (sb *sandbox) getEndpoint(id string) *endpoint {
  305. sb.Lock()
  306. defer sb.Unlock()
  307. for _, ep := range sb.endpoints {
  308. if ep.id == id {
  309. return ep
  310. }
  311. }
  312. return nil
  313. }
  314. func (sb *sandbox) updateGateway(ep *endpoint) error {
  315. sb.Lock()
  316. osSbox := sb.osSbox
  317. sb.Unlock()
  318. if osSbox == nil {
  319. return nil
  320. }
  321. osSbox.UnsetGateway()
  322. osSbox.UnsetGatewayIPv6()
  323. if ep == nil {
  324. return nil
  325. }
  326. ep.Lock()
  327. joinInfo := ep.joinInfo
  328. ep.Unlock()
  329. if err := osSbox.SetGateway(joinInfo.gw); err != nil {
  330. return fmt.Errorf("failed to set gateway while updating gateway: %v", err)
  331. }
  332. if err := osSbox.SetGatewayIPv6(joinInfo.gw6); err != nil {
  333. return fmt.Errorf("failed to set IPv6 gateway while updating gateway: %v", err)
  334. }
  335. return nil
  336. }
  337. func (sb *sandbox) ResolveIP(ip string) string {
  338. var svc string
  339. log.Debugf("IP To resolve %v", ip)
  340. for _, ep := range sb.getConnectedEndpoints() {
  341. n := ep.getNetwork()
  342. sr, ok := n.getController().svcDb[n.ID()]
  343. if !ok {
  344. continue
  345. }
  346. nwName := n.Name()
  347. n.Lock()
  348. svc, ok = sr.ipMap[ip]
  349. n.Unlock()
  350. if ok {
  351. return svc + "." + nwName
  352. }
  353. }
  354. return svc
  355. }
  356. func (sb *sandbox) execFunc(f func()) {
  357. sb.osSbox.InvokeFunc(f)
  358. }
  359. func (sb *sandbox) ResolveName(name string, ipType int) ([]net.IP, bool) {
  360. // Embedded server owns the docker network domain. Resolution should work
  361. // for both container_name and container_name.network_name
  362. // We allow '.' in service name and network name. For a name a.b.c.d the
  363. // following have to tried;
  364. // {a.b.c.d in the networks container is connected to}
  365. // {a.b.c in network d},
  366. // {a.b in network c.d},
  367. // {a in network b.c.d},
  368. log.Debugf("Name To resolve: %v", name)
  369. name = strings.TrimSuffix(name, ".")
  370. reqName := []string{name}
  371. networkName := []string{""}
  372. if strings.Contains(name, ".") {
  373. var i int
  374. dup := name
  375. for {
  376. if i = strings.LastIndex(dup, "."); i == -1 {
  377. break
  378. }
  379. networkName = append(networkName, name[i+1:])
  380. reqName = append(reqName, name[:i])
  381. dup = dup[:i]
  382. }
  383. }
  384. epList := sb.getConnectedEndpoints()
  385. for i := 0; i < len(reqName); i++ {
  386. // First check for local container alias
  387. ip, ipv6Miss := sb.resolveName(reqName[i], networkName[i], epList, true, ipType)
  388. if ip != nil {
  389. return ip, false
  390. }
  391. if ipv6Miss {
  392. return ip, ipv6Miss
  393. }
  394. // Resolve the actual container name
  395. ip, ipv6Miss = sb.resolveName(reqName[i], networkName[i], epList, false, ipType)
  396. if ip != nil {
  397. return ip, false
  398. }
  399. if ipv6Miss {
  400. return ip, ipv6Miss
  401. }
  402. }
  403. return nil, false
  404. }
  405. func (sb *sandbox) resolveName(req string, networkName string, epList []*endpoint, alias bool, ipType int) ([]net.IP, bool) {
  406. var ipv6Miss bool
  407. for _, ep := range epList {
  408. name := req
  409. n := ep.getNetwork()
  410. if networkName != "" && networkName != n.Name() {
  411. continue
  412. }
  413. if alias {
  414. if ep.aliases == nil {
  415. continue
  416. }
  417. var ok bool
  418. ep.Lock()
  419. name, ok = ep.aliases[req]
  420. ep.Unlock()
  421. if !ok {
  422. continue
  423. }
  424. } else {
  425. // If it is a regular lookup and if the requested name is an alias
  426. // don't perform a svc lookup for this endpoint.
  427. ep.Lock()
  428. if _, ok := ep.aliases[req]; ok {
  429. ep.Unlock()
  430. continue
  431. }
  432. ep.Unlock()
  433. }
  434. sr, ok := n.getController().svcDb[n.ID()]
  435. if !ok {
  436. continue
  437. }
  438. var ip []net.IP
  439. n.Lock()
  440. ip, ok = sr.svcMap[name]
  441. if ipType == types.IPv6 {
  442. // If the name resolved to v4 address then its a valid name in
  443. // the docker network domain. If the network is not v6 enabled
  444. // set ipv6Miss to filter the DNS query from going to external
  445. // resolvers.
  446. if ok && n.enableIPv6 == false {
  447. ipv6Miss = true
  448. }
  449. ip = sr.svcIPv6Map[name]
  450. }
  451. n.Unlock()
  452. if ip != nil {
  453. return ip, false
  454. }
  455. }
  456. return nil, ipv6Miss
  457. }
  458. func (sb *sandbox) SetKey(basePath string) error {
  459. start := time.Now()
  460. defer func() {
  461. log.Debugf("sandbox set key processing took %s for container %s", time.Now().Sub(start), sb.ContainerID())
  462. }()
  463. if basePath == "" {
  464. return types.BadRequestErrorf("invalid sandbox key")
  465. }
  466. sb.Lock()
  467. oldosSbox := sb.osSbox
  468. sb.Unlock()
  469. if oldosSbox != nil {
  470. // If we already have an OS sandbox, release the network resources from that
  471. // and destroy the OS snab. We are moving into a new home further down. Note that none
  472. // of the network resources gets destroyed during the move.
  473. sb.releaseOSSbox()
  474. }
  475. osSbox, err := osl.GetSandboxForExternalKey(basePath, sb.Key())
  476. if err != nil {
  477. return err
  478. }
  479. sb.Lock()
  480. sb.osSbox = osSbox
  481. sb.Unlock()
  482. defer func() {
  483. if err != nil {
  484. sb.Lock()
  485. sb.osSbox = nil
  486. sb.Unlock()
  487. }
  488. }()
  489. // If the resolver was setup before stop it and set it up in the
  490. // new osl sandbox.
  491. if oldosSbox != nil && sb.resolver != nil {
  492. sb.resolver.Stop()
  493. sb.osSbox.InvokeFunc(sb.resolver.SetupFunc())
  494. if err := sb.resolver.Start(); err != nil {
  495. log.Errorf("Resolver Setup/Start failed for container %s, %q", sb.ContainerID(), err)
  496. }
  497. }
  498. for _, ep := range sb.getConnectedEndpoints() {
  499. if err = sb.populateNetworkResources(ep); err != nil {
  500. return err
  501. }
  502. }
  503. return nil
  504. }
  505. func releaseOSSboxResources(osSbox osl.Sandbox, ep *endpoint) {
  506. for _, i := range osSbox.Info().Interfaces() {
  507. // Only remove the interfaces owned by this endpoint from the sandbox.
  508. if ep.hasInterface(i.SrcName()) {
  509. if err := i.Remove(); err != nil {
  510. log.Debugf("Remove interface %s failed: %v", i.SrcName(), err)
  511. }
  512. }
  513. }
  514. ep.Lock()
  515. joinInfo := ep.joinInfo
  516. ep.Unlock()
  517. if joinInfo == nil {
  518. return
  519. }
  520. // Remove non-interface routes.
  521. for _, r := range joinInfo.StaticRoutes {
  522. if err := osSbox.RemoveStaticRoute(r); err != nil {
  523. log.Debugf("Remove route failed: %v", err)
  524. }
  525. }
  526. }
  527. func (sb *sandbox) releaseOSSbox() {
  528. sb.Lock()
  529. osSbox := sb.osSbox
  530. sb.osSbox = nil
  531. sb.Unlock()
  532. if osSbox == nil {
  533. return
  534. }
  535. for _, ep := range sb.getConnectedEndpoints() {
  536. releaseOSSboxResources(osSbox, ep)
  537. }
  538. osSbox.Destroy()
  539. }
  540. func (sb *sandbox) populateNetworkResources(ep *endpoint) error {
  541. sb.Lock()
  542. if sb.osSbox == nil {
  543. sb.Unlock()
  544. return nil
  545. }
  546. inDelete := sb.inDelete
  547. sb.Unlock()
  548. ep.Lock()
  549. joinInfo := ep.joinInfo
  550. i := ep.iface
  551. ep.Unlock()
  552. if ep.needResolver() {
  553. sb.startResolver()
  554. }
  555. if i != nil && i.srcName != "" {
  556. var ifaceOptions []osl.IfaceOption
  557. ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().Address(i.addr), sb.osSbox.InterfaceOptions().Routes(i.routes))
  558. if i.addrv6 != nil && i.addrv6.IP.To16() != nil {
  559. ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().AddressIPv6(i.addrv6))
  560. }
  561. if i.mac != nil {
  562. ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().MacAddress(i.mac))
  563. }
  564. if err := sb.osSbox.AddInterface(i.srcName, i.dstPrefix, ifaceOptions...); err != nil {
  565. return fmt.Errorf("failed to add interface %s to sandbox: %v", i.srcName, err)
  566. }
  567. }
  568. if joinInfo != nil {
  569. // Set up non-interface routes.
  570. for _, r := range joinInfo.StaticRoutes {
  571. if err := sb.osSbox.AddStaticRoute(r); err != nil {
  572. return fmt.Errorf("failed to add static route %s: %v", r.Destination.String(), err)
  573. }
  574. }
  575. }
  576. if ep == sb.getGatewayEndpoint() {
  577. if err := sb.updateGateway(ep); err != nil {
  578. return err
  579. }
  580. }
  581. // Only update the store if we did not come here as part of
  582. // sandbox delete. If we came here as part of delete then do
  583. // not bother updating the store. The sandbox object will be
  584. // deleted anyway
  585. if !inDelete {
  586. return sb.storeUpdate()
  587. }
  588. return nil
  589. }
  590. func (sb *sandbox) clearNetworkResources(origEp *endpoint) error {
  591. ep := sb.getEndpoint(origEp.id)
  592. if ep == nil {
  593. return fmt.Errorf("could not find the sandbox endpoint data for endpoint %s",
  594. origEp.id)
  595. }
  596. sb.Lock()
  597. osSbox := sb.osSbox
  598. inDelete := sb.inDelete
  599. sb.Unlock()
  600. if osSbox != nil {
  601. releaseOSSboxResources(osSbox, ep)
  602. }
  603. sb.Lock()
  604. if len(sb.endpoints) == 0 {
  605. // sb.endpoints should never be empty and this is unexpected error condition
  606. // We log an error message to note this down for debugging purposes.
  607. log.Errorf("No endpoints in sandbox while trying to remove endpoint %s", ep.Name())
  608. sb.Unlock()
  609. return nil
  610. }
  611. var (
  612. gwepBefore, gwepAfter *endpoint
  613. index = -1
  614. )
  615. for i, e := range sb.endpoints {
  616. if e == ep {
  617. index = i
  618. }
  619. if len(e.Gateway()) > 0 && gwepBefore == nil {
  620. gwepBefore = e
  621. }
  622. if index != -1 && gwepBefore != nil {
  623. break
  624. }
  625. }
  626. heap.Remove(&sb.endpoints, index)
  627. for _, e := range sb.endpoints {
  628. if len(e.Gateway()) > 0 {
  629. gwepAfter = e
  630. break
  631. }
  632. }
  633. delete(sb.epPriority, ep.ID())
  634. sb.Unlock()
  635. if gwepAfter != nil && gwepBefore != gwepAfter {
  636. sb.updateGateway(gwepAfter)
  637. }
  638. // Only update the store if we did not come here as part of
  639. // sandbox delete. If we came here as part of delete then do
  640. // not bother updating the store. The sandbox object will be
  641. // deleted anyway
  642. if !inDelete {
  643. return sb.storeUpdate()
  644. }
  645. return nil
  646. }
  647. // joinLeaveStart waits to ensure there are no joins or leaves in progress and
  648. // marks this join/leave in progress without race
  649. func (sb *sandbox) joinLeaveStart() {
  650. sb.Lock()
  651. defer sb.Unlock()
  652. for sb.joinLeaveDone != nil {
  653. joinLeaveDone := sb.joinLeaveDone
  654. sb.Unlock()
  655. select {
  656. case <-joinLeaveDone:
  657. }
  658. sb.Lock()
  659. }
  660. sb.joinLeaveDone = make(chan struct{})
  661. }
  662. // joinLeaveEnd marks the end of this join/leave operation and
  663. // signals the same without race to other join and leave waiters
  664. func (sb *sandbox) joinLeaveEnd() {
  665. sb.Lock()
  666. defer sb.Unlock()
  667. if sb.joinLeaveDone != nil {
  668. close(sb.joinLeaveDone)
  669. sb.joinLeaveDone = nil
  670. }
  671. }
  672. func (sb *sandbox) hasPortConfigs() bool {
  673. opts := sb.Labels()
  674. _, hasExpPorts := opts[netlabel.ExposedPorts]
  675. _, hasPortMaps := opts[netlabel.PortMap]
  676. return hasExpPorts || hasPortMaps
  677. }
  678. // OptionHostname function returns an option setter for hostname option to
  679. // be passed to NewSandbox method.
  680. func OptionHostname(name string) SandboxOption {
  681. return func(sb *sandbox) {
  682. sb.config.hostName = name
  683. }
  684. }
  685. // OptionDomainname function returns an option setter for domainname option to
  686. // be passed to NewSandbox method.
  687. func OptionDomainname(name string) SandboxOption {
  688. return func(sb *sandbox) {
  689. sb.config.domainName = name
  690. }
  691. }
  692. // OptionHostsPath function returns an option setter for hostspath option to
  693. // be passed to NewSandbox method.
  694. func OptionHostsPath(path string) SandboxOption {
  695. return func(sb *sandbox) {
  696. sb.config.hostsPath = path
  697. }
  698. }
  699. // OptionOriginHostsPath function returns an option setter for origin hosts file path
  700. // tbeo passed to NewSandbox method.
  701. func OptionOriginHostsPath(path string) SandboxOption {
  702. return func(sb *sandbox) {
  703. sb.config.originHostsPath = path
  704. }
  705. }
  706. // OptionExtraHost function returns an option setter for extra /etc/hosts options
  707. // which is a name and IP as strings.
  708. func OptionExtraHost(name string, IP string) SandboxOption {
  709. return func(sb *sandbox) {
  710. sb.config.extraHosts = append(sb.config.extraHosts, extraHost{name: name, IP: IP})
  711. }
  712. }
  713. // OptionParentUpdate function returns an option setter for parent container
  714. // which needs to update the IP address for the linked container.
  715. func OptionParentUpdate(cid string, name, ip string) SandboxOption {
  716. return func(sb *sandbox) {
  717. sb.config.parentUpdates = append(sb.config.parentUpdates, parentUpdate{cid: cid, name: name, ip: ip})
  718. }
  719. }
  720. // OptionResolvConfPath function returns an option setter for resolvconfpath option to
  721. // be passed to net container methods.
  722. func OptionResolvConfPath(path string) SandboxOption {
  723. return func(sb *sandbox) {
  724. sb.config.resolvConfPath = path
  725. }
  726. }
  727. // OptionOriginResolvConfPath function returns an option setter to set the path to the
  728. // origin resolv.conf file to be passed to net container methods.
  729. func OptionOriginResolvConfPath(path string) SandboxOption {
  730. return func(sb *sandbox) {
  731. sb.config.originResolvConfPath = path
  732. }
  733. }
  734. // OptionDNS function returns an option setter for dns entry option to
  735. // be passed to container Create method.
  736. func OptionDNS(dns string) SandboxOption {
  737. return func(sb *sandbox) {
  738. sb.config.dnsList = append(sb.config.dnsList, dns)
  739. }
  740. }
  741. // OptionDNSSearch function returns an option setter for dns search entry option to
  742. // be passed to container Create method.
  743. func OptionDNSSearch(search string) SandboxOption {
  744. return func(sb *sandbox) {
  745. sb.config.dnsSearchList = append(sb.config.dnsSearchList, search)
  746. }
  747. }
  748. // OptionDNSOptions function returns an option setter for dns options entry option to
  749. // be passed to container Create method.
  750. func OptionDNSOptions(options string) SandboxOption {
  751. return func(sb *sandbox) {
  752. sb.config.dnsOptionsList = append(sb.config.dnsOptionsList, options)
  753. }
  754. }
  755. // OptionUseDefaultSandbox function returns an option setter for using default sandbox to
  756. // be passed to container Create method.
  757. func OptionUseDefaultSandbox() SandboxOption {
  758. return func(sb *sandbox) {
  759. sb.config.useDefaultSandBox = true
  760. }
  761. }
  762. // OptionUseExternalKey function returns an option setter for using provided namespace
  763. // instead of creating one.
  764. func OptionUseExternalKey() SandboxOption {
  765. return func(sb *sandbox) {
  766. sb.config.useExternalKey = true
  767. }
  768. }
  769. // OptionGeneric function returns an option setter for Generic configuration
  770. // that is not managed by libNetwork but can be used by the Drivers during the call to
  771. // net container creation method. Container Labels are a good example.
  772. func OptionGeneric(generic map[string]interface{}) SandboxOption {
  773. return func(sb *sandbox) {
  774. if sb.config.generic == nil {
  775. sb.config.generic = make(map[string]interface{}, len(generic))
  776. }
  777. for k, v := range generic {
  778. sb.config.generic[k] = v
  779. }
  780. }
  781. }
  782. // OptionExposedPorts function returns an option setter for the container exposed
  783. // ports option to be passed to container Create method.
  784. func OptionExposedPorts(exposedPorts []types.TransportPort) SandboxOption {
  785. return func(sb *sandbox) {
  786. if sb.config.generic == nil {
  787. sb.config.generic = make(map[string]interface{})
  788. }
  789. // Defensive copy
  790. eps := make([]types.TransportPort, len(exposedPorts))
  791. copy(eps, exposedPorts)
  792. // Store endpoint label and in generic because driver needs it
  793. sb.config.exposedPorts = eps
  794. sb.config.generic[netlabel.ExposedPorts] = eps
  795. }
  796. }
  797. // OptionPortMapping function returns an option setter for the mapping
  798. // ports option to be passed to container Create method.
  799. func OptionPortMapping(portBindings []types.PortBinding) SandboxOption {
  800. return func(sb *sandbox) {
  801. if sb.config.generic == nil {
  802. sb.config.generic = make(map[string]interface{})
  803. }
  804. // Store a copy of the bindings as generic data to pass to the driver
  805. pbs := make([]types.PortBinding, len(portBindings))
  806. copy(pbs, portBindings)
  807. sb.config.generic[netlabel.PortMap] = pbs
  808. }
  809. }
  810. func (eh epHeap) Len() int { return len(eh) }
  811. func (eh epHeap) Less(i, j int) bool {
  812. var (
  813. cip, cjp int
  814. ok bool
  815. )
  816. ci, _ := eh[i].getSandbox()
  817. cj, _ := eh[j].getSandbox()
  818. epi := eh[i]
  819. epj := eh[j]
  820. if epi.endpointInGWNetwork() {
  821. return false
  822. }
  823. if epj.endpointInGWNetwork() {
  824. return true
  825. }
  826. if epi.getNetwork().Internal() {
  827. return false
  828. }
  829. if epj.getNetwork().Internal() {
  830. return true
  831. }
  832. if ci != nil {
  833. cip, ok = ci.epPriority[eh[i].ID()]
  834. if !ok {
  835. cip = 0
  836. }
  837. }
  838. if cj != nil {
  839. cjp, ok = cj.epPriority[eh[j].ID()]
  840. if !ok {
  841. cjp = 0
  842. }
  843. }
  844. if cip == cjp {
  845. return eh[i].network.Name() < eh[j].network.Name()
  846. }
  847. return cip > cjp
  848. }
  849. func (eh epHeap) Swap(i, j int) { eh[i], eh[j] = eh[j], eh[i] }
  850. func (eh *epHeap) Push(x interface{}) {
  851. *eh = append(*eh, x.(*endpoint))
  852. }
  853. func (eh *epHeap) Pop() interface{} {
  854. old := *eh
  855. n := len(old)
  856. x := old[n-1]
  857. *eh = old[0 : n-1]
  858. return x
  859. }