utils.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  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. log "github.com/Sirupsen/logrus"
  21. "github.com/docker/docker/dockerversion"
  22. "github.com/docker/docker/pkg/archive"
  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. var (
  31. validHex = regexp.MustCompile(`^([a-f0-9]{64})$`)
  32. )
  33. // Request a given URL and return an io.Reader
  34. func Download(url string) (resp *http.Response, err error) {
  35. if resp, err = http.Get(url); err != nil {
  36. return nil, err
  37. }
  38. if resp.StatusCode >= 400 {
  39. return nil, fmt.Errorf("Got HTTP status code >= 400: %s", resp.Status)
  40. }
  41. return resp, nil
  42. }
  43. func Trunc(s string, maxlen int) string {
  44. if len(s) <= maxlen {
  45. return s
  46. }
  47. return s[:maxlen]
  48. }
  49. // Figure out the absolute path of our own binary (if it's still around).
  50. func SelfPath() string {
  51. path, err := exec.LookPath(os.Args[0])
  52. if err != nil {
  53. if os.IsNotExist(err) {
  54. return ""
  55. }
  56. if execErr, ok := err.(*exec.Error); ok && os.IsNotExist(execErr.Err) {
  57. return ""
  58. }
  59. panic(err)
  60. }
  61. path, err = filepath.Abs(path)
  62. if err != nil {
  63. if os.IsNotExist(err) {
  64. return ""
  65. }
  66. panic(err)
  67. }
  68. return path
  69. }
  70. func dockerInitSha1(target string) string {
  71. f, err := os.Open(target)
  72. if err != nil {
  73. return ""
  74. }
  75. defer f.Close()
  76. h := sha1.New()
  77. _, err = io.Copy(h, f)
  78. if err != nil {
  79. return ""
  80. }
  81. return hex.EncodeToString(h.Sum(nil))
  82. }
  83. func isValidDockerInitPath(target string, selfPath string) bool { // target and selfPath should be absolute (InitPath and SelfPath already do this)
  84. if target == "" {
  85. return false
  86. }
  87. if dockerversion.IAMSTATIC {
  88. if selfPath == "" {
  89. return false
  90. }
  91. if target == selfPath {
  92. return true
  93. }
  94. targetFileInfo, err := os.Lstat(target)
  95. if err != nil {
  96. return false
  97. }
  98. selfPathFileInfo, err := os.Lstat(selfPath)
  99. if err != nil {
  100. return false
  101. }
  102. return os.SameFile(targetFileInfo, selfPathFileInfo)
  103. }
  104. return dockerversion.INITSHA1 != "" && dockerInitSha1(target) == dockerversion.INITSHA1
  105. }
  106. // Figure out the path of our dockerinit (which may be SelfPath())
  107. func DockerInitPath(localCopy string) string {
  108. selfPath := SelfPath()
  109. if isValidDockerInitPath(selfPath, selfPath) {
  110. // if we're valid, don't bother checking anything else
  111. return selfPath
  112. }
  113. var possibleInits = []string{
  114. localCopy,
  115. dockerversion.INITPATH,
  116. filepath.Join(filepath.Dir(selfPath), "dockerinit"),
  117. // 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."
  118. // http://www.linuxbase.org/betaspecs/fhs/fhs.html#usrlibexec
  119. "/usr/libexec/docker/dockerinit",
  120. "/usr/local/libexec/docker/dockerinit",
  121. // 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."
  122. // http://refspecs.linuxfoundation.org/FHS_2.3/fhs-2.3.html#USRLIBLIBRARIESFORPROGRAMMINGANDPA
  123. "/usr/lib/docker/dockerinit",
  124. "/usr/local/lib/docker/dockerinit",
  125. }
  126. for _, dockerInit := range possibleInits {
  127. if dockerInit == "" {
  128. continue
  129. }
  130. path, err := exec.LookPath(dockerInit)
  131. if err == nil {
  132. path, err = filepath.Abs(path)
  133. if err != nil {
  134. // LookPath already validated that this file exists and is executable (following symlinks), so how could Abs fail?
  135. panic(err)
  136. }
  137. if isValidDockerInitPath(path, selfPath) {
  138. return path
  139. }
  140. }
  141. }
  142. return ""
  143. }
  144. func GetTotalUsedFds() int {
  145. if fds, err := ioutil.ReadDir(fmt.Sprintf("/proc/%d/fd", os.Getpid())); err != nil {
  146. log.Errorf("Error opening /proc/%d/fd: %s", os.Getpid(), err)
  147. } else {
  148. return len(fds)
  149. }
  150. return -1
  151. }
  152. // TruncateID returns a shorthand version of a string identifier for convenience.
  153. // A collision with other shorthands is very unlikely, but possible.
  154. // In case of a collision a lookup with TruncIndex.Get() will fail, and the caller
  155. // will need to use a langer prefix, or the full-length Id.
  156. func TruncateID(id string) string {
  157. shortLen := 12
  158. if len(id) < shortLen {
  159. shortLen = len(id)
  160. }
  161. return id[:shortLen]
  162. }
  163. // GenerateRandomID returns an unique id
  164. func GenerateRandomID() string {
  165. for {
  166. id := make([]byte, 32)
  167. if _, err := io.ReadFull(rand.Reader, id); err != nil {
  168. panic(err) // This shouldn't happen
  169. }
  170. value := hex.EncodeToString(id)
  171. // if we try to parse the truncated for as an int and we don't have
  172. // an error then the value is all numberic and causes issues when
  173. // used as a hostname. ref #3869
  174. if _, err := strconv.ParseInt(TruncateID(value), 10, 64); err == nil {
  175. continue
  176. }
  177. return value
  178. }
  179. }
  180. func ValidateID(id string) error {
  181. if ok := validHex.MatchString(id); !ok {
  182. err := fmt.Errorf("image ID '%s' is invalid", id)
  183. return err
  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. // An StatusError reports an unsuccessful exit by a command.
  270. type StatusError struct {
  271. Status string
  272. StatusCode int
  273. }
  274. func (e *StatusError) Error() string {
  275. return fmt.Sprintf("Status: %s, Code: %d", e.Status, e.StatusCode)
  276. }
  277. func quote(word string, buf *bytes.Buffer) {
  278. // Bail out early for "simple" strings
  279. if word != "" && !strings.ContainsAny(word, "\\'\"`${[|&;<>()~*?! \t\n") {
  280. buf.WriteString(word)
  281. return
  282. }
  283. buf.WriteString("'")
  284. for i := 0; i < len(word); i++ {
  285. b := word[i]
  286. if b == '\'' {
  287. // Replace literal ' with a close ', a \', and a open '
  288. buf.WriteString("'\\''")
  289. } else {
  290. buf.WriteByte(b)
  291. }
  292. }
  293. buf.WriteString("'")
  294. }
  295. // Take a list of strings and escape them so they will be handled right
  296. // when passed as arguments to an program via a shell
  297. func ShellQuoteArguments(args []string) string {
  298. var buf bytes.Buffer
  299. for i, arg := range args {
  300. if i != 0 {
  301. buf.WriteByte(' ')
  302. }
  303. quote(arg, &buf)
  304. }
  305. return buf.String()
  306. }
  307. var globalTestID string
  308. // TestDirectory creates a new temporary directory and returns its path.
  309. // The contents of directory at path `templateDir` is copied into the
  310. // new directory.
  311. func TestDirectory(templateDir string) (dir string, err error) {
  312. if globalTestID == "" {
  313. globalTestID = RandomString()[:4]
  314. }
  315. prefix := fmt.Sprintf("docker-test%s-%s-", globalTestID, GetCallerName(2))
  316. if prefix == "" {
  317. prefix = "docker-test-"
  318. }
  319. dir, err = ioutil.TempDir("", prefix)
  320. if err = os.Remove(dir); err != nil {
  321. return
  322. }
  323. if templateDir != "" {
  324. if err = archive.CopyWithTar(templateDir, dir); err != nil {
  325. return
  326. }
  327. }
  328. return
  329. }
  330. // GetCallerName introspects the call stack and returns the name of the
  331. // function `depth` levels down in the stack.
  332. func GetCallerName(depth int) string {
  333. // Use the caller function name as a prefix.
  334. // This helps trace temp directories back to their test.
  335. pc, _, _, _ := runtime.Caller(depth + 1)
  336. callerLongName := runtime.FuncForPC(pc).Name()
  337. parts := strings.Split(callerLongName, ".")
  338. callerShortName := parts[len(parts)-1]
  339. return callerShortName
  340. }
  341. func CopyFile(src, dst string) (int64, error) {
  342. if src == dst {
  343. return 0, nil
  344. }
  345. sf, err := os.Open(src)
  346. if err != nil {
  347. return 0, err
  348. }
  349. defer sf.Close()
  350. if err := os.Remove(dst); err != nil && !os.IsNotExist(err) {
  351. return 0, err
  352. }
  353. df, err := os.Create(dst)
  354. if err != nil {
  355. return 0, err
  356. }
  357. defer df.Close()
  358. return io.Copy(df, sf)
  359. }
  360. // ReplaceOrAppendValues returns the defaults with the overrides either
  361. // replaced by env key or appended to the list
  362. func ReplaceOrAppendEnvValues(defaults, overrides []string) []string {
  363. cache := make(map[string]int, len(defaults))
  364. for i, e := range defaults {
  365. parts := strings.SplitN(e, "=", 2)
  366. cache[parts[0]] = i
  367. }
  368. for _, value := range overrides {
  369. parts := strings.SplitN(value, "=", 2)
  370. if i, exists := cache[parts[0]]; exists {
  371. defaults[i] = value
  372. } else {
  373. defaults = append(defaults, value)
  374. }
  375. }
  376. return defaults
  377. }
  378. // ReadSymlinkedDirectory returns the target directory of a symlink.
  379. // The target of the symbolic link may not be a file.
  380. func ReadSymlinkedDirectory(path string) (string, error) {
  381. var realPath string
  382. var err error
  383. if realPath, err = filepath.Abs(path); err != nil {
  384. return "", fmt.Errorf("unable to get absolute path for %s: %s", path, err)
  385. }
  386. if realPath, err = filepath.EvalSymlinks(realPath); err != nil {
  387. return "", fmt.Errorf("failed to canonicalise path for %s: %s", path, err)
  388. }
  389. realPathInfo, err := os.Stat(realPath)
  390. if err != nil {
  391. return "", fmt.Errorf("failed to stat target '%s' of '%s': %s", realPath, path, err)
  392. }
  393. if !realPathInfo.Mode().IsDir() {
  394. return "", fmt.Errorf("canonical path points to a file '%s'", realPath)
  395. }
  396. return realPath, nil
  397. }
  398. // ValidateContextDirectory checks if all the contents of the directory
  399. // can be read and returns an error if some files can't be read
  400. // symlinks which point to non-existing files don't trigger an error
  401. func ValidateContextDirectory(srcPath string, excludes []string) error {
  402. return filepath.Walk(filepath.Join(srcPath, "."), func(filePath string, f os.FileInfo, err error) error {
  403. // skip this directory/file if it's not in the path, it won't get added to the context
  404. if relFilePath, err := filepath.Rel(srcPath, filePath); err != nil {
  405. return err
  406. } else if skip, err := fileutils.Matches(relFilePath, excludes); err != nil {
  407. return err
  408. } else if skip {
  409. if f.IsDir() {
  410. return filepath.SkipDir
  411. }
  412. return nil
  413. }
  414. if err != nil {
  415. if os.IsPermission(err) {
  416. return fmt.Errorf("can't stat '%s'", filePath)
  417. }
  418. if os.IsNotExist(err) {
  419. return nil
  420. }
  421. return err
  422. }
  423. // skip checking if symlinks point to non-existing files, such symlinks can be useful
  424. // also skip named pipes, because they hanging on open
  425. if f.Mode()&(os.ModeSymlink|os.ModeNamedPipe) != 0 {
  426. return nil
  427. }
  428. if !f.IsDir() {
  429. currentFile, err := os.Open(filePath)
  430. if err != nil && os.IsPermission(err) {
  431. return fmt.Errorf("no permission to read from '%s'", filePath)
  432. }
  433. currentFile.Close()
  434. }
  435. return nil
  436. })
  437. }
  438. func StringsContainsNoCase(slice []string, s string) bool {
  439. for _, ss := range slice {
  440. if strings.ToLower(s) == strings.ToLower(ss) {
  441. return true
  442. }
  443. }
  444. return false
  445. }