utils.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. package utils
  2. import (
  3. "bufio"
  4. "bytes"
  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. "strings"
  18. "sync"
  19. "github.com/Sirupsen/logrus"
  20. "github.com/docker/docker/autogen/dockerversion"
  21. "github.com/docker/docker/pkg/archive"
  22. "github.com/docker/docker/pkg/fileutils"
  23. "github.com/docker/docker/pkg/ioutils"
  24. "github.com/docker/docker/pkg/jsonmessage"
  25. "github.com/docker/docker/pkg/stringutils"
  26. )
  27. type KeyValuePair struct {
  28. Key string
  29. Value string
  30. }
  31. var (
  32. validHex = regexp.MustCompile(`^([a-f0-9]{64})$`)
  33. )
  34. // Request a given URL and return an io.Reader
  35. func Download(url string) (resp *http.Response, err error) {
  36. if resp, err = http.Get(url); err != nil {
  37. return nil, err
  38. }
  39. if resp.StatusCode >= 400 {
  40. return nil, fmt.Errorf("Got HTTP status code >= 400: %s", resp.Status)
  41. }
  42. return resp, nil
  43. }
  44. func Trunc(s string, maxlen int) string {
  45. if len(s) <= maxlen {
  46. return s
  47. }
  48. return s[:maxlen]
  49. }
  50. // Figure out the absolute path of our own binary (if it's still around).
  51. func SelfPath() string {
  52. path, err := exec.LookPath(os.Args[0])
  53. if err != nil {
  54. if os.IsNotExist(err) {
  55. return ""
  56. }
  57. if execErr, ok := err.(*exec.Error); ok && os.IsNotExist(execErr.Err) {
  58. return ""
  59. }
  60. panic(err)
  61. }
  62. path, err = filepath.Abs(path)
  63. if err != nil {
  64. if os.IsNotExist(err) {
  65. return ""
  66. }
  67. panic(err)
  68. }
  69. return path
  70. }
  71. func dockerInitSha1(target string) string {
  72. f, err := os.Open(target)
  73. if err != nil {
  74. return ""
  75. }
  76. defer f.Close()
  77. h := sha1.New()
  78. _, err = io.Copy(h, f)
  79. if err != nil {
  80. return ""
  81. }
  82. return hex.EncodeToString(h.Sum(nil))
  83. }
  84. func isValidDockerInitPath(target string, selfPath string) bool { // target and selfPath should be absolute (InitPath and SelfPath already do this)
  85. if target == "" {
  86. return false
  87. }
  88. if dockerversion.IAMSTATIC == "true" {
  89. if selfPath == "" {
  90. return false
  91. }
  92. if target == selfPath {
  93. return true
  94. }
  95. targetFileInfo, err := os.Lstat(target)
  96. if err != nil {
  97. return false
  98. }
  99. selfPathFileInfo, err := os.Lstat(selfPath)
  100. if err != nil {
  101. return false
  102. }
  103. return os.SameFile(targetFileInfo, selfPathFileInfo)
  104. }
  105. return dockerversion.INITSHA1 != "" && dockerInitSha1(target) == dockerversion.INITSHA1
  106. }
  107. // Figure out the path of our dockerinit (which may be SelfPath())
  108. func DockerInitPath(localCopy string) string {
  109. selfPath := SelfPath()
  110. if isValidDockerInitPath(selfPath, selfPath) {
  111. // if we're valid, don't bother checking anything else
  112. return selfPath
  113. }
  114. var possibleInits = []string{
  115. localCopy,
  116. dockerversion.INITPATH,
  117. filepath.Join(filepath.Dir(selfPath), "dockerinit"),
  118. // 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."
  119. // http://www.linuxbase.org/betaspecs/fhs/fhs.html#usrlibexec
  120. "/usr/libexec/docker/dockerinit",
  121. "/usr/local/libexec/docker/dockerinit",
  122. // 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."
  123. // http://refspecs.linuxfoundation.org/FHS_2.3/fhs-2.3.html#USRLIBLIBRARIESFORPROGRAMMINGANDPA
  124. "/usr/lib/docker/dockerinit",
  125. "/usr/local/lib/docker/dockerinit",
  126. }
  127. for _, dockerInit := range possibleInits {
  128. if dockerInit == "" {
  129. continue
  130. }
  131. path, err := exec.LookPath(dockerInit)
  132. if err == nil {
  133. path, err = filepath.Abs(path)
  134. if err != nil {
  135. // LookPath already validated that this file exists and is executable (following symlinks), so how could Abs fail?
  136. panic(err)
  137. }
  138. if isValidDockerInitPath(path, selfPath) {
  139. return path
  140. }
  141. }
  142. }
  143. return ""
  144. }
  145. func GetTotalUsedFds() int {
  146. if fds, err := ioutil.ReadDir(fmt.Sprintf("/proc/%d/fd", os.Getpid())); err != nil {
  147. logrus.Errorf("Error opening /proc/%d/fd: %s", os.Getpid(), err)
  148. } else {
  149. return len(fds)
  150. }
  151. return -1
  152. }
  153. func ValidateID(id string) error {
  154. if ok := validHex.MatchString(id); !ok {
  155. err := fmt.Errorf("image ID '%s' is invalid", id)
  156. return err
  157. }
  158. return nil
  159. }
  160. // Code c/c from io.Copy() modified to handle escape sequence
  161. func CopyEscapable(dst io.Writer, src io.ReadCloser) (written int64, err error) {
  162. buf := make([]byte, 32*1024)
  163. for {
  164. nr, er := src.Read(buf)
  165. if nr > 0 {
  166. // ---- Docker addition
  167. // char 16 is C-p
  168. if nr == 1 && buf[0] == 16 {
  169. nr, er = src.Read(buf)
  170. // char 17 is C-q
  171. if nr == 1 && buf[0] == 17 {
  172. if err := src.Close(); err != nil {
  173. return 0, err
  174. }
  175. return 0, nil
  176. }
  177. }
  178. // ---- End of docker
  179. nw, ew := dst.Write(buf[0:nr])
  180. if nw > 0 {
  181. written += int64(nw)
  182. }
  183. if ew != nil {
  184. err = ew
  185. break
  186. }
  187. if nr != nw {
  188. err = io.ErrShortWrite
  189. break
  190. }
  191. }
  192. if er == io.EOF {
  193. break
  194. }
  195. if er != nil {
  196. err = er
  197. break
  198. }
  199. }
  200. return written, err
  201. }
  202. func HashData(src io.Reader) (string, error) {
  203. h := sha256.New()
  204. if _, err := io.Copy(h, src); err != nil {
  205. return "", err
  206. }
  207. return "sha256:" + hex.EncodeToString(h.Sum(nil)), nil
  208. }
  209. type WriteFlusher struct {
  210. sync.Mutex
  211. w io.Writer
  212. flusher http.Flusher
  213. }
  214. func (wf *WriteFlusher) Write(b []byte) (n int, err error) {
  215. wf.Lock()
  216. defer wf.Unlock()
  217. n, err = wf.w.Write(b)
  218. wf.flusher.Flush()
  219. return n, err
  220. }
  221. // Flush the stream immediately.
  222. func (wf *WriteFlusher) Flush() {
  223. wf.Lock()
  224. defer wf.Unlock()
  225. wf.flusher.Flush()
  226. }
  227. func NewWriteFlusher(w io.Writer) *WriteFlusher {
  228. var flusher http.Flusher
  229. if f, ok := w.(http.Flusher); ok {
  230. flusher = f
  231. } else {
  232. flusher = &ioutils.NopFlusher{}
  233. }
  234. return &WriteFlusher{w: w, flusher: flusher}
  235. }
  236. func NewHTTPRequestError(msg string, res *http.Response) error {
  237. return &jsonmessage.JSONError{
  238. Message: msg,
  239. Code: res.StatusCode,
  240. }
  241. }
  242. // An StatusError reports an unsuccessful exit by a command.
  243. type StatusError struct {
  244. Status string
  245. StatusCode int
  246. }
  247. func (e *StatusError) Error() string {
  248. return fmt.Sprintf("Status: %s, Code: %d", e.Status, e.StatusCode)
  249. }
  250. func quote(word string, buf *bytes.Buffer) {
  251. // Bail out early for "simple" strings
  252. if word != "" && !strings.ContainsAny(word, "\\'\"`${[|&;<>()~*?! \t\n") {
  253. buf.WriteString(word)
  254. return
  255. }
  256. buf.WriteString("'")
  257. for i := 0; i < len(word); i++ {
  258. b := word[i]
  259. if b == '\'' {
  260. // Replace literal ' with a close ', a \', and a open '
  261. buf.WriteString("'\\''")
  262. } else {
  263. buf.WriteByte(b)
  264. }
  265. }
  266. buf.WriteString("'")
  267. }
  268. // Take a list of strings and escape them so they will be handled right
  269. // when passed as arguments to an program via a shell
  270. func ShellQuoteArguments(args []string) string {
  271. var buf bytes.Buffer
  272. for i, arg := range args {
  273. if i != 0 {
  274. buf.WriteByte(' ')
  275. }
  276. quote(arg, &buf)
  277. }
  278. return buf.String()
  279. }
  280. var globalTestID string
  281. // TestDirectory creates a new temporary directory and returns its path.
  282. // The contents of directory at path `templateDir` is copied into the
  283. // new directory.
  284. func TestDirectory(templateDir string) (dir string, err error) {
  285. if globalTestID == "" {
  286. globalTestID = stringutils.GenerateRandomString()[:4]
  287. }
  288. prefix := fmt.Sprintf("docker-test%s-%s-", globalTestID, GetCallerName(2))
  289. if prefix == "" {
  290. prefix = "docker-test-"
  291. }
  292. dir, err = ioutil.TempDir("", prefix)
  293. if err = os.Remove(dir); err != nil {
  294. return
  295. }
  296. if templateDir != "" {
  297. if err = archive.CopyWithTar(templateDir, dir); err != nil {
  298. return
  299. }
  300. }
  301. return
  302. }
  303. // GetCallerName introspects the call stack and returns the name of the
  304. // function `depth` levels down in the stack.
  305. func GetCallerName(depth int) string {
  306. // Use the caller function name as a prefix.
  307. // This helps trace temp directories back to their test.
  308. pc, _, _, _ := runtime.Caller(depth + 1)
  309. callerLongName := runtime.FuncForPC(pc).Name()
  310. parts := strings.Split(callerLongName, ".")
  311. callerShortName := parts[len(parts)-1]
  312. return callerShortName
  313. }
  314. func CopyFile(src, dst string) (int64, error) {
  315. if src == dst {
  316. return 0, nil
  317. }
  318. sf, err := os.Open(src)
  319. if err != nil {
  320. return 0, err
  321. }
  322. defer sf.Close()
  323. if err := os.Remove(dst); err != nil && !os.IsNotExist(err) {
  324. return 0, err
  325. }
  326. df, err := os.Create(dst)
  327. if err != nil {
  328. return 0, err
  329. }
  330. defer df.Close()
  331. return io.Copy(df, sf)
  332. }
  333. // ReplaceOrAppendValues returns the defaults with the overrides either
  334. // replaced by env key or appended to the list
  335. func ReplaceOrAppendEnvValues(defaults, overrides []string) []string {
  336. cache := make(map[string]int, len(defaults))
  337. for i, e := range defaults {
  338. parts := strings.SplitN(e, "=", 2)
  339. cache[parts[0]] = i
  340. }
  341. for _, value := range overrides {
  342. // Values w/o = means they want this env to be removed/unset.
  343. if !strings.Contains(value, "=") {
  344. if i, exists := cache[value]; exists {
  345. defaults[i] = "" // Used to indicate it should be removed
  346. }
  347. continue
  348. }
  349. // Just do a normal set/update
  350. parts := strings.SplitN(value, "=", 2)
  351. if i, exists := cache[parts[0]]; exists {
  352. defaults[i] = value
  353. } else {
  354. defaults = append(defaults, value)
  355. }
  356. }
  357. // Now remove all entries that we want to "unset"
  358. for i := 0; i < len(defaults); i++ {
  359. if defaults[i] == "" {
  360. defaults = append(defaults[:i], defaults[i+1:]...)
  361. i--
  362. }
  363. }
  364. return defaults
  365. }
  366. func DoesEnvExist(name string) bool {
  367. for _, entry := range os.Environ() {
  368. parts := strings.SplitN(entry, "=", 2)
  369. if parts[0] == name {
  370. return true
  371. }
  372. }
  373. return false
  374. }
  375. // ReadSymlinkedDirectory returns the target directory of a symlink.
  376. // The target of the symbolic link may not be a file.
  377. func ReadSymlinkedDirectory(path string) (string, error) {
  378. var realPath string
  379. var err error
  380. if realPath, err = filepath.Abs(path); err != nil {
  381. return "", fmt.Errorf("unable to get absolute path for %s: %s", path, err)
  382. }
  383. if realPath, err = filepath.EvalSymlinks(realPath); err != nil {
  384. return "", fmt.Errorf("failed to canonicalise path for %s: %s", path, err)
  385. }
  386. realPathInfo, err := os.Stat(realPath)
  387. if err != nil {
  388. return "", fmt.Errorf("failed to stat target '%s' of '%s': %s", realPath, path, err)
  389. }
  390. if !realPathInfo.Mode().IsDir() {
  391. return "", fmt.Errorf("canonical path points to a file '%s'", realPath)
  392. }
  393. return realPath, nil
  394. }
  395. // ValidateContextDirectory checks if all the contents of the directory
  396. // can be read and returns an error if some files can't be read
  397. // symlinks which point to non-existing files don't trigger an error
  398. func ValidateContextDirectory(srcPath string, excludes []string) error {
  399. return filepath.Walk(filepath.Join(srcPath, "."), func(filePath string, f os.FileInfo, err error) error {
  400. // skip this directory/file if it's not in the path, it won't get added to the context
  401. if relFilePath, err := filepath.Rel(srcPath, filePath); err != nil {
  402. return err
  403. } else if skip, err := fileutils.Matches(relFilePath, excludes); err != nil {
  404. return err
  405. } else if skip {
  406. if f.IsDir() {
  407. return filepath.SkipDir
  408. }
  409. return nil
  410. }
  411. if err != nil {
  412. if os.IsPermission(err) {
  413. return fmt.Errorf("can't stat '%s'", filePath)
  414. }
  415. if os.IsNotExist(err) {
  416. return nil
  417. }
  418. return err
  419. }
  420. // skip checking if symlinks point to non-existing files, such symlinks can be useful
  421. // also skip named pipes, because they hanging on open
  422. if f.Mode()&(os.ModeSymlink|os.ModeNamedPipe) != 0 {
  423. return nil
  424. }
  425. if !f.IsDir() {
  426. currentFile, err := os.Open(filePath)
  427. if err != nil && os.IsPermission(err) {
  428. return fmt.Errorf("no permission to read from '%s'", filePath)
  429. }
  430. currentFile.Close()
  431. }
  432. return nil
  433. })
  434. }
  435. func StringsContainsNoCase(slice []string, s string) bool {
  436. for _, ss := range slice {
  437. if strings.ToLower(s) == strings.ToLower(ss) {
  438. return true
  439. }
  440. }
  441. return false
  442. }
  443. // Reads a .dockerignore file and returns the list of file patterns
  444. // to ignore. Note this will trim whitespace from each line as well
  445. // as use GO's "clean" func to get the shortest/cleanest path for each.
  446. func ReadDockerIgnore(path string) ([]string, error) {
  447. // Note that a missing .dockerignore file isn't treated as an error
  448. reader, err := os.Open(path)
  449. if err != nil {
  450. if !os.IsNotExist(err) {
  451. return nil, fmt.Errorf("Error reading '%s': %v", path, err)
  452. }
  453. return nil, nil
  454. }
  455. defer reader.Close()
  456. scanner := bufio.NewScanner(reader)
  457. var excludes []string
  458. for scanner.Scan() {
  459. pattern := strings.TrimSpace(scanner.Text())
  460. if pattern == "" {
  461. continue
  462. }
  463. pattern = filepath.Clean(pattern)
  464. excludes = append(excludes, pattern)
  465. }
  466. if err = scanner.Err(); err != nil {
  467. return nil, fmt.Errorf("Error reading '%s': %v", path, err)
  468. }
  469. return excludes, nil
  470. }
  471. // Wrap a concrete io.Writer and hold a count of the number
  472. // of bytes written to the writer during a "session".
  473. // This can be convenient when write return is masked
  474. // (e.g., json.Encoder.Encode())
  475. type WriteCounter struct {
  476. Count int64
  477. Writer io.Writer
  478. }
  479. func NewWriteCounter(w io.Writer) *WriteCounter {
  480. return &WriteCounter{
  481. Writer: w,
  482. }
  483. }
  484. func (wc *WriteCounter) Write(p []byte) (count int, err error) {
  485. count, err = wc.Writer.Write(p)
  486. wc.Count += int64(count)
  487. return
  488. }
  489. // ImageReference combines `repo` and `ref` and returns a string representing
  490. // the combination. If `ref` is a digest (meaning it's of the form
  491. // <algorithm>:<digest>, the returned string is <repo>@<ref>. Otherwise,
  492. // ref is assumed to be a tag, and the returned string is <repo>:<tag>.
  493. func ImageReference(repo, ref string) string {
  494. if DigestReference(ref) {
  495. return repo + "@" + ref
  496. }
  497. return repo + ":" + ref
  498. }
  499. // DigestReference returns true if ref is a digest reference; i.e. if it
  500. // is of the form <algorithm>:<digest>.
  501. func DigestReference(ref string) bool {
  502. return strings.Contains(ref, ":")
  503. }