utils.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  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. // An StatusError reports an unsuccessful exit by a command.
  271. type StatusError struct {
  272. Status string
  273. StatusCode int
  274. }
  275. func (e *StatusError) Error() string {
  276. return fmt.Sprintf("Status: %s, Code: %d", e.Status, e.StatusCode)
  277. }
  278. func quote(word string, buf *bytes.Buffer) {
  279. // Bail out early for "simple" strings
  280. if word != "" && !strings.ContainsAny(word, "\\'\"`${[|&;<>()~*?! \t\n") {
  281. buf.WriteString(word)
  282. return
  283. }
  284. buf.WriteString("'")
  285. for i := 0; i < len(word); i++ {
  286. b := word[i]
  287. if b == '\'' {
  288. // Replace literal ' with a close ', a \', and a open '
  289. buf.WriteString("'\\''")
  290. } else {
  291. buf.WriteByte(b)
  292. }
  293. }
  294. buf.WriteString("'")
  295. }
  296. // Take a list of strings and escape them so they will be handled right
  297. // when passed as arguments to an program via a shell
  298. func ShellQuoteArguments(args []string) string {
  299. var buf bytes.Buffer
  300. for i, arg := range args {
  301. if i != 0 {
  302. buf.WriteByte(' ')
  303. }
  304. quote(arg, &buf)
  305. }
  306. return buf.String()
  307. }
  308. var globalTestID string
  309. // TestDirectory creates a new temporary directory and returns its path.
  310. // The contents of directory at path `templateDir` is copied into the
  311. // new directory.
  312. func TestDirectory(templateDir string) (dir string, err error) {
  313. if globalTestID == "" {
  314. globalTestID = RandomString()[:4]
  315. }
  316. prefix := fmt.Sprintf("docker-test%s-%s-", globalTestID, GetCallerName(2))
  317. if prefix == "" {
  318. prefix = "docker-test-"
  319. }
  320. dir, err = ioutil.TempDir("", prefix)
  321. if err = os.Remove(dir); err != nil {
  322. return
  323. }
  324. if templateDir != "" {
  325. if err = archive.CopyWithTar(templateDir, dir); err != nil {
  326. return
  327. }
  328. }
  329. return
  330. }
  331. // GetCallerName introspects the call stack and returns the name of the
  332. // function `depth` levels down in the stack.
  333. func GetCallerName(depth int) string {
  334. // Use the caller function name as a prefix.
  335. // This helps trace temp directories back to their test.
  336. pc, _, _, _ := runtime.Caller(depth + 1)
  337. callerLongName := runtime.FuncForPC(pc).Name()
  338. parts := strings.Split(callerLongName, ".")
  339. callerShortName := parts[len(parts)-1]
  340. return callerShortName
  341. }
  342. func CopyFile(src, dst string) (int64, error) {
  343. if src == dst {
  344. return 0, nil
  345. }
  346. sf, err := os.Open(src)
  347. if err != nil {
  348. return 0, err
  349. }
  350. defer sf.Close()
  351. if err := os.Remove(dst); err != nil && !os.IsNotExist(err) {
  352. return 0, err
  353. }
  354. df, err := os.Create(dst)
  355. if err != nil {
  356. return 0, err
  357. }
  358. defer df.Close()
  359. return io.Copy(df, sf)
  360. }
  361. // ReplaceOrAppendValues returns the defaults with the overrides either
  362. // replaced by env key or appended to the list
  363. func ReplaceOrAppendEnvValues(defaults, overrides []string) []string {
  364. cache := make(map[string]int, len(defaults))
  365. for i, e := range defaults {
  366. parts := strings.SplitN(e, "=", 2)
  367. cache[parts[0]] = i
  368. }
  369. for _, value := range overrides {
  370. parts := strings.SplitN(value, "=", 2)
  371. if i, exists := cache[parts[0]]; exists {
  372. defaults[i] = value
  373. } else {
  374. defaults = append(defaults, value)
  375. }
  376. }
  377. return defaults
  378. }
  379. // ReadSymlinkedDirectory returns the target directory of a symlink.
  380. // The target of the symbolic link may not be a file.
  381. func ReadSymlinkedDirectory(path string) (string, error) {
  382. var realPath string
  383. var err error
  384. if realPath, err = filepath.Abs(path); err != nil {
  385. return "", fmt.Errorf("unable to get absolute path for %s: %s", path, err)
  386. }
  387. if realPath, err = filepath.EvalSymlinks(realPath); err != nil {
  388. return "", fmt.Errorf("failed to canonicalise path for %s: %s", path, err)
  389. }
  390. realPathInfo, err := os.Stat(realPath)
  391. if err != nil {
  392. return "", fmt.Errorf("failed to stat target '%s' of '%s': %s", realPath, path, err)
  393. }
  394. if !realPathInfo.Mode().IsDir() {
  395. return "", fmt.Errorf("canonical path points to a file '%s'", realPath)
  396. }
  397. return realPath, nil
  398. }
  399. // ValidateContextDirectory checks if all the contents of the directory
  400. // can be read and returns an error if some files can't be read
  401. // symlinks which point to non-existing files don't trigger an error
  402. func ValidateContextDirectory(srcPath string, excludes []string) error {
  403. return filepath.Walk(filepath.Join(srcPath, "."), func(filePath string, f os.FileInfo, err error) error {
  404. // skip this directory/file if it's not in the path, it won't get added to the context
  405. if relFilePath, err := filepath.Rel(srcPath, filePath); err != nil {
  406. return err
  407. } else if skip, err := fileutils.Matches(relFilePath, excludes); err != nil {
  408. return err
  409. } else if skip {
  410. if f.IsDir() {
  411. return filepath.SkipDir
  412. }
  413. return nil
  414. }
  415. if err != nil {
  416. if os.IsPermission(err) {
  417. return fmt.Errorf("can't stat '%s'", filePath)
  418. }
  419. if os.IsNotExist(err) {
  420. return nil
  421. }
  422. return err
  423. }
  424. // skip checking if symlinks point to non-existing files, such symlinks can be useful
  425. // also skip named pipes, because they hanging on open
  426. if f.Mode()&(os.ModeSymlink|os.ModeNamedPipe) != 0 {
  427. return nil
  428. }
  429. if !f.IsDir() {
  430. currentFile, err := os.Open(filePath)
  431. if err != nil && os.IsPermission(err) {
  432. return fmt.Errorf("no permission to read from '%s'", filePath)
  433. }
  434. currentFile.Close()
  435. }
  436. return nil
  437. })
  438. }
  439. func StringsContainsNoCase(slice []string, s string) bool {
  440. for _, ss := range slice {
  441. if strings.ToLower(s) == strings.ToLower(ss) {
  442. return true
  443. }
  444. }
  445. return false
  446. }
  447. // Reads a .dockerignore file and returns the list of file patterns
  448. // to ignore. Note this will trim whitespace from each line as well
  449. // as use GO's "clean" func to get the shortest/cleanest path for each.
  450. func ReadDockerIgnore(path string) ([]string, error) {
  451. // Note that a missing .dockerignore file isn't treated as an error
  452. reader, err := os.Open(path)
  453. if err != nil {
  454. if !os.IsNotExist(err) {
  455. return nil, fmt.Errorf("Error reading '%s': %v", path, err)
  456. }
  457. return nil, nil
  458. }
  459. defer reader.Close()
  460. scanner := bufio.NewScanner(reader)
  461. var excludes []string
  462. for scanner.Scan() {
  463. pattern := strings.TrimSpace(scanner.Text())
  464. if pattern == "" {
  465. continue
  466. }
  467. pattern = filepath.Clean(pattern)
  468. excludes = append(excludes, pattern)
  469. }
  470. if err = scanner.Err(); err != nil {
  471. return nil, fmt.Errorf("Error reading '%s': %v", path, err)
  472. }
  473. return excludes, nil
  474. }