utils.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. package utils
  2. import (
  3. "bufio"
  4. "bytes"
  5. "crypto/rand"
  6. "crypto/sha1"
  7. "crypto/sha256"
  8. "encoding/hex"
  9. "fmt"
  10. "io"
  11. "io/ioutil"
  12. "net/http"
  13. "os"
  14. "os/exec"
  15. "path/filepath"
  16. "regexp"
  17. "runtime"
  18. "strconv"
  19. "strings"
  20. "sync"
  21. log "github.com/Sirupsen/logrus"
  22. "github.com/docker/docker/dockerversion"
  23. "github.com/docker/docker/pkg/archive"
  24. "github.com/docker/docker/pkg/fileutils"
  25. "github.com/docker/docker/pkg/ioutils"
  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 {
  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. log.Errorf("Error opening /proc/%d/fd: %s", os.Getpid(), err)
  148. } else {
  149. return len(fds)
  150. }
  151. return -1
  152. }
  153. // TruncateID returns a shorthand version of a string identifier for convenience.
  154. // A collision with other shorthands is very unlikely, but possible.
  155. // In case of a collision a lookup with TruncIndex.Get() will fail, and the caller
  156. // will need to use a langer prefix, or the full-length Id.
  157. func TruncateID(id string) string {
  158. shortLen := 12
  159. if len(id) < shortLen {
  160. shortLen = len(id)
  161. }
  162. return id[:shortLen]
  163. }
  164. // GenerateRandomID returns an unique id
  165. func GenerateRandomID() string {
  166. for {
  167. id := make([]byte, 32)
  168. if _, err := io.ReadFull(rand.Reader, id); err != nil {
  169. panic(err) // This shouldn't happen
  170. }
  171. value := hex.EncodeToString(id)
  172. // if we try to parse the truncated for as an int and we don't have
  173. // an error then the value is all numberic and causes issues when
  174. // used as a hostname. ref #3869
  175. if _, err := strconv.ParseInt(TruncateID(value), 10, 64); err == nil {
  176. continue
  177. }
  178. return value
  179. }
  180. }
  181. func ValidateID(id string) error {
  182. if ok := validHex.MatchString(id); !ok {
  183. err := fmt.Errorf("image ID '%s' is invalid", id)
  184. return err
  185. }
  186. return nil
  187. }
  188. // Code c/c from io.Copy() modified to handle escape sequence
  189. func CopyEscapable(dst io.Writer, src io.ReadCloser) (written int64, err error) {
  190. buf := make([]byte, 32*1024)
  191. for {
  192. nr, er := src.Read(buf)
  193. if nr > 0 {
  194. // ---- Docker addition
  195. // char 16 is C-p
  196. if nr == 1 && buf[0] == 16 {
  197. nr, er = src.Read(buf)
  198. // char 17 is C-q
  199. if nr == 1 && buf[0] == 17 {
  200. if err := src.Close(); err != nil {
  201. return 0, err
  202. }
  203. return 0, nil
  204. }
  205. }
  206. // ---- End of docker
  207. nw, ew := dst.Write(buf[0:nr])
  208. if nw > 0 {
  209. written += int64(nw)
  210. }
  211. if ew != nil {
  212. err = ew
  213. break
  214. }
  215. if nr != nw {
  216. err = io.ErrShortWrite
  217. break
  218. }
  219. }
  220. if er == io.EOF {
  221. break
  222. }
  223. if er != nil {
  224. err = er
  225. break
  226. }
  227. }
  228. return written, err
  229. }
  230. func HashData(src io.Reader) (string, error) {
  231. h := sha256.New()
  232. if _, err := io.Copy(h, src); err != nil {
  233. return "", err
  234. }
  235. return "sha256:" + hex.EncodeToString(h.Sum(nil)), nil
  236. }
  237. type WriteFlusher struct {
  238. sync.Mutex
  239. w io.Writer
  240. flusher http.Flusher
  241. }
  242. func (wf *WriteFlusher) Write(b []byte) (n int, err error) {
  243. wf.Lock()
  244. defer wf.Unlock()
  245. n, err = wf.w.Write(b)
  246. wf.flusher.Flush()
  247. return n, err
  248. }
  249. // Flush the stream immediately.
  250. func (wf *WriteFlusher) Flush() {
  251. wf.Lock()
  252. defer wf.Unlock()
  253. wf.flusher.Flush()
  254. }
  255. func NewWriteFlusher(w io.Writer) *WriteFlusher {
  256. var flusher http.Flusher
  257. if f, ok := w.(http.Flusher); ok {
  258. flusher = f
  259. } else {
  260. flusher = &ioutils.NopFlusher{}
  261. }
  262. return &WriteFlusher{w: w, flusher: flusher}
  263. }
  264. func NewHTTPRequestError(msg string, res *http.Response) error {
  265. return &JSONError{
  266. Message: msg,
  267. Code: res.StatusCode,
  268. }
  269. }
  270. var localHostRx = regexp.MustCompile(`(?m)^nameserver 127[^\n]+\n*`)
  271. // RemoveLocalDns looks into the /etc/resolv.conf,
  272. // and removes any local nameserver entries.
  273. func RemoveLocalDns(resolvConf []byte) []byte {
  274. return localHostRx.ReplaceAll(resolvConf, []byte{})
  275. }
  276. // An StatusError reports an unsuccessful exit by a command.
  277. type StatusError struct {
  278. Status string
  279. StatusCode int
  280. }
  281. func (e *StatusError) Error() string {
  282. return fmt.Sprintf("Status: %s, Code: %d", e.Status, e.StatusCode)
  283. }
  284. func quote(word string, buf *bytes.Buffer) {
  285. // Bail out early for "simple" strings
  286. if word != "" && !strings.ContainsAny(word, "\\'\"`${[|&;<>()~*?! \t\n") {
  287. buf.WriteString(word)
  288. return
  289. }
  290. buf.WriteString("'")
  291. for i := 0; i < len(word); i++ {
  292. b := word[i]
  293. if b == '\'' {
  294. // Replace literal ' with a close ', a \', and a open '
  295. buf.WriteString("'\\''")
  296. } else {
  297. buf.WriteByte(b)
  298. }
  299. }
  300. buf.WriteString("'")
  301. }
  302. // Take a list of strings and escape them so they will be handled right
  303. // when passed as arguments to an program via a shell
  304. func ShellQuoteArguments(args []string) string {
  305. var buf bytes.Buffer
  306. for i, arg := range args {
  307. if i != 0 {
  308. buf.WriteByte(' ')
  309. }
  310. quote(arg, &buf)
  311. }
  312. return buf.String()
  313. }
  314. var globalTestID string
  315. // TestDirectory creates a new temporary directory and returns its path.
  316. // The contents of directory at path `templateDir` is copied into the
  317. // new directory.
  318. func TestDirectory(templateDir string) (dir string, err error) {
  319. if globalTestID == "" {
  320. globalTestID = RandomString()[:4]
  321. }
  322. prefix := fmt.Sprintf("docker-test%s-%s-", globalTestID, GetCallerName(2))
  323. if prefix == "" {
  324. prefix = "docker-test-"
  325. }
  326. dir, err = ioutil.TempDir("", prefix)
  327. if err = os.Remove(dir); err != nil {
  328. return
  329. }
  330. if templateDir != "" {
  331. if err = archive.CopyWithTar(templateDir, dir); err != nil {
  332. return
  333. }
  334. }
  335. return
  336. }
  337. // GetCallerName introspects the call stack and returns the name of the
  338. // function `depth` levels down in the stack.
  339. func GetCallerName(depth int) string {
  340. // Use the caller function name as a prefix.
  341. // This helps trace temp directories back to their test.
  342. pc, _, _, _ := runtime.Caller(depth + 1)
  343. callerLongName := runtime.FuncForPC(pc).Name()
  344. parts := strings.Split(callerLongName, ".")
  345. callerShortName := parts[len(parts)-1]
  346. return callerShortName
  347. }
  348. func CopyFile(src, dst string) (int64, error) {
  349. if src == dst {
  350. return 0, nil
  351. }
  352. sf, err := os.Open(src)
  353. if err != nil {
  354. return 0, err
  355. }
  356. defer sf.Close()
  357. if err := os.Remove(dst); err != nil && !os.IsNotExist(err) {
  358. return 0, err
  359. }
  360. df, err := os.Create(dst)
  361. if err != nil {
  362. return 0, err
  363. }
  364. defer df.Close()
  365. return io.Copy(df, sf)
  366. }
  367. // ReplaceOrAppendValues returns the defaults with the overrides either
  368. // replaced by env key or appended to the list
  369. func ReplaceOrAppendEnvValues(defaults, overrides []string) []string {
  370. cache := make(map[string]int, len(defaults))
  371. for i, e := range defaults {
  372. parts := strings.SplitN(e, "=", 2)
  373. cache[parts[0]] = i
  374. }
  375. for _, value := range overrides {
  376. parts := strings.SplitN(value, "=", 2)
  377. if i, exists := cache[parts[0]]; exists {
  378. defaults[i] = value
  379. } else {
  380. defaults = append(defaults, value)
  381. }
  382. }
  383. return defaults
  384. }
  385. // ReadSymlinkedDirectory returns the target directory of a symlink.
  386. // The target of the symbolic link may not be a file.
  387. func ReadSymlinkedDirectory(path string) (string, error) {
  388. var realPath string
  389. var err error
  390. if realPath, err = filepath.Abs(path); err != nil {
  391. return "", fmt.Errorf("unable to get absolute path for %s: %s", path, err)
  392. }
  393. if realPath, err = filepath.EvalSymlinks(realPath); err != nil {
  394. return "", fmt.Errorf("failed to canonicalise path for %s: %s", path, err)
  395. }
  396. realPathInfo, err := os.Stat(realPath)
  397. if err != nil {
  398. return "", fmt.Errorf("failed to stat target '%s' of '%s': %s", realPath, path, err)
  399. }
  400. if !realPathInfo.Mode().IsDir() {
  401. return "", fmt.Errorf("canonical path points to a file '%s'", realPath)
  402. }
  403. return realPath, nil
  404. }
  405. // ValidateContextDirectory checks if all the contents of the directory
  406. // can be read and returns an error if some files can't be read
  407. // symlinks which point to non-existing files don't trigger an error
  408. func ValidateContextDirectory(srcPath string, excludes []string) error {
  409. return filepath.Walk(filepath.Join(srcPath, "."), func(filePath string, f os.FileInfo, err error) error {
  410. // skip this directory/file if it's not in the path, it won't get added to the context
  411. if relFilePath, err := filepath.Rel(srcPath, filePath); err != nil {
  412. return err
  413. } else if skip, err := fileutils.Matches(relFilePath, excludes); err != nil {
  414. return err
  415. } else if skip {
  416. if f.IsDir() {
  417. return filepath.SkipDir
  418. }
  419. return nil
  420. }
  421. if err != nil {
  422. if os.IsPermission(err) {
  423. return fmt.Errorf("can't stat '%s'", filePath)
  424. }
  425. if os.IsNotExist(err) {
  426. return nil
  427. }
  428. return err
  429. }
  430. // skip checking if symlinks point to non-existing files, such symlinks can be useful
  431. // also skip named pipes, because they hanging on open
  432. if f.Mode()&(os.ModeSymlink|os.ModeNamedPipe) != 0 {
  433. return nil
  434. }
  435. if !f.IsDir() {
  436. currentFile, err := os.Open(filePath)
  437. if err != nil && os.IsPermission(err) {
  438. return fmt.Errorf("no permission to read from '%s'", filePath)
  439. }
  440. currentFile.Close()
  441. }
  442. return nil
  443. })
  444. }
  445. func StringsContainsNoCase(slice []string, s string) bool {
  446. for _, ss := range slice {
  447. if strings.ToLower(s) == strings.ToLower(ss) {
  448. return true
  449. }
  450. }
  451. return false
  452. }
  453. // Reads a .dockerignore file and returns the list of file patterns
  454. // to ignore. Note this will trim whitespace from each line as well
  455. // as use GO's "clean" func to get the shortest/cleanest path for each.
  456. func ReadDockerIgnore(path string) ([]string, error) {
  457. // Note that a missing .dockerignore file isn't treated as an error
  458. reader, err := os.Open(path)
  459. if err != nil {
  460. if !os.IsNotExist(err) {
  461. return nil, fmt.Errorf("Error reading '%s': %v", path, err)
  462. }
  463. return nil, nil
  464. }
  465. defer reader.Close()
  466. scanner := bufio.NewScanner(reader)
  467. var excludes []string
  468. for scanner.Scan() {
  469. pattern := strings.TrimSpace(scanner.Text())
  470. if pattern == "" {
  471. continue
  472. }
  473. pattern = filepath.Clean(pattern)
  474. excludes = append(excludes, pattern)
  475. }
  476. if err = scanner.Err(); err != nil {
  477. return nil, fmt.Errorf("Error reading '%s': %v", path, err)
  478. }
  479. return excludes, nil
  480. }