utils.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  1. package utils
  2. import (
  3. "bytes"
  4. "crypto/rand"
  5. "crypto/sha1"
  6. "crypto/sha256"
  7. "encoding/hex"
  8. "fmt"
  9. "io"
  10. "io/ioutil"
  11. "net/http"
  12. "os"
  13. "os/exec"
  14. "path/filepath"
  15. "runtime"
  16. "strconv"
  17. "strings"
  18. "sync"
  19. "syscall"
  20. "github.com/docker/docker/dockerversion"
  21. "github.com/docker/docker/pkg/log"
  22. )
  23. type KeyValuePair struct {
  24. Key string
  25. Value string
  26. }
  27. // A common interface to access the Fatal method of
  28. // both testing.B and testing.T.
  29. type Fataler interface {
  30. Fatal(args ...interface{})
  31. }
  32. // Go is a basic promise implementation: it wraps calls a function in a goroutine,
  33. // and returns a channel which will later return the function's return value.
  34. func Go(f func() error) chan error {
  35. ch := make(chan error, 1)
  36. go func() {
  37. ch <- f()
  38. }()
  39. return ch
  40. }
  41. // Request a given URL and return an io.Reader
  42. func Download(url string) (resp *http.Response, err error) {
  43. if resp, err = http.Get(url); err != nil {
  44. return nil, err
  45. }
  46. if resp.StatusCode >= 400 {
  47. return nil, fmt.Errorf("Got HTTP status code >= 400: %s", resp.Status)
  48. }
  49. return resp, nil
  50. }
  51. func Trunc(s string, maxlen int) string {
  52. if len(s) <= maxlen {
  53. return s
  54. }
  55. return s[:maxlen]
  56. }
  57. // Figure out the absolute path of our own binary (if it's still around).
  58. func SelfPath() string {
  59. path, err := exec.LookPath(os.Args[0])
  60. if err != nil {
  61. if os.IsNotExist(err) {
  62. return ""
  63. }
  64. if execErr, ok := err.(*exec.Error); ok && os.IsNotExist(execErr.Err) {
  65. return ""
  66. }
  67. panic(err)
  68. }
  69. path, err = filepath.Abs(path)
  70. if err != nil {
  71. if os.IsNotExist(err) {
  72. return ""
  73. }
  74. panic(err)
  75. }
  76. return path
  77. }
  78. func dockerInitSha1(target string) string {
  79. f, err := os.Open(target)
  80. if err != nil {
  81. return ""
  82. }
  83. defer f.Close()
  84. h := sha1.New()
  85. _, err = io.Copy(h, f)
  86. if err != nil {
  87. return ""
  88. }
  89. return hex.EncodeToString(h.Sum(nil))
  90. }
  91. func isValidDockerInitPath(target string, selfPath string) bool { // target and selfPath should be absolute (InitPath and SelfPath already do this)
  92. if target == "" {
  93. return false
  94. }
  95. if dockerversion.IAMSTATIC {
  96. if selfPath == "" {
  97. return false
  98. }
  99. if target == selfPath {
  100. return true
  101. }
  102. targetFileInfo, err := os.Lstat(target)
  103. if err != nil {
  104. return false
  105. }
  106. selfPathFileInfo, err := os.Lstat(selfPath)
  107. if err != nil {
  108. return false
  109. }
  110. return os.SameFile(targetFileInfo, selfPathFileInfo)
  111. }
  112. return dockerversion.INITSHA1 != "" && dockerInitSha1(target) == dockerversion.INITSHA1
  113. }
  114. // Figure out the path of our dockerinit (which may be SelfPath())
  115. func DockerInitPath(localCopy string) string {
  116. selfPath := SelfPath()
  117. if isValidDockerInitPath(selfPath, selfPath) {
  118. // if we're valid, don't bother checking anything else
  119. return selfPath
  120. }
  121. var possibleInits = []string{
  122. localCopy,
  123. dockerversion.INITPATH,
  124. filepath.Join(filepath.Dir(selfPath), "dockerinit"),
  125. // 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."
  126. // http://www.linuxbase.org/betaspecs/fhs/fhs.html#usrlibexec
  127. "/usr/libexec/docker/dockerinit",
  128. "/usr/local/libexec/docker/dockerinit",
  129. // 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."
  130. // http://refspecs.linuxfoundation.org/FHS_2.3/fhs-2.3.html#USRLIBLIBRARIESFORPROGRAMMINGANDPA
  131. "/usr/lib/docker/dockerinit",
  132. "/usr/local/lib/docker/dockerinit",
  133. }
  134. for _, dockerInit := range possibleInits {
  135. if dockerInit == "" {
  136. continue
  137. }
  138. path, err := exec.LookPath(dockerInit)
  139. if err == nil {
  140. path, err = filepath.Abs(path)
  141. if err != nil {
  142. // LookPath already validated that this file exists and is executable (following symlinks), so how could Abs fail?
  143. panic(err)
  144. }
  145. if isValidDockerInitPath(path, selfPath) {
  146. return path
  147. }
  148. }
  149. }
  150. return ""
  151. }
  152. type NopWriter struct{}
  153. func (*NopWriter) Write(buf []byte) (int, error) {
  154. return len(buf), nil
  155. }
  156. type nopWriteCloser struct {
  157. io.Writer
  158. }
  159. func (w *nopWriteCloser) Close() error { return nil }
  160. func NopWriteCloser(w io.Writer) io.WriteCloser {
  161. return &nopWriteCloser{w}
  162. }
  163. type bufReader struct {
  164. sync.Mutex
  165. buf *bytes.Buffer
  166. reader io.Reader
  167. err error
  168. wait sync.Cond
  169. }
  170. func NewBufReader(r io.Reader) *bufReader {
  171. reader := &bufReader{
  172. buf: &bytes.Buffer{},
  173. reader: r,
  174. }
  175. reader.wait.L = &reader.Mutex
  176. go reader.drain()
  177. return reader
  178. }
  179. func (r *bufReader) drain() {
  180. buf := make([]byte, 1024)
  181. for {
  182. n, err := r.reader.Read(buf)
  183. r.Lock()
  184. if err != nil {
  185. r.err = err
  186. } else {
  187. r.buf.Write(buf[0:n])
  188. }
  189. r.wait.Signal()
  190. r.Unlock()
  191. if err != nil {
  192. break
  193. }
  194. }
  195. }
  196. func (r *bufReader) Read(p []byte) (n int, err error) {
  197. r.Lock()
  198. defer r.Unlock()
  199. for {
  200. n, err = r.buf.Read(p)
  201. if n > 0 {
  202. return n, err
  203. }
  204. if r.err != nil {
  205. return 0, r.err
  206. }
  207. r.wait.Wait()
  208. }
  209. }
  210. func (r *bufReader) Close() error {
  211. closer, ok := r.reader.(io.ReadCloser)
  212. if !ok {
  213. return nil
  214. }
  215. return closer.Close()
  216. }
  217. func GetTotalUsedFds() int {
  218. if fds, err := ioutil.ReadDir(fmt.Sprintf("/proc/%d/fd", os.Getpid())); err != nil {
  219. log.Errorf("Error opening /proc/%d/fd: %s", os.Getpid(), err)
  220. } else {
  221. return len(fds)
  222. }
  223. return -1
  224. }
  225. // TruncateID returns a shorthand version of a string identifier for convenience.
  226. // A collision with other shorthands is very unlikely, but possible.
  227. // In case of a collision a lookup with TruncIndex.Get() will fail, and the caller
  228. // will need to use a langer prefix, or the full-length Id.
  229. func TruncateID(id string) string {
  230. shortLen := 12
  231. if len(id) < shortLen {
  232. shortLen = len(id)
  233. }
  234. return id[:shortLen]
  235. }
  236. // GenerateRandomID returns an unique id
  237. func GenerateRandomID() string {
  238. for {
  239. id := make([]byte, 32)
  240. if _, err := io.ReadFull(rand.Reader, id); err != nil {
  241. panic(err) // This shouldn't happen
  242. }
  243. value := hex.EncodeToString(id)
  244. // if we try to parse the truncated for as an int and we don't have
  245. // an error then the value is all numberic and causes issues when
  246. // used as a hostname. ref #3869
  247. if _, err := strconv.ParseInt(TruncateID(value), 10, 64); err == nil {
  248. continue
  249. }
  250. return value
  251. }
  252. }
  253. func ValidateID(id string) error {
  254. if id == "" {
  255. return fmt.Errorf("Id can't be empty")
  256. }
  257. if strings.Contains(id, ":") {
  258. return fmt.Errorf("Invalid character in id: ':'")
  259. }
  260. return nil
  261. }
  262. // Code c/c from io.Copy() modified to handle escape sequence
  263. func CopyEscapable(dst io.Writer, src io.ReadCloser) (written int64, err error) {
  264. buf := make([]byte, 32*1024)
  265. for {
  266. nr, er := src.Read(buf)
  267. if nr > 0 {
  268. // ---- Docker addition
  269. // char 16 is C-p
  270. if nr == 1 && buf[0] == 16 {
  271. nr, er = src.Read(buf)
  272. // char 17 is C-q
  273. if nr == 1 && buf[0] == 17 {
  274. if err := src.Close(); err != nil {
  275. return 0, err
  276. }
  277. return 0, nil
  278. }
  279. }
  280. // ---- End of docker
  281. nw, ew := dst.Write(buf[0:nr])
  282. if nw > 0 {
  283. written += int64(nw)
  284. }
  285. if ew != nil {
  286. err = ew
  287. break
  288. }
  289. if nr != nw {
  290. err = io.ErrShortWrite
  291. break
  292. }
  293. }
  294. if er == io.EOF {
  295. break
  296. }
  297. if er != nil {
  298. err = er
  299. break
  300. }
  301. }
  302. return written, err
  303. }
  304. func HashData(src io.Reader) (string, error) {
  305. h := sha256.New()
  306. if _, err := io.Copy(h, src); err != nil {
  307. return "", err
  308. }
  309. return "sha256:" + hex.EncodeToString(h.Sum(nil)), nil
  310. }
  311. // FIXME: this is deprecated by CopyWithTar in archive.go
  312. func CopyDirectory(source, dest string) error {
  313. if output, err := exec.Command("cp", "-ra", source, dest).CombinedOutput(); err != nil {
  314. return fmt.Errorf("Error copy: %s (%s)", err, output)
  315. }
  316. return nil
  317. }
  318. type NopFlusher struct{}
  319. func (f *NopFlusher) Flush() {}
  320. type WriteFlusher struct {
  321. sync.Mutex
  322. w io.Writer
  323. flusher http.Flusher
  324. }
  325. func (wf *WriteFlusher) Write(b []byte) (n int, err error) {
  326. wf.Lock()
  327. defer wf.Unlock()
  328. n, err = wf.w.Write(b)
  329. wf.flusher.Flush()
  330. return n, err
  331. }
  332. // Flush the stream immediately.
  333. func (wf *WriteFlusher) Flush() {
  334. wf.Lock()
  335. defer wf.Unlock()
  336. wf.flusher.Flush()
  337. }
  338. func NewWriteFlusher(w io.Writer) *WriteFlusher {
  339. var flusher http.Flusher
  340. if f, ok := w.(http.Flusher); ok {
  341. flusher = f
  342. } else {
  343. flusher = &NopFlusher{}
  344. }
  345. return &WriteFlusher{w: w, flusher: flusher}
  346. }
  347. func NewHTTPRequestError(msg string, res *http.Response) error {
  348. return &JSONError{
  349. Message: msg,
  350. Code: res.StatusCode,
  351. }
  352. }
  353. func IsURL(str string) bool {
  354. return strings.HasPrefix(str, "http://") || strings.HasPrefix(str, "https://")
  355. }
  356. func IsGIT(str string) bool {
  357. return strings.HasPrefix(str, "git://") || strings.HasPrefix(str, "github.com/") || strings.HasPrefix(str, "git@github.com:") || (strings.HasSuffix(str, ".git") && IsURL(str))
  358. }
  359. // CheckLocalDns looks into the /etc/resolv.conf,
  360. // it returns true if there is a local nameserver or if there is no nameserver.
  361. func CheckLocalDns(resolvConf []byte) bool {
  362. for _, line := range GetLines(resolvConf, []byte("#")) {
  363. if !bytes.Contains(line, []byte("nameserver")) {
  364. continue
  365. }
  366. for _, ip := range [][]byte{
  367. []byte("127.0.0.1"),
  368. []byte("127.0.1.1"),
  369. } {
  370. if bytes.Contains(line, ip) {
  371. return true
  372. }
  373. }
  374. return false
  375. }
  376. return true
  377. }
  378. // GetLines parses input into lines and strips away comments.
  379. func GetLines(input []byte, commentMarker []byte) [][]byte {
  380. lines := bytes.Split(input, []byte("\n"))
  381. var output [][]byte
  382. for _, currentLine := range lines {
  383. var commentIndex = bytes.Index(currentLine, commentMarker)
  384. if commentIndex == -1 {
  385. output = append(output, currentLine)
  386. } else {
  387. output = append(output, currentLine[:commentIndex])
  388. }
  389. }
  390. return output
  391. }
  392. // An StatusError reports an unsuccessful exit by a command.
  393. type StatusError struct {
  394. Status string
  395. StatusCode int
  396. }
  397. func (e *StatusError) Error() string {
  398. return fmt.Sprintf("Status: %s, Code: %d", e.Status, e.StatusCode)
  399. }
  400. func quote(word string, buf *bytes.Buffer) {
  401. // Bail out early for "simple" strings
  402. if word != "" && !strings.ContainsAny(word, "\\'\"`${[|&;<>()~*?! \t\n") {
  403. buf.WriteString(word)
  404. return
  405. }
  406. buf.WriteString("'")
  407. for i := 0; i < len(word); i++ {
  408. b := word[i]
  409. if b == '\'' {
  410. // Replace literal ' with a close ', a \', and a open '
  411. buf.WriteString("'\\''")
  412. } else {
  413. buf.WriteByte(b)
  414. }
  415. }
  416. buf.WriteString("'")
  417. }
  418. // Take a list of strings and escape them so they will be handled right
  419. // when passed as arguments to an program via a shell
  420. func ShellQuoteArguments(args []string) string {
  421. var buf bytes.Buffer
  422. for i, arg := range args {
  423. if i != 0 {
  424. buf.WriteByte(' ')
  425. }
  426. quote(arg, &buf)
  427. }
  428. return buf.String()
  429. }
  430. var globalTestID string
  431. // TestDirectory creates a new temporary directory and returns its path.
  432. // The contents of directory at path `templateDir` is copied into the
  433. // new directory.
  434. func TestDirectory(templateDir string) (dir string, err error) {
  435. if globalTestID == "" {
  436. globalTestID = RandomString()[:4]
  437. }
  438. prefix := fmt.Sprintf("docker-test%s-%s-", globalTestID, GetCallerName(2))
  439. if prefix == "" {
  440. prefix = "docker-test-"
  441. }
  442. dir, err = ioutil.TempDir("", prefix)
  443. if err = os.Remove(dir); err != nil {
  444. return
  445. }
  446. if templateDir != "" {
  447. if err = CopyDirectory(templateDir, dir); err != nil {
  448. return
  449. }
  450. }
  451. return
  452. }
  453. // GetCallerName introspects the call stack and returns the name of the
  454. // function `depth` levels down in the stack.
  455. func GetCallerName(depth int) string {
  456. // Use the caller function name as a prefix.
  457. // This helps trace temp directories back to their test.
  458. pc, _, _, _ := runtime.Caller(depth + 1)
  459. callerLongName := runtime.FuncForPC(pc).Name()
  460. parts := strings.Split(callerLongName, ".")
  461. callerShortName := parts[len(parts)-1]
  462. return callerShortName
  463. }
  464. func CopyFile(src, dst string) (int64, error) {
  465. if src == dst {
  466. return 0, nil
  467. }
  468. sf, err := os.Open(src)
  469. if err != nil {
  470. return 0, err
  471. }
  472. defer sf.Close()
  473. if err := os.Remove(dst); err != nil && !os.IsNotExist(err) {
  474. return 0, err
  475. }
  476. df, err := os.Create(dst)
  477. if err != nil {
  478. return 0, err
  479. }
  480. defer df.Close()
  481. return io.Copy(df, sf)
  482. }
  483. type readCloserWrapper struct {
  484. io.Reader
  485. closer func() error
  486. }
  487. func (r *readCloserWrapper) Close() error {
  488. return r.closer()
  489. }
  490. func NewReadCloserWrapper(r io.Reader, closer func() error) io.ReadCloser {
  491. return &readCloserWrapper{
  492. Reader: r,
  493. closer: closer,
  494. }
  495. }
  496. // ReplaceOrAppendValues returns the defaults with the overrides either
  497. // replaced by env key or appended to the list
  498. func ReplaceOrAppendEnvValues(defaults, overrides []string) []string {
  499. cache := make(map[string]int, len(defaults))
  500. for i, e := range defaults {
  501. parts := strings.SplitN(e, "=", 2)
  502. cache[parts[0]] = i
  503. }
  504. for _, value := range overrides {
  505. parts := strings.SplitN(value, "=", 2)
  506. if i, exists := cache[parts[0]]; exists {
  507. defaults[i] = value
  508. } else {
  509. defaults = append(defaults, value)
  510. }
  511. }
  512. return defaults
  513. }
  514. // ReadSymlinkedDirectory returns the target directory of a symlink.
  515. // The target of the symbolic link may not be a file.
  516. func ReadSymlinkedDirectory(path string) (string, error) {
  517. var realPath string
  518. var err error
  519. if realPath, err = filepath.Abs(path); err != nil {
  520. return "", fmt.Errorf("unable to get absolute path for %s: %s", path, err)
  521. }
  522. if realPath, err = filepath.EvalSymlinks(realPath); err != nil {
  523. return "", fmt.Errorf("failed to canonicalise path for %s: %s", path, err)
  524. }
  525. realPathInfo, err := os.Stat(realPath)
  526. if err != nil {
  527. return "", fmt.Errorf("failed to stat target '%s' of '%s': %s", realPath, path, err)
  528. }
  529. if !realPathInfo.Mode().IsDir() {
  530. return "", fmt.Errorf("canonical path points to a file '%s'", realPath)
  531. }
  532. return realPath, nil
  533. }
  534. // TreeSize walks a directory tree and returns its total size in bytes.
  535. func TreeSize(dir string) (size int64, err error) {
  536. data := make(map[uint64]struct{})
  537. err = filepath.Walk(dir, func(d string, fileInfo os.FileInfo, e error) error {
  538. // Ignore directory sizes
  539. if fileInfo == nil {
  540. return nil
  541. }
  542. s := fileInfo.Size()
  543. if fileInfo.IsDir() || s == 0 {
  544. return nil
  545. }
  546. // Check inode to handle hard links correctly
  547. inode := fileInfo.Sys().(*syscall.Stat_t).Ino
  548. // inode is not a uint64 on all platforms. Cast it to avoid issues.
  549. if _, exists := data[uint64(inode)]; exists {
  550. return nil
  551. }
  552. // inode is not a uint64 on all platforms. Cast it to avoid issues.
  553. data[uint64(inode)] = struct{}{}
  554. size += s
  555. return nil
  556. })
  557. return
  558. }
  559. // ValidateContextDirectory checks if all the contents of the directory
  560. // can be read and returns an error if some files can't be read
  561. // symlinks which point to non-existing files don't trigger an error
  562. func ValidateContextDirectory(srcPath string, excludes []string) error {
  563. var finalError error
  564. filepath.Walk(filepath.Join(srcPath, "."), func(filePath string, f os.FileInfo, err error) error {
  565. // skip this directory/file if it's not in the path, it won't get added to the context
  566. relFilePath, err := filepath.Rel(srcPath, filePath)
  567. if err != nil && os.IsPermission(err) {
  568. return nil
  569. }
  570. skip, err := Matches(relFilePath, excludes)
  571. if err != nil {
  572. finalError = err
  573. }
  574. if skip {
  575. if f.IsDir() {
  576. return filepath.SkipDir
  577. }
  578. return nil
  579. }
  580. if _, err := os.Stat(filePath); err != nil && os.IsPermission(err) {
  581. finalError = fmt.Errorf("can't stat '%s'", filePath)
  582. return err
  583. }
  584. // skip checking if symlinks point to non-existing files, such symlinks can be useful
  585. lstat, _ := os.Lstat(filePath)
  586. if lstat.Mode()&os.ModeSymlink == os.ModeSymlink {
  587. return err
  588. }
  589. if !f.IsDir() {
  590. currentFile, err := os.Open(filePath)
  591. if err != nil && os.IsPermission(err) {
  592. finalError = fmt.Errorf("no permission to read from '%s'", filePath)
  593. return err
  594. } else {
  595. currentFile.Close()
  596. }
  597. }
  598. return nil
  599. })
  600. return finalError
  601. }
  602. func StringsContainsNoCase(slice []string, s string) bool {
  603. for _, ss := range slice {
  604. if strings.ToLower(s) == strings.ToLower(ss) {
  605. return true
  606. }
  607. }
  608. return false
  609. }
  610. // Matches returns true if relFilePath matches any of the patterns
  611. func Matches(relFilePath string, patterns []string) (bool, error) {
  612. for _, exclude := range patterns {
  613. matched, err := filepath.Match(exclude, relFilePath)
  614. if err != nil {
  615. log.Errorf("Error matching: %s (pattern: %s)", relFilePath, exclude)
  616. return false, err
  617. }
  618. if matched {
  619. if filepath.Clean(relFilePath) == "." {
  620. log.Errorf("Can't exclude whole path, excluding pattern: %s", exclude)
  621. continue
  622. }
  623. log.Debugf("Skipping excluded path: %s", relFilePath)
  624. return true, nil
  625. }
  626. }
  627. return false, nil
  628. }