sandbox.go 28 KB

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