utils.go 15 KB

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