utils.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. package utils
  2. import (
  3. "crypto/sha1"
  4. "encoding/hex"
  5. "fmt"
  6. "io"
  7. "io/ioutil"
  8. "os"
  9. "os/exec"
  10. "path/filepath"
  11. "runtime"
  12. "strings"
  13. "github.com/docker/distribution/registry/api/errcode"
  14. "github.com/docker/docker/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.GenerateNonCryptoID()[: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. contextRoot, err := getContextRoot(srcPath)
  186. if err != nil {
  187. return err
  188. }
  189. return filepath.Walk(contextRoot, func(filePath string, f os.FileInfo, err error) error {
  190. // skip this directory/file if it's not in the path, it won't get added to the context
  191. if relFilePath, err := filepath.Rel(contextRoot, filePath); err != nil {
  192. return err
  193. } else if skip, err := fileutils.Matches(relFilePath, excludes); err != nil {
  194. return err
  195. } else if skip {
  196. if f.IsDir() {
  197. return filepath.SkipDir
  198. }
  199. return nil
  200. }
  201. if err != nil {
  202. if os.IsPermission(err) {
  203. return fmt.Errorf("can't stat '%s'", filePath)
  204. }
  205. if os.IsNotExist(err) {
  206. return nil
  207. }
  208. return err
  209. }
  210. // skip checking if symlinks point to non-existing files, such symlinks can be useful
  211. // also skip named pipes, because they hanging on open
  212. if f.Mode()&(os.ModeSymlink|os.ModeNamedPipe) != 0 {
  213. return nil
  214. }
  215. if !f.IsDir() {
  216. currentFile, err := os.Open(filePath)
  217. if err != nil && os.IsPermission(err) {
  218. return fmt.Errorf("no permission to read from '%s'", filePath)
  219. }
  220. currentFile.Close()
  221. }
  222. return nil
  223. })
  224. }
  225. // GetErrorMessage returns the human readable message associated with
  226. // the passed-in error. In some cases the default Error() func returns
  227. // something that is less than useful so based on its types this func
  228. // will go and get a better piece of text.
  229. func GetErrorMessage(err error) string {
  230. switch err.(type) {
  231. case errcode.Error:
  232. e, _ := err.(errcode.Error)
  233. return e.Message
  234. case errcode.ErrorCode:
  235. ec, _ := err.(errcode.ErrorCode)
  236. return ec.Message()
  237. default:
  238. return err.Error()
  239. }
  240. }