utils.go 25 KB

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