sandbox.go 28 KB

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