utils.go 12 KB

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