sandbox.go 20 KB

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