utils.go 12 KB

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