utils.go 13 KB

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