utils.go 12 KB

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