utils.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995
  1. package utils
  2. import (
  3. "bytes"
  4. "crypto/rand"
  5. "crypto/sha1"
  6. "crypto/sha256"
  7. "encoding/hex"
  8. "encoding/json"
  9. "errors"
  10. "fmt"
  11. "io"
  12. "io/ioutil"
  13. "net/http"
  14. "os"
  15. "os/exec"
  16. "path/filepath"
  17. "runtime"
  18. "strconv"
  19. "strings"
  20. "sync"
  21. "syscall"
  22. "time"
  23. "github.com/dotcloud/docker/dockerversion"
  24. )
  25. type KeyValuePair struct {
  26. Key string
  27. Value string
  28. }
  29. // A common interface to access the Fatal method of
  30. // both testing.B and testing.T.
  31. type Fataler interface {
  32. Fatal(args ...interface{})
  33. }
  34. // Go is a basic promise implementation: it wraps calls a function in a goroutine,
  35. // and returns a channel which will later return the function's return value.
  36. func Go(f func() error) chan error {
  37. ch := make(chan error, 1)
  38. go func() {
  39. ch <- f()
  40. }()
  41. return ch
  42. }
  43. // Request a given URL and return an io.Reader
  44. func Download(url string) (resp *http.Response, err error) {
  45. if resp, err = http.Get(url); err != nil {
  46. return nil, err
  47. }
  48. if resp.StatusCode >= 400 {
  49. return nil, fmt.Errorf("Got HTTP status code >= 400: %s", resp.Status)
  50. }
  51. return resp, nil
  52. }
  53. func logf(level string, format string, a ...interface{}) {
  54. // Retrieve the stack infos
  55. _, file, line, ok := runtime.Caller(2)
  56. if !ok {
  57. file = "<unknown>"
  58. line = -1
  59. } else {
  60. file = file[strings.LastIndex(file, "/")+1:]
  61. }
  62. fmt.Fprintf(os.Stderr, fmt.Sprintf("[%s] %s:%d %s\n", level, file, line, format), a...)
  63. }
  64. // Debug function, if the debug flag is set, then display. Do nothing otherwise
  65. // If Docker is in damon mode, also send the debug info on the socket
  66. func Debugf(format string, a ...interface{}) {
  67. if os.Getenv("DEBUG") != "" {
  68. logf("debug", format, a...)
  69. }
  70. }
  71. func Errorf(format string, a ...interface{}) {
  72. logf("error", format, a...)
  73. }
  74. func Trunc(s string, maxlen int) string {
  75. if len(s) <= maxlen {
  76. return s
  77. }
  78. return s[:maxlen]
  79. }
  80. // Figure out the absolute path of our own binary (if it's still around).
  81. func SelfPath() string {
  82. path, err := exec.LookPath(os.Args[0])
  83. if err != nil {
  84. if os.IsNotExist(err) {
  85. return ""
  86. }
  87. if execErr, ok := err.(*exec.Error); ok && os.IsNotExist(execErr.Err) {
  88. return ""
  89. }
  90. panic(err)
  91. }
  92. path, err = filepath.Abs(path)
  93. if err != nil {
  94. if os.IsNotExist(err) {
  95. return ""
  96. }
  97. panic(err)
  98. }
  99. return path
  100. }
  101. func dockerInitSha1(target string) string {
  102. f, err := os.Open(target)
  103. if err != nil {
  104. return ""
  105. }
  106. defer f.Close()
  107. h := sha1.New()
  108. _, err = io.Copy(h, f)
  109. if err != nil {
  110. return ""
  111. }
  112. return hex.EncodeToString(h.Sum(nil))
  113. }
  114. func isValidDockerInitPath(target string, selfPath string) bool { // target and selfPath should be absolute (InitPath and SelfPath already do this)
  115. if target == "" {
  116. return false
  117. }
  118. if dockerversion.IAMSTATIC {
  119. if selfPath == "" {
  120. return false
  121. }
  122. if target == selfPath {
  123. return true
  124. }
  125. targetFileInfo, err := os.Lstat(target)
  126. if err != nil {
  127. return false
  128. }
  129. selfPathFileInfo, err := os.Lstat(selfPath)
  130. if err != nil {
  131. return false
  132. }
  133. return os.SameFile(targetFileInfo, selfPathFileInfo)
  134. }
  135. return dockerversion.INITSHA1 != "" && dockerInitSha1(target) == dockerversion.INITSHA1
  136. }
  137. // Figure out the path of our dockerinit (which may be SelfPath())
  138. func DockerInitPath(localCopy string) string {
  139. selfPath := SelfPath()
  140. if isValidDockerInitPath(selfPath, selfPath) {
  141. // if we're valid, don't bother checking anything else
  142. return selfPath
  143. }
  144. var possibleInits = []string{
  145. localCopy,
  146. dockerversion.INITPATH,
  147. filepath.Join(filepath.Dir(selfPath), "dockerinit"),
  148. // 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."
  149. // http://www.linuxbase.org/betaspecs/fhs/fhs.html#usrlibexec
  150. "/usr/libexec/docker/dockerinit",
  151. "/usr/local/libexec/docker/dockerinit",
  152. // 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."
  153. // http://refspecs.linuxfoundation.org/FHS_2.3/fhs-2.3.html#USRLIBLIBRARIESFORPROGRAMMINGANDPA
  154. "/usr/lib/docker/dockerinit",
  155. "/usr/local/lib/docker/dockerinit",
  156. }
  157. for _, dockerInit := range possibleInits {
  158. if dockerInit == "" {
  159. continue
  160. }
  161. path, err := exec.LookPath(dockerInit)
  162. if err == nil {
  163. path, err = filepath.Abs(path)
  164. if err != nil {
  165. // LookPath already validated that this file exists and is executable (following symlinks), so how could Abs fail?
  166. panic(err)
  167. }
  168. if isValidDockerInitPath(path, selfPath) {
  169. return path
  170. }
  171. }
  172. }
  173. return ""
  174. }
  175. type NopWriter struct{}
  176. func (*NopWriter) Write(buf []byte) (int, error) {
  177. return len(buf), nil
  178. }
  179. type nopWriteCloser struct {
  180. io.Writer
  181. }
  182. func (w *nopWriteCloser) Close() error { return nil }
  183. func NopWriteCloser(w io.Writer) io.WriteCloser {
  184. return &nopWriteCloser{w}
  185. }
  186. type bufReader struct {
  187. sync.Mutex
  188. buf *bytes.Buffer
  189. reader io.Reader
  190. err error
  191. wait sync.Cond
  192. }
  193. func NewBufReader(r io.Reader) *bufReader {
  194. reader := &bufReader{
  195. buf: &bytes.Buffer{},
  196. reader: r,
  197. }
  198. reader.wait.L = &reader.Mutex
  199. go reader.drain()
  200. return reader
  201. }
  202. func (r *bufReader) drain() {
  203. buf := make([]byte, 1024)
  204. for {
  205. n, err := r.reader.Read(buf)
  206. r.Lock()
  207. if err != nil {
  208. r.err = err
  209. } else {
  210. r.buf.Write(buf[0:n])
  211. }
  212. r.wait.Signal()
  213. r.Unlock()
  214. if err != nil {
  215. break
  216. }
  217. }
  218. }
  219. func (r *bufReader) Read(p []byte) (n int, err error) {
  220. r.Lock()
  221. defer r.Unlock()
  222. for {
  223. n, err = r.buf.Read(p)
  224. if n > 0 {
  225. return n, err
  226. }
  227. if r.err != nil {
  228. return 0, r.err
  229. }
  230. r.wait.Wait()
  231. }
  232. }
  233. func (r *bufReader) Close() error {
  234. closer, ok := r.reader.(io.ReadCloser)
  235. if !ok {
  236. return nil
  237. }
  238. return closer.Close()
  239. }
  240. type WriteBroadcaster struct {
  241. sync.Mutex
  242. buf *bytes.Buffer
  243. streams map[string](map[io.WriteCloser]struct{})
  244. }
  245. func (w *WriteBroadcaster) AddWriter(writer io.WriteCloser, stream string) {
  246. w.Lock()
  247. if _, ok := w.streams[stream]; !ok {
  248. w.streams[stream] = make(map[io.WriteCloser]struct{})
  249. }
  250. w.streams[stream][writer] = struct{}{}
  251. w.Unlock()
  252. }
  253. type JSONLog struct {
  254. Log string `json:"log,omitempty"`
  255. Stream string `json:"stream,omitempty"`
  256. Created time.Time `json:"time"`
  257. }
  258. func (jl *JSONLog) Format(format string) (string, error) {
  259. if format == "" {
  260. return jl.Log, nil
  261. }
  262. if format == "json" {
  263. m, err := json.Marshal(jl)
  264. return string(m), err
  265. }
  266. return fmt.Sprintf("[%s] %s", jl.Created.Format(format), jl.Log), nil
  267. }
  268. func WriteLog(src io.Reader, dst io.WriteCloser, format string) error {
  269. dec := json.NewDecoder(src)
  270. for {
  271. l := &JSONLog{}
  272. if err := dec.Decode(l); err == io.EOF {
  273. return nil
  274. } else if err != nil {
  275. Errorf("Error streaming logs: %s", err)
  276. return err
  277. }
  278. line, err := l.Format(format)
  279. if err != nil {
  280. return err
  281. }
  282. fmt.Fprintf(dst, "%s", line)
  283. }
  284. }
  285. type LogFormatter struct {
  286. wc io.WriteCloser
  287. timeFormat string
  288. }
  289. func (w *WriteBroadcaster) Write(p []byte) (n int, err error) {
  290. created := time.Now().UTC()
  291. w.Lock()
  292. defer w.Unlock()
  293. if writers, ok := w.streams[""]; ok {
  294. for sw := range writers {
  295. if n, err := sw.Write(p); err != nil || n != len(p) {
  296. // On error, evict the writer
  297. delete(writers, sw)
  298. }
  299. }
  300. }
  301. w.buf.Write(p)
  302. lines := []string{}
  303. for {
  304. line, err := w.buf.ReadString('\n')
  305. if err != nil {
  306. w.buf.Write([]byte(line))
  307. break
  308. }
  309. lines = append(lines, line)
  310. }
  311. if len(lines) != 0 {
  312. for stream, writers := range w.streams {
  313. if stream == "" {
  314. continue
  315. }
  316. var lp []byte
  317. for _, line := range lines {
  318. b, err := json.Marshal(&JSONLog{Log: line, Stream: stream, Created: created})
  319. if err != nil {
  320. Errorf("Error making JSON log line: %s", err)
  321. }
  322. lp = append(lp, b...)
  323. lp = append(lp, '\n')
  324. }
  325. for sw := range writers {
  326. if _, err := sw.Write(lp); err != nil {
  327. delete(writers, sw)
  328. }
  329. }
  330. }
  331. }
  332. return len(p), nil
  333. }
  334. func (w *WriteBroadcaster) CloseWriters() error {
  335. w.Lock()
  336. defer w.Unlock()
  337. for _, writers := range w.streams {
  338. for w := range writers {
  339. w.Close()
  340. }
  341. }
  342. w.streams = make(map[string](map[io.WriteCloser]struct{}))
  343. return nil
  344. }
  345. func NewWriteBroadcaster() *WriteBroadcaster {
  346. return &WriteBroadcaster{
  347. streams: make(map[string](map[io.WriteCloser]struct{})),
  348. buf: bytes.NewBuffer(nil),
  349. }
  350. }
  351. func GetTotalUsedFds() int {
  352. if fds, err := ioutil.ReadDir(fmt.Sprintf("/proc/%d/fd", os.Getpid())); err != nil {
  353. Errorf("Error opening /proc/%d/fd: %s", os.Getpid(), err)
  354. } else {
  355. return len(fds)
  356. }
  357. return -1
  358. }
  359. // TruncateID returns a shorthand version of a string identifier for convenience.
  360. // A collision with other shorthands is very unlikely, but possible.
  361. // In case of a collision a lookup with TruncIndex.Get() will fail, and the caller
  362. // will need to use a langer prefix, or the full-length Id.
  363. func TruncateID(id string) string {
  364. shortLen := 12
  365. if len(id) < shortLen {
  366. shortLen = len(id)
  367. }
  368. return id[:shortLen]
  369. }
  370. // GenerateRandomID returns an unique id
  371. func GenerateRandomID() string {
  372. for {
  373. id := make([]byte, 32)
  374. if _, err := io.ReadFull(rand.Reader, id); err != nil {
  375. panic(err) // This shouldn't happen
  376. }
  377. value := hex.EncodeToString(id)
  378. // if we try to parse the truncated for as an int and we don't have
  379. // an error then the value is all numberic and causes issues when
  380. // used as a hostname. ref #3869
  381. if _, err := strconv.ParseInt(TruncateID(value), 10, 64); err == nil {
  382. continue
  383. }
  384. return value
  385. }
  386. }
  387. func ValidateID(id string) error {
  388. if id == "" {
  389. return fmt.Errorf("Id can't be empty")
  390. }
  391. if strings.Contains(id, ":") {
  392. return fmt.Errorf("Invalid character in id: ':'")
  393. }
  394. return nil
  395. }
  396. // Code c/c from io.Copy() modified to handle escape sequence
  397. func CopyEscapable(dst io.Writer, src io.ReadCloser) (written int64, err error) {
  398. buf := make([]byte, 32*1024)
  399. for {
  400. nr, er := src.Read(buf)
  401. if nr > 0 {
  402. // ---- Docker addition
  403. // char 16 is C-p
  404. if nr == 1 && buf[0] == 16 {
  405. nr, er = src.Read(buf)
  406. // char 17 is C-q
  407. if nr == 1 && buf[0] == 17 {
  408. if err := src.Close(); err != nil {
  409. return 0, err
  410. }
  411. return 0, nil
  412. }
  413. }
  414. // ---- End of docker
  415. nw, ew := dst.Write(buf[0:nr])
  416. if nw > 0 {
  417. written += int64(nw)
  418. }
  419. if ew != nil {
  420. err = ew
  421. break
  422. }
  423. if nr != nw {
  424. err = io.ErrShortWrite
  425. break
  426. }
  427. }
  428. if er == io.EOF {
  429. break
  430. }
  431. if er != nil {
  432. err = er
  433. break
  434. }
  435. }
  436. return written, err
  437. }
  438. func HashData(src io.Reader) (string, error) {
  439. h := sha256.New()
  440. if _, err := io.Copy(h, src); err != nil {
  441. return "", err
  442. }
  443. return "sha256:" + hex.EncodeToString(h.Sum(nil)), nil
  444. }
  445. type KernelVersionInfo struct {
  446. Kernel int
  447. Major int
  448. Minor int
  449. Flavor string
  450. }
  451. func (k *KernelVersionInfo) String() string {
  452. return fmt.Sprintf("%d.%d.%d%s", k.Kernel, k.Major, k.Minor, k.Flavor)
  453. }
  454. // Compare two KernelVersionInfo struct.
  455. // Returns -1 if a < b, 0 if a == b, 1 it a > b
  456. func CompareKernelVersion(a, b *KernelVersionInfo) int {
  457. if a.Kernel < b.Kernel {
  458. return -1
  459. } else if a.Kernel > b.Kernel {
  460. return 1
  461. }
  462. if a.Major < b.Major {
  463. return -1
  464. } else if a.Major > b.Major {
  465. return 1
  466. }
  467. if a.Minor < b.Minor {
  468. return -1
  469. } else if a.Minor > b.Minor {
  470. return 1
  471. }
  472. return 0
  473. }
  474. func GetKernelVersion() (*KernelVersionInfo, error) {
  475. var (
  476. err error
  477. )
  478. uts, err := uname()
  479. if err != nil {
  480. return nil, err
  481. }
  482. release := make([]byte, len(uts.Release))
  483. i := 0
  484. for _, c := range uts.Release {
  485. release[i] = byte(c)
  486. i++
  487. }
  488. // Remove the \x00 from the release for Atoi to parse correctly
  489. release = release[:bytes.IndexByte(release, 0)]
  490. return ParseRelease(string(release))
  491. }
  492. func ParseRelease(release string) (*KernelVersionInfo, error) {
  493. var (
  494. kernel, major, minor, parsed int
  495. flavor, partial string
  496. )
  497. // Ignore error from Sscanf to allow an empty flavor. Instead, just
  498. // make sure we got all the version numbers.
  499. parsed, _ = fmt.Sscanf(release, "%d.%d%s", &kernel, &major, &partial)
  500. if parsed < 2 {
  501. return nil, errors.New("Can't parse kernel version " + release)
  502. }
  503. // sometimes we have 3.12.25-gentoo, but sometimes we just have 3.12-1-amd64
  504. parsed, _ = fmt.Sscanf(partial, ".%d%s", &minor, &flavor)
  505. if parsed < 1 {
  506. flavor = partial
  507. }
  508. return &KernelVersionInfo{
  509. Kernel: kernel,
  510. Major: major,
  511. Minor: minor,
  512. Flavor: flavor,
  513. }, nil
  514. }
  515. // FIXME: this is deprecated by CopyWithTar in archive.go
  516. func CopyDirectory(source, dest string) error {
  517. if output, err := exec.Command("cp", "-ra", source, dest).CombinedOutput(); err != nil {
  518. return fmt.Errorf("Error copy: %s (%s)", err, output)
  519. }
  520. return nil
  521. }
  522. type NopFlusher struct{}
  523. func (f *NopFlusher) Flush() {}
  524. type WriteFlusher struct {
  525. sync.Mutex
  526. w io.Writer
  527. flusher http.Flusher
  528. }
  529. func (wf *WriteFlusher) Write(b []byte) (n int, err error) {
  530. wf.Lock()
  531. defer wf.Unlock()
  532. n, err = wf.w.Write(b)
  533. wf.flusher.Flush()
  534. return n, err
  535. }
  536. // Flush the stream immediately.
  537. func (wf *WriteFlusher) Flush() {
  538. wf.Lock()
  539. defer wf.Unlock()
  540. wf.flusher.Flush()
  541. }
  542. func NewWriteFlusher(w io.Writer) *WriteFlusher {
  543. var flusher http.Flusher
  544. if f, ok := w.(http.Flusher); ok {
  545. flusher = f
  546. } else {
  547. flusher = &NopFlusher{}
  548. }
  549. return &WriteFlusher{w: w, flusher: flusher}
  550. }
  551. func NewHTTPRequestError(msg string, res *http.Response) error {
  552. return &JSONError{
  553. Message: msg,
  554. Code: res.StatusCode,
  555. }
  556. }
  557. func IsURL(str string) bool {
  558. return strings.HasPrefix(str, "http://") || strings.HasPrefix(str, "https://")
  559. }
  560. func IsGIT(str string) bool {
  561. return strings.HasPrefix(str, "git://") || strings.HasPrefix(str, "github.com/") || strings.HasPrefix(str, "git@github.com:") || (strings.HasSuffix(str, ".git") && IsURL(str))
  562. }
  563. // CheckLocalDns looks into the /etc/resolv.conf,
  564. // it returns true if there is a local nameserver or if there is no nameserver.
  565. func CheckLocalDns(resolvConf []byte) bool {
  566. for _, line := range GetLines(resolvConf, []byte("#")) {
  567. if !bytes.Contains(line, []byte("nameserver")) {
  568. continue
  569. }
  570. for _, ip := range [][]byte{
  571. []byte("127.0.0.1"),
  572. []byte("127.0.1.1"),
  573. } {
  574. if bytes.Contains(line, ip) {
  575. return true
  576. }
  577. }
  578. return false
  579. }
  580. return true
  581. }
  582. // GetLines parses input into lines and strips away comments.
  583. func GetLines(input []byte, commentMarker []byte) [][]byte {
  584. lines := bytes.Split(input, []byte("\n"))
  585. var output [][]byte
  586. for _, currentLine := range lines {
  587. var commentIndex = bytes.Index(currentLine, commentMarker)
  588. if commentIndex == -1 {
  589. output = append(output, currentLine)
  590. } else {
  591. output = append(output, currentLine[:commentIndex])
  592. }
  593. }
  594. return output
  595. }
  596. // FIXME: Change this not to receive default value as parameter
  597. func ParseHost(defaultHost string, defaultUnix, addr string) (string, error) {
  598. var (
  599. proto string
  600. host string
  601. port int
  602. )
  603. addr = strings.TrimSpace(addr)
  604. switch {
  605. case addr == "tcp://":
  606. return "", fmt.Errorf("Invalid bind address format: %s", addr)
  607. case strings.HasPrefix(addr, "unix://"):
  608. proto = "unix"
  609. addr = strings.TrimPrefix(addr, "unix://")
  610. if addr == "" {
  611. addr = defaultUnix
  612. }
  613. case strings.HasPrefix(addr, "tcp://"):
  614. proto = "tcp"
  615. addr = strings.TrimPrefix(addr, "tcp://")
  616. case strings.HasPrefix(addr, "fd://"):
  617. return addr, nil
  618. case addr == "":
  619. proto = "unix"
  620. addr = defaultUnix
  621. default:
  622. if strings.Contains(addr, "://") {
  623. return "", fmt.Errorf("Invalid bind address protocol: %s", addr)
  624. }
  625. proto = "tcp"
  626. }
  627. if proto != "unix" && strings.Contains(addr, ":") {
  628. hostParts := strings.Split(addr, ":")
  629. if len(hostParts) != 2 {
  630. return "", fmt.Errorf("Invalid bind address format: %s", addr)
  631. }
  632. if hostParts[0] != "" {
  633. host = hostParts[0]
  634. } else {
  635. host = defaultHost
  636. }
  637. if p, err := strconv.Atoi(hostParts[1]); err == nil && p != 0 {
  638. port = p
  639. } else {
  640. return "", fmt.Errorf("Invalid bind address format: %s", addr)
  641. }
  642. } else if proto == "tcp" && !strings.Contains(addr, ":") {
  643. return "", fmt.Errorf("Invalid bind address format: %s", addr)
  644. } else {
  645. host = addr
  646. }
  647. if proto == "unix" {
  648. return fmt.Sprintf("%s://%s", proto, host), nil
  649. }
  650. return fmt.Sprintf("%s://%s:%d", proto, host, port), nil
  651. }
  652. // Get a repos name and returns the right reposName + tag
  653. // The tag can be confusing because of a port in a repository name.
  654. // Ex: localhost.localdomain:5000/samalba/hipache:latest
  655. func ParseRepositoryTag(repos string) (string, string) {
  656. n := strings.LastIndex(repos, ":")
  657. if n < 0 {
  658. return repos, ""
  659. }
  660. if tag := repos[n+1:]; !strings.Contains(tag, "/") {
  661. return repos[:n], tag
  662. }
  663. return repos, ""
  664. }
  665. // An StatusError reports an unsuccessful exit by a command.
  666. type StatusError struct {
  667. Status string
  668. StatusCode int
  669. }
  670. func (e *StatusError) Error() string {
  671. return fmt.Sprintf("Status: %s, Code: %d", e.Status, e.StatusCode)
  672. }
  673. func quote(word string, buf *bytes.Buffer) {
  674. // Bail out early for "simple" strings
  675. if word != "" && !strings.ContainsAny(word, "\\'\"`${[|&;<>()~*?! \t\n") {
  676. buf.WriteString(word)
  677. return
  678. }
  679. buf.WriteString("'")
  680. for i := 0; i < len(word); i++ {
  681. b := word[i]
  682. if b == '\'' {
  683. // Replace literal ' with a close ', a \', and a open '
  684. buf.WriteString("'\\''")
  685. } else {
  686. buf.WriteByte(b)
  687. }
  688. }
  689. buf.WriteString("'")
  690. }
  691. // Take a list of strings and escape them so they will be handled right
  692. // when passed as arguments to an program via a shell
  693. func ShellQuoteArguments(args []string) string {
  694. var buf bytes.Buffer
  695. for i, arg := range args {
  696. if i != 0 {
  697. buf.WriteByte(' ')
  698. }
  699. quote(arg, &buf)
  700. }
  701. return buf.String()
  702. }
  703. func PartParser(template, data string) (map[string]string, error) {
  704. // ip:public:private
  705. var (
  706. templateParts = strings.Split(template, ":")
  707. parts = strings.Split(data, ":")
  708. out = make(map[string]string, len(templateParts))
  709. )
  710. if len(parts) != len(templateParts) {
  711. return nil, fmt.Errorf("Invalid format to parse. %s should match template %s", data, template)
  712. }
  713. for i, t := range templateParts {
  714. value := ""
  715. if len(parts) > i {
  716. value = parts[i]
  717. }
  718. out[t] = value
  719. }
  720. return out, nil
  721. }
  722. var globalTestID string
  723. // TestDirectory creates a new temporary directory and returns its path.
  724. // The contents of directory at path `templateDir` is copied into the
  725. // new directory.
  726. func TestDirectory(templateDir string) (dir string, err error) {
  727. if globalTestID == "" {
  728. globalTestID = RandomString()[:4]
  729. }
  730. prefix := fmt.Sprintf("docker-test%s-%s-", globalTestID, GetCallerName(2))
  731. if prefix == "" {
  732. prefix = "docker-test-"
  733. }
  734. dir, err = ioutil.TempDir("", prefix)
  735. if err = os.Remove(dir); err != nil {
  736. return
  737. }
  738. if templateDir != "" {
  739. if err = CopyDirectory(templateDir, dir); err != nil {
  740. return
  741. }
  742. }
  743. return
  744. }
  745. // GetCallerName introspects the call stack and returns the name of the
  746. // function `depth` levels down in the stack.
  747. func GetCallerName(depth int) string {
  748. // Use the caller function name as a prefix.
  749. // This helps trace temp directories back to their test.
  750. pc, _, _, _ := runtime.Caller(depth + 1)
  751. callerLongName := runtime.FuncForPC(pc).Name()
  752. parts := strings.Split(callerLongName, ".")
  753. callerShortName := parts[len(parts)-1]
  754. return callerShortName
  755. }
  756. func CopyFile(src, dst string) (int64, error) {
  757. if src == dst {
  758. return 0, nil
  759. }
  760. sf, err := os.Open(src)
  761. if err != nil {
  762. return 0, err
  763. }
  764. defer sf.Close()
  765. if err := os.Remove(dst); err != nil && !os.IsNotExist(err) {
  766. return 0, err
  767. }
  768. df, err := os.Create(dst)
  769. if err != nil {
  770. return 0, err
  771. }
  772. defer df.Close()
  773. return io.Copy(df, sf)
  774. }
  775. type readCloserWrapper struct {
  776. io.Reader
  777. closer func() error
  778. }
  779. func (r *readCloserWrapper) Close() error {
  780. return r.closer()
  781. }
  782. func NewReadCloserWrapper(r io.Reader, closer func() error) io.ReadCloser {
  783. return &readCloserWrapper{
  784. Reader: r,
  785. closer: closer,
  786. }
  787. }
  788. // ReplaceOrAppendValues returns the defaults with the overrides either
  789. // replaced by env key or appended to the list
  790. func ReplaceOrAppendEnvValues(defaults, overrides []string) []string {
  791. cache := make(map[string]int, len(defaults))
  792. for i, e := range defaults {
  793. parts := strings.SplitN(e, "=", 2)
  794. cache[parts[0]] = i
  795. }
  796. for _, value := range overrides {
  797. parts := strings.SplitN(value, "=", 2)
  798. if i, exists := cache[parts[0]]; exists {
  799. defaults[i] = value
  800. } else {
  801. defaults = append(defaults, value)
  802. }
  803. }
  804. return defaults
  805. }
  806. // ReadSymlinkedDirectory returns the target directory of a symlink.
  807. // The target of the symbolic link may not be a file.
  808. func ReadSymlinkedDirectory(path string) (string, error) {
  809. var realPath string
  810. var err error
  811. if realPath, err = filepath.Abs(path); err != nil {
  812. return "", fmt.Errorf("unable to get absolute path for %s: %s", path, err)
  813. }
  814. if realPath, err = filepath.EvalSymlinks(realPath); err != nil {
  815. return "", fmt.Errorf("failed to canonicalise path for %s: %s", path, err)
  816. }
  817. realPathInfo, err := os.Stat(realPath)
  818. if err != nil {
  819. return "", fmt.Errorf("failed to stat target '%s' of '%s': %s", realPath, path, err)
  820. }
  821. if !realPathInfo.Mode().IsDir() {
  822. return "", fmt.Errorf("canonical path points to a file '%s'", realPath)
  823. }
  824. return realPath, nil
  825. }
  826. func ParseKeyValueOpt(opt string) (string, string, error) {
  827. parts := strings.SplitN(opt, "=", 2)
  828. if len(parts) != 2 {
  829. return "", "", fmt.Errorf("Unable to parse key/value option: %s", opt)
  830. }
  831. return strings.TrimSpace(parts[0]), strings.TrimSpace(parts[1]), nil
  832. }
  833. // TreeSize walks a directory tree and returns its total size in bytes.
  834. func TreeSize(dir string) (size int64, err error) {
  835. data := make(map[uint64]struct{})
  836. err = filepath.Walk(dir, func(d string, fileInfo os.FileInfo, e error) error {
  837. // Ignore directory sizes
  838. if fileInfo == nil {
  839. return nil
  840. }
  841. s := fileInfo.Size()
  842. if fileInfo.IsDir() || s == 0 {
  843. return nil
  844. }
  845. // Check inode to handle hard links correctly
  846. inode := fileInfo.Sys().(*syscall.Stat_t).Ino
  847. // inode is not a uint64 on all platforms. Cast it to avoid issues.
  848. if _, exists := data[uint64(inode)]; exists {
  849. return nil
  850. }
  851. // inode is not a uint64 on all platforms. Cast it to avoid issues.
  852. data[uint64(inode)] = struct{}{}
  853. size += s
  854. return nil
  855. })
  856. return
  857. }
  858. // ValidateContextDirectory checks if all the contents of the directory
  859. // can be read and returns an error if some files can't be read
  860. // symlinks which point to non-existing files don't trigger an error
  861. func ValidateContextDirectory(srcPath string) error {
  862. var finalError error
  863. filepath.Walk(filepath.Join(srcPath, "."), func(filePath string, f os.FileInfo, err error) error {
  864. // skip this directory/file if it's not in the path, it won't get added to the context
  865. _, err = filepath.Rel(srcPath, filePath)
  866. if err != nil && os.IsPermission(err) {
  867. return nil
  868. }
  869. if _, err := os.Stat(filePath); err != nil && os.IsPermission(err) {
  870. finalError = fmt.Errorf("can't stat '%s'", filePath)
  871. return err
  872. }
  873. // skip checking if symlinks point to non-existing files, such symlinks can be useful
  874. lstat, _ := os.Lstat(filePath)
  875. if lstat.Mode()&os.ModeSymlink == os.ModeSymlink {
  876. return err
  877. }
  878. if !f.IsDir() {
  879. currentFile, err := os.Open(filePath)
  880. if err != nil && os.IsPermission(err) {
  881. finalError = fmt.Errorf("no permission to read from '%s'", filePath)
  882. return err
  883. } else {
  884. currentFile.Close()
  885. }
  886. }
  887. return nil
  888. })
  889. return finalError
  890. }