utils.go 16 KB

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