utils.go 13 KB

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