utils.go 8.7 KB

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