utils.go 17 KB

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