utils.go 15 KB

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