utils.go 13 KB

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