sandbox.go 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201
  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-applies 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. // Endpoints returns all the endpoints connected to the sandbox
  38. Endpoints() []Endpoint
  39. // ResolveService returns all the backend details about the containers or hosts
  40. // backing a service. Its purpose is to satisfy an SRV query
  41. ResolveService(name string) ([]*net.SRV, []net.IP)
  42. // EnableService makes a managed container's service available by adding the
  43. // endpoint to the service load balancer and service discovery
  44. EnableService() error
  45. // DisableService removes a managed contianer's endpoints from the load balancer
  46. // and service discovery
  47. DisableService() error
  48. }
  49. // SandboxOption is an option setter function type used to pass various options to
  50. // NewNetContainer method. The various setter functions of type SandboxOption are
  51. // provided by libnetwork, they look like ContainerOptionXXXX(...)
  52. type SandboxOption func(sb *sandbox)
  53. func (sb *sandbox) processOptions(options ...SandboxOption) {
  54. for _, opt := range options {
  55. if opt != nil {
  56. opt(sb)
  57. }
  58. }
  59. }
  60. type epHeap []*endpoint
  61. type sandbox struct {
  62. id string
  63. containerID string
  64. config containerConfig
  65. extDNS []string
  66. osSbox osl.Sandbox
  67. controller *controller
  68. resolver Resolver
  69. resolverOnce sync.Once
  70. refCnt int
  71. endpoints epHeap
  72. epPriority map[string]int
  73. populatedEndpoints map[string]struct{}
  74. joinLeaveDone chan struct{}
  75. dbIndex uint64
  76. dbExists bool
  77. isStub bool
  78. inDelete bool
  79. ingress bool
  80. ndotsSet bool
  81. sync.Mutex
  82. }
  83. // These are the container configs used to customize container /etc/hosts file.
  84. type hostsPathConfig struct {
  85. hostName string
  86. domainName string
  87. hostsPath string
  88. originHostsPath string
  89. extraHosts []extraHost
  90. parentUpdates []parentUpdate
  91. }
  92. type parentUpdate struct {
  93. cid string
  94. name string
  95. ip string
  96. }
  97. type extraHost struct {
  98. name string
  99. IP string
  100. }
  101. // These are the container configs used to customize container /etc/resolv.conf file.
  102. type resolvConfPathConfig struct {
  103. resolvConfPath string
  104. originResolvConfPath string
  105. resolvConfHashFile string
  106. dnsList []string
  107. dnsSearchList []string
  108. dnsOptionsList []string
  109. }
  110. type containerConfig struct {
  111. hostsPathConfig
  112. resolvConfPathConfig
  113. generic map[string]interface{}
  114. useDefaultSandBox bool
  115. useExternalKey bool
  116. prio int // higher the value, more the priority
  117. exposedPorts []types.TransportPort
  118. }
  119. const (
  120. resolverIPSandbox = "127.0.0.11"
  121. )
  122. func (sb *sandbox) ID() string {
  123. return sb.id
  124. }
  125. func (sb *sandbox) ContainerID() string {
  126. return sb.containerID
  127. }
  128. func (sb *sandbox) Key() string {
  129. if sb.config.useDefaultSandBox {
  130. return osl.GenerateKey("default")
  131. }
  132. return osl.GenerateKey(sb.id)
  133. }
  134. func (sb *sandbox) Labels() map[string]interface{} {
  135. sb.Lock()
  136. defer sb.Unlock()
  137. opts := make(map[string]interface{}, len(sb.config.generic))
  138. for k, v := range sb.config.generic {
  139. opts[k] = v
  140. }
  141. return opts
  142. }
  143. func (sb *sandbox) Statistics() (map[string]*types.InterfaceStatistics, error) {
  144. m := make(map[string]*types.InterfaceStatistics)
  145. sb.Lock()
  146. osb := sb.osSbox
  147. sb.Unlock()
  148. if osb == nil {
  149. return m, nil
  150. }
  151. var err error
  152. for _, i := range osb.Info().Interfaces() {
  153. if m[i.DstName()], err = i.Statistics(); err != nil {
  154. return m, err
  155. }
  156. }
  157. return m, nil
  158. }
  159. func (sb *sandbox) Delete() error {
  160. return sb.delete(false)
  161. }
  162. func (sb *sandbox) delete(force bool) error {
  163. sb.Lock()
  164. if sb.inDelete {
  165. sb.Unlock()
  166. return types.ForbiddenErrorf("another sandbox delete in progress")
  167. }
  168. // Set the inDelete flag. This will ensure that we don't
  169. // update the store until we have completed all the endpoint
  170. // leaves and deletes. And when endpoint leaves and deletes
  171. // are completed then we can finally delete the sandbox object
  172. // altogether from the data store. If the daemon exits
  173. // ungracefully in the middle of a sandbox delete this way we
  174. // will have all the references to the endpoints in the
  175. // sandbox so that we can clean them up when we restart
  176. sb.inDelete = true
  177. sb.Unlock()
  178. c := sb.controller
  179. // Detach from all endpoints
  180. retain := false
  181. for _, ep := range sb.getConnectedEndpoints() {
  182. // gw network endpoint detach and removal are automatic
  183. if ep.endpointInGWNetwork() && !force {
  184. continue
  185. }
  186. // Retain the sanbdox if we can't obtain the network from store.
  187. if _, err := c.getNetworkFromStore(ep.getNetwork().ID()); err != nil {
  188. if c.isDistributedControl() {
  189. retain = true
  190. }
  191. log.Warnf("Failed getting network for ep %s during sandbox %s delete: %v", ep.ID(), sb.ID(), err)
  192. continue
  193. }
  194. if !force {
  195. if err := ep.Leave(sb); err != nil {
  196. log.Warnf("Failed detaching sandbox %s from endpoint %s: %v\n", sb.ID(), ep.ID(), err)
  197. }
  198. }
  199. if err := ep.Delete(force); err != nil {
  200. log.Warnf("Failed deleting endpoint %s: %v\n", ep.ID(), err)
  201. }
  202. }
  203. if retain {
  204. sb.Lock()
  205. sb.inDelete = false
  206. sb.Unlock()
  207. return fmt.Errorf("could not cleanup all the endpoints in container %s / sandbox %s", sb.containerID, sb.id)
  208. }
  209. // Container is going away. Path cache in etchosts is most
  210. // likely not required any more. Drop it.
  211. etchosts.Drop(sb.config.hostsPath)
  212. if sb.resolver != nil {
  213. sb.resolver.Stop()
  214. }
  215. if sb.osSbox != nil && !sb.config.useDefaultSandBox {
  216. sb.osSbox.Destroy()
  217. }
  218. if err := sb.storeDelete(); err != nil {
  219. log.Warnf("Failed to delete sandbox %s from store: %v", sb.ID(), err)
  220. }
  221. c.Lock()
  222. if sb.ingress {
  223. c.ingressSandbox = nil
  224. }
  225. delete(c.sandboxes, sb.ID())
  226. c.Unlock()
  227. return nil
  228. }
  229. func (sb *sandbox) Rename(name string) error {
  230. var err error
  231. for _, ep := range sb.getConnectedEndpoints() {
  232. if ep.endpointInGWNetwork() {
  233. continue
  234. }
  235. oldName := ep.Name()
  236. lEp := ep
  237. if err = ep.rename(name); err != nil {
  238. break
  239. }
  240. defer func() {
  241. if err != nil {
  242. lEp.rename(oldName)
  243. }
  244. }()
  245. }
  246. return err
  247. }
  248. func (sb *sandbox) Refresh(options ...SandboxOption) error {
  249. // Store connected endpoints
  250. epList := sb.getConnectedEndpoints()
  251. // Detach from all endpoints
  252. for _, ep := range epList {
  253. if err := ep.Leave(sb); err != nil {
  254. log.Warnf("Failed detaching sandbox %s from endpoint %s: %v\n", sb.ID(), ep.ID(), err)
  255. }
  256. }
  257. // Re-apply options
  258. sb.config = containerConfig{}
  259. sb.processOptions(options...)
  260. // Setup discovery files
  261. if err := sb.setupResolutionFiles(); err != nil {
  262. return err
  263. }
  264. // Re-connect to all endpoints
  265. for _, ep := range epList {
  266. if err := ep.Join(sb); err != nil {
  267. log.Warnf("Failed attach sandbox %s to endpoint %s: %v\n", sb.ID(), ep.ID(), err)
  268. }
  269. }
  270. return nil
  271. }
  272. func (sb *sandbox) MarshalJSON() ([]byte, error) {
  273. sb.Lock()
  274. defer sb.Unlock()
  275. // We are just interested in the container ID. This can be expanded to include all of containerInfo if there is a need
  276. return json.Marshal(sb.id)
  277. }
  278. func (sb *sandbox) UnmarshalJSON(b []byte) (err error) {
  279. sb.Lock()
  280. defer sb.Unlock()
  281. var id string
  282. if err := json.Unmarshal(b, &id); err != nil {
  283. return err
  284. }
  285. sb.id = id
  286. return nil
  287. }
  288. func (sb *sandbox) Endpoints() []Endpoint {
  289. sb.Lock()
  290. defer sb.Unlock()
  291. endpoints := make([]Endpoint, len(sb.endpoints))
  292. for i, ep := range sb.endpoints {
  293. endpoints[i] = ep
  294. }
  295. return endpoints
  296. }
  297. func (sb *sandbox) getConnectedEndpoints() []*endpoint {
  298. sb.Lock()
  299. defer sb.Unlock()
  300. eps := make([]*endpoint, len(sb.endpoints))
  301. for i, ep := range sb.endpoints {
  302. eps[i] = ep
  303. }
  304. return eps
  305. }
  306. func (sb *sandbox) removeEndpoint(ep *endpoint) {
  307. sb.Lock()
  308. defer sb.Unlock()
  309. for i, e := range sb.endpoints {
  310. if e == ep {
  311. heap.Remove(&sb.endpoints, i)
  312. return
  313. }
  314. }
  315. }
  316. func (sb *sandbox) getEndpoint(id string) *endpoint {
  317. sb.Lock()
  318. defer sb.Unlock()
  319. for _, ep := range sb.endpoints {
  320. if ep.id == id {
  321. return ep
  322. }
  323. }
  324. return nil
  325. }
  326. func (sb *sandbox) updateGateway(ep *endpoint) error {
  327. sb.Lock()
  328. osSbox := sb.osSbox
  329. sb.Unlock()
  330. if osSbox == nil {
  331. return nil
  332. }
  333. osSbox.UnsetGateway()
  334. osSbox.UnsetGatewayIPv6()
  335. if ep == nil {
  336. return nil
  337. }
  338. ep.Lock()
  339. joinInfo := ep.joinInfo
  340. ep.Unlock()
  341. if err := osSbox.SetGateway(joinInfo.gw); err != nil {
  342. return fmt.Errorf("failed to set gateway while updating gateway: %v", err)
  343. }
  344. if err := osSbox.SetGatewayIPv6(joinInfo.gw6); err != nil {
  345. return fmt.Errorf("failed to set IPv6 gateway while updating gateway: %v", err)
  346. }
  347. return nil
  348. }
  349. func (sb *sandbox) ResolveIP(ip string) string {
  350. var svc string
  351. log.Debugf("IP To resolve %v", ip)
  352. for _, ep := range sb.getConnectedEndpoints() {
  353. n := ep.getNetwork()
  354. svc = n.ResolveIP(ip)
  355. if len(svc) != 0 {
  356. return svc
  357. }
  358. }
  359. return svc
  360. }
  361. func (sb *sandbox) ExecFunc(f func()) error {
  362. return sb.osSbox.InvokeFunc(f)
  363. }
  364. func (sb *sandbox) ResolveService(name string) ([]*net.SRV, []net.IP) {
  365. srv := []*net.SRV{}
  366. ip := []net.IP{}
  367. log.Debugf("Service name To resolve: %v", name)
  368. // There are DNS implementaions that allow SRV queries for names not in
  369. // the format defined by RFC 2782. Hence specific validations checks are
  370. // not done
  371. parts := strings.Split(name, ".")
  372. if len(parts) < 3 {
  373. return nil, nil
  374. }
  375. for _, ep := range sb.getConnectedEndpoints() {
  376. n := ep.getNetwork()
  377. srv, ip = n.ResolveService(name)
  378. if len(srv) > 0 {
  379. break
  380. }
  381. }
  382. return srv, ip
  383. }
  384. func getDynamicNwEndpoints(epList []*endpoint) []*endpoint {
  385. eps := []*endpoint{}
  386. for _, ep := range epList {
  387. n := ep.getNetwork()
  388. if n.dynamic && !n.ingress {
  389. eps = append(eps, ep)
  390. }
  391. }
  392. return eps
  393. }
  394. func getIngressNwEndpoint(epList []*endpoint) *endpoint {
  395. for _, ep := range epList {
  396. n := ep.getNetwork()
  397. if n.ingress {
  398. return ep
  399. }
  400. }
  401. return nil
  402. }
  403. func getLocalNwEndpoints(epList []*endpoint) []*endpoint {
  404. eps := []*endpoint{}
  405. for _, ep := range epList {
  406. n := ep.getNetwork()
  407. if !n.dynamic && !n.ingress {
  408. eps = append(eps, ep)
  409. }
  410. }
  411. return eps
  412. }
  413. func (sb *sandbox) ResolveName(name string, ipType int) ([]net.IP, bool) {
  414. // Embedded server owns the docker network domain. Resolution should work
  415. // for both container_name and container_name.network_name
  416. // We allow '.' in service name and network name. For a name a.b.c.d the
  417. // following have to tried;
  418. // {a.b.c.d in the networks container is connected to}
  419. // {a.b.c in network d},
  420. // {a.b in network c.d},
  421. // {a in network b.c.d},
  422. log.Debugf("Name To resolve: %v", name)
  423. name = strings.TrimSuffix(name, ".")
  424. reqName := []string{name}
  425. networkName := []string{""}
  426. if strings.Contains(name, ".") {
  427. var i int
  428. dup := name
  429. for {
  430. if i = strings.LastIndex(dup, "."); i == -1 {
  431. break
  432. }
  433. networkName = append(networkName, name[i+1:])
  434. reqName = append(reqName, name[:i])
  435. dup = dup[:i]
  436. }
  437. }
  438. epList := sb.getConnectedEndpoints()
  439. // In swarm mode services with exposed ports are connected to user overlay
  440. // network, ingress network and docker_gwbridge network. Name resolution
  441. // should prioritize returning the VIP/IPs on user overlay network.
  442. newList := []*endpoint{}
  443. if !sb.controller.isDistributedControl() {
  444. newList = append(newList, getDynamicNwEndpoints(epList)...)
  445. ingressEP := getIngressNwEndpoint(epList)
  446. if ingressEP != nil {
  447. newList = append(newList, ingressEP)
  448. }
  449. newList = append(newList, getLocalNwEndpoints(epList)...)
  450. epList = newList
  451. }
  452. for i := 0; i < len(reqName); i++ {
  453. // First check for local container alias
  454. ip, ipv6Miss := sb.resolveName(reqName[i], networkName[i], epList, true, ipType)
  455. if ip != nil {
  456. return ip, false
  457. }
  458. if ipv6Miss {
  459. return ip, ipv6Miss
  460. }
  461. // Resolve the actual container name
  462. ip, ipv6Miss = sb.resolveName(reqName[i], networkName[i], epList, false, ipType)
  463. if ip != nil {
  464. return ip, false
  465. }
  466. if ipv6Miss {
  467. return ip, ipv6Miss
  468. }
  469. }
  470. return nil, false
  471. }
  472. func (sb *sandbox) resolveName(req string, networkName string, epList []*endpoint, alias bool, ipType int) ([]net.IP, bool) {
  473. var ipv6Miss bool
  474. for _, ep := range epList {
  475. name := req
  476. n := ep.getNetwork()
  477. if networkName != "" && networkName != n.Name() {
  478. continue
  479. }
  480. if alias {
  481. if ep.aliases == nil {
  482. continue
  483. }
  484. var ok bool
  485. ep.Lock()
  486. name, ok = ep.aliases[req]
  487. ep.Unlock()
  488. if !ok {
  489. continue
  490. }
  491. } else {
  492. // If it is a regular lookup and if the requested name is an alias
  493. // don't perform a svc lookup for this endpoint.
  494. ep.Lock()
  495. if _, ok := ep.aliases[req]; ok {
  496. ep.Unlock()
  497. continue
  498. }
  499. ep.Unlock()
  500. }
  501. ip, miss := n.ResolveName(name, ipType)
  502. if ip != nil {
  503. return ip, false
  504. }
  505. if miss {
  506. ipv6Miss = miss
  507. }
  508. }
  509. return nil, ipv6Miss
  510. }
  511. func (sb *sandbox) SetKey(basePath string) error {
  512. start := time.Now()
  513. defer func() {
  514. log.Debugf("sandbox set key processing took %s for container %s", time.Now().Sub(start), sb.ContainerID())
  515. }()
  516. if basePath == "" {
  517. return types.BadRequestErrorf("invalid sandbox key")
  518. }
  519. sb.Lock()
  520. oldosSbox := sb.osSbox
  521. sb.Unlock()
  522. if oldosSbox != nil {
  523. // If we already have an OS sandbox, release the network resources from that
  524. // and destroy the OS snab. We are moving into a new home further down. Note that none
  525. // of the network resources gets destroyed during the move.
  526. sb.releaseOSSbox()
  527. }
  528. osSbox, err := osl.GetSandboxForExternalKey(basePath, sb.Key())
  529. if err != nil {
  530. return err
  531. }
  532. sb.Lock()
  533. sb.osSbox = osSbox
  534. sb.Unlock()
  535. defer func() {
  536. if err != nil {
  537. sb.Lock()
  538. sb.osSbox = nil
  539. sb.Unlock()
  540. }
  541. }()
  542. // If the resolver was setup before stop it and set it up in the
  543. // new osl sandbox.
  544. if oldosSbox != nil && sb.resolver != nil {
  545. sb.resolver.Stop()
  546. if err := sb.osSbox.InvokeFunc(sb.resolver.SetupFunc(0)); err == nil {
  547. if err := sb.resolver.Start(); err != nil {
  548. log.Errorf("Resolver Start failed for container %s, %q", sb.ContainerID(), err)
  549. }
  550. } else {
  551. log.Errorf("Resolver Setup Function failed for container %s, %q", sb.ContainerID(), err)
  552. }
  553. }
  554. for _, ep := range sb.getConnectedEndpoints() {
  555. if err = sb.populateNetworkResources(ep); err != nil {
  556. return err
  557. }
  558. }
  559. return nil
  560. }
  561. func (sb *sandbox) EnableService() error {
  562. for _, ep := range sb.getConnectedEndpoints() {
  563. if ep.enableService(true) {
  564. if err := ep.addToCluster(); err != nil {
  565. ep.enableService(false)
  566. return fmt.Errorf("could not update state for endpoint %s into cluster: %v", ep.Name(), err)
  567. }
  568. }
  569. }
  570. return nil
  571. }
  572. func (sb *sandbox) DisableService() error {
  573. for _, ep := range sb.getConnectedEndpoints() {
  574. if ep.enableService(false) {
  575. if err := ep.deleteFromCluster(); err != nil {
  576. ep.enableService(true)
  577. return fmt.Errorf("could not delete state for endpoint %s from cluster: %v", ep.Name(), err)
  578. }
  579. }
  580. }
  581. return nil
  582. }
  583. func releaseOSSboxResources(osSbox osl.Sandbox, ep *endpoint) {
  584. for _, i := range osSbox.Info().Interfaces() {
  585. // Only remove the interfaces owned by this endpoint from the sandbox.
  586. if ep.hasInterface(i.SrcName()) {
  587. if err := i.Remove(); err != nil {
  588. log.Debugf("Remove interface %s failed: %v", i.SrcName(), err)
  589. }
  590. }
  591. }
  592. ep.Lock()
  593. joinInfo := ep.joinInfo
  594. ep.Unlock()
  595. if joinInfo == nil {
  596. return
  597. }
  598. // Remove non-interface routes.
  599. for _, r := range joinInfo.StaticRoutes {
  600. if err := osSbox.RemoveStaticRoute(r); err != nil {
  601. log.Debugf("Remove route failed: %v", err)
  602. }
  603. }
  604. }
  605. func (sb *sandbox) releaseOSSbox() {
  606. sb.Lock()
  607. osSbox := sb.osSbox
  608. sb.osSbox = nil
  609. sb.Unlock()
  610. if osSbox == nil {
  611. return
  612. }
  613. for _, ep := range sb.getConnectedEndpoints() {
  614. releaseOSSboxResources(osSbox, ep)
  615. }
  616. osSbox.Destroy()
  617. }
  618. func (sb *sandbox) restoreOslSandbox() error {
  619. var routes []*types.StaticRoute
  620. // restore osl sandbox
  621. Ifaces := make(map[string][]osl.IfaceOption)
  622. for _, ep := range sb.endpoints {
  623. var ifaceOptions []osl.IfaceOption
  624. ep.Lock()
  625. joinInfo := ep.joinInfo
  626. i := ep.iface
  627. ep.Unlock()
  628. if i == nil {
  629. log.Errorf("error restoring endpoint %s for container %s", ep.Name(), sb.ContainerID())
  630. continue
  631. }
  632. ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().Address(i.addr), sb.osSbox.InterfaceOptions().Routes(i.routes))
  633. if i.addrv6 != nil && i.addrv6.IP.To16() != nil {
  634. ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().AddressIPv6(i.addrv6))
  635. }
  636. if i.mac != nil {
  637. ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().MacAddress(i.mac))
  638. }
  639. if len(i.llAddrs) != 0 {
  640. ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().LinkLocalAddresses(i.llAddrs))
  641. }
  642. if len(ep.virtualIP) != 0 {
  643. vipAlias := &net.IPNet{IP: ep.virtualIP, Mask: net.CIDRMask(32, 32)}
  644. ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().IPAliases([]*net.IPNet{vipAlias}))
  645. }
  646. Ifaces[fmt.Sprintf("%s+%s", i.srcName, i.dstPrefix)] = ifaceOptions
  647. if joinInfo != nil {
  648. for _, r := range joinInfo.StaticRoutes {
  649. routes = append(routes, r)
  650. }
  651. }
  652. if ep.needResolver() {
  653. sb.startResolver(true)
  654. }
  655. }
  656. gwep := sb.getGatewayEndpoint()
  657. if gwep == nil {
  658. return nil
  659. }
  660. // restore osl sandbox
  661. err := sb.osSbox.Restore(Ifaces, routes, gwep.joinInfo.gw, gwep.joinInfo.gw6)
  662. if err != nil {
  663. return err
  664. }
  665. return nil
  666. }
  667. func (sb *sandbox) populateNetworkResources(ep *endpoint) error {
  668. sb.Lock()
  669. if sb.osSbox == nil {
  670. sb.Unlock()
  671. return nil
  672. }
  673. inDelete := sb.inDelete
  674. sb.Unlock()
  675. ep.Lock()
  676. joinInfo := ep.joinInfo
  677. i := ep.iface
  678. ep.Unlock()
  679. if ep.needResolver() {
  680. sb.startResolver(false)
  681. }
  682. if i != nil && i.srcName != "" {
  683. var ifaceOptions []osl.IfaceOption
  684. ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().Address(i.addr), sb.osSbox.InterfaceOptions().Routes(i.routes))
  685. if i.addrv6 != nil && i.addrv6.IP.To16() != nil {
  686. ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().AddressIPv6(i.addrv6))
  687. }
  688. if len(i.llAddrs) != 0 {
  689. ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().LinkLocalAddresses(i.llAddrs))
  690. }
  691. if len(ep.virtualIP) != 0 {
  692. vipAlias := &net.IPNet{IP: ep.virtualIP, Mask: net.CIDRMask(32, 32)}
  693. ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().IPAliases([]*net.IPNet{vipAlias}))
  694. }
  695. if i.mac != nil {
  696. ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().MacAddress(i.mac))
  697. }
  698. if err := sb.osSbox.AddInterface(i.srcName, i.dstPrefix, ifaceOptions...); err != nil {
  699. return fmt.Errorf("failed to add interface %s to sandbox: %v", i.srcName, err)
  700. }
  701. }
  702. if joinInfo != nil {
  703. // Set up non-interface routes.
  704. for _, r := range joinInfo.StaticRoutes {
  705. if err := sb.osSbox.AddStaticRoute(r); err != nil {
  706. return fmt.Errorf("failed to add static route %s: %v", r.Destination.String(), err)
  707. }
  708. }
  709. }
  710. if ep == sb.getGatewayEndpoint() {
  711. if err := sb.updateGateway(ep); err != nil {
  712. return err
  713. }
  714. }
  715. // Make sure to add the endpoint to the populated endpoint set
  716. // before populating loadbalancers.
  717. sb.Lock()
  718. sb.populatedEndpoints[ep.ID()] = struct{}{}
  719. sb.Unlock()
  720. // Populate load balancer only after updating all the other
  721. // information including gateway and other routes so that
  722. // loadbalancers are populated all the network state is in
  723. // place in the sandbox.
  724. sb.populateLoadbalancers(ep)
  725. // Only update the store if we did not come here as part of
  726. // sandbox delete. If we came here as part of delete then do
  727. // not bother updating the store. The sandbox object will be
  728. // deleted anyway
  729. if !inDelete {
  730. return sb.storeUpdate()
  731. }
  732. return nil
  733. }
  734. func (sb *sandbox) clearNetworkResources(origEp *endpoint) error {
  735. ep := sb.getEndpoint(origEp.id)
  736. if ep == nil {
  737. return fmt.Errorf("could not find the sandbox endpoint data for endpoint %s",
  738. origEp.id)
  739. }
  740. sb.Lock()
  741. osSbox := sb.osSbox
  742. inDelete := sb.inDelete
  743. sb.Unlock()
  744. if osSbox != nil {
  745. releaseOSSboxResources(osSbox, ep)
  746. }
  747. sb.Lock()
  748. delete(sb.populatedEndpoints, ep.ID())
  749. if len(sb.endpoints) == 0 {
  750. // sb.endpoints should never be empty and this is unexpected error condition
  751. // We log an error message to note this down for debugging purposes.
  752. log.Errorf("No endpoints in sandbox while trying to remove endpoint %s", ep.Name())
  753. sb.Unlock()
  754. return nil
  755. }
  756. var (
  757. gwepBefore, gwepAfter *endpoint
  758. index = -1
  759. )
  760. for i, e := range sb.endpoints {
  761. if e == ep {
  762. index = i
  763. }
  764. if len(e.Gateway()) > 0 && gwepBefore == nil {
  765. gwepBefore = e
  766. }
  767. if index != -1 && gwepBefore != nil {
  768. break
  769. }
  770. }
  771. heap.Remove(&sb.endpoints, index)
  772. for _, e := range sb.endpoints {
  773. if len(e.Gateway()) > 0 {
  774. gwepAfter = e
  775. break
  776. }
  777. }
  778. delete(sb.epPriority, ep.ID())
  779. sb.Unlock()
  780. if gwepAfter != nil && gwepBefore != gwepAfter {
  781. sb.updateGateway(gwepAfter)
  782. }
  783. // Only update the store if we did not come here as part of
  784. // sandbox delete. If we came here as part of delete then do
  785. // not bother updating the store. The sandbox object will be
  786. // deleted anyway
  787. if !inDelete {
  788. return sb.storeUpdate()
  789. }
  790. return nil
  791. }
  792. func (sb *sandbox) isEndpointPopulated(ep *endpoint) bool {
  793. sb.Lock()
  794. _, ok := sb.populatedEndpoints[ep.ID()]
  795. sb.Unlock()
  796. return ok
  797. }
  798. // joinLeaveStart waits to ensure there are no joins or leaves in progress and
  799. // marks this join/leave in progress without race
  800. func (sb *sandbox) joinLeaveStart() {
  801. sb.Lock()
  802. defer sb.Unlock()
  803. for sb.joinLeaveDone != nil {
  804. joinLeaveDone := sb.joinLeaveDone
  805. sb.Unlock()
  806. select {
  807. case <-joinLeaveDone:
  808. }
  809. sb.Lock()
  810. }
  811. sb.joinLeaveDone = make(chan struct{})
  812. }
  813. // joinLeaveEnd marks the end of this join/leave operation and
  814. // signals the same without race to other join and leave waiters
  815. func (sb *sandbox) joinLeaveEnd() {
  816. sb.Lock()
  817. defer sb.Unlock()
  818. if sb.joinLeaveDone != nil {
  819. close(sb.joinLeaveDone)
  820. sb.joinLeaveDone = nil
  821. }
  822. }
  823. func (sb *sandbox) hasPortConfigs() bool {
  824. opts := sb.Labels()
  825. _, hasExpPorts := opts[netlabel.ExposedPorts]
  826. _, hasPortMaps := opts[netlabel.PortMap]
  827. return hasExpPorts || hasPortMaps
  828. }
  829. // OptionHostname function returns an option setter for hostname option to
  830. // be passed to NewSandbox method.
  831. func OptionHostname(name string) SandboxOption {
  832. return func(sb *sandbox) {
  833. sb.config.hostName = name
  834. }
  835. }
  836. // OptionDomainname function returns an option setter for domainname option to
  837. // be passed to NewSandbox method.
  838. func OptionDomainname(name string) SandboxOption {
  839. return func(sb *sandbox) {
  840. sb.config.domainName = name
  841. }
  842. }
  843. // OptionHostsPath function returns an option setter for hostspath option to
  844. // be passed to NewSandbox method.
  845. func OptionHostsPath(path string) SandboxOption {
  846. return func(sb *sandbox) {
  847. sb.config.hostsPath = path
  848. }
  849. }
  850. // OptionOriginHostsPath function returns an option setter for origin hosts file path
  851. // to be passed to NewSandbox method.
  852. func OptionOriginHostsPath(path string) SandboxOption {
  853. return func(sb *sandbox) {
  854. sb.config.originHostsPath = path
  855. }
  856. }
  857. // OptionExtraHost function returns an option setter for extra /etc/hosts options
  858. // which is a name and IP as strings.
  859. func OptionExtraHost(name string, IP string) SandboxOption {
  860. return func(sb *sandbox) {
  861. sb.config.extraHosts = append(sb.config.extraHosts, extraHost{name: name, IP: IP})
  862. }
  863. }
  864. // OptionParentUpdate function returns an option setter for parent container
  865. // which needs to update the IP address for the linked container.
  866. func OptionParentUpdate(cid string, name, ip string) SandboxOption {
  867. return func(sb *sandbox) {
  868. sb.config.parentUpdates = append(sb.config.parentUpdates, parentUpdate{cid: cid, name: name, ip: ip})
  869. }
  870. }
  871. // OptionResolvConfPath function returns an option setter for resolvconfpath option to
  872. // be passed to net container methods.
  873. func OptionResolvConfPath(path string) SandboxOption {
  874. return func(sb *sandbox) {
  875. sb.config.resolvConfPath = path
  876. }
  877. }
  878. // OptionOriginResolvConfPath function returns an option setter to set the path to the
  879. // origin resolv.conf file to be passed to net container methods.
  880. func OptionOriginResolvConfPath(path string) SandboxOption {
  881. return func(sb *sandbox) {
  882. sb.config.originResolvConfPath = path
  883. }
  884. }
  885. // OptionDNS function returns an option setter for dns entry option to
  886. // be passed to container Create method.
  887. func OptionDNS(dns string) SandboxOption {
  888. return func(sb *sandbox) {
  889. sb.config.dnsList = append(sb.config.dnsList, dns)
  890. }
  891. }
  892. // OptionDNSSearch function returns an option setter for dns search entry option to
  893. // be passed to container Create method.
  894. func OptionDNSSearch(search string) SandboxOption {
  895. return func(sb *sandbox) {
  896. sb.config.dnsSearchList = append(sb.config.dnsSearchList, search)
  897. }
  898. }
  899. // OptionDNSOptions function returns an option setter for dns options entry option to
  900. // be passed to container Create method.
  901. func OptionDNSOptions(options string) SandboxOption {
  902. return func(sb *sandbox) {
  903. sb.config.dnsOptionsList = append(sb.config.dnsOptionsList, options)
  904. }
  905. }
  906. // OptionUseDefaultSandbox function returns an option setter for using default sandbox to
  907. // be passed to container Create method.
  908. func OptionUseDefaultSandbox() SandboxOption {
  909. return func(sb *sandbox) {
  910. sb.config.useDefaultSandBox = true
  911. }
  912. }
  913. // OptionUseExternalKey function returns an option setter for using provided namespace
  914. // instead of creating one.
  915. func OptionUseExternalKey() SandboxOption {
  916. return func(sb *sandbox) {
  917. sb.config.useExternalKey = true
  918. }
  919. }
  920. // OptionGeneric function returns an option setter for Generic configuration
  921. // that is not managed by libNetwork but can be used by the Drivers during the call to
  922. // net container creation method. Container Labels are a good example.
  923. func OptionGeneric(generic map[string]interface{}) SandboxOption {
  924. return func(sb *sandbox) {
  925. if sb.config.generic == nil {
  926. sb.config.generic = make(map[string]interface{}, len(generic))
  927. }
  928. for k, v := range generic {
  929. sb.config.generic[k] = v
  930. }
  931. }
  932. }
  933. // OptionExposedPorts function returns an option setter for the container exposed
  934. // ports option to be passed to container Create method.
  935. func OptionExposedPorts(exposedPorts []types.TransportPort) SandboxOption {
  936. return func(sb *sandbox) {
  937. if sb.config.generic == nil {
  938. sb.config.generic = make(map[string]interface{})
  939. }
  940. // Defensive copy
  941. eps := make([]types.TransportPort, len(exposedPorts))
  942. copy(eps, exposedPorts)
  943. // Store endpoint label and in generic because driver needs it
  944. sb.config.exposedPorts = eps
  945. sb.config.generic[netlabel.ExposedPorts] = eps
  946. }
  947. }
  948. // OptionPortMapping function returns an option setter for the mapping
  949. // ports option to be passed to container Create method.
  950. func OptionPortMapping(portBindings []types.PortBinding) SandboxOption {
  951. return func(sb *sandbox) {
  952. if sb.config.generic == nil {
  953. sb.config.generic = make(map[string]interface{})
  954. }
  955. // Store a copy of the bindings as generic data to pass to the driver
  956. pbs := make([]types.PortBinding, len(portBindings))
  957. copy(pbs, portBindings)
  958. sb.config.generic[netlabel.PortMap] = pbs
  959. }
  960. }
  961. // OptionIngress function returns an option setter for marking a
  962. // sandbox as the controller's ingress sandbox.
  963. func OptionIngress() SandboxOption {
  964. return func(sb *sandbox) {
  965. sb.ingress = true
  966. }
  967. }
  968. func (eh epHeap) Len() int { return len(eh) }
  969. func (eh epHeap) Less(i, j int) bool {
  970. var (
  971. cip, cjp int
  972. ok bool
  973. )
  974. ci, _ := eh[i].getSandbox()
  975. cj, _ := eh[j].getSandbox()
  976. epi := eh[i]
  977. epj := eh[j]
  978. if epi.endpointInGWNetwork() {
  979. return false
  980. }
  981. if epj.endpointInGWNetwork() {
  982. return true
  983. }
  984. if epi.getNetwork().Internal() {
  985. return false
  986. }
  987. if epj.getNetwork().Internal() {
  988. return true
  989. }
  990. if ci != nil {
  991. cip, ok = ci.epPriority[eh[i].ID()]
  992. if !ok {
  993. cip = 0
  994. }
  995. }
  996. if cj != nil {
  997. cjp, ok = cj.epPriority[eh[j].ID()]
  998. if !ok {
  999. cjp = 0
  1000. }
  1001. }
  1002. if cip == cjp {
  1003. return eh[i].network.Name() < eh[j].network.Name()
  1004. }
  1005. return cip > cjp
  1006. }
  1007. func (eh epHeap) Swap(i, j int) { eh[i], eh[j] = eh[j], eh[i] }
  1008. func (eh *epHeap) Push(x interface{}) {
  1009. *eh = append(*eh, x.(*endpoint))
  1010. }
  1011. func (eh *epHeap) Pop() interface{} {
  1012. old := *eh
  1013. n := len(old)
  1014. x := old[n-1]
  1015. *eh = old[0 : n-1]
  1016. return x
  1017. }
  1018. func (sb *sandbox) NdotsSet() bool {
  1019. return sb.ndotsSet
  1020. }