utils.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  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. var (
  290. localHostRx = regexp.MustCompile(`(?m)^nameserver 127[^\n]+\n*`)
  291. )
  292. // RemoveLocalDns looks into the /etc/resolv.conf,
  293. // and removes any local nameserver entries.
  294. func RemoveLocalDns(resolvConf []byte) []byte {
  295. return localHostRx.ReplaceAll(resolvConf, []byte{})
  296. }
  297. // An StatusError reports an unsuccessful exit by a command.
  298. type StatusError struct {
  299. Status string
  300. StatusCode int
  301. }
  302. func (e *StatusError) Error() string {
  303. return fmt.Sprintf("Status: %s, Code: %d", e.Status, e.StatusCode)
  304. }
  305. func quote(word string, buf *bytes.Buffer) {
  306. // Bail out early for "simple" strings
  307. if word != "" && !strings.ContainsAny(word, "\\'\"`${[|&;<>()~*?! \t\n") {
  308. buf.WriteString(word)
  309. return
  310. }
  311. buf.WriteString("'")
  312. for i := 0; i < len(word); i++ {
  313. b := word[i]
  314. if b == '\'' {
  315. // Replace literal ' with a close ', a \', and a open '
  316. buf.WriteString("'\\''")
  317. } else {
  318. buf.WriteByte(b)
  319. }
  320. }
  321. buf.WriteString("'")
  322. }
  323. // Take a list of strings and escape them so they will be handled right
  324. // when passed as arguments to an program via a shell
  325. func ShellQuoteArguments(args []string) string {
  326. var buf bytes.Buffer
  327. for i, arg := range args {
  328. if i != 0 {
  329. buf.WriteByte(' ')
  330. }
  331. quote(arg, &buf)
  332. }
  333. return buf.String()
  334. }
  335. var globalTestID string
  336. // TestDirectory creates a new temporary directory and returns its path.
  337. // The contents of directory at path `templateDir` is copied into the
  338. // new directory.
  339. func TestDirectory(templateDir string) (dir string, err error) {
  340. if globalTestID == "" {
  341. globalTestID = RandomString()[:4]
  342. }
  343. prefix := fmt.Sprintf("docker-test%s-%s-", globalTestID, GetCallerName(2))
  344. if prefix == "" {
  345. prefix = "docker-test-"
  346. }
  347. dir, err = ioutil.TempDir("", prefix)
  348. if err = os.Remove(dir); err != nil {
  349. return
  350. }
  351. if templateDir != "" {
  352. if err = CopyDirectory(templateDir, dir); err != nil {
  353. return
  354. }
  355. }
  356. return
  357. }
  358. // GetCallerName introspects the call stack and returns the name of the
  359. // function `depth` levels down in the stack.
  360. func GetCallerName(depth int) string {
  361. // Use the caller function name as a prefix.
  362. // This helps trace temp directories back to their test.
  363. pc, _, _, _ := runtime.Caller(depth + 1)
  364. callerLongName := runtime.FuncForPC(pc).Name()
  365. parts := strings.Split(callerLongName, ".")
  366. callerShortName := parts[len(parts)-1]
  367. return callerShortName
  368. }
  369. func CopyFile(src, dst string) (int64, error) {
  370. if src == dst {
  371. return 0, nil
  372. }
  373. sf, err := os.Open(src)
  374. if err != nil {
  375. return 0, err
  376. }
  377. defer sf.Close()
  378. if err := os.Remove(dst); err != nil && !os.IsNotExist(err) {
  379. return 0, err
  380. }
  381. df, err := os.Create(dst)
  382. if err != nil {
  383. return 0, err
  384. }
  385. defer df.Close()
  386. return io.Copy(df, sf)
  387. }
  388. // ReplaceOrAppendValues returns the defaults with the overrides either
  389. // replaced by env key or appended to the list
  390. func ReplaceOrAppendEnvValues(defaults, overrides []string) []string {
  391. cache := make(map[string]int, len(defaults))
  392. for i, e := range defaults {
  393. parts := strings.SplitN(e, "=", 2)
  394. cache[parts[0]] = i
  395. }
  396. for _, value := range overrides {
  397. parts := strings.SplitN(value, "=", 2)
  398. if i, exists := cache[parts[0]]; exists {
  399. defaults[i] = value
  400. } else {
  401. defaults = append(defaults, value)
  402. }
  403. }
  404. return defaults
  405. }
  406. // ReadSymlinkedDirectory returns the target directory of a symlink.
  407. // The target of the symbolic link may not be a file.
  408. func ReadSymlinkedDirectory(path string) (string, error) {
  409. var realPath string
  410. var err error
  411. if realPath, err = filepath.Abs(path); err != nil {
  412. return "", fmt.Errorf("unable to get absolute path for %s: %s", path, err)
  413. }
  414. if realPath, err = filepath.EvalSymlinks(realPath); err != nil {
  415. return "", fmt.Errorf("failed to canonicalise path for %s: %s", path, err)
  416. }
  417. realPathInfo, err := os.Stat(realPath)
  418. if err != nil {
  419. return "", fmt.Errorf("failed to stat target '%s' of '%s': %s", realPath, path, err)
  420. }
  421. if !realPathInfo.Mode().IsDir() {
  422. return "", fmt.Errorf("canonical path points to a file '%s'", realPath)
  423. }
  424. return realPath, nil
  425. }
  426. // TreeSize walks a directory tree and returns its total size in bytes.
  427. func TreeSize(dir string) (size int64, err error) {
  428. data := make(map[uint64]struct{})
  429. err = filepath.Walk(dir, func(d string, fileInfo os.FileInfo, e error) error {
  430. // Ignore directory sizes
  431. if fileInfo == nil {
  432. return nil
  433. }
  434. s := fileInfo.Size()
  435. if fileInfo.IsDir() || s == 0 {
  436. return nil
  437. }
  438. // Check inode to handle hard links correctly
  439. inode := fileInfo.Sys().(*syscall.Stat_t).Ino
  440. // inode is not a uint64 on all platforms. Cast it to avoid issues.
  441. if _, exists := data[uint64(inode)]; exists {
  442. return nil
  443. }
  444. // inode is not a uint64 on all platforms. Cast it to avoid issues.
  445. data[uint64(inode)] = struct{}{}
  446. size += s
  447. return nil
  448. })
  449. return
  450. }
  451. // ValidateContextDirectory checks if all the contents of the directory
  452. // can be read and returns an error if some files can't be read
  453. // symlinks which point to non-existing files don't trigger an error
  454. func ValidateContextDirectory(srcPath string, excludes []string) error {
  455. return filepath.Walk(filepath.Join(srcPath, "."), func(filePath string, f os.FileInfo, err error) error {
  456. // skip this directory/file if it's not in the path, it won't get added to the context
  457. if relFilePath, err := filepath.Rel(srcPath, filePath); err != nil {
  458. return err
  459. } else if skip, err := Matches(relFilePath, excludes); err != nil {
  460. return err
  461. } else if skip {
  462. if f.IsDir() {
  463. return filepath.SkipDir
  464. }
  465. return nil
  466. }
  467. if err != nil {
  468. if os.IsPermission(err) {
  469. return fmt.Errorf("can't stat '%s'", filePath)
  470. }
  471. if os.IsNotExist(err) {
  472. return nil
  473. }
  474. return err
  475. }
  476. // skip checking if symlinks point to non-existing files, such symlinks can be useful
  477. // also skip named pipes, because they hanging on open
  478. if f.Mode()&(os.ModeSymlink|os.ModeNamedPipe) != 0 {
  479. return nil
  480. }
  481. if !f.IsDir() {
  482. currentFile, err := os.Open(filePath)
  483. if err != nil && os.IsPermission(err) {
  484. return fmt.Errorf("no permission to read from '%s'", filePath)
  485. }
  486. currentFile.Close()
  487. }
  488. return nil
  489. })
  490. }
  491. func StringsContainsNoCase(slice []string, s string) bool {
  492. for _, ss := range slice {
  493. if strings.ToLower(s) == strings.ToLower(ss) {
  494. return true
  495. }
  496. }
  497. return false
  498. }
  499. // Matches returns true if relFilePath matches any of the patterns
  500. func Matches(relFilePath string, patterns []string) (bool, error) {
  501. for _, exclude := range patterns {
  502. matched, err := filepath.Match(exclude, relFilePath)
  503. if err != nil {
  504. log.Errorf("Error matching: %s (pattern: %s)", relFilePath, exclude)
  505. return false, err
  506. }
  507. if matched {
  508. if filepath.Clean(relFilePath) == "." {
  509. log.Errorf("Can't exclude whole path, excluding pattern: %s", exclude)
  510. continue
  511. }
  512. log.Debugf("Skipping excluded path: %s", relFilePath)
  513. return true, nil
  514. }
  515. }
  516. return false, nil
  517. }