utils.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918
  1. package utils
  2. import (
  3. "bytes"
  4. "crypto/rand"
  5. "crypto/sha1"
  6. "crypto/sha256"
  7. "encoding/hex"
  8. "encoding/json"
  9. "errors"
  10. "fmt"
  11. "io"
  12. "io/ioutil"
  13. "net/http"
  14. "os"
  15. "os/exec"
  16. "path/filepath"
  17. "runtime"
  18. "strconv"
  19. "strings"
  20. "sync"
  21. "syscall"
  22. "time"
  23. "github.com/dotcloud/docker/dockerversion"
  24. )
  25. type KeyValuePair struct {
  26. Key string
  27. Value string
  28. }
  29. // A common interface to access the Fatal method of
  30. // both testing.B and testing.T.
  31. type Fataler interface {
  32. Fatal(args ...interface{})
  33. }
  34. // Go is a basic promise implementation: it wraps calls a function in a goroutine,
  35. // and returns a channel which will later return the function's return value.
  36. func Go(f func() error) chan error {
  37. ch := make(chan error, 1)
  38. go func() {
  39. ch <- f()
  40. }()
  41. return ch
  42. }
  43. // Request a given URL and return an io.Reader
  44. func Download(url string) (resp *http.Response, err error) {
  45. if resp, err = http.Get(url); err != nil {
  46. return nil, err
  47. }
  48. if resp.StatusCode >= 400 {
  49. return nil, fmt.Errorf("Got HTTP status code >= 400: %s", resp.Status)
  50. }
  51. return resp, nil
  52. }
  53. func logf(level string, format string, a ...interface{}) {
  54. // Retrieve the stack infos
  55. _, file, line, ok := runtime.Caller(2)
  56. if !ok {
  57. file = "<unknown>"
  58. line = -1
  59. } else {
  60. file = file[strings.LastIndex(file, "/")+1:]
  61. }
  62. fmt.Fprintf(os.Stderr, fmt.Sprintf("[%s] %s:%d %s\n", level, file, line, format), a...)
  63. }
  64. // Debug function, if the debug flag is set, then display. Do nothing otherwise
  65. // If Docker is in damon mode, also send the debug info on the socket
  66. func Debugf(format string, a ...interface{}) {
  67. if os.Getenv("DEBUG") != "" {
  68. logf("debug", format, a...)
  69. }
  70. }
  71. func Errorf(format string, a ...interface{}) {
  72. logf("error", format, a...)
  73. }
  74. func Trunc(s string, maxlen int) string {
  75. if len(s) <= maxlen {
  76. return s
  77. }
  78. return s[:maxlen]
  79. }
  80. // Figure out the absolute path of our own binary (if it's still around).
  81. func SelfPath() string {
  82. path, err := exec.LookPath(os.Args[0])
  83. if err != nil {
  84. if os.IsNotExist(err) {
  85. return ""
  86. }
  87. if execErr, ok := err.(*exec.Error); ok && os.IsNotExist(execErr.Err) {
  88. return ""
  89. }
  90. panic(err)
  91. }
  92. path, err = filepath.Abs(path)
  93. if err != nil {
  94. if os.IsNotExist(err) {
  95. return ""
  96. }
  97. panic(err)
  98. }
  99. return path
  100. }
  101. func dockerInitSha1(target string) string {
  102. f, err := os.Open(target)
  103. if err != nil {
  104. return ""
  105. }
  106. defer f.Close()
  107. h := sha1.New()
  108. _, err = io.Copy(h, f)
  109. if err != nil {
  110. return ""
  111. }
  112. return hex.EncodeToString(h.Sum(nil))
  113. }
  114. func isValidDockerInitPath(target string, selfPath string) bool { // target and selfPath should be absolute (InitPath and SelfPath already do this)
  115. if target == "" {
  116. return false
  117. }
  118. if dockerversion.IAMSTATIC {
  119. if selfPath == "" {
  120. return false
  121. }
  122. if target == selfPath {
  123. return true
  124. }
  125. targetFileInfo, err := os.Lstat(target)
  126. if err != nil {
  127. return false
  128. }
  129. selfPathFileInfo, err := os.Lstat(selfPath)
  130. if err != nil {
  131. return false
  132. }
  133. return os.SameFile(targetFileInfo, selfPathFileInfo)
  134. }
  135. return dockerversion.INITSHA1 != "" && dockerInitSha1(target) == dockerversion.INITSHA1
  136. }
  137. // Figure out the path of our dockerinit (which may be SelfPath())
  138. func DockerInitPath(localCopy string) string {
  139. selfPath := SelfPath()
  140. if isValidDockerInitPath(selfPath, selfPath) {
  141. // if we're valid, don't bother checking anything else
  142. return selfPath
  143. }
  144. var possibleInits = []string{
  145. localCopy,
  146. dockerversion.INITPATH,
  147. filepath.Join(filepath.Dir(selfPath), "dockerinit"),
  148. // FHS 3.0 Draft: "/usr/libexec includes internal binaries that are not intended to be executed directly by users or shell scripts. Applications may use a single subdirectory under /usr/libexec."
  149. // http://www.linuxbase.org/betaspecs/fhs/fhs.html#usrlibexec
  150. "/usr/libexec/docker/dockerinit",
  151. "/usr/local/libexec/docker/dockerinit",
  152. // FHS 2.3: "/usr/lib includes object files, libraries, and internal binaries that are not intended to be executed directly by users or shell scripts."
  153. // http://refspecs.linuxfoundation.org/FHS_2.3/fhs-2.3.html#USRLIBLIBRARIESFORPROGRAMMINGANDPA
  154. "/usr/lib/docker/dockerinit",
  155. "/usr/local/lib/docker/dockerinit",
  156. }
  157. for _, dockerInit := range possibleInits {
  158. if dockerInit == "" {
  159. continue
  160. }
  161. path, err := exec.LookPath(dockerInit)
  162. if err == nil {
  163. path, err = filepath.Abs(path)
  164. if err != nil {
  165. // LookPath already validated that this file exists and is executable (following symlinks), so how could Abs fail?
  166. panic(err)
  167. }
  168. if isValidDockerInitPath(path, selfPath) {
  169. return path
  170. }
  171. }
  172. }
  173. return ""
  174. }
  175. type NopWriter struct{}
  176. func (*NopWriter) Write(buf []byte) (int, error) {
  177. return len(buf), nil
  178. }
  179. type nopWriteCloser struct {
  180. io.Writer
  181. }
  182. func (w *nopWriteCloser) Close() error { return nil }
  183. func NopWriteCloser(w io.Writer) io.WriteCloser {
  184. return &nopWriteCloser{w}
  185. }
  186. type bufReader struct {
  187. sync.Mutex
  188. buf *bytes.Buffer
  189. reader io.Reader
  190. err error
  191. wait sync.Cond
  192. }
  193. func NewBufReader(r io.Reader) *bufReader {
  194. reader := &bufReader{
  195. buf: &bytes.Buffer{},
  196. reader: r,
  197. }
  198. reader.wait.L = &reader.Mutex
  199. go reader.drain()
  200. return reader
  201. }
  202. func (r *bufReader) drain() {
  203. buf := make([]byte, 1024)
  204. for {
  205. n, err := r.reader.Read(buf)
  206. r.Lock()
  207. if err != nil {
  208. r.err = err
  209. } else {
  210. r.buf.Write(buf[0:n])
  211. }
  212. r.wait.Signal()
  213. r.Unlock()
  214. if err != nil {
  215. break
  216. }
  217. }
  218. }
  219. func (r *bufReader) Read(p []byte) (n int, err error) {
  220. r.Lock()
  221. defer r.Unlock()
  222. for {
  223. n, err = r.buf.Read(p)
  224. if n > 0 {
  225. return n, err
  226. }
  227. if r.err != nil {
  228. return 0, r.err
  229. }
  230. r.wait.Wait()
  231. }
  232. }
  233. func (r *bufReader) Close() error {
  234. closer, ok := r.reader.(io.ReadCloser)
  235. if !ok {
  236. return nil
  237. }
  238. return closer.Close()
  239. }
  240. type JSONLog struct {
  241. Log string `json:"log,omitempty"`
  242. Stream string `json:"stream,omitempty"`
  243. Created time.Time `json:"time"`
  244. }
  245. func (jl *JSONLog) Format(format string) (string, error) {
  246. if format == "" {
  247. return jl.Log, nil
  248. }
  249. if format == "json" {
  250. m, err := json.Marshal(jl)
  251. return string(m), err
  252. }
  253. return fmt.Sprintf("[%s] %s", jl.Created.Format(format), jl.Log), nil
  254. }
  255. func WriteLog(src io.Reader, dst io.WriteCloser, format string) error {
  256. dec := json.NewDecoder(src)
  257. for {
  258. l := &JSONLog{}
  259. if err := dec.Decode(l); err == io.EOF {
  260. return nil
  261. } else if err != nil {
  262. Errorf("Error streaming logs: %s", err)
  263. return err
  264. }
  265. line, err := l.Format(format)
  266. if err != nil {
  267. return err
  268. }
  269. fmt.Fprintf(dst, "%s", line)
  270. }
  271. }
  272. func GetTotalUsedFds() int {
  273. if fds, err := ioutil.ReadDir(fmt.Sprintf("/proc/%d/fd", os.Getpid())); err != nil {
  274. Errorf("Error opening /proc/%d/fd: %s", os.Getpid(), err)
  275. } else {
  276. return len(fds)
  277. }
  278. return -1
  279. }
  280. // TruncateID returns a shorthand version of a string identifier for convenience.
  281. // A collision with other shorthands is very unlikely, but possible.
  282. // In case of a collision a lookup with TruncIndex.Get() will fail, and the caller
  283. // will need to use a langer prefix, or the full-length Id.
  284. func TruncateID(id string) string {
  285. shortLen := 12
  286. if len(id) < shortLen {
  287. shortLen = len(id)
  288. }
  289. return id[:shortLen]
  290. }
  291. // GenerateRandomID returns an unique id
  292. func GenerateRandomID() string {
  293. for {
  294. id := make([]byte, 32)
  295. if _, err := io.ReadFull(rand.Reader, id); err != nil {
  296. panic(err) // This shouldn't happen
  297. }
  298. value := hex.EncodeToString(id)
  299. // if we try to parse the truncated for as an int and we don't have
  300. // an error then the value is all numberic and causes issues when
  301. // used as a hostname. ref #3869
  302. if _, err := strconv.ParseInt(TruncateID(value), 10, 64); err == nil {
  303. continue
  304. }
  305. return value
  306. }
  307. }
  308. func ValidateID(id string) error {
  309. if id == "" {
  310. return fmt.Errorf("Id can't be empty")
  311. }
  312. if strings.Contains(id, ":") {
  313. return fmt.Errorf("Invalid character in id: ':'")
  314. }
  315. return nil
  316. }
  317. // Code c/c from io.Copy() modified to handle escape sequence
  318. func CopyEscapable(dst io.Writer, src io.ReadCloser) (written int64, err error) {
  319. buf := make([]byte, 32*1024)
  320. for {
  321. nr, er := src.Read(buf)
  322. if nr > 0 {
  323. // ---- Docker addition
  324. // char 16 is C-p
  325. if nr == 1 && buf[0] == 16 {
  326. nr, er = src.Read(buf)
  327. // char 17 is C-q
  328. if nr == 1 && buf[0] == 17 {
  329. if err := src.Close(); err != nil {
  330. return 0, err
  331. }
  332. return 0, nil
  333. }
  334. }
  335. // ---- End of docker
  336. nw, ew := dst.Write(buf[0:nr])
  337. if nw > 0 {
  338. written += int64(nw)
  339. }
  340. if ew != nil {
  341. err = ew
  342. break
  343. }
  344. if nr != nw {
  345. err = io.ErrShortWrite
  346. break
  347. }
  348. }
  349. if er == io.EOF {
  350. break
  351. }
  352. if er != nil {
  353. err = er
  354. break
  355. }
  356. }
  357. return written, err
  358. }
  359. func HashData(src io.Reader) (string, error) {
  360. h := sha256.New()
  361. if _, err := io.Copy(h, src); err != nil {
  362. return "", err
  363. }
  364. return "sha256:" + hex.EncodeToString(h.Sum(nil)), nil
  365. }
  366. type KernelVersionInfo struct {
  367. Kernel int
  368. Major int
  369. Minor int
  370. Flavor string
  371. }
  372. func (k *KernelVersionInfo) String() string {
  373. return fmt.Sprintf("%d.%d.%d%s", k.Kernel, k.Major, k.Minor, k.Flavor)
  374. }
  375. // Compare two KernelVersionInfo struct.
  376. // Returns -1 if a < b, 0 if a == b, 1 it a > b
  377. func CompareKernelVersion(a, b *KernelVersionInfo) int {
  378. if a.Kernel < b.Kernel {
  379. return -1
  380. } else if a.Kernel > b.Kernel {
  381. return 1
  382. }
  383. if a.Major < b.Major {
  384. return -1
  385. } else if a.Major > b.Major {
  386. return 1
  387. }
  388. if a.Minor < b.Minor {
  389. return -1
  390. } else if a.Minor > b.Minor {
  391. return 1
  392. }
  393. return 0
  394. }
  395. func GetKernelVersion() (*KernelVersionInfo, error) {
  396. var (
  397. err error
  398. )
  399. uts, err := uname()
  400. if err != nil {
  401. return nil, err
  402. }
  403. release := make([]byte, len(uts.Release))
  404. i := 0
  405. for _, c := range uts.Release {
  406. release[i] = byte(c)
  407. i++
  408. }
  409. // Remove the \x00 from the release for Atoi to parse correctly
  410. release = release[:bytes.IndexByte(release, 0)]
  411. return ParseRelease(string(release))
  412. }
  413. func ParseRelease(release string) (*KernelVersionInfo, error) {
  414. var (
  415. kernel, major, minor, parsed int
  416. flavor, partial string
  417. )
  418. // Ignore error from Sscanf to allow an empty flavor. Instead, just
  419. // make sure we got all the version numbers.
  420. parsed, _ = fmt.Sscanf(release, "%d.%d%s", &kernel, &major, &partial)
  421. if parsed < 2 {
  422. return nil, errors.New("Can't parse kernel version " + release)
  423. }
  424. // sometimes we have 3.12.25-gentoo, but sometimes we just have 3.12-1-amd64
  425. parsed, _ = fmt.Sscanf(partial, ".%d%s", &minor, &flavor)
  426. if parsed < 1 {
  427. flavor = partial
  428. }
  429. return &KernelVersionInfo{
  430. Kernel: kernel,
  431. Major: major,
  432. Minor: minor,
  433. Flavor: flavor,
  434. }, nil
  435. }
  436. // FIXME: this is deprecated by CopyWithTar in archive.go
  437. func CopyDirectory(source, dest string) error {
  438. if output, err := exec.Command("cp", "-ra", source, dest).CombinedOutput(); err != nil {
  439. return fmt.Errorf("Error copy: %s (%s)", err, output)
  440. }
  441. return nil
  442. }
  443. type NopFlusher struct{}
  444. func (f *NopFlusher) Flush() {}
  445. type WriteFlusher struct {
  446. sync.Mutex
  447. w io.Writer
  448. flusher http.Flusher
  449. }
  450. func (wf *WriteFlusher) Write(b []byte) (n int, err error) {
  451. wf.Lock()
  452. defer wf.Unlock()
  453. n, err = wf.w.Write(b)
  454. wf.flusher.Flush()
  455. return n, err
  456. }
  457. // Flush the stream immediately.
  458. func (wf *WriteFlusher) Flush() {
  459. wf.Lock()
  460. defer wf.Unlock()
  461. wf.flusher.Flush()
  462. }
  463. func NewWriteFlusher(w io.Writer) *WriteFlusher {
  464. var flusher http.Flusher
  465. if f, ok := w.(http.Flusher); ok {
  466. flusher = f
  467. } else {
  468. flusher = &NopFlusher{}
  469. }
  470. return &WriteFlusher{w: w, flusher: flusher}
  471. }
  472. func NewHTTPRequestError(msg string, res *http.Response) error {
  473. return &JSONError{
  474. Message: msg,
  475. Code: res.StatusCode,
  476. }
  477. }
  478. func IsURL(str string) bool {
  479. return strings.HasPrefix(str, "http://") || strings.HasPrefix(str, "https://")
  480. }
  481. func IsGIT(str string) bool {
  482. return strings.HasPrefix(str, "git://") || strings.HasPrefix(str, "github.com/") || strings.HasPrefix(str, "git@github.com:") || (strings.HasSuffix(str, ".git") && IsURL(str))
  483. }
  484. // CheckLocalDns looks into the /etc/resolv.conf,
  485. // it returns true if there is a local nameserver or if there is no nameserver.
  486. func CheckLocalDns(resolvConf []byte) bool {
  487. for _, line := range GetLines(resolvConf, []byte("#")) {
  488. if !bytes.Contains(line, []byte("nameserver")) {
  489. continue
  490. }
  491. for _, ip := range [][]byte{
  492. []byte("127.0.0.1"),
  493. []byte("127.0.1.1"),
  494. } {
  495. if bytes.Contains(line, ip) {
  496. return true
  497. }
  498. }
  499. return false
  500. }
  501. return true
  502. }
  503. // GetLines parses input into lines and strips away comments.
  504. func GetLines(input []byte, commentMarker []byte) [][]byte {
  505. lines := bytes.Split(input, []byte("\n"))
  506. var output [][]byte
  507. for _, currentLine := range lines {
  508. var commentIndex = bytes.Index(currentLine, commentMarker)
  509. if commentIndex == -1 {
  510. output = append(output, currentLine)
  511. } else {
  512. output = append(output, currentLine[:commentIndex])
  513. }
  514. }
  515. return output
  516. }
  517. // FIXME: Change this not to receive default value as parameter
  518. func ParseHost(defaultHost string, defaultUnix, addr string) (string, error) {
  519. var (
  520. proto string
  521. host string
  522. port int
  523. )
  524. addr = strings.TrimSpace(addr)
  525. switch {
  526. case addr == "tcp://":
  527. return "", fmt.Errorf("Invalid bind address format: %s", addr)
  528. case strings.HasPrefix(addr, "unix://"):
  529. proto = "unix"
  530. addr = strings.TrimPrefix(addr, "unix://")
  531. if addr == "" {
  532. addr = defaultUnix
  533. }
  534. case strings.HasPrefix(addr, "tcp://"):
  535. proto = "tcp"
  536. addr = strings.TrimPrefix(addr, "tcp://")
  537. case strings.HasPrefix(addr, "fd://"):
  538. return addr, nil
  539. case addr == "":
  540. proto = "unix"
  541. addr = defaultUnix
  542. default:
  543. if strings.Contains(addr, "://") {
  544. return "", fmt.Errorf("Invalid bind address protocol: %s", addr)
  545. }
  546. proto = "tcp"
  547. }
  548. if proto != "unix" && strings.Contains(addr, ":") {
  549. hostParts := strings.Split(addr, ":")
  550. if len(hostParts) != 2 {
  551. return "", fmt.Errorf("Invalid bind address format: %s", addr)
  552. }
  553. if hostParts[0] != "" {
  554. host = hostParts[0]
  555. } else {
  556. host = defaultHost
  557. }
  558. if p, err := strconv.Atoi(hostParts[1]); err == nil && p != 0 {
  559. port = p
  560. } else {
  561. return "", fmt.Errorf("Invalid bind address format: %s", addr)
  562. }
  563. } else if proto == "tcp" && !strings.Contains(addr, ":") {
  564. return "", fmt.Errorf("Invalid bind address format: %s", addr)
  565. } else {
  566. host = addr
  567. }
  568. if proto == "unix" {
  569. return fmt.Sprintf("%s://%s", proto, host), nil
  570. }
  571. return fmt.Sprintf("%s://%s:%d", proto, host, port), nil
  572. }
  573. // Get a repos name and returns the right reposName + tag
  574. // The tag can be confusing because of a port in a repository name.
  575. // Ex: localhost.localdomain:5000/samalba/hipache:latest
  576. func ParseRepositoryTag(repos string) (string, string) {
  577. n := strings.LastIndex(repos, ":")
  578. if n < 0 {
  579. return repos, ""
  580. }
  581. if tag := repos[n+1:]; !strings.Contains(tag, "/") {
  582. return repos[:n], tag
  583. }
  584. return repos, ""
  585. }
  586. // An StatusError reports an unsuccessful exit by a command.
  587. type StatusError struct {
  588. Status string
  589. StatusCode int
  590. }
  591. func (e *StatusError) Error() string {
  592. return fmt.Sprintf("Status: %s, Code: %d", e.Status, e.StatusCode)
  593. }
  594. func quote(word string, buf *bytes.Buffer) {
  595. // Bail out early for "simple" strings
  596. if word != "" && !strings.ContainsAny(word, "\\'\"`${[|&;<>()~*?! \t\n") {
  597. buf.WriteString(word)
  598. return
  599. }
  600. buf.WriteString("'")
  601. for i := 0; i < len(word); i++ {
  602. b := word[i]
  603. if b == '\'' {
  604. // Replace literal ' with a close ', a \', and a open '
  605. buf.WriteString("'\\''")
  606. } else {
  607. buf.WriteByte(b)
  608. }
  609. }
  610. buf.WriteString("'")
  611. }
  612. // Take a list of strings and escape them so they will be handled right
  613. // when passed as arguments to an program via a shell
  614. func ShellQuoteArguments(args []string) string {
  615. var buf bytes.Buffer
  616. for i, arg := range args {
  617. if i != 0 {
  618. buf.WriteByte(' ')
  619. }
  620. quote(arg, &buf)
  621. }
  622. return buf.String()
  623. }
  624. func PartParser(template, data string) (map[string]string, error) {
  625. // ip:public:private
  626. var (
  627. templateParts = strings.Split(template, ":")
  628. parts = strings.Split(data, ":")
  629. out = make(map[string]string, len(templateParts))
  630. )
  631. if len(parts) != len(templateParts) {
  632. return nil, fmt.Errorf("Invalid format to parse. %s should match template %s", data, template)
  633. }
  634. for i, t := range templateParts {
  635. value := ""
  636. if len(parts) > i {
  637. value = parts[i]
  638. }
  639. out[t] = value
  640. }
  641. return out, nil
  642. }
  643. var globalTestID string
  644. // TestDirectory creates a new temporary directory and returns its path.
  645. // The contents of directory at path `templateDir` is copied into the
  646. // new directory.
  647. func TestDirectory(templateDir string) (dir string, err error) {
  648. if globalTestID == "" {
  649. globalTestID = RandomString()[:4]
  650. }
  651. prefix := fmt.Sprintf("docker-test%s-%s-", globalTestID, GetCallerName(2))
  652. if prefix == "" {
  653. prefix = "docker-test-"
  654. }
  655. dir, err = ioutil.TempDir("", prefix)
  656. if err = os.Remove(dir); err != nil {
  657. return
  658. }
  659. if templateDir != "" {
  660. if err = CopyDirectory(templateDir, dir); err != nil {
  661. return
  662. }
  663. }
  664. return
  665. }
  666. // GetCallerName introspects the call stack and returns the name of the
  667. // function `depth` levels down in the stack.
  668. func GetCallerName(depth int) string {
  669. // Use the caller function name as a prefix.
  670. // This helps trace temp directories back to their test.
  671. pc, _, _, _ := runtime.Caller(depth + 1)
  672. callerLongName := runtime.FuncForPC(pc).Name()
  673. parts := strings.Split(callerLongName, ".")
  674. callerShortName := parts[len(parts)-1]
  675. return callerShortName
  676. }
  677. func CopyFile(src, dst string) (int64, error) {
  678. if src == dst {
  679. return 0, nil
  680. }
  681. sf, err := os.Open(src)
  682. if err != nil {
  683. return 0, err
  684. }
  685. defer sf.Close()
  686. if err := os.Remove(dst); err != nil && !os.IsNotExist(err) {
  687. return 0, err
  688. }
  689. df, err := os.Create(dst)
  690. if err != nil {
  691. return 0, err
  692. }
  693. defer df.Close()
  694. return io.Copy(df, sf)
  695. }
  696. type readCloserWrapper struct {
  697. io.Reader
  698. closer func() error
  699. }
  700. func (r *readCloserWrapper) Close() error {
  701. return r.closer()
  702. }
  703. func NewReadCloserWrapper(r io.Reader, closer func() error) io.ReadCloser {
  704. return &readCloserWrapper{
  705. Reader: r,
  706. closer: closer,
  707. }
  708. }
  709. // ReplaceOrAppendValues returns the defaults with the overrides either
  710. // replaced by env key or appended to the list
  711. func ReplaceOrAppendEnvValues(defaults, overrides []string) []string {
  712. cache := make(map[string]int, len(defaults))
  713. for i, e := range defaults {
  714. parts := strings.SplitN(e, "=", 2)
  715. cache[parts[0]] = i
  716. }
  717. for _, value := range overrides {
  718. parts := strings.SplitN(value, "=", 2)
  719. if i, exists := cache[parts[0]]; exists {
  720. defaults[i] = value
  721. } else {
  722. defaults = append(defaults, value)
  723. }
  724. }
  725. return defaults
  726. }
  727. // ReadSymlinkedDirectory returns the target directory of a symlink.
  728. // The target of the symbolic link may not be a file.
  729. func ReadSymlinkedDirectory(path string) (string, error) {
  730. var realPath string
  731. var err error
  732. if realPath, err = filepath.Abs(path); err != nil {
  733. return "", fmt.Errorf("unable to get absolute path for %s: %s", path, err)
  734. }
  735. if realPath, err = filepath.EvalSymlinks(realPath); err != nil {
  736. return "", fmt.Errorf("failed to canonicalise path for %s: %s", path, err)
  737. }
  738. realPathInfo, err := os.Stat(realPath)
  739. if err != nil {
  740. return "", fmt.Errorf("failed to stat target '%s' of '%s': %s", realPath, path, err)
  741. }
  742. if !realPathInfo.Mode().IsDir() {
  743. return "", fmt.Errorf("canonical path points to a file '%s'", realPath)
  744. }
  745. return realPath, nil
  746. }
  747. func ParseKeyValueOpt(opt string) (string, string, error) {
  748. parts := strings.SplitN(opt, "=", 2)
  749. if len(parts) != 2 {
  750. return "", "", fmt.Errorf("Unable to parse key/value option: %s", opt)
  751. }
  752. return strings.TrimSpace(parts[0]), strings.TrimSpace(parts[1]), nil
  753. }
  754. // TreeSize walks a directory tree and returns its total size in bytes.
  755. func TreeSize(dir string) (size int64, err error) {
  756. data := make(map[uint64]struct{})
  757. err = filepath.Walk(dir, func(d string, fileInfo os.FileInfo, e error) error {
  758. // Ignore directory sizes
  759. if fileInfo == nil {
  760. return nil
  761. }
  762. s := fileInfo.Size()
  763. if fileInfo.IsDir() || s == 0 {
  764. return nil
  765. }
  766. // Check inode to handle hard links correctly
  767. inode := fileInfo.Sys().(*syscall.Stat_t).Ino
  768. // inode is not a uint64 on all platforms. Cast it to avoid issues.
  769. if _, exists := data[uint64(inode)]; exists {
  770. return nil
  771. }
  772. // inode is not a uint64 on all platforms. Cast it to avoid issues.
  773. data[uint64(inode)] = struct{}{}
  774. size += s
  775. return nil
  776. })
  777. return
  778. }
  779. // ValidateContextDirectory checks if all the contents of the directory
  780. // can be read and returns an error if some files can't be read
  781. // symlinks which point to non-existing files don't trigger an error
  782. func ValidateContextDirectory(srcPath string) error {
  783. var finalError error
  784. filepath.Walk(filepath.Join(srcPath, "."), func(filePath string, f os.FileInfo, err error) error {
  785. // skip this directory/file if it's not in the path, it won't get added to the context
  786. _, err = filepath.Rel(srcPath, filePath)
  787. if err != nil && os.IsPermission(err) {
  788. return nil
  789. }
  790. if _, err := os.Stat(filePath); err != nil && os.IsPermission(err) {
  791. finalError = fmt.Errorf("can't stat '%s'", filePath)
  792. return err
  793. }
  794. // skip checking if symlinks point to non-existing files, such symlinks can be useful
  795. lstat, _ := os.Lstat(filePath)
  796. if lstat.Mode()&os.ModeSymlink == os.ModeSymlink {
  797. return err
  798. }
  799. if !f.IsDir() {
  800. currentFile, err := os.Open(filePath)
  801. if err != nil && os.IsPermission(err) {
  802. finalError = fmt.Errorf("no permission to read from '%s'", filePath)
  803. return err
  804. } else {
  805. currentFile.Close()
  806. }
  807. }
  808. return nil
  809. })
  810. return finalError
  811. }
  812. func StringsContains(slice []string, s string) bool {
  813. for _, ss := range slice {
  814. if s == ss {
  815. return true
  816. }
  817. }
  818. return false
  819. }