utils.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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. flushed bool
  123. }
  124. func (wf *WriteFlusher) Write(b []byte) (n int, err error) {
  125. wf.Lock()
  126. defer wf.Unlock()
  127. n, err = wf.w.Write(b)
  128. wf.flushed = true
  129. wf.flusher.Flush()
  130. return n, err
  131. }
  132. // Flush the stream immediately.
  133. func (wf *WriteFlusher) Flush() {
  134. wf.Lock()
  135. defer wf.Unlock()
  136. wf.flushed = true
  137. wf.flusher.Flush()
  138. }
  139. func (wf *WriteFlusher) Flushed() bool {
  140. wf.Lock()
  141. defer wf.Unlock()
  142. return wf.flushed
  143. }
  144. func NewWriteFlusher(w io.Writer) *WriteFlusher {
  145. var flusher http.Flusher
  146. if f, ok := w.(http.Flusher); ok {
  147. flusher = f
  148. } else {
  149. flusher = &ioutils.NopFlusher{}
  150. }
  151. return &WriteFlusher{w: w, flusher: flusher}
  152. }
  153. var globalTestID string
  154. // TestDirectory creates a new temporary directory and returns its path.
  155. // The contents of directory at path `templateDir` is copied into the
  156. // new directory.
  157. func TestDirectory(templateDir string) (dir string, err error) {
  158. if globalTestID == "" {
  159. globalTestID = stringid.GenerateRandomID()[:4]
  160. }
  161. prefix := fmt.Sprintf("docker-test%s-%s-", globalTestID, GetCallerName(2))
  162. if prefix == "" {
  163. prefix = "docker-test-"
  164. }
  165. dir, err = ioutil.TempDir("", prefix)
  166. if err = os.Remove(dir); err != nil {
  167. return
  168. }
  169. if templateDir != "" {
  170. if err = archive.CopyWithTar(templateDir, dir); err != nil {
  171. return
  172. }
  173. }
  174. return
  175. }
  176. // GetCallerName introspects the call stack and returns the name of the
  177. // function `depth` levels down in the stack.
  178. func GetCallerName(depth int) string {
  179. // Use the caller function name as a prefix.
  180. // This helps trace temp directories back to their test.
  181. pc, _, _, _ := runtime.Caller(depth + 1)
  182. callerLongName := runtime.FuncForPC(pc).Name()
  183. parts := strings.Split(callerLongName, ".")
  184. callerShortName := parts[len(parts)-1]
  185. return callerShortName
  186. }
  187. // ReplaceOrAppendValues returns the defaults with the overrides either
  188. // replaced by env key or appended to the list
  189. func ReplaceOrAppendEnvValues(defaults, overrides []string) []string {
  190. cache := make(map[string]int, len(defaults))
  191. for i, e := range defaults {
  192. parts := strings.SplitN(e, "=", 2)
  193. cache[parts[0]] = i
  194. }
  195. for _, value := range overrides {
  196. // Values w/o = means they want this env to be removed/unset.
  197. if !strings.Contains(value, "=") {
  198. if i, exists := cache[value]; exists {
  199. defaults[i] = "" // Used to indicate it should be removed
  200. }
  201. continue
  202. }
  203. // Just do a normal set/update
  204. parts := strings.SplitN(value, "=", 2)
  205. if i, exists := cache[parts[0]]; exists {
  206. defaults[i] = value
  207. } else {
  208. defaults = append(defaults, value)
  209. }
  210. }
  211. // Now remove all entries that we want to "unset"
  212. for i := 0; i < len(defaults); i++ {
  213. if defaults[i] == "" {
  214. defaults = append(defaults[:i], defaults[i+1:]...)
  215. i--
  216. }
  217. }
  218. return defaults
  219. }
  220. func DoesEnvExist(name string) bool {
  221. for _, entry := range os.Environ() {
  222. parts := strings.SplitN(entry, "=", 2)
  223. if parts[0] == name {
  224. return true
  225. }
  226. }
  227. return false
  228. }
  229. // ValidateContextDirectory checks if all the contents of the directory
  230. // can be read and returns an error if some files can't be read
  231. // symlinks which point to non-existing files don't trigger an error
  232. func ValidateContextDirectory(srcPath string, excludes []string) error {
  233. return filepath.Walk(filepath.Join(srcPath, "."), func(filePath string, f os.FileInfo, err error) error {
  234. // skip this directory/file if it's not in the path, it won't get added to the context
  235. if relFilePath, err := filepath.Rel(srcPath, filePath); err != nil {
  236. return err
  237. } else if skip, err := fileutils.Matches(relFilePath, excludes); err != nil {
  238. return err
  239. } else if skip {
  240. if f.IsDir() {
  241. return filepath.SkipDir
  242. }
  243. return nil
  244. }
  245. if err != nil {
  246. if os.IsPermission(err) {
  247. return fmt.Errorf("can't stat '%s'", filePath)
  248. }
  249. if os.IsNotExist(err) {
  250. return nil
  251. }
  252. return err
  253. }
  254. // skip checking if symlinks point to non-existing files, such symlinks can be useful
  255. // also skip named pipes, because they hanging on open
  256. if f.Mode()&(os.ModeSymlink|os.ModeNamedPipe) != 0 {
  257. return nil
  258. }
  259. if !f.IsDir() {
  260. currentFile, err := os.Open(filePath)
  261. if err != nil && os.IsPermission(err) {
  262. return fmt.Errorf("no permission to read from '%s'", filePath)
  263. }
  264. currentFile.Close()
  265. }
  266. return nil
  267. })
  268. }
  269. // Reads a .dockerignore file and returns the list of file patterns
  270. // to ignore. Note this will trim whitespace from each line as well
  271. // as use GO's "clean" func to get the shortest/cleanest path for each.
  272. func ReadDockerIgnore(path string) ([]string, error) {
  273. // Note that a missing .dockerignore file isn't treated as an error
  274. reader, err := os.Open(path)
  275. if err != nil {
  276. if !os.IsNotExist(err) {
  277. return nil, fmt.Errorf("Error reading '%s': %v", path, err)
  278. }
  279. return nil, nil
  280. }
  281. defer reader.Close()
  282. scanner := bufio.NewScanner(reader)
  283. var excludes []string
  284. for scanner.Scan() {
  285. pattern := strings.TrimSpace(scanner.Text())
  286. if pattern == "" {
  287. continue
  288. }
  289. pattern = filepath.Clean(pattern)
  290. excludes = append(excludes, pattern)
  291. }
  292. if err = scanner.Err(); err != nil {
  293. return nil, fmt.Errorf("Error reading '%s': %v", path, err)
  294. }
  295. return excludes, nil
  296. }
  297. // ImageReference combines `repo` and `ref` and returns a string representing
  298. // the combination. If `ref` is a digest (meaning it's of the form
  299. // <algorithm>:<digest>, the returned string is <repo>@<ref>. Otherwise,
  300. // ref is assumed to be a tag, and the returned string is <repo>:<tag>.
  301. func ImageReference(repo, ref string) string {
  302. if DigestReference(ref) {
  303. return repo + "@" + ref
  304. }
  305. return repo + ":" + ref
  306. }
  307. // DigestReference returns true if ref is a digest reference; i.e. if it
  308. // is of the form <algorithm>:<digest>.
  309. func DigestReference(ref string) bool {
  310. return strings.Contains(ref, ":")
  311. }