sandbox.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146
  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(); 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. for _, ep := range sb.getConnectedEndpoints() {
  356. n := ep.getNetwork()
  357. if len(parts) > 1 && parts[1] != "" && parts[1] != n.Name() {
  358. continue
  359. }
  360. sr, ok := n.getController().svcDb[n.ID()]
  361. if !ok {
  362. continue
  363. }
  364. n.Lock()
  365. ip, ok = sr.svcMap[parts[0]]
  366. n.Unlock()
  367. if ok {
  368. return ip
  369. }
  370. }
  371. return ip
  372. }
  373. func (sb *sandbox) SetKey(basePath string) error {
  374. var err error
  375. if basePath == "" {
  376. return types.BadRequestErrorf("invalid sandbox key")
  377. }
  378. sb.Lock()
  379. osSbox := sb.osSbox
  380. sb.Unlock()
  381. if osSbox != nil {
  382. // If we already have an OS sandbox, release the network resources from that
  383. // and destroy the OS snab. We are moving into a new home further down. Note that none
  384. // of the network resources gets destroyed during the move.
  385. sb.releaseOSSbox()
  386. }
  387. osSbox, err = osl.GetSandboxForExternalKey(basePath, sb.Key())
  388. if err != nil {
  389. return err
  390. }
  391. sb.Lock()
  392. sb.osSbox = osSbox
  393. sb.Unlock()
  394. defer func() {
  395. if err != nil {
  396. sb.Lock()
  397. sb.osSbox = nil
  398. sb.Unlock()
  399. }
  400. }()
  401. for _, ep := range sb.getConnectedEndpoints() {
  402. if err = sb.populateNetworkResources(ep); err != nil {
  403. return err
  404. }
  405. }
  406. return nil
  407. }
  408. func releaseOSSboxResources(osSbox osl.Sandbox, ep *endpoint) {
  409. for _, i := range osSbox.Info().Interfaces() {
  410. // Only remove the interfaces owned by this endpoint from the sandbox.
  411. if ep.hasInterface(i.SrcName()) {
  412. if err := i.Remove(); err != nil {
  413. log.Debugf("Remove interface failed: %v", err)
  414. }
  415. }
  416. }
  417. ep.Lock()
  418. joinInfo := ep.joinInfo
  419. ep.Unlock()
  420. if joinInfo == nil {
  421. return
  422. }
  423. // Remove non-interface routes.
  424. for _, r := range joinInfo.StaticRoutes {
  425. if err := osSbox.RemoveStaticRoute(r); err != nil {
  426. log.Debugf("Remove route failed: %v", err)
  427. }
  428. }
  429. }
  430. func (sb *sandbox) releaseOSSbox() {
  431. sb.Lock()
  432. osSbox := sb.osSbox
  433. sb.osSbox = nil
  434. sb.Unlock()
  435. if osSbox == nil {
  436. return
  437. }
  438. for _, ep := range sb.getConnectedEndpoints() {
  439. releaseOSSboxResources(osSbox, ep)
  440. }
  441. osSbox.Destroy()
  442. }
  443. func (sb *sandbox) populateNetworkResources(ep *endpoint) error {
  444. sb.Lock()
  445. if sb.osSbox == nil {
  446. sb.Unlock()
  447. return nil
  448. }
  449. inDelete := sb.inDelete
  450. sb.Unlock()
  451. ep.Lock()
  452. joinInfo := ep.joinInfo
  453. i := ep.iface
  454. ep.Unlock()
  455. if ep.needResolver() {
  456. sb.startResolver()
  457. }
  458. if i != nil && i.srcName != "" {
  459. var ifaceOptions []osl.IfaceOption
  460. ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().Address(i.addr), sb.osSbox.InterfaceOptions().Routes(i.routes))
  461. if i.addrv6 != nil && i.addrv6.IP.To16() != nil {
  462. ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().AddressIPv6(i.addrv6))
  463. }
  464. if err := sb.osSbox.AddInterface(i.srcName, i.dstPrefix, ifaceOptions...); err != nil {
  465. return fmt.Errorf("failed to add interface %s to sandbox: %v", i.srcName, err)
  466. }
  467. }
  468. if joinInfo != nil {
  469. // Set up non-interface routes.
  470. for _, r := range joinInfo.StaticRoutes {
  471. if err := sb.osSbox.AddStaticRoute(r); err != nil {
  472. return fmt.Errorf("failed to add static route %s: %v", r.Destination.String(), err)
  473. }
  474. }
  475. }
  476. for _, gwep := range sb.getConnectedEndpoints() {
  477. if len(gwep.Gateway()) > 0 {
  478. if gwep != ep {
  479. break
  480. }
  481. if err := sb.updateGateway(gwep); err != nil {
  482. return err
  483. }
  484. }
  485. }
  486. // Only update the store if we did not come here as part of
  487. // sandbox delete. If we came here as part of delete then do
  488. // not bother updating the store. The sandbox object will be
  489. // deleted anyway
  490. if !inDelete {
  491. return sb.storeUpdate()
  492. }
  493. return nil
  494. }
  495. func (sb *sandbox) clearNetworkResources(origEp *endpoint) error {
  496. ep := sb.getEndpoint(origEp.id)
  497. if ep == nil {
  498. return fmt.Errorf("could not find the sandbox endpoint data for endpoint %s",
  499. ep.name)
  500. }
  501. sb.Lock()
  502. osSbox := sb.osSbox
  503. inDelete := sb.inDelete
  504. sb.Unlock()
  505. if osSbox != nil {
  506. releaseOSSboxResources(osSbox, ep)
  507. }
  508. sb.Lock()
  509. if len(sb.endpoints) == 0 {
  510. // sb.endpoints should never be empty and this is unexpected error condition
  511. // We log an error message to note this down for debugging purposes.
  512. log.Errorf("No endpoints in sandbox while trying to remove endpoint %s", ep.Name())
  513. sb.Unlock()
  514. return nil
  515. }
  516. var (
  517. gwepBefore, gwepAfter *endpoint
  518. index = -1
  519. )
  520. for i, e := range sb.endpoints {
  521. if e == ep {
  522. index = i
  523. }
  524. if len(e.Gateway()) > 0 && gwepBefore == nil {
  525. gwepBefore = e
  526. }
  527. if index != -1 && gwepBefore != nil {
  528. break
  529. }
  530. }
  531. heap.Remove(&sb.endpoints, index)
  532. for _, e := range sb.endpoints {
  533. if len(e.Gateway()) > 0 {
  534. gwepAfter = e
  535. break
  536. }
  537. }
  538. delete(sb.epPriority, ep.ID())
  539. sb.Unlock()
  540. if gwepAfter != nil && gwepBefore != gwepAfter {
  541. sb.updateGateway(gwepAfter)
  542. }
  543. // Only update the store if we did not come here as part of
  544. // sandbox delete. If we came here as part of delete then do
  545. // not bother updating the store. The sandbox object will be
  546. // deleted anyway
  547. if !inDelete {
  548. return sb.storeUpdate()
  549. }
  550. return nil
  551. }
  552. const (
  553. defaultPrefix = "/var/lib/docker/network/files"
  554. dirPerm = 0755
  555. filePerm = 0644
  556. )
  557. func (sb *sandbox) buildHostsFile() error {
  558. if sb.config.hostsPath == "" {
  559. sb.config.hostsPath = defaultPrefix + "/" + sb.id + "/hosts"
  560. }
  561. dir, _ := filepath.Split(sb.config.hostsPath)
  562. if err := createBasePath(dir); err != nil {
  563. return err
  564. }
  565. // This is for the host mode networking
  566. if sb.config.originHostsPath != "" {
  567. if err := copyFile(sb.config.originHostsPath, sb.config.hostsPath); err != nil && !os.IsNotExist(err) {
  568. return types.InternalErrorf("could not copy source hosts file %s to %s: %v", sb.config.originHostsPath, sb.config.hostsPath, err)
  569. }
  570. return nil
  571. }
  572. extraContent := make([]etchosts.Record, 0, len(sb.config.extraHosts))
  573. for _, extraHost := range sb.config.extraHosts {
  574. extraContent = append(extraContent, etchosts.Record{Hosts: extraHost.name, IP: extraHost.IP})
  575. }
  576. return etchosts.Build(sb.config.hostsPath, "", sb.config.hostName, sb.config.domainName, extraContent)
  577. }
  578. func (sb *sandbox) updateHostsFile(ifaceIP string) error {
  579. var mhost string
  580. if sb.config.originHostsPath != "" {
  581. return nil
  582. }
  583. if sb.config.domainName != "" {
  584. mhost = fmt.Sprintf("%s.%s %s", sb.config.hostName, sb.config.domainName,
  585. sb.config.hostName)
  586. } else {
  587. mhost = sb.config.hostName
  588. }
  589. extraContent := []etchosts.Record{{Hosts: mhost, IP: ifaceIP}}
  590. sb.addHostsEntries(extraContent)
  591. return nil
  592. }
  593. func (sb *sandbox) addHostsEntries(recs []etchosts.Record) {
  594. if err := etchosts.Add(sb.config.hostsPath, recs); err != nil {
  595. log.Warnf("Failed adding service host entries to the running container: %v", err)
  596. }
  597. }
  598. func (sb *sandbox) deleteHostsEntries(recs []etchosts.Record) {
  599. if err := etchosts.Delete(sb.config.hostsPath, recs); err != nil {
  600. log.Warnf("Failed deleting service host entries to the running container: %v", err)
  601. }
  602. }
  603. func (sb *sandbox) updateParentHosts() error {
  604. var pSb Sandbox
  605. for _, update := range sb.config.parentUpdates {
  606. sb.controller.WalkSandboxes(SandboxContainerWalker(&pSb, update.cid))
  607. if pSb == nil {
  608. continue
  609. }
  610. if err := etchosts.Update(pSb.(*sandbox).config.hostsPath, update.ip, update.name); err != nil {
  611. return err
  612. }
  613. }
  614. return nil
  615. }
  616. func (sb *sandbox) setupDNS() error {
  617. var newRC *resolvconf.File
  618. if sb.config.resolvConfPath == "" {
  619. sb.config.resolvConfPath = defaultPrefix + "/" + sb.id + "/resolv.conf"
  620. }
  621. sb.config.resolvConfHashFile = sb.config.resolvConfPath + ".hash"
  622. dir, _ := filepath.Split(sb.config.resolvConfPath)
  623. if err := createBasePath(dir); err != nil {
  624. return err
  625. }
  626. // This is for the host mode networking
  627. if sb.config.originResolvConfPath != "" {
  628. if err := copyFile(sb.config.originResolvConfPath, sb.config.resolvConfPath); err != nil {
  629. return fmt.Errorf("could not copy source resolv.conf file %s to %s: %v", sb.config.originResolvConfPath, sb.config.resolvConfPath, err)
  630. }
  631. return nil
  632. }
  633. currRC, err := resolvconf.Get()
  634. if err != nil {
  635. return err
  636. }
  637. if len(sb.config.dnsList) > 0 || len(sb.config.dnsSearchList) > 0 || len(sb.config.dnsOptionsList) > 0 {
  638. var (
  639. err error
  640. dnsList = resolvconf.GetNameservers(currRC.Content)
  641. dnsSearchList = resolvconf.GetSearchDomains(currRC.Content)
  642. dnsOptionsList = resolvconf.GetOptions(currRC.Content)
  643. )
  644. if len(sb.config.dnsList) > 0 {
  645. dnsList = sb.config.dnsList
  646. }
  647. if len(sb.config.dnsSearchList) > 0 {
  648. dnsSearchList = sb.config.dnsSearchList
  649. }
  650. if len(sb.config.dnsOptionsList) > 0 {
  651. dnsOptionsList = sb.config.dnsOptionsList
  652. }
  653. newRC, err = resolvconf.Build(sb.config.resolvConfPath, dnsList, dnsSearchList, dnsOptionsList)
  654. if err != nil {
  655. return err
  656. }
  657. } else {
  658. // Replace any localhost/127.* (at this point we have no info about ipv6, pass it as true)
  659. if newRC, err = resolvconf.FilterResolvDNS(currRC.Content, true); err != nil {
  660. return err
  661. }
  662. // No contention on container resolv.conf file at sandbox creation
  663. if err := ioutil.WriteFile(sb.config.resolvConfPath, newRC.Content, filePerm); err != nil {
  664. return types.InternalErrorf("failed to write unhaltered resolv.conf file content when setting up dns for sandbox %s: %v", sb.ID(), err)
  665. }
  666. }
  667. // Write hash
  668. if err := ioutil.WriteFile(sb.config.resolvConfHashFile, []byte(newRC.Hash), filePerm); err != nil {
  669. return types.InternalErrorf("failed to write resolv.conf hash file when setting up dns for sandbox %s: %v", sb.ID(), err)
  670. }
  671. return nil
  672. }
  673. func (sb *sandbox) updateDNS(ipv6Enabled bool) error {
  674. var (
  675. currHash string
  676. hashFile = sb.config.resolvConfHashFile
  677. )
  678. if len(sb.config.dnsList) > 0 || len(sb.config.dnsSearchList) > 0 || len(sb.config.dnsOptionsList) > 0 {
  679. return nil
  680. }
  681. currRC, err := resolvconf.GetSpecific(sb.config.resolvConfPath)
  682. if err != nil {
  683. if !os.IsNotExist(err) {
  684. return err
  685. }
  686. } else {
  687. h, err := ioutil.ReadFile(hashFile)
  688. if err != nil {
  689. if !os.IsNotExist(err) {
  690. return err
  691. }
  692. } else {
  693. currHash = string(h)
  694. }
  695. }
  696. if currHash != "" && currHash != currRC.Hash {
  697. // Seems the user has changed the container resolv.conf since the last time
  698. // we checked so return without doing anything.
  699. log.Infof("Skipping update of resolv.conf file with ipv6Enabled: %t because file was touched by user", ipv6Enabled)
  700. return nil
  701. }
  702. // replace any localhost/127.* and remove IPv6 nameservers if IPv6 disabled.
  703. newRC, err := resolvconf.FilterResolvDNS(currRC.Content, ipv6Enabled)
  704. if err != nil {
  705. return err
  706. }
  707. // for atomic updates to these files, use temporary files with os.Rename:
  708. dir := path.Dir(sb.config.resolvConfPath)
  709. tmpHashFile, err := ioutil.TempFile(dir, "hash")
  710. if err != nil {
  711. return err
  712. }
  713. tmpResolvFile, err := ioutil.TempFile(dir, "resolv")
  714. if err != nil {
  715. return err
  716. }
  717. // Change the perms to filePerm (0644) since ioutil.TempFile creates it by default as 0600
  718. if err := os.Chmod(tmpResolvFile.Name(), filePerm); err != nil {
  719. return err
  720. }
  721. // write the updates to the temp files
  722. if err = ioutil.WriteFile(tmpHashFile.Name(), []byte(newRC.Hash), filePerm); err != nil {
  723. return err
  724. }
  725. if err = ioutil.WriteFile(tmpResolvFile.Name(), newRC.Content, filePerm); err != nil {
  726. return err
  727. }
  728. // rename the temp files for atomic replace
  729. if err = os.Rename(tmpHashFile.Name(), hashFile); err != nil {
  730. return err
  731. }
  732. return os.Rename(tmpResolvFile.Name(), sb.config.resolvConfPath)
  733. }
  734. // Embedded DNS server has to be enabled for this sandbox. Rebuild the container's
  735. // resolv.conf by doing the follwing
  736. // - Save the external name servers in resolv.conf in the sandbox
  737. // - Add only the embedded server's IP to container's resolv.conf
  738. // - If the embedded server needs any resolv.conf options add it to the current list
  739. func (sb *sandbox) rebuildDNS() error {
  740. currRC, err := resolvconf.GetSpecific(sb.config.resolvConfPath)
  741. if err != nil {
  742. return err
  743. }
  744. // localhost entries have already been filtered out from the list
  745. sb.extDNS = resolvconf.GetNameservers(currRC.Content)
  746. var (
  747. dnsList = []string{sb.resolver.NameServer()}
  748. dnsOptionsList = resolvconf.GetOptions(currRC.Content)
  749. dnsSearchList = resolvconf.GetSearchDomains(currRC.Content)
  750. )
  751. // Resolver returns the options in the format resolv.conf expects
  752. dnsOptionsList = append(dnsOptionsList, sb.resolver.ResolverOptions()...)
  753. dir := path.Dir(sb.config.resolvConfPath)
  754. tmpResolvFile, err := ioutil.TempFile(dir, "resolv")
  755. if err != nil {
  756. return err
  757. }
  758. // Change the perms to filePerm (0644) since ioutil.TempFile creates it by default as 0600
  759. if err := os.Chmod(tmpResolvFile.Name(), filePerm); err != nil {
  760. return err
  761. }
  762. _, err = resolvconf.Build(tmpResolvFile.Name(), dnsList, dnsSearchList, dnsOptionsList)
  763. if err != nil {
  764. return err
  765. }
  766. return os.Rename(tmpResolvFile.Name(), sb.config.resolvConfPath)
  767. }
  768. // joinLeaveStart waits to ensure there are no joins or leaves in progress and
  769. // marks this join/leave in progress without race
  770. func (sb *sandbox) joinLeaveStart() {
  771. sb.Lock()
  772. defer sb.Unlock()
  773. for sb.joinLeaveDone != nil {
  774. joinLeaveDone := sb.joinLeaveDone
  775. sb.Unlock()
  776. select {
  777. case <-joinLeaveDone:
  778. }
  779. sb.Lock()
  780. }
  781. sb.joinLeaveDone = make(chan struct{})
  782. }
  783. // joinLeaveEnd marks the end of this join/leave operation and
  784. // signals the same without race to other join and leave waiters
  785. func (sb *sandbox) joinLeaveEnd() {
  786. sb.Lock()
  787. defer sb.Unlock()
  788. if sb.joinLeaveDone != nil {
  789. close(sb.joinLeaveDone)
  790. sb.joinLeaveDone = nil
  791. }
  792. }
  793. // OptionHostname function returns an option setter for hostname option to
  794. // be passed to NewSandbox method.
  795. func OptionHostname(name string) SandboxOption {
  796. return func(sb *sandbox) {
  797. sb.config.hostName = name
  798. }
  799. }
  800. // OptionDomainname function returns an option setter for domainname option to
  801. // be passed to NewSandbox method.
  802. func OptionDomainname(name string) SandboxOption {
  803. return func(sb *sandbox) {
  804. sb.config.domainName = name
  805. }
  806. }
  807. // OptionHostsPath function returns an option setter for hostspath option to
  808. // be passed to NewSandbox method.
  809. func OptionHostsPath(path string) SandboxOption {
  810. return func(sb *sandbox) {
  811. sb.config.hostsPath = path
  812. }
  813. }
  814. // OptionOriginHostsPath function returns an option setter for origin hosts file path
  815. // tbeo passed to NewSandbox method.
  816. func OptionOriginHostsPath(path string) SandboxOption {
  817. return func(sb *sandbox) {
  818. sb.config.originHostsPath = path
  819. }
  820. }
  821. // OptionExtraHost function returns an option setter for extra /etc/hosts options
  822. // which is a name and IP as strings.
  823. func OptionExtraHost(name string, IP string) SandboxOption {
  824. return func(sb *sandbox) {
  825. sb.config.extraHosts = append(sb.config.extraHosts, extraHost{name: name, IP: IP})
  826. }
  827. }
  828. // OptionParentUpdate function returns an option setter for parent container
  829. // which needs to update the IP address for the linked container.
  830. func OptionParentUpdate(cid string, name, ip string) SandboxOption {
  831. return func(sb *sandbox) {
  832. sb.config.parentUpdates = append(sb.config.parentUpdates, parentUpdate{cid: cid, name: name, ip: ip})
  833. }
  834. }
  835. // OptionResolvConfPath function returns an option setter for resolvconfpath option to
  836. // be passed to net container methods.
  837. func OptionResolvConfPath(path string) SandboxOption {
  838. return func(sb *sandbox) {
  839. sb.config.resolvConfPath = path
  840. }
  841. }
  842. // OptionOriginResolvConfPath function returns an option setter to set the path to the
  843. // origin resolv.conf file to be passed to net container methods.
  844. func OptionOriginResolvConfPath(path string) SandboxOption {
  845. return func(sb *sandbox) {
  846. sb.config.originResolvConfPath = path
  847. }
  848. }
  849. // OptionDNS function returns an option setter for dns entry option to
  850. // be passed to container Create method.
  851. func OptionDNS(dns string) SandboxOption {
  852. return func(sb *sandbox) {
  853. sb.config.dnsList = append(sb.config.dnsList, dns)
  854. }
  855. }
  856. // OptionDNSSearch function returns an option setter for dns search entry option to
  857. // be passed to container Create method.
  858. func OptionDNSSearch(search string) SandboxOption {
  859. return func(sb *sandbox) {
  860. sb.config.dnsSearchList = append(sb.config.dnsSearchList, search)
  861. }
  862. }
  863. // OptionDNSOptions function returns an option setter for dns options entry option to
  864. // be passed to container Create method.
  865. func OptionDNSOptions(options string) SandboxOption {
  866. return func(sb *sandbox) {
  867. sb.config.dnsOptionsList = append(sb.config.dnsOptionsList, options)
  868. }
  869. }
  870. // OptionUseDefaultSandbox function returns an option setter for using default sandbox to
  871. // be passed to container Create method.
  872. func OptionUseDefaultSandbox() SandboxOption {
  873. return func(sb *sandbox) {
  874. sb.config.useDefaultSandBox = true
  875. }
  876. }
  877. // OptionUseExternalKey function returns an option setter for using provided namespace
  878. // instead of creating one.
  879. func OptionUseExternalKey() SandboxOption {
  880. return func(sb *sandbox) {
  881. sb.config.useExternalKey = true
  882. }
  883. }
  884. // OptionGeneric function returns an option setter for Generic configuration
  885. // that is not managed by libNetwork but can be used by the Drivers during the call to
  886. // net container creation method. Container Labels are a good example.
  887. func OptionGeneric(generic map[string]interface{}) SandboxOption {
  888. return func(sb *sandbox) {
  889. sb.config.generic = generic
  890. }
  891. }
  892. func (eh epHeap) Len() int { return len(eh) }
  893. func (eh epHeap) Less(i, j int) bool {
  894. var (
  895. cip, cjp int
  896. ok bool
  897. )
  898. ci, _ := eh[i].getSandbox()
  899. cj, _ := eh[j].getSandbox()
  900. epi := eh[i]
  901. epj := eh[j]
  902. if epi.endpointInGWNetwork() {
  903. return false
  904. }
  905. if epj.endpointInGWNetwork() {
  906. return true
  907. }
  908. if ci != nil {
  909. cip, ok = ci.epPriority[eh[i].ID()]
  910. if !ok {
  911. cip = 0
  912. }
  913. }
  914. if cj != nil {
  915. cjp, ok = cj.epPriority[eh[j].ID()]
  916. if !ok {
  917. cjp = 0
  918. }
  919. }
  920. if cip == cjp {
  921. return eh[i].network.Name() < eh[j].network.Name()
  922. }
  923. return cip > cjp
  924. }
  925. func (eh epHeap) Swap(i, j int) { eh[i], eh[j] = eh[j], eh[i] }
  926. func (eh *epHeap) Push(x interface{}) {
  927. *eh = append(*eh, x.(*endpoint))
  928. }
  929. func (eh *epHeap) Pop() interface{} {
  930. old := *eh
  931. n := len(old)
  932. x := old[n-1]
  933. *eh = old[0 : n-1]
  934. return x
  935. }
  936. func createBasePath(dir string) error {
  937. return os.MkdirAll(dir, dirPerm)
  938. }
  939. func createFile(path string) error {
  940. var f *os.File
  941. dir, _ := filepath.Split(path)
  942. err := createBasePath(dir)
  943. if err != nil {
  944. return err
  945. }
  946. f, err = os.Create(path)
  947. if err == nil {
  948. f.Close()
  949. }
  950. return err
  951. }
  952. func copyFile(src, dst string) error {
  953. sBytes, err := ioutil.ReadFile(src)
  954. if err != nil {
  955. return err
  956. }
  957. return ioutil.WriteFile(dst, sBytes, filePerm)
  958. }