sandbox.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906
  1. package libnetwork
  2. import (
  3. "container/heap"
  4. "encoding/json"
  5. "fmt"
  6. "io/ioutil"
  7. "os"
  8. "path"
  9. "path/filepath"
  10. "sync"
  11. log "github.com/Sirupsen/logrus"
  12. "github.com/docker/libnetwork/etchosts"
  13. "github.com/docker/libnetwork/osl"
  14. "github.com/docker/libnetwork/resolvconf"
  15. "github.com/docker/libnetwork/types"
  16. )
  17. // Sandbox provides the control over the network container entity. It is a one to one mapping with the container.
  18. type Sandbox interface {
  19. // ID returns the ID of the sandbox
  20. ID() string
  21. // Key returns the sandbox's key
  22. Key() string
  23. // ContainerID returns the container id associated to this sandbox
  24. ContainerID() string
  25. // Labels returns the sandbox's labels
  26. Labels() map[string]interface{}
  27. // Statistics retrieves the interfaces' statistics for the sandbox
  28. Statistics() (map[string]*types.InterfaceStatistics, error)
  29. // Refresh leaves all the endpoints, resets and re-apply the options,
  30. // re-joins all the endpoints without destroying the osl sandbox
  31. Refresh(options ...SandboxOption) error
  32. // SetKey updates the Sandbox Key
  33. SetKey(key string) error
  34. // Delete destroys this container after detaching it from all connected endpoints.
  35. Delete() error
  36. }
  37. // SandboxOption is a option setter function type used to pass varios options to
  38. // NewNetContainer method. The various setter functions of type SandboxOption are
  39. // provided by libnetwork, they look like ContainerOptionXXXX(...)
  40. type SandboxOption func(sb *sandbox)
  41. func (sb *sandbox) processOptions(options ...SandboxOption) {
  42. for _, opt := range options {
  43. if opt != nil {
  44. opt(sb)
  45. }
  46. }
  47. }
  48. type epHeap []*endpoint
  49. type sandbox struct {
  50. id string
  51. containerID string
  52. config containerConfig
  53. osSbox osl.Sandbox
  54. controller *controller
  55. refCnt int
  56. hostsOnce sync.Once
  57. endpoints epHeap
  58. epPriority map[string]int
  59. joinLeaveDone chan struct{}
  60. sync.Mutex
  61. }
  62. // These are the container configs used to customize container /etc/hosts file.
  63. type hostsPathConfig struct {
  64. hostName string
  65. domainName string
  66. hostsPath string
  67. originHostsPath string
  68. extraHosts []extraHost
  69. parentUpdates []parentUpdate
  70. }
  71. type parentUpdate struct {
  72. cid string
  73. name string
  74. ip string
  75. }
  76. type extraHost struct {
  77. name string
  78. IP string
  79. }
  80. // These are the container configs used to customize container /etc/resolv.conf file.
  81. type resolvConfPathConfig struct {
  82. resolvConfPath string
  83. originResolvConfPath string
  84. resolvConfHashFile string
  85. dnsList []string
  86. dnsSearchList []string
  87. dnsOptionsList []string
  88. }
  89. type containerConfig struct {
  90. hostsPathConfig
  91. resolvConfPathConfig
  92. generic map[string]interface{}
  93. useDefaultSandBox bool
  94. useExternalKey bool
  95. prio int // higher the value, more the priority
  96. }
  97. func (sb *sandbox) ID() string {
  98. return sb.id
  99. }
  100. func (sb *sandbox) ContainerID() string {
  101. return sb.containerID
  102. }
  103. func (sb *sandbox) Key() string {
  104. if sb.config.useDefaultSandBox {
  105. return osl.GenerateKey("default")
  106. }
  107. return osl.GenerateKey(sb.id)
  108. }
  109. func (sb *sandbox) Labels() map[string]interface{} {
  110. return sb.config.generic
  111. }
  112. func (sb *sandbox) Statistics() (map[string]*types.InterfaceStatistics, error) {
  113. m := make(map[string]*types.InterfaceStatistics)
  114. if sb.osSbox == nil {
  115. return m, nil
  116. }
  117. var err error
  118. for _, i := range sb.osSbox.Info().Interfaces() {
  119. if m[i.DstName()], err = i.Statistics(); err != nil {
  120. return m, err
  121. }
  122. }
  123. return m, nil
  124. }
  125. func (sb *sandbox) Delete() error {
  126. c := sb.controller
  127. // Detach from all endpoints
  128. for _, ep := range sb.getConnectedEndpoints() {
  129. // endpoint in the Gateway network will be cleaned up
  130. // when when sandbox no longer needs external connectivity
  131. if ep.endpointInGWNetwork() {
  132. continue
  133. }
  134. if err := ep.Leave(sb); err != nil {
  135. log.Warnf("Failed detaching sandbox %s from endpoint %s: %v\n", sb.ID(), ep.ID(), err)
  136. }
  137. }
  138. if sb.osSbox != nil {
  139. sb.osSbox.Destroy()
  140. }
  141. c.Lock()
  142. delete(c.sandboxes, sb.ID())
  143. c.Unlock()
  144. return nil
  145. }
  146. func (sb *sandbox) Refresh(options ...SandboxOption) error {
  147. // Store connected endpoints
  148. epList := sb.getConnectedEndpoints()
  149. // Detach from all endpoints
  150. for _, ep := range epList {
  151. if err := ep.Leave(sb); err != nil {
  152. log.Warnf("Failed detaching sandbox %s from endpoint %s: %v\n", sb.ID(), ep.ID(), err)
  153. }
  154. }
  155. // Re-apply options
  156. sb.config = containerConfig{}
  157. sb.processOptions(options...)
  158. // Setup discovery files
  159. if err := sb.setupResolutionFiles(); err != nil {
  160. return err
  161. }
  162. // Re -connect to all endpoints
  163. for _, ep := range epList {
  164. if err := ep.Join(sb); err != nil {
  165. log.Warnf("Failed attach sandbox %s to endpoint %s: %v\n", sb.ID(), ep.ID(), err)
  166. }
  167. }
  168. return nil
  169. }
  170. func (sb *sandbox) MarshalJSON() ([]byte, error) {
  171. sb.Lock()
  172. defer sb.Unlock()
  173. // We are just interested in the container ID. This can be expanded to include all of containerInfo if there is a need
  174. return json.Marshal(sb.id)
  175. }
  176. func (sb *sandbox) UnmarshalJSON(b []byte) (err error) {
  177. sb.Lock()
  178. defer sb.Unlock()
  179. var id string
  180. if err := json.Unmarshal(b, &id); err != nil {
  181. return err
  182. }
  183. sb.id = id
  184. return nil
  185. }
  186. func (sb *sandbox) setupResolutionFiles() error {
  187. if err := sb.buildHostsFile(); err != nil {
  188. return err
  189. }
  190. if err := sb.updateParentHosts(); err != nil {
  191. return err
  192. }
  193. if err := sb.setupDNS(); err != nil {
  194. return err
  195. }
  196. return nil
  197. }
  198. func (sb *sandbox) getConnectedEndpoints() []*endpoint {
  199. sb.Lock()
  200. defer sb.Unlock()
  201. eps := make([]*endpoint, len(sb.endpoints))
  202. for i, ep := range sb.endpoints {
  203. eps[i] = ep
  204. }
  205. return eps
  206. }
  207. func (sb *sandbox) getEndpoint(id string) *endpoint {
  208. sb.Lock()
  209. defer sb.Unlock()
  210. for _, ep := range sb.endpoints {
  211. if ep.id == id {
  212. return ep
  213. }
  214. }
  215. return nil
  216. }
  217. func (sb *sandbox) updateGateway(ep *endpoint) error {
  218. sb.Lock()
  219. osSbox := sb.osSbox
  220. sb.Unlock()
  221. if osSbox == nil {
  222. return nil
  223. }
  224. osSbox.UnsetGateway()
  225. osSbox.UnsetGatewayIPv6()
  226. if ep == nil {
  227. return nil
  228. }
  229. ep.Lock()
  230. joinInfo := ep.joinInfo
  231. ep.Unlock()
  232. if err := osSbox.SetGateway(joinInfo.gw); err != nil {
  233. return fmt.Errorf("failed to set gateway while updating gateway: %v", err)
  234. }
  235. if err := osSbox.SetGatewayIPv6(joinInfo.gw6); err != nil {
  236. return fmt.Errorf("failed to set IPv6 gateway while updating gateway: %v", err)
  237. }
  238. return nil
  239. }
  240. func (sb *sandbox) SetKey(basePath string) error {
  241. var err error
  242. if basePath == "" {
  243. return types.BadRequestErrorf("invalid sandbox key")
  244. }
  245. sb.Lock()
  246. if sb.osSbox != nil {
  247. sb.Unlock()
  248. return types.ForbiddenErrorf("failed to set sandbox key : already assigned")
  249. }
  250. sb.Unlock()
  251. osSbox, err := osl.GetSandboxForExternalKey(basePath, sb.Key())
  252. if err != nil {
  253. return err
  254. }
  255. sb.Lock()
  256. sb.osSbox = osSbox
  257. sb.Unlock()
  258. defer func() {
  259. if err != nil {
  260. sb.Lock()
  261. sb.osSbox = nil
  262. sb.Unlock()
  263. }
  264. }()
  265. for _, ep := range sb.getConnectedEndpoints() {
  266. if err = sb.populateNetworkResources(ep); err != nil {
  267. return err
  268. }
  269. }
  270. return nil
  271. }
  272. func (sb *sandbox) populateNetworkResources(ep *endpoint) error {
  273. sb.Lock()
  274. if sb.osSbox == nil {
  275. sb.Unlock()
  276. return nil
  277. }
  278. sb.Unlock()
  279. ep.Lock()
  280. joinInfo := ep.joinInfo
  281. i := ep.iface
  282. ep.Unlock()
  283. if i.srcName != "" {
  284. var ifaceOptions []osl.IfaceOption
  285. ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().Address(i.addr), sb.osSbox.InterfaceOptions().Routes(i.routes))
  286. if i.addrv6 != nil && i.addrv6.IP.To16() != nil {
  287. ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().AddressIPv6(i.addrv6))
  288. }
  289. if err := sb.osSbox.AddInterface(i.srcName, i.dstPrefix, ifaceOptions...); err != nil {
  290. return fmt.Errorf("failed to add interface %s to sandbox: %v", i.srcName, err)
  291. }
  292. }
  293. if joinInfo != nil {
  294. // Set up non-interface routes.
  295. for _, r := range joinInfo.StaticRoutes {
  296. if err := sb.osSbox.AddStaticRoute(r); err != nil {
  297. return fmt.Errorf("failed to add static route %s: %v", r.Destination.String(), err)
  298. }
  299. }
  300. }
  301. for _, gwep := range sb.getConnectedEndpoints() {
  302. if len(gwep.Gateway()) > 0 {
  303. if gwep != ep {
  304. return nil
  305. }
  306. if err := sb.updateGateway(gwep); err != nil {
  307. return err
  308. }
  309. }
  310. }
  311. return nil
  312. }
  313. func (sb *sandbox) clearNetworkResources(origEp *endpoint) error {
  314. ep := sb.getEndpoint(origEp.id)
  315. if ep == nil {
  316. return fmt.Errorf("could not find the sandbox endpoint data for endpoint %s",
  317. ep.name)
  318. }
  319. sb.Lock()
  320. osSbox := sb.osSbox
  321. sb.Unlock()
  322. if osSbox != nil {
  323. for _, i := range osSbox.Info().Interfaces() {
  324. // Only remove the interfaces owned by this endpoint from the sandbox.
  325. if ep.hasInterface(i.SrcName()) {
  326. if err := i.Remove(); err != nil {
  327. log.Debugf("Remove interface failed: %v", err)
  328. }
  329. }
  330. }
  331. ep.Lock()
  332. joinInfo := ep.joinInfo
  333. ep.Unlock()
  334. // Remove non-interface routes.
  335. for _, r := range joinInfo.StaticRoutes {
  336. if err := osSbox.RemoveStaticRoute(r); err != nil {
  337. log.Debugf("Remove route failed: %v", err)
  338. }
  339. }
  340. }
  341. sb.Lock()
  342. if len(sb.endpoints) == 0 {
  343. // sb.endpoints should never be empty and this is unexpected error condition
  344. // We log an error message to note this down for debugging purposes.
  345. log.Errorf("No endpoints in sandbox while trying to remove endpoint %s", ep.Name())
  346. sb.Unlock()
  347. return nil
  348. }
  349. var (
  350. gwepBefore, gwepAfter *endpoint
  351. index = -1
  352. )
  353. for i, e := range sb.endpoints {
  354. if e == ep {
  355. index = i
  356. }
  357. if len(e.Gateway()) > 0 && gwepBefore == nil {
  358. gwepBefore = e
  359. }
  360. if index != -1 && gwepBefore != nil {
  361. break
  362. }
  363. }
  364. heap.Remove(&sb.endpoints, index)
  365. for _, e := range sb.endpoints {
  366. if len(e.Gateway()) > 0 {
  367. gwepAfter = e
  368. break
  369. }
  370. }
  371. delete(sb.epPriority, ep.ID())
  372. sb.Unlock()
  373. if gwepAfter != nil && gwepBefore != gwepAfter {
  374. sb.updateGateway(gwepAfter)
  375. }
  376. return nil
  377. }
  378. const (
  379. defaultPrefix = "/var/lib/docker/network/files"
  380. dirPerm = 0755
  381. filePerm = 0644
  382. )
  383. func (sb *sandbox) buildHostsFile() error {
  384. if sb.config.hostsPath == "" {
  385. sb.config.hostsPath = defaultPrefix + "/" + sb.id + "/hosts"
  386. }
  387. dir, _ := filepath.Split(sb.config.hostsPath)
  388. if err := createBasePath(dir); err != nil {
  389. return err
  390. }
  391. // This is for the host mode networking
  392. if sb.config.originHostsPath != "" {
  393. if err := copyFile(sb.config.originHostsPath, sb.config.hostsPath); err != nil && !os.IsNotExist(err) {
  394. return types.InternalErrorf("could not copy source hosts file %s to %s: %v", sb.config.originHostsPath, sb.config.hostsPath, err)
  395. }
  396. return nil
  397. }
  398. extraContent := make([]etchosts.Record, 0, len(sb.config.extraHosts))
  399. for _, extraHost := range sb.config.extraHosts {
  400. extraContent = append(extraContent, etchosts.Record{Hosts: extraHost.name, IP: extraHost.IP})
  401. }
  402. return etchosts.Build(sb.config.hostsPath, "", sb.config.hostName, sb.config.domainName, extraContent)
  403. }
  404. func (sb *sandbox) updateHostsFile(ifaceIP string, svcRecords []etchosts.Record) error {
  405. var err error
  406. if sb.config.originHostsPath != "" {
  407. return nil
  408. }
  409. max := func(a, b int) int {
  410. if a < b {
  411. return b
  412. }
  413. return a
  414. }
  415. extraContent := make([]etchosts.Record, 0,
  416. max(len(sb.config.extraHosts), len(svcRecords)))
  417. sb.hostsOnce.Do(func() {
  418. // Rebuild the hosts file accounting for the passed
  419. // interface IP and service records
  420. for _, extraHost := range sb.config.extraHosts {
  421. extraContent = append(extraContent,
  422. etchosts.Record{Hosts: extraHost.name, IP: extraHost.IP})
  423. }
  424. err = etchosts.Build(sb.config.hostsPath, ifaceIP,
  425. sb.config.hostName, sb.config.domainName, extraContent)
  426. })
  427. if err != nil {
  428. return err
  429. }
  430. extraContent = extraContent[:0]
  431. for _, svc := range svcRecords {
  432. extraContent = append(extraContent, svc)
  433. }
  434. sb.addHostsEntries(extraContent)
  435. return nil
  436. }
  437. func (sb *sandbox) addHostsEntries(recs []etchosts.Record) {
  438. if err := etchosts.Add(sb.config.hostsPath, recs); err != nil {
  439. log.Warnf("Failed adding service host entries to the running container: %v", err)
  440. }
  441. }
  442. func (sb *sandbox) deleteHostsEntries(recs []etchosts.Record) {
  443. if err := etchosts.Delete(sb.config.hostsPath, recs); err != nil {
  444. log.Warnf("Failed deleting service host entries to the running container: %v", err)
  445. }
  446. }
  447. func (sb *sandbox) updateParentHosts() error {
  448. var pSb Sandbox
  449. for _, update := range sb.config.parentUpdates {
  450. sb.controller.WalkSandboxes(SandboxContainerWalker(&pSb, update.cid))
  451. if pSb == nil {
  452. continue
  453. }
  454. if err := etchosts.Update(pSb.(*sandbox).config.hostsPath, update.ip, update.name); err != nil {
  455. return err
  456. }
  457. }
  458. return nil
  459. }
  460. func (sb *sandbox) setupDNS() error {
  461. var newRC *resolvconf.File
  462. if sb.config.resolvConfPath == "" {
  463. sb.config.resolvConfPath = defaultPrefix + "/" + sb.id + "/resolv.conf"
  464. }
  465. sb.config.resolvConfHashFile = sb.config.resolvConfPath + ".hash"
  466. dir, _ := filepath.Split(sb.config.resolvConfPath)
  467. if err := createBasePath(dir); err != nil {
  468. return err
  469. }
  470. // This is for the host mode networking
  471. if sb.config.originResolvConfPath != "" {
  472. if err := copyFile(sb.config.originResolvConfPath, sb.config.resolvConfPath); err != nil {
  473. return fmt.Errorf("could not copy source resolv.conf file %s to %s: %v", sb.config.originResolvConfPath, sb.config.resolvConfPath, err)
  474. }
  475. return nil
  476. }
  477. currRC, err := resolvconf.Get()
  478. if err != nil {
  479. return err
  480. }
  481. if len(sb.config.dnsList) > 0 || len(sb.config.dnsSearchList) > 0 || len(sb.config.dnsOptionsList) > 0 {
  482. var (
  483. err error
  484. dnsList = resolvconf.GetNameservers(currRC.Content)
  485. dnsSearchList = resolvconf.GetSearchDomains(currRC.Content)
  486. dnsOptionsList = resolvconf.GetOptions(currRC.Content)
  487. )
  488. if len(sb.config.dnsList) > 0 {
  489. dnsList = sb.config.dnsList
  490. }
  491. if len(sb.config.dnsSearchList) > 0 {
  492. dnsSearchList = sb.config.dnsSearchList
  493. }
  494. if len(sb.config.dnsOptionsList) > 0 {
  495. dnsOptionsList = sb.config.dnsOptionsList
  496. }
  497. newRC, err = resolvconf.Build(sb.config.resolvConfPath, dnsList, dnsSearchList, dnsOptionsList)
  498. if err != nil {
  499. return err
  500. }
  501. } else {
  502. // Replace any localhost/127.* (at this point we have no info about ipv6, pass it as true)
  503. if newRC, err = resolvconf.FilterResolvDNS(currRC.Content, true); err != nil {
  504. return err
  505. }
  506. // No contention on container resolv.conf file at sandbox creation
  507. if err := ioutil.WriteFile(sb.config.resolvConfPath, newRC.Content, filePerm); err != nil {
  508. return types.InternalErrorf("failed to write unhaltered resolv.conf file content when setting up dns for sandbox %s: %v", sb.ID(), err)
  509. }
  510. }
  511. // Write hash
  512. if err := ioutil.WriteFile(sb.config.resolvConfHashFile, []byte(newRC.Hash), filePerm); err != nil {
  513. return types.InternalErrorf("failed to write resolv.conf hash file when setting up dns for sandbox %s: %v", sb.ID(), err)
  514. }
  515. return nil
  516. }
  517. func (sb *sandbox) updateDNS(ipv6Enabled bool) error {
  518. var (
  519. currHash string
  520. hashFile = sb.config.resolvConfHashFile
  521. )
  522. if len(sb.config.dnsList) > 0 || len(sb.config.dnsSearchList) > 0 || len(sb.config.dnsOptionsList) > 0 {
  523. return nil
  524. }
  525. currRC, err := resolvconf.GetSpecific(sb.config.resolvConfPath)
  526. if err != nil {
  527. if !os.IsNotExist(err) {
  528. return err
  529. }
  530. } else {
  531. h, err := ioutil.ReadFile(hashFile)
  532. if err != nil {
  533. if !os.IsNotExist(err) {
  534. return err
  535. }
  536. } else {
  537. currHash = string(h)
  538. }
  539. }
  540. if currHash != "" && currHash != currRC.Hash {
  541. // Seems the user has changed the container resolv.conf since the last time
  542. // we checked so return without doing anything.
  543. log.Infof("Skipping update of resolv.conf file with ipv6Enabled: %t because file was touched by user", ipv6Enabled)
  544. return nil
  545. }
  546. // replace any localhost/127.* and remove IPv6 nameservers if IPv6 disabled.
  547. newRC, err := resolvconf.FilterResolvDNS(currRC.Content, ipv6Enabled)
  548. if err != nil {
  549. return err
  550. }
  551. // for atomic updates to these files, use temporary files with os.Rename:
  552. dir := path.Dir(sb.config.resolvConfPath)
  553. tmpHashFile, err := ioutil.TempFile(dir, "hash")
  554. if err != nil {
  555. return err
  556. }
  557. tmpResolvFile, err := ioutil.TempFile(dir, "resolv")
  558. if err != nil {
  559. return err
  560. }
  561. // Change the perms to filePerm (0644) since ioutil.TempFile creates it by default as 0600
  562. if err := os.Chmod(tmpResolvFile.Name(), filePerm); err != nil {
  563. return err
  564. }
  565. // write the updates to the temp files
  566. if err = ioutil.WriteFile(tmpHashFile.Name(), []byte(newRC.Hash), filePerm); err != nil {
  567. return err
  568. }
  569. if err = ioutil.WriteFile(tmpResolvFile.Name(), newRC.Content, filePerm); err != nil {
  570. return err
  571. }
  572. // rename the temp files for atomic replace
  573. if err = os.Rename(tmpHashFile.Name(), hashFile); err != nil {
  574. return err
  575. }
  576. return os.Rename(tmpResolvFile.Name(), sb.config.resolvConfPath)
  577. }
  578. // joinLeaveStart waits to ensure there are no joins or leaves in progress and
  579. // marks this join/leave in progress without race
  580. func (sb *sandbox) joinLeaveStart() {
  581. sb.Lock()
  582. defer sb.Unlock()
  583. for sb.joinLeaveDone != nil {
  584. joinLeaveDone := sb.joinLeaveDone
  585. sb.Unlock()
  586. select {
  587. case <-joinLeaveDone:
  588. }
  589. sb.Lock()
  590. }
  591. sb.joinLeaveDone = make(chan struct{})
  592. }
  593. // joinLeaveEnd marks the end of this join/leave operation and
  594. // signals the same without race to other join and leave waiters
  595. func (sb *sandbox) joinLeaveEnd() {
  596. sb.Lock()
  597. defer sb.Unlock()
  598. if sb.joinLeaveDone != nil {
  599. close(sb.joinLeaveDone)
  600. sb.joinLeaveDone = nil
  601. }
  602. }
  603. // OptionHostname function returns an option setter for hostname option to
  604. // be passed to NewSandbox method.
  605. func OptionHostname(name string) SandboxOption {
  606. return func(sb *sandbox) {
  607. sb.config.hostName = name
  608. }
  609. }
  610. // OptionDomainname function returns an option setter for domainname option to
  611. // be passed to NewSandbox method.
  612. func OptionDomainname(name string) SandboxOption {
  613. return func(sb *sandbox) {
  614. sb.config.domainName = name
  615. }
  616. }
  617. // OptionHostsPath function returns an option setter for hostspath option to
  618. // be passed to NewSandbox method.
  619. func OptionHostsPath(path string) SandboxOption {
  620. return func(sb *sandbox) {
  621. sb.config.hostsPath = path
  622. }
  623. }
  624. // OptionOriginHostsPath function returns an option setter for origin hosts file path
  625. // tbeo passed to NewSandbox method.
  626. func OptionOriginHostsPath(path string) SandboxOption {
  627. return func(sb *sandbox) {
  628. sb.config.originHostsPath = path
  629. }
  630. }
  631. // OptionExtraHost function returns an option setter for extra /etc/hosts options
  632. // which is a name and IP as strings.
  633. func OptionExtraHost(name string, IP string) SandboxOption {
  634. return func(sb *sandbox) {
  635. sb.config.extraHosts = append(sb.config.extraHosts, extraHost{name: name, IP: IP})
  636. }
  637. }
  638. // OptionParentUpdate function returns an option setter for parent container
  639. // which needs to update the IP address for the linked container.
  640. func OptionParentUpdate(cid string, name, ip string) SandboxOption {
  641. return func(sb *sandbox) {
  642. sb.config.parentUpdates = append(sb.config.parentUpdates, parentUpdate{cid: cid, name: name, ip: ip})
  643. }
  644. }
  645. // OptionResolvConfPath function returns an option setter for resolvconfpath option to
  646. // be passed to net container methods.
  647. func OptionResolvConfPath(path string) SandboxOption {
  648. return func(sb *sandbox) {
  649. sb.config.resolvConfPath = path
  650. }
  651. }
  652. // OptionOriginResolvConfPath function returns an option setter to set the path to the
  653. // origin resolv.conf file to be passed to net container methods.
  654. func OptionOriginResolvConfPath(path string) SandboxOption {
  655. return func(sb *sandbox) {
  656. sb.config.originResolvConfPath = path
  657. }
  658. }
  659. // OptionDNS function returns an option setter for dns entry option to
  660. // be passed to container Create method.
  661. func OptionDNS(dns string) SandboxOption {
  662. return func(sb *sandbox) {
  663. sb.config.dnsList = append(sb.config.dnsList, dns)
  664. }
  665. }
  666. // OptionDNSSearch function returns an option setter for dns search entry option to
  667. // be passed to container Create method.
  668. func OptionDNSSearch(search string) SandboxOption {
  669. return func(sb *sandbox) {
  670. sb.config.dnsSearchList = append(sb.config.dnsSearchList, search)
  671. }
  672. }
  673. // OptionDNSOptions function returns an option setter for dns options entry option to
  674. // be passed to container Create method.
  675. func OptionDNSOptions(options string) SandboxOption {
  676. return func(sb *sandbox) {
  677. sb.config.dnsOptionsList = append(sb.config.dnsOptionsList, options)
  678. }
  679. }
  680. // OptionUseDefaultSandbox function returns an option setter for using default sandbox to
  681. // be passed to container Create method.
  682. func OptionUseDefaultSandbox() SandboxOption {
  683. return func(sb *sandbox) {
  684. sb.config.useDefaultSandBox = true
  685. }
  686. }
  687. // OptionUseExternalKey function returns an option setter for using provided namespace
  688. // instead of creating one.
  689. func OptionUseExternalKey() SandboxOption {
  690. return func(sb *sandbox) {
  691. sb.config.useExternalKey = true
  692. }
  693. }
  694. // OptionGeneric function returns an option setter for Generic configuration
  695. // that is not managed by libNetwork but can be used by the Drivers during the call to
  696. // net container creation method. Container Labels are a good example.
  697. func OptionGeneric(generic map[string]interface{}) SandboxOption {
  698. return func(sb *sandbox) {
  699. sb.config.generic = generic
  700. }
  701. }
  702. func (eh epHeap) Len() int { return len(eh) }
  703. func (eh epHeap) Less(i, j int) bool {
  704. ci, _ := eh[i].getSandbox()
  705. cj, _ := eh[j].getSandbox()
  706. epi := eh[i]
  707. epj := eh[j]
  708. if epi.endpointInGWNetwork() {
  709. return false
  710. }
  711. if epj.endpointInGWNetwork() {
  712. return true
  713. }
  714. cip, ok := ci.epPriority[eh[i].ID()]
  715. if !ok {
  716. cip = 0
  717. }
  718. cjp, ok := cj.epPriority[eh[j].ID()]
  719. if !ok {
  720. cjp = 0
  721. }
  722. if cip == cjp {
  723. return eh[i].network.Name() < eh[j].network.Name()
  724. }
  725. return cip > cjp
  726. }
  727. func (eh epHeap) Swap(i, j int) { eh[i], eh[j] = eh[j], eh[i] }
  728. func (eh *epHeap) Push(x interface{}) {
  729. *eh = append(*eh, x.(*endpoint))
  730. }
  731. func (eh *epHeap) Pop() interface{} {
  732. old := *eh
  733. n := len(old)
  734. x := old[n-1]
  735. *eh = old[0 : n-1]
  736. return x
  737. }
  738. func createBasePath(dir string) error {
  739. return os.MkdirAll(dir, dirPerm)
  740. }
  741. func createFile(path string) error {
  742. var f *os.File
  743. dir, _ := filepath.Split(path)
  744. err := createBasePath(dir)
  745. if err != nil {
  746. return err
  747. }
  748. f, err = os.Create(path)
  749. if err == nil {
  750. f.Close()
  751. }
  752. return err
  753. }
  754. func copyFile(src, dst string) error {
  755. sBytes, err := ioutil.ReadFile(src)
  756. if err != nil {
  757. return err
  758. }
  759. return ioutil.WriteFile(dst, sBytes, filePerm)
  760. }