utils.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. package utils
  2. import (
  3. "bufio"
  4. "crypto/sha1"
  5. "encoding/hex"
  6. "fmt"
  7. "io"
  8. "io/ioutil"
  9. "os"
  10. "os/exec"
  11. "path/filepath"
  12. "runtime"
  13. "strings"
  14. "github.com/docker/docker/autogen/dockerversion"
  15. "github.com/docker/docker/pkg/archive"
  16. "github.com/docker/docker/pkg/fileutils"
  17. "github.com/docker/docker/pkg/stringid"
  18. )
  19. // SelfPath figures out the absolute path of our own binary (if it's still around).
  20. func SelfPath() string {
  21. path, err := exec.LookPath(os.Args[0])
  22. if err != nil {
  23. if os.IsNotExist(err) {
  24. return ""
  25. }
  26. if execErr, ok := err.(*exec.Error); ok && os.IsNotExist(execErr.Err) {
  27. return ""
  28. }
  29. panic(err)
  30. }
  31. path, err = filepath.Abs(path)
  32. if err != nil {
  33. if os.IsNotExist(err) {
  34. return ""
  35. }
  36. panic(err)
  37. }
  38. return path
  39. }
  40. func dockerInitSha1(target string) string {
  41. f, err := os.Open(target)
  42. if err != nil {
  43. return ""
  44. }
  45. defer f.Close()
  46. h := sha1.New()
  47. _, err = io.Copy(h, f)
  48. if err != nil {
  49. return ""
  50. }
  51. return hex.EncodeToString(h.Sum(nil))
  52. }
  53. func isValidDockerInitPath(target string, selfPath string) bool { // target and selfPath should be absolute (InitPath and SelfPath already do this)
  54. if target == "" {
  55. return false
  56. }
  57. if dockerversion.IAMSTATIC == "true" {
  58. if selfPath == "" {
  59. return false
  60. }
  61. if target == selfPath {
  62. return true
  63. }
  64. targetFileInfo, err := os.Lstat(target)
  65. if err != nil {
  66. return false
  67. }
  68. selfPathFileInfo, err := os.Lstat(selfPath)
  69. if err != nil {
  70. return false
  71. }
  72. return os.SameFile(targetFileInfo, selfPathFileInfo)
  73. }
  74. return dockerversion.INITSHA1 != "" && dockerInitSha1(target) == dockerversion.INITSHA1
  75. }
  76. // DockerInitPath figures out the path of our dockerinit (which may be SelfPath())
  77. func DockerInitPath(localCopy string) string {
  78. selfPath := SelfPath()
  79. if isValidDockerInitPath(selfPath, selfPath) {
  80. // if we're valid, don't bother checking anything else
  81. return selfPath
  82. }
  83. var possibleInits = []string{
  84. localCopy,
  85. dockerversion.INITPATH,
  86. filepath.Join(filepath.Dir(selfPath), "dockerinit"),
  87. // 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."
  88. // https://www.linuxbase.org/betaspecs/fhs/fhs.html#usrlibexec
  89. "/usr/libexec/docker/dockerinit",
  90. "/usr/local/libexec/docker/dockerinit",
  91. // 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."
  92. // https://refspecs.linuxfoundation.org/FHS_2.3/fhs-2.3.html#USRLIBLIBRARIESFORPROGRAMMINGANDPA
  93. "/usr/lib/docker/dockerinit",
  94. "/usr/local/lib/docker/dockerinit",
  95. }
  96. for _, dockerInit := range possibleInits {
  97. if dockerInit == "" {
  98. continue
  99. }
  100. path, err := exec.LookPath(dockerInit)
  101. if err == nil {
  102. path, err = filepath.Abs(path)
  103. if err != nil {
  104. // LookPath already validated that this file exists and is executable (following symlinks), so how could Abs fail?
  105. panic(err)
  106. }
  107. if isValidDockerInitPath(path, selfPath) {
  108. return path
  109. }
  110. }
  111. }
  112. return ""
  113. }
  114. var globalTestID string
  115. // TestDirectory creates a new temporary directory and returns its path.
  116. // The contents of directory at path `templateDir` is copied into the
  117. // new directory.
  118. func TestDirectory(templateDir string) (dir string, err error) {
  119. if globalTestID == "" {
  120. globalTestID = stringid.GenerateRandomID()[:4]
  121. }
  122. prefix := fmt.Sprintf("docker-test%s-%s-", globalTestID, GetCallerName(2))
  123. if prefix == "" {
  124. prefix = "docker-test-"
  125. }
  126. dir, err = ioutil.TempDir("", prefix)
  127. if err = os.Remove(dir); err != nil {
  128. return
  129. }
  130. if templateDir != "" {
  131. if err = archive.CopyWithTar(templateDir, dir); err != nil {
  132. return
  133. }
  134. }
  135. return
  136. }
  137. // GetCallerName introspects the call stack and returns the name of the
  138. // function `depth` levels down in the stack.
  139. func GetCallerName(depth int) string {
  140. // Use the caller function name as a prefix.
  141. // This helps trace temp directories back to their test.
  142. pc, _, _, _ := runtime.Caller(depth + 1)
  143. callerLongName := runtime.FuncForPC(pc).Name()
  144. parts := strings.Split(callerLongName, ".")
  145. callerShortName := parts[len(parts)-1]
  146. return callerShortName
  147. }
  148. // ReplaceOrAppendEnvValues returns the defaults with the overrides either
  149. // replaced by env key or appended to the list
  150. func ReplaceOrAppendEnvValues(defaults, overrides []string) []string {
  151. cache := make(map[string]int, len(defaults))
  152. for i, e := range defaults {
  153. parts := strings.SplitN(e, "=", 2)
  154. cache[parts[0]] = i
  155. }
  156. for _, value := range overrides {
  157. // Values w/o = means they want this env to be removed/unset.
  158. if !strings.Contains(value, "=") {
  159. if i, exists := cache[value]; exists {
  160. defaults[i] = "" // Used to indicate it should be removed
  161. }
  162. continue
  163. }
  164. // Just do a normal set/update
  165. parts := strings.SplitN(value, "=", 2)
  166. if i, exists := cache[parts[0]]; exists {
  167. defaults[i] = value
  168. } else {
  169. defaults = append(defaults, value)
  170. }
  171. }
  172. // Now remove all entries that we want to "unset"
  173. for i := 0; i < len(defaults); i++ {
  174. if defaults[i] == "" {
  175. defaults = append(defaults[:i], defaults[i+1:]...)
  176. i--
  177. }
  178. }
  179. return defaults
  180. }
  181. // ValidateContextDirectory checks if all the contents of the directory
  182. // can be read and returns an error if some files can't be read
  183. // symlinks which point to non-existing files don't trigger an error
  184. func ValidateContextDirectory(srcPath string, excludes []string) error {
  185. return filepath.Walk(filepath.Join(srcPath, "."), func(filePath string, f os.FileInfo, err error) error {
  186. // skip this directory/file if it's not in the path, it won't get added to the context
  187. if relFilePath, err := filepath.Rel(srcPath, filePath); err != nil {
  188. return err
  189. } else if skip, err := fileutils.Matches(relFilePath, excludes); err != nil {
  190. return err
  191. } else if skip {
  192. if f.IsDir() {
  193. return filepath.SkipDir
  194. }
  195. return nil
  196. }
  197. if err != nil {
  198. if os.IsPermission(err) {
  199. return fmt.Errorf("can't stat '%s'", filePath)
  200. }
  201. if os.IsNotExist(err) {
  202. return nil
  203. }
  204. return err
  205. }
  206. // skip checking if symlinks point to non-existing files, such symlinks can be useful
  207. // also skip named pipes, because they hanging on open
  208. if f.Mode()&(os.ModeSymlink|os.ModeNamedPipe) != 0 {
  209. return nil
  210. }
  211. if !f.IsDir() {
  212. currentFile, err := os.Open(filePath)
  213. if err != nil && os.IsPermission(err) {
  214. return fmt.Errorf("no permission to read from '%s'", filePath)
  215. }
  216. currentFile.Close()
  217. }
  218. return nil
  219. })
  220. }
  221. // ReadDockerIgnore reads a .dockerignore file and returns the list of file patterns
  222. // to ignore. Note this will trim whitespace from each line as well
  223. // as use GO's "clean" func to get the shortest/cleanest path for each.
  224. func ReadDockerIgnore(path string) ([]string, error) {
  225. // Note that a missing .dockerignore file isn't treated as an error
  226. reader, err := os.Open(path)
  227. if err != nil {
  228. if !os.IsNotExist(err) {
  229. return nil, fmt.Errorf("Error reading '%s': %v", path, err)
  230. }
  231. return nil, nil
  232. }
  233. defer reader.Close()
  234. scanner := bufio.NewScanner(reader)
  235. var excludes []string
  236. for scanner.Scan() {
  237. pattern := strings.TrimSpace(scanner.Text())
  238. if pattern == "" {
  239. continue
  240. }
  241. pattern = filepath.Clean(pattern)
  242. excludes = append(excludes, pattern)
  243. }
  244. if err = scanner.Err(); err != nil {
  245. return nil, fmt.Errorf("Error reading '%s': %v", path, err)
  246. }
  247. return excludes, nil
  248. }
  249. // ImageReference combines `repo` and `ref` and returns a string representing
  250. // the combination. If `ref` is a digest (meaning it's of the form
  251. // <algorithm>:<digest>, the returned string is <repo>@<ref>. Otherwise,
  252. // ref is assumed to be a tag, and the returned string is <repo>:<tag>.
  253. func ImageReference(repo, ref string) string {
  254. if DigestReference(ref) {
  255. return repo + "@" + ref
  256. }
  257. return repo + ":" + ref
  258. }
  259. // DigestReference returns true if ref is a digest reference; i.e. if it
  260. // is of the form <algorithm>:<digest>.
  261. func DigestReference(ref string) bool {
  262. return strings.Contains(ref, ":")
  263. }