sandbox.go 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177
  1. package libnetwork
  2. import (
  3. "container/heap"
  4. "encoding/json"
  5. "fmt"
  6. "io/ioutil"
  7. "net"
  8. "os"
  9. "path"
  10. "path/filepath"
  11. "strings"
  12. "sync"
  13. log "github.com/Sirupsen/logrus"
  14. "github.com/docker/libnetwork/etchosts"
  15. "github.com/docker/libnetwork/osl"
  16. "github.com/docker/libnetwork/resolvconf"
  17. "github.com/docker/libnetwork/types"
  18. )
  19. // Sandbox provides the control over the network container entity. It is a one to one mapping with the container.
  20. type Sandbox interface {
  21. // ID returns the ID of the sandbox
  22. ID() string
  23. // Key returns the sandbox's key
  24. Key() string
  25. // ContainerID returns the container id associated to this sandbox
  26. ContainerID() string
  27. // Labels returns the sandbox's labels
  28. Labels() map[string]interface{}
  29. // Statistics retrieves the interfaces' statistics for the sandbox
  30. Statistics() (map[string]*types.InterfaceStatistics, error)
  31. // Refresh leaves all the endpoints, resets and re-apply the options,
  32. // re-joins all the endpoints without destroying the osl sandbox
  33. Refresh(options ...SandboxOption) error
  34. // SetKey updates the Sandbox Key
  35. SetKey(key string) error
  36. // Rename changes the name of all attached Endpoints
  37. Rename(name string) error
  38. // Delete destroys this container after detaching it from all connected endpoints.
  39. Delete() error
  40. // ResolveName searches for the service name in the networks to which the sandbox
  41. // is connected to.
  42. ResolveName(name string) net.IP
  43. // ResolveIP returns the service name for the passed in IP. IP is in reverse dotted
  44. // notation; the format used for DNS PTR records
  45. ResolveIP(name string) string
  46. }
  47. // SandboxOption is an option setter function type used to pass various options to
  48. // NewNetContainer method. The various setter functions of type SandboxOption are
  49. // provided by libnetwork, they look like ContainerOptionXXXX(...)
  50. type SandboxOption func(sb *sandbox)
  51. func (sb *sandbox) processOptions(options ...SandboxOption) {
  52. for _, opt := range options {
  53. if opt != nil {
  54. opt(sb)
  55. }
  56. }
  57. }
  58. type epHeap []*endpoint
  59. type sandbox struct {
  60. id string
  61. containerID string
  62. config containerConfig
  63. extDNS []string
  64. osSbox osl.Sandbox
  65. controller *controller
  66. resolver Resolver
  67. resolverOnce sync.Once
  68. refCnt int
  69. endpoints epHeap
  70. epPriority map[string]int
  71. joinLeaveDone chan struct{}
  72. dbIndex uint64
  73. dbExists bool
  74. isStub bool
  75. inDelete bool
  76. sync.Mutex
  77. }
  78. // These are the container configs used to customize container /etc/hosts file.
  79. type hostsPathConfig struct {
  80. hostName string
  81. domainName string
  82. hostsPath string
  83. originHostsPath string
  84. extraHosts []extraHost
  85. parentUpdates []parentUpdate
  86. }
  87. type parentUpdate struct {
  88. cid string
  89. name string
  90. ip string
  91. }
  92. type extraHost struct {
  93. name string
  94. IP string
  95. }
  96. // These are the container configs used to customize container /etc/resolv.conf file.
  97. type resolvConfPathConfig struct {
  98. resolvConfPath string
  99. originResolvConfPath string
  100. resolvConfHashFile string
  101. dnsList []string
  102. dnsSearchList []string
  103. dnsOptionsList []string
  104. }
  105. type containerConfig struct {
  106. hostsPathConfig
  107. resolvConfPathConfig
  108. generic map[string]interface{}
  109. useDefaultSandBox bool
  110. useExternalKey bool
  111. prio int // higher the value, more the priority
  112. }
  113. func (sb *sandbox) ID() string {
  114. return sb.id
  115. }
  116. func (sb *sandbox) ContainerID() string {
  117. return sb.containerID
  118. }
  119. func (sb *sandbox) Key() string {
  120. if sb.config.useDefaultSandBox {
  121. return osl.GenerateKey("default")
  122. }
  123. return osl.GenerateKey(sb.id)
  124. }
  125. func (sb *sandbox) Labels() map[string]interface{} {
  126. return sb.config.generic
  127. }
  128. func (sb *sandbox) Statistics() (map[string]*types.InterfaceStatistics, error) {
  129. m := make(map[string]*types.InterfaceStatistics)
  130. if sb.osSbox == nil {
  131. return m, nil
  132. }
  133. var err error
  134. for _, i := range sb.osSbox.Info().Interfaces() {
  135. if m[i.DstName()], err = i.Statistics(); err != nil {
  136. return m, err
  137. }
  138. }
  139. return m, nil
  140. }
  141. func (sb *sandbox) Delete() error {
  142. return sb.delete(false)
  143. }
  144. func (sb *sandbox) delete(force bool) error {
  145. sb.Lock()
  146. if sb.inDelete {
  147. sb.Unlock()
  148. return types.ForbiddenErrorf("another sandbox delete in progress")
  149. }
  150. // Set the inDelete flag. This will ensure that we don't
  151. // update the store until we have completed all the endpoint
  152. // leaves and deletes. And when endpoint leaves and deletes
  153. // are completed then we can finally delete the sandbox object
  154. // altogether from the data store. If the daemon exits
  155. // ungracefully in the middle of a sandbox delete this way we
  156. // will have all the references to the endpoints in the
  157. // sandbox so that we can clean them up when we restart
  158. sb.inDelete = true
  159. sb.Unlock()
  160. c := sb.controller
  161. // Detach from all endpoints
  162. retain := false
  163. for _, ep := range sb.getConnectedEndpoints() {
  164. // endpoint in the Gateway network will be cleaned up
  165. // when when sandbox no longer needs external connectivity
  166. if ep.endpointInGWNetwork() {
  167. continue
  168. }
  169. // Retain the sanbdox if we can't obtain the network from store.
  170. if _, err := c.getNetworkFromStore(ep.getNetwork().ID()); err != nil {
  171. retain = true
  172. log.Warnf("Failed getting network for ep %s during sandbox %s delete: %v", ep.ID(), sb.ID(), err)
  173. continue
  174. }
  175. if !force {
  176. if err := ep.Leave(sb); err != nil {
  177. log.Warnf("Failed detaching sandbox %s from endpoint %s: %v\n", sb.ID(), ep.ID(), err)
  178. }
  179. }
  180. if err := ep.Delete(force); err != nil {
  181. log.Warnf("Failed deleting endpoint %s: %v\n", ep.ID(), err)
  182. }
  183. }
  184. if retain {
  185. sb.Lock()
  186. sb.inDelete = false
  187. sb.Unlock()
  188. return fmt.Errorf("could not cleanup all the endpoints in container %s / sandbox %s", sb.containerID, sb.id)
  189. }
  190. // Container is going away. Path cache in etchosts is most
  191. // likely not required any more. Drop it.
  192. etchosts.Drop(sb.config.hostsPath)
  193. if sb.resolver != nil {
  194. sb.resolver.Stop()
  195. }
  196. if sb.osSbox != nil && !sb.config.useDefaultSandBox {
  197. sb.osSbox.Destroy()
  198. }
  199. if err := sb.storeDelete(); err != nil {
  200. log.Warnf("Failed to delete sandbox %s from store: %v", sb.ID(), err)
  201. }
  202. c.Lock()
  203. delete(c.sandboxes, sb.ID())
  204. c.Unlock()
  205. return nil
  206. }
  207. func (sb *sandbox) Rename(name string) error {
  208. var err error
  209. for _, ep := range sb.getConnectedEndpoints() {
  210. if ep.endpointInGWNetwork() {
  211. continue
  212. }
  213. oldName := ep.Name()
  214. lEp := ep
  215. if err = ep.rename(name); err != nil {
  216. break
  217. }
  218. defer func() {
  219. if err != nil {
  220. lEp.rename(oldName)
  221. }
  222. }()
  223. }
  224. return err
  225. }
  226. func (sb *sandbox) Refresh(options ...SandboxOption) error {
  227. // Store connected endpoints
  228. epList := sb.getConnectedEndpoints()
  229. // Detach from all endpoints
  230. for _, ep := range epList {
  231. if err := ep.Leave(sb); err != nil {
  232. log.Warnf("Failed detaching sandbox %s from endpoint %s: %v\n", sb.ID(), ep.ID(), err)
  233. }
  234. }
  235. // Re-apply options
  236. sb.config = containerConfig{}
  237. sb.processOptions(options...)
  238. // Setup discovery files
  239. if err := sb.setupResolutionFiles(); err != nil {
  240. return err
  241. }
  242. // Re -connect to all endpoints
  243. for _, ep := range epList {
  244. if err := ep.Join(sb); err != nil {
  245. log.Warnf("Failed attach sandbox %s to endpoint %s: %v\n", sb.ID(), ep.ID(), err)
  246. }
  247. }
  248. return nil
  249. }
  250. func (sb *sandbox) MarshalJSON() ([]byte, error) {
  251. sb.Lock()
  252. defer sb.Unlock()
  253. // We are just interested in the container ID. This can be expanded to include all of containerInfo if there is a need
  254. return json.Marshal(sb.id)
  255. }
  256. func (sb *sandbox) UnmarshalJSON(b []byte) (err error) {
  257. sb.Lock()
  258. defer sb.Unlock()
  259. var id string
  260. if err := json.Unmarshal(b, &id); err != nil {
  261. return err
  262. }
  263. sb.id = id
  264. return nil
  265. }
  266. func (sb *sandbox) startResolver() {
  267. sb.resolverOnce.Do(func() {
  268. var err error
  269. sb.resolver = NewResolver(sb)
  270. defer func() {
  271. if err != nil {
  272. sb.resolver = nil
  273. }
  274. }()
  275. err = sb.rebuildDNS()
  276. if err != nil {
  277. log.Errorf("Updating resolv.conf failed for container %s, %q", sb.ContainerID(), err)
  278. return
  279. }
  280. sb.resolver.SetExtServers(sb.extDNS)
  281. sb.osSbox.InvokeFunc(sb.resolver.SetupFunc())
  282. if err = sb.resolver.Start(); err != nil {
  283. log.Errorf("Resolver Setup/Start failed for container %s, %q", sb.ContainerID(), err)
  284. }
  285. })
  286. }
  287. func (sb *sandbox) setupResolutionFiles() error {
  288. if err := sb.buildHostsFile(); err != nil {
  289. return err
  290. }
  291. if err := sb.updateParentHosts(); err != nil {
  292. return err
  293. }
  294. if err := sb.setupDNS(); err != nil {
  295. return err
  296. }
  297. return nil
  298. }
  299. func (sb *sandbox) getConnectedEndpoints() []*endpoint {
  300. sb.Lock()
  301. defer sb.Unlock()
  302. eps := make([]*endpoint, len(sb.endpoints))
  303. for i, ep := range sb.endpoints {
  304. eps[i] = ep
  305. }
  306. return eps
  307. }
  308. func (sb *sandbox) getEndpoint(id string) *endpoint {
  309. sb.Lock()
  310. defer sb.Unlock()
  311. for _, ep := range sb.endpoints {
  312. if ep.id == id {
  313. return ep
  314. }
  315. }
  316. return nil
  317. }
  318. func (sb *sandbox) updateGateway(ep *endpoint) error {
  319. sb.Lock()
  320. osSbox := sb.osSbox
  321. sb.Unlock()
  322. if osSbox == nil {
  323. return nil
  324. }
  325. osSbox.UnsetGateway()
  326. osSbox.UnsetGatewayIPv6()
  327. if ep == nil {
  328. return nil
  329. }
  330. ep.Lock()
  331. joinInfo := ep.joinInfo
  332. ep.Unlock()
  333. if err := osSbox.SetGateway(joinInfo.gw); err != nil {
  334. return fmt.Errorf("failed to set gateway while updating gateway: %v", err)
  335. }
  336. if err := osSbox.SetGatewayIPv6(joinInfo.gw6); err != nil {
  337. return fmt.Errorf("failed to set IPv6 gateway while updating gateway: %v", err)
  338. }
  339. return nil
  340. }
  341. func (sb *sandbox) ResolveIP(ip string) string {
  342. var svc string
  343. log.Debugf("IP To resolve %v", ip)
  344. for _, ep := range sb.getConnectedEndpoints() {
  345. n := ep.getNetwork()
  346. sr, ok := n.getController().svcDb[n.ID()]
  347. if !ok {
  348. continue
  349. }
  350. nwName := n.Name()
  351. n.Lock()
  352. svc, ok = sr.ipMap[ip]
  353. n.Unlock()
  354. if ok {
  355. return svc + "." + nwName
  356. }
  357. }
  358. return svc
  359. }
  360. func (sb *sandbox) ResolveName(name string) net.IP {
  361. var ip net.IP
  362. parts := strings.Split(name, ".")
  363. log.Debugf("To resolve %v", parts)
  364. reqName := parts[0]
  365. networkName := ""
  366. if len(parts) > 1 {
  367. networkName = parts[1]
  368. }
  369. epList := sb.getConnectedEndpoints()
  370. // First check for local container alias
  371. ip = sb.resolveName(reqName, networkName, epList, true)
  372. if ip != nil {
  373. return ip
  374. }
  375. // Resolve the actual container name
  376. return sb.resolveName(reqName, networkName, epList, false)
  377. }
  378. func (sb *sandbox) resolveName(req string, networkName string, epList []*endpoint, alias bool) net.IP {
  379. for _, ep := range epList {
  380. name := req
  381. n := ep.getNetwork()
  382. if networkName != "" && networkName != n.Name() {
  383. continue
  384. }
  385. if alias {
  386. if ep.aliases == nil {
  387. continue
  388. }
  389. var ok bool
  390. ep.Lock()
  391. name, ok = ep.aliases[req]
  392. ep.Unlock()
  393. if !ok {
  394. continue
  395. }
  396. } else {
  397. // If it is a regular lookup and if the requested name is an alias
  398. // dont perform a svc lookup for this endpoint.
  399. ep.Lock()
  400. if _, ok := ep.aliases[req]; ok {
  401. ep.Unlock()
  402. continue
  403. }
  404. ep.Unlock()
  405. }
  406. sr, ok := n.getController().svcDb[n.ID()]
  407. if !ok {
  408. continue
  409. }
  410. n.Lock()
  411. ip, ok := sr.svcMap[name]
  412. n.Unlock()
  413. if ok {
  414. return ip[0]
  415. }
  416. }
  417. return nil
  418. }
  419. func (sb *sandbox) SetKey(basePath string) error {
  420. if basePath == "" {
  421. return types.BadRequestErrorf("invalid sandbox key")
  422. }
  423. sb.Lock()
  424. oldosSbox := sb.osSbox
  425. sb.Unlock()
  426. if oldosSbox != nil {
  427. // If we already have an OS sandbox, release the network resources from that
  428. // and destroy the OS snab. We are moving into a new home further down. Note that none
  429. // of the network resources gets destroyed during the move.
  430. sb.releaseOSSbox()
  431. }
  432. osSbox, err := osl.GetSandboxForExternalKey(basePath, sb.Key())
  433. if err != nil {
  434. return err
  435. }
  436. sb.Lock()
  437. sb.osSbox = osSbox
  438. sb.Unlock()
  439. defer func() {
  440. if err != nil {
  441. sb.Lock()
  442. sb.osSbox = nil
  443. sb.Unlock()
  444. }
  445. }()
  446. // If the resolver was setup before stop it and set it up in the
  447. // new osl sandbox.
  448. if oldosSbox != nil && sb.resolver != nil {
  449. sb.resolver.Stop()
  450. sb.osSbox.InvokeFunc(sb.resolver.SetupFunc())
  451. if err := sb.resolver.Start(); err != nil {
  452. log.Errorf("Resolver Setup/Start failed for container %s, %q", sb.ContainerID(), err)
  453. }
  454. }
  455. for _, ep := range sb.getConnectedEndpoints() {
  456. if err = sb.populateNetworkResources(ep); err != nil {
  457. return err
  458. }
  459. }
  460. return nil
  461. }
  462. func releaseOSSboxResources(osSbox osl.Sandbox, ep *endpoint) {
  463. for _, i := range osSbox.Info().Interfaces() {
  464. // Only remove the interfaces owned by this endpoint from the sandbox.
  465. if ep.hasInterface(i.SrcName()) {
  466. if err := i.Remove(); err != nil {
  467. log.Debugf("Remove interface failed: %v", err)
  468. }
  469. }
  470. }
  471. ep.Lock()
  472. joinInfo := ep.joinInfo
  473. ep.Unlock()
  474. if joinInfo == nil {
  475. return
  476. }
  477. // Remove non-interface routes.
  478. for _, r := range joinInfo.StaticRoutes {
  479. if err := osSbox.RemoveStaticRoute(r); err != nil {
  480. log.Debugf("Remove route failed: %v", err)
  481. }
  482. }
  483. }
  484. func (sb *sandbox) releaseOSSbox() {
  485. sb.Lock()
  486. osSbox := sb.osSbox
  487. sb.osSbox = nil
  488. sb.Unlock()
  489. if osSbox == nil {
  490. return
  491. }
  492. for _, ep := range sb.getConnectedEndpoints() {
  493. releaseOSSboxResources(osSbox, ep)
  494. }
  495. osSbox.Destroy()
  496. }
  497. func (sb *sandbox) populateNetworkResources(ep *endpoint) error {
  498. sb.Lock()
  499. if sb.osSbox == nil {
  500. sb.Unlock()
  501. return nil
  502. }
  503. inDelete := sb.inDelete
  504. sb.Unlock()
  505. ep.Lock()
  506. joinInfo := ep.joinInfo
  507. i := ep.iface
  508. ep.Unlock()
  509. if ep.needResolver() {
  510. sb.startResolver()
  511. }
  512. if i != nil && i.srcName != "" {
  513. var ifaceOptions []osl.IfaceOption
  514. ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().Address(i.addr), sb.osSbox.InterfaceOptions().Routes(i.routes))
  515. if i.addrv6 != nil && i.addrv6.IP.To16() != nil {
  516. ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().AddressIPv6(i.addrv6))
  517. }
  518. if err := sb.osSbox.AddInterface(i.srcName, i.dstPrefix, ifaceOptions...); err != nil {
  519. return fmt.Errorf("failed to add interface %s to sandbox: %v", i.srcName, err)
  520. }
  521. }
  522. if joinInfo != nil {
  523. // Set up non-interface routes.
  524. for _, r := range joinInfo.StaticRoutes {
  525. if err := sb.osSbox.AddStaticRoute(r); err != nil {
  526. return fmt.Errorf("failed to add static route %s: %v", r.Destination.String(), err)
  527. }
  528. }
  529. }
  530. for _, gwep := range sb.getConnectedEndpoints() {
  531. if len(gwep.Gateway()) > 0 {
  532. if gwep != ep {
  533. break
  534. }
  535. if err := sb.updateGateway(gwep); err != nil {
  536. return err
  537. }
  538. }
  539. }
  540. // Only update the store if we did not come here as part of
  541. // sandbox delete. If we came here as part of delete then do
  542. // not bother updating the store. The sandbox object will be
  543. // deleted anyway
  544. if !inDelete {
  545. return sb.storeUpdate()
  546. }
  547. return nil
  548. }
  549. func (sb *sandbox) clearNetworkResources(origEp *endpoint) error {
  550. ep := sb.getEndpoint(origEp.id)
  551. if ep == nil {
  552. return fmt.Errorf("could not find the sandbox endpoint data for endpoint %s",
  553. ep.name)
  554. }
  555. sb.Lock()
  556. osSbox := sb.osSbox
  557. inDelete := sb.inDelete
  558. sb.Unlock()
  559. if osSbox != nil {
  560. releaseOSSboxResources(osSbox, ep)
  561. }
  562. sb.Lock()
  563. if len(sb.endpoints) == 0 {
  564. // sb.endpoints should never be empty and this is unexpected error condition
  565. // We log an error message to note this down for debugging purposes.
  566. log.Errorf("No endpoints in sandbox while trying to remove endpoint %s", ep.Name())
  567. sb.Unlock()
  568. return nil
  569. }
  570. var (
  571. gwepBefore, gwepAfter *endpoint
  572. index = -1
  573. )
  574. for i, e := range sb.endpoints {
  575. if e == ep {
  576. index = i
  577. }
  578. if len(e.Gateway()) > 0 && gwepBefore == nil {
  579. gwepBefore = e
  580. }
  581. if index != -1 && gwepBefore != nil {
  582. break
  583. }
  584. }
  585. heap.Remove(&sb.endpoints, index)
  586. for _, e := range sb.endpoints {
  587. if len(e.Gateway()) > 0 {
  588. gwepAfter = e
  589. break
  590. }
  591. }
  592. delete(sb.epPriority, ep.ID())
  593. sb.Unlock()
  594. if gwepAfter != nil && gwepBefore != gwepAfter {
  595. sb.updateGateway(gwepAfter)
  596. }
  597. // Only update the store if we did not come here as part of
  598. // sandbox delete. If we came here as part of delete then do
  599. // not bother updating the store. The sandbox object will be
  600. // deleted anyway
  601. if !inDelete {
  602. return sb.storeUpdate()
  603. }
  604. return nil
  605. }
  606. const (
  607. defaultPrefix = "/var/lib/docker/network/files"
  608. dirPerm = 0755
  609. filePerm = 0644
  610. )
  611. func (sb *sandbox) buildHostsFile() error {
  612. if sb.config.hostsPath == "" {
  613. sb.config.hostsPath = defaultPrefix + "/" + sb.id + "/hosts"
  614. }
  615. dir, _ := filepath.Split(sb.config.hostsPath)
  616. if err := createBasePath(dir); err != nil {
  617. return err
  618. }
  619. // This is for the host mode networking
  620. if sb.config.originHostsPath != "" {
  621. if err := copyFile(sb.config.originHostsPath, sb.config.hostsPath); err != nil && !os.IsNotExist(err) {
  622. return types.InternalErrorf("could not copy source hosts file %s to %s: %v", sb.config.originHostsPath, sb.config.hostsPath, err)
  623. }
  624. return nil
  625. }
  626. extraContent := make([]etchosts.Record, 0, len(sb.config.extraHosts))
  627. for _, extraHost := range sb.config.extraHosts {
  628. extraContent = append(extraContent, etchosts.Record{Hosts: extraHost.name, IP: extraHost.IP})
  629. }
  630. return etchosts.Build(sb.config.hostsPath, "", sb.config.hostName, sb.config.domainName, extraContent)
  631. }
  632. func (sb *sandbox) updateHostsFile(ifaceIP string) error {
  633. var mhost string
  634. if sb.config.originHostsPath != "" {
  635. return nil
  636. }
  637. if sb.config.domainName != "" {
  638. mhost = fmt.Sprintf("%s.%s %s", sb.config.hostName, sb.config.domainName,
  639. sb.config.hostName)
  640. } else {
  641. mhost = sb.config.hostName
  642. }
  643. extraContent := []etchosts.Record{{Hosts: mhost, IP: ifaceIP}}
  644. sb.addHostsEntries(extraContent)
  645. return nil
  646. }
  647. func (sb *sandbox) addHostsEntries(recs []etchosts.Record) {
  648. if err := etchosts.Add(sb.config.hostsPath, recs); err != nil {
  649. log.Warnf("Failed adding service host entries to the running container: %v", err)
  650. }
  651. }
  652. func (sb *sandbox) deleteHostsEntries(recs []etchosts.Record) {
  653. if err := etchosts.Delete(sb.config.hostsPath, recs); err != nil {
  654. log.Warnf("Failed deleting service host entries to the running container: %v", err)
  655. }
  656. }
  657. func (sb *sandbox) updateParentHosts() error {
  658. var pSb Sandbox
  659. for _, update := range sb.config.parentUpdates {
  660. sb.controller.WalkSandboxes(SandboxContainerWalker(&pSb, update.cid))
  661. if pSb == nil {
  662. continue
  663. }
  664. if err := etchosts.Update(pSb.(*sandbox).config.hostsPath, update.ip, update.name); err != nil {
  665. return err
  666. }
  667. }
  668. return nil
  669. }
  670. func (sb *sandbox) setupDNS() error {
  671. var newRC *resolvconf.File
  672. if sb.config.resolvConfPath == "" {
  673. sb.config.resolvConfPath = defaultPrefix + "/" + sb.id + "/resolv.conf"
  674. }
  675. sb.config.resolvConfHashFile = sb.config.resolvConfPath + ".hash"
  676. dir, _ := filepath.Split(sb.config.resolvConfPath)
  677. if err := createBasePath(dir); err != nil {
  678. return err
  679. }
  680. // This is for the host mode networking
  681. if sb.config.originResolvConfPath != "" {
  682. if err := copyFile(sb.config.originResolvConfPath, sb.config.resolvConfPath); err != nil {
  683. return fmt.Errorf("could not copy source resolv.conf file %s to %s: %v", sb.config.originResolvConfPath, sb.config.resolvConfPath, err)
  684. }
  685. return nil
  686. }
  687. currRC, err := resolvconf.Get()
  688. if err != nil {
  689. return err
  690. }
  691. if len(sb.config.dnsList) > 0 || len(sb.config.dnsSearchList) > 0 || len(sb.config.dnsOptionsList) > 0 {
  692. var (
  693. err error
  694. dnsList = resolvconf.GetNameservers(currRC.Content)
  695. dnsSearchList = resolvconf.GetSearchDomains(currRC.Content)
  696. dnsOptionsList = resolvconf.GetOptions(currRC.Content)
  697. )
  698. if len(sb.config.dnsList) > 0 {
  699. dnsList = sb.config.dnsList
  700. }
  701. if len(sb.config.dnsSearchList) > 0 {
  702. dnsSearchList = sb.config.dnsSearchList
  703. }
  704. if len(sb.config.dnsOptionsList) > 0 {
  705. dnsOptionsList = sb.config.dnsOptionsList
  706. }
  707. newRC, err = resolvconf.Build(sb.config.resolvConfPath, dnsList, dnsSearchList, dnsOptionsList)
  708. if err != nil {
  709. return err
  710. }
  711. } else {
  712. // Replace any localhost/127.* (at this point we have no info about ipv6, pass it as true)
  713. if newRC, err = resolvconf.FilterResolvDNS(currRC.Content, true); err != nil {
  714. return err
  715. }
  716. // No contention on container resolv.conf file at sandbox creation
  717. if err := ioutil.WriteFile(sb.config.resolvConfPath, newRC.Content, filePerm); err != nil {
  718. return types.InternalErrorf("failed to write unhaltered resolv.conf file content when setting up dns for sandbox %s: %v", sb.ID(), err)
  719. }
  720. }
  721. // Write hash
  722. if err := ioutil.WriteFile(sb.config.resolvConfHashFile, []byte(newRC.Hash), filePerm); err != nil {
  723. return types.InternalErrorf("failed to write resolv.conf hash file when setting up dns for sandbox %s: %v", sb.ID(), err)
  724. }
  725. return nil
  726. }
  727. func (sb *sandbox) updateDNS(ipv6Enabled bool) error {
  728. var (
  729. currHash string
  730. hashFile = sb.config.resolvConfHashFile
  731. )
  732. if len(sb.config.dnsList) > 0 || len(sb.config.dnsSearchList) > 0 || len(sb.config.dnsOptionsList) > 0 {
  733. return nil
  734. }
  735. currRC, err := resolvconf.GetSpecific(sb.config.resolvConfPath)
  736. if err != nil {
  737. if !os.IsNotExist(err) {
  738. return err
  739. }
  740. } else {
  741. h, err := ioutil.ReadFile(hashFile)
  742. if err != nil {
  743. if !os.IsNotExist(err) {
  744. return err
  745. }
  746. } else {
  747. currHash = string(h)
  748. }
  749. }
  750. if currHash != "" && currHash != currRC.Hash {
  751. // Seems the user has changed the container resolv.conf since the last time
  752. // we checked so return without doing anything.
  753. log.Infof("Skipping update of resolv.conf file with ipv6Enabled: %t because file was touched by user", ipv6Enabled)
  754. return nil
  755. }
  756. // replace any localhost/127.* and remove IPv6 nameservers if IPv6 disabled.
  757. newRC, err := resolvconf.FilterResolvDNS(currRC.Content, ipv6Enabled)
  758. if err != nil {
  759. return err
  760. }
  761. err = ioutil.WriteFile(sb.config.resolvConfPath, newRC.Content, 0644)
  762. if err != nil {
  763. return err
  764. }
  765. // write the new hash in a temp file and rename it to make the update atomic
  766. dir := path.Dir(sb.config.resolvConfPath)
  767. tmpHashFile, err := ioutil.TempFile(dir, "hash")
  768. if err != nil {
  769. return err
  770. }
  771. if err = ioutil.WriteFile(tmpHashFile.Name(), []byte(newRC.Hash), filePerm); err != nil {
  772. return err
  773. }
  774. return os.Rename(tmpHashFile.Name(), hashFile)
  775. }
  776. // Embedded DNS server has to be enabled for this sandbox. Rebuild the container's
  777. // resolv.conf by doing the follwing
  778. // - Save the external name servers in resolv.conf in the sandbox
  779. // - Add only the embedded server's IP to container's resolv.conf
  780. // - If the embedded server needs any resolv.conf options add it to the current list
  781. func (sb *sandbox) rebuildDNS() error {
  782. currRC, err := resolvconf.GetSpecific(sb.config.resolvConfPath)
  783. if err != nil {
  784. return err
  785. }
  786. // localhost entries have already been filtered out from the list
  787. sb.extDNS = resolvconf.GetNameservers(currRC.Content)
  788. var (
  789. dnsList = []string{sb.resolver.NameServer()}
  790. dnsOptionsList = resolvconf.GetOptions(currRC.Content)
  791. dnsSearchList = resolvconf.GetSearchDomains(currRC.Content)
  792. )
  793. // Resolver returns the options in the format resolv.conf expects
  794. dnsOptionsList = append(dnsOptionsList, sb.resolver.ResolverOptions()...)
  795. _, err = resolvconf.Build(sb.config.resolvConfPath, dnsList, dnsSearchList, dnsOptionsList)
  796. return err
  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. // OptionHostname function returns an option setter for hostname option to
  824. // be passed to NewSandbox method.
  825. func OptionHostname(name string) SandboxOption {
  826. return func(sb *sandbox) {
  827. sb.config.hostName = name
  828. }
  829. }
  830. // OptionDomainname function returns an option setter for domainname option to
  831. // be passed to NewSandbox method.
  832. func OptionDomainname(name string) SandboxOption {
  833. return func(sb *sandbox) {
  834. sb.config.domainName = name
  835. }
  836. }
  837. // OptionHostsPath function returns an option setter for hostspath option to
  838. // be passed to NewSandbox method.
  839. func OptionHostsPath(path string) SandboxOption {
  840. return func(sb *sandbox) {
  841. sb.config.hostsPath = path
  842. }
  843. }
  844. // OptionOriginHostsPath function returns an option setter for origin hosts file path
  845. // tbeo passed to NewSandbox method.
  846. func OptionOriginHostsPath(path string) SandboxOption {
  847. return func(sb *sandbox) {
  848. sb.config.originHostsPath = path
  849. }
  850. }
  851. // OptionExtraHost function returns an option setter for extra /etc/hosts options
  852. // which is a name and IP as strings.
  853. func OptionExtraHost(name string, IP string) SandboxOption {
  854. return func(sb *sandbox) {
  855. sb.config.extraHosts = append(sb.config.extraHosts, extraHost{name: name, IP: IP})
  856. }
  857. }
  858. // OptionParentUpdate function returns an option setter for parent container
  859. // which needs to update the IP address for the linked container.
  860. func OptionParentUpdate(cid string, name, ip string) SandboxOption {
  861. return func(sb *sandbox) {
  862. sb.config.parentUpdates = append(sb.config.parentUpdates, parentUpdate{cid: cid, name: name, ip: ip})
  863. }
  864. }
  865. // OptionResolvConfPath function returns an option setter for resolvconfpath option to
  866. // be passed to net container methods.
  867. func OptionResolvConfPath(path string) SandboxOption {
  868. return func(sb *sandbox) {
  869. sb.config.resolvConfPath = path
  870. }
  871. }
  872. // OptionOriginResolvConfPath function returns an option setter to set the path to the
  873. // origin resolv.conf file to be passed to net container methods.
  874. func OptionOriginResolvConfPath(path string) SandboxOption {
  875. return func(sb *sandbox) {
  876. sb.config.originResolvConfPath = path
  877. }
  878. }
  879. // OptionDNS function returns an option setter for dns entry option to
  880. // be passed to container Create method.
  881. func OptionDNS(dns string) SandboxOption {
  882. return func(sb *sandbox) {
  883. sb.config.dnsList = append(sb.config.dnsList, dns)
  884. }
  885. }
  886. // OptionDNSSearch function returns an option setter for dns search entry option to
  887. // be passed to container Create method.
  888. func OptionDNSSearch(search string) SandboxOption {
  889. return func(sb *sandbox) {
  890. sb.config.dnsSearchList = append(sb.config.dnsSearchList, search)
  891. }
  892. }
  893. // OptionDNSOptions function returns an option setter for dns options entry option to
  894. // be passed to container Create method.
  895. func OptionDNSOptions(options string) SandboxOption {
  896. return func(sb *sandbox) {
  897. sb.config.dnsOptionsList = append(sb.config.dnsOptionsList, options)
  898. }
  899. }
  900. // OptionUseDefaultSandbox function returns an option setter for using default sandbox to
  901. // be passed to container Create method.
  902. func OptionUseDefaultSandbox() SandboxOption {
  903. return func(sb *sandbox) {
  904. sb.config.useDefaultSandBox = true
  905. }
  906. }
  907. // OptionUseExternalKey function returns an option setter for using provided namespace
  908. // instead of creating one.
  909. func OptionUseExternalKey() SandboxOption {
  910. return func(sb *sandbox) {
  911. sb.config.useExternalKey = true
  912. }
  913. }
  914. // OptionGeneric function returns an option setter for Generic configuration
  915. // that is not managed by libNetwork but can be used by the Drivers during the call to
  916. // net container creation method. Container Labels are a good example.
  917. func OptionGeneric(generic map[string]interface{}) SandboxOption {
  918. return func(sb *sandbox) {
  919. sb.config.generic = generic
  920. }
  921. }
  922. func (eh epHeap) Len() int { return len(eh) }
  923. func (eh epHeap) Less(i, j int) bool {
  924. var (
  925. cip, cjp int
  926. ok bool
  927. )
  928. ci, _ := eh[i].getSandbox()
  929. cj, _ := eh[j].getSandbox()
  930. epi := eh[i]
  931. epj := eh[j]
  932. if epi.endpointInGWNetwork() {
  933. return false
  934. }
  935. if epj.endpointInGWNetwork() {
  936. return true
  937. }
  938. if ci != nil {
  939. cip, ok = ci.epPriority[eh[i].ID()]
  940. if !ok {
  941. cip = 0
  942. }
  943. }
  944. if cj != nil {
  945. cjp, ok = cj.epPriority[eh[j].ID()]
  946. if !ok {
  947. cjp = 0
  948. }
  949. }
  950. if cip == cjp {
  951. return eh[i].network.Name() < eh[j].network.Name()
  952. }
  953. return cip > cjp
  954. }
  955. func (eh epHeap) Swap(i, j int) { eh[i], eh[j] = eh[j], eh[i] }
  956. func (eh *epHeap) Push(x interface{}) {
  957. *eh = append(*eh, x.(*endpoint))
  958. }
  959. func (eh *epHeap) Pop() interface{} {
  960. old := *eh
  961. n := len(old)
  962. x := old[n-1]
  963. *eh = old[0 : n-1]
  964. return x
  965. }
  966. func createBasePath(dir string) error {
  967. return os.MkdirAll(dir, dirPerm)
  968. }
  969. func createFile(path string) error {
  970. var f *os.File
  971. dir, _ := filepath.Split(path)
  972. err := createBasePath(dir)
  973. if err != nil {
  974. return err
  975. }
  976. f, err = os.Create(path)
  977. if err == nil {
  978. f.Close()
  979. }
  980. return err
  981. }
  982. func copyFile(src, dst string) error {
  983. sBytes, err := ioutil.ReadFile(src)
  984. if err != nil {
  985. return err
  986. }
  987. return ioutil.WriteFile(dst, sBytes, filePerm)
  988. }