utils.go 24 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024
  1. package utils
  2. import (
  3. "bytes"
  4. "crypto/sha1"
  5. "crypto/sha256"
  6. "encoding/hex"
  7. "encoding/json"
  8. "errors"
  9. "fmt"
  10. "index/suffixarray"
  11. "io"
  12. "io/ioutil"
  13. "net/http"
  14. "os"
  15. "os/exec"
  16. "path/filepath"
  17. "regexp"
  18. "runtime"
  19. "strconv"
  20. "strings"
  21. "sync"
  22. "time"
  23. )
  24. var (
  25. IAMSTATIC bool // whether or not Docker itself was compiled statically via ./hack/make.sh binary
  26. INITSHA1 string // sha1sum of separate static dockerinit, if Docker itself was compiled dynamically via ./hack/make.sh dynbinary
  27. INITPATH string // custom location to search for a valid dockerinit binary (available for packagers as a last resort escape hatch)
  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)
  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) (*http.Response, error) {
  45. var resp *http.Response
  46. var err error
  47. if resp, err = http.Get(url); err != nil {
  48. return nil, err
  49. }
  50. if resp.StatusCode >= 400 {
  51. return nil, errors.New("Got HTTP status code >= 400: " + resp.Status)
  52. }
  53. return resp, nil
  54. }
  55. func logf(level string, format string, a ...interface{}) {
  56. // Retrieve the stack infos
  57. _, file, line, ok := runtime.Caller(2)
  58. if !ok {
  59. file = "<unknown>"
  60. line = -1
  61. } else {
  62. file = file[strings.LastIndex(file, "/")+1:]
  63. }
  64. fmt.Fprintf(os.Stderr, fmt.Sprintf("[%s] %s:%d %s\n", level, file, line, format), a...)
  65. }
  66. // Debug function, if the debug flag is set, then display. Do nothing otherwise
  67. // If Docker is in damon mode, also send the debug info on the socket
  68. func Debugf(format string, a ...interface{}) {
  69. if os.Getenv("DEBUG") != "" {
  70. logf("debug", format, a...)
  71. }
  72. }
  73. func Errorf(format string, a ...interface{}) {
  74. logf("error", format, a...)
  75. }
  76. // HumanDuration returns a human-readable approximation of a duration
  77. // (eg. "About a minute", "4 hours ago", etc.)
  78. func HumanDuration(d time.Duration) string {
  79. if seconds := int(d.Seconds()); seconds < 1 {
  80. return "Less than a second"
  81. } else if seconds < 60 {
  82. return fmt.Sprintf("%d seconds", seconds)
  83. } else if minutes := int(d.Minutes()); minutes == 1 {
  84. return "About a minute"
  85. } else if minutes < 60 {
  86. return fmt.Sprintf("%d minutes", minutes)
  87. } else if hours := int(d.Hours()); hours == 1 {
  88. return "About an hour"
  89. } else if hours < 48 {
  90. return fmt.Sprintf("%d hours", hours)
  91. } else if hours < 24*7*2 {
  92. return fmt.Sprintf("%d days", hours/24)
  93. } else if hours < 24*30*3 {
  94. return fmt.Sprintf("%d weeks", hours/24/7)
  95. } else if hours < 24*365*2 {
  96. return fmt.Sprintf("%d months", hours/24/30)
  97. }
  98. return fmt.Sprintf("%f years", d.Hours()/24/365)
  99. }
  100. // HumanSize returns a human-readable approximation of a size
  101. // using SI standard (eg. "44kB", "17MB")
  102. func HumanSize(size int64) string {
  103. i := 0
  104. var sizef float64
  105. sizef = float64(size)
  106. units := []string{"B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"}
  107. for sizef >= 1000.0 {
  108. sizef = sizef / 1000.0
  109. i++
  110. }
  111. return fmt.Sprintf("%.4g %s", sizef, units[i])
  112. }
  113. // Parses a human-readable string representing an amount of RAM
  114. // in bytes, kibibytes, mebibytes or gibibytes, and returns the
  115. // number of bytes, or -1 if the string is unparseable.
  116. // Units are case-insensitive, and the 'b' suffix is optional.
  117. func RAMInBytes(size string) (bytes int64, err error) {
  118. re, error := regexp.Compile("^(\\d+)([kKmMgG])?[bB]?$")
  119. if error != nil {
  120. return -1, error
  121. }
  122. matches := re.FindStringSubmatch(size)
  123. if len(matches) != 3 {
  124. return -1, fmt.Errorf("Invalid size: '%s'", size)
  125. }
  126. memLimit, error := strconv.ParseInt(matches[1], 10, 0)
  127. if error != nil {
  128. return -1, error
  129. }
  130. unit := strings.ToLower(matches[2])
  131. if unit == "k" {
  132. memLimit *= 1024
  133. } else if unit == "m" {
  134. memLimit *= 1024 * 1024
  135. } else if unit == "g" {
  136. memLimit *= 1024 * 1024 * 1024
  137. }
  138. return memLimit, nil
  139. }
  140. func Trunc(s string, maxlen int) string {
  141. if len(s) <= maxlen {
  142. return s
  143. }
  144. return s[:maxlen]
  145. }
  146. // Figure out the absolute path of our own binary (if it's still around).
  147. func SelfPath() string {
  148. path, err := exec.LookPath(os.Args[0])
  149. if err != nil {
  150. if os.IsNotExist(err) {
  151. return ""
  152. }
  153. if execErr, ok := err.(*exec.Error); ok && os.IsNotExist(execErr.Err) {
  154. return ""
  155. }
  156. panic(err)
  157. }
  158. path, err = filepath.Abs(path)
  159. if err != nil {
  160. if os.IsNotExist(err) {
  161. return ""
  162. }
  163. panic(err)
  164. }
  165. return path
  166. }
  167. func dockerInitSha1(target string) string {
  168. f, err := os.Open(target)
  169. if err != nil {
  170. return ""
  171. }
  172. defer f.Close()
  173. h := sha1.New()
  174. _, err = io.Copy(h, f)
  175. if err != nil {
  176. return ""
  177. }
  178. return hex.EncodeToString(h.Sum(nil))
  179. }
  180. func isValidDockerInitPath(target string, selfPath string) bool { // target and selfPath should be absolute (InitPath and SelfPath already do this)
  181. if target == "" {
  182. return false
  183. }
  184. if IAMSTATIC {
  185. if selfPath == "" {
  186. return false
  187. }
  188. if target == selfPath {
  189. return true
  190. }
  191. targetFileInfo, err := os.Lstat(target)
  192. if err != nil {
  193. return false
  194. }
  195. selfPathFileInfo, err := os.Lstat(selfPath)
  196. if err != nil {
  197. return false
  198. }
  199. return os.SameFile(targetFileInfo, selfPathFileInfo)
  200. }
  201. return INITSHA1 != "" && dockerInitSha1(target) == INITSHA1
  202. }
  203. // Figure out the path of our dockerinit (which may be SelfPath())
  204. func DockerInitPath(localCopy string) string {
  205. selfPath := SelfPath()
  206. if isValidDockerInitPath(selfPath, selfPath) {
  207. // if we're valid, don't bother checking anything else
  208. return selfPath
  209. }
  210. var possibleInits = []string{
  211. localCopy,
  212. INITPATH,
  213. filepath.Join(filepath.Dir(selfPath), "dockerinit"),
  214. // 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."
  215. // http://www.linuxbase.org/betaspecs/fhs/fhs.html#usrlibexec
  216. "/usr/libexec/docker/dockerinit",
  217. "/usr/local/libexec/docker/dockerinit",
  218. // 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."
  219. // http://refspecs.linuxfoundation.org/FHS_2.3/fhs-2.3.html#USRLIBLIBRARIESFORPROGRAMMINGANDPA
  220. "/usr/lib/docker/dockerinit",
  221. "/usr/local/lib/docker/dockerinit",
  222. }
  223. for _, dockerInit := range possibleInits {
  224. if dockerInit == "" {
  225. continue
  226. }
  227. path, err := exec.LookPath(dockerInit)
  228. if err == nil {
  229. path, err = filepath.Abs(path)
  230. if err != nil {
  231. // LookPath already validated that this file exists and is executable (following symlinks), so how could Abs fail?
  232. panic(err)
  233. }
  234. if isValidDockerInitPath(path, selfPath) {
  235. return path
  236. }
  237. }
  238. }
  239. return ""
  240. }
  241. type NopWriter struct{}
  242. func (*NopWriter) Write(buf []byte) (int, error) {
  243. return len(buf), nil
  244. }
  245. type nopWriteCloser struct {
  246. io.Writer
  247. }
  248. func (w *nopWriteCloser) Close() error { return nil }
  249. func NopWriteCloser(w io.Writer) io.WriteCloser {
  250. return &nopWriteCloser{w}
  251. }
  252. type bufReader struct {
  253. sync.Mutex
  254. buf *bytes.Buffer
  255. reader io.Reader
  256. err error
  257. wait sync.Cond
  258. }
  259. func NewBufReader(r io.Reader) *bufReader {
  260. reader := &bufReader{
  261. buf: &bytes.Buffer{},
  262. reader: r,
  263. }
  264. reader.wait.L = &reader.Mutex
  265. go reader.drain()
  266. return reader
  267. }
  268. func (r *bufReader) drain() {
  269. buf := make([]byte, 1024)
  270. for {
  271. n, err := r.reader.Read(buf)
  272. r.Lock()
  273. if err != nil {
  274. r.err = err
  275. } else {
  276. r.buf.Write(buf[0:n])
  277. }
  278. r.wait.Signal()
  279. r.Unlock()
  280. if err != nil {
  281. break
  282. }
  283. }
  284. }
  285. func (r *bufReader) Read(p []byte) (n int, err error) {
  286. r.Lock()
  287. defer r.Unlock()
  288. for {
  289. n, err = r.buf.Read(p)
  290. if n > 0 {
  291. return n, err
  292. }
  293. if r.err != nil {
  294. return 0, r.err
  295. }
  296. r.wait.Wait()
  297. }
  298. }
  299. func (r *bufReader) Close() error {
  300. closer, ok := r.reader.(io.ReadCloser)
  301. if !ok {
  302. return nil
  303. }
  304. return closer.Close()
  305. }
  306. type WriteBroadcaster struct {
  307. sync.Mutex
  308. buf *bytes.Buffer
  309. writers map[StreamWriter]bool
  310. }
  311. type StreamWriter struct {
  312. wc io.WriteCloser
  313. stream string
  314. }
  315. func (w *WriteBroadcaster) AddWriter(writer io.WriteCloser, stream string) {
  316. w.Lock()
  317. sw := StreamWriter{wc: writer, stream: stream}
  318. w.writers[sw] = true
  319. w.Unlock()
  320. }
  321. type JSONLog struct {
  322. Log string `json:"log,omitempty"`
  323. Stream string `json:"stream,omitempty"`
  324. Created time.Time `json:"time"`
  325. }
  326. func (w *WriteBroadcaster) Write(p []byte) (n int, err error) {
  327. w.Lock()
  328. defer w.Unlock()
  329. w.buf.Write(p)
  330. for sw := range w.writers {
  331. lp := p
  332. if sw.stream != "" {
  333. lp = nil
  334. for {
  335. line, err := w.buf.ReadString('\n')
  336. if err != nil {
  337. w.buf.Write([]byte(line))
  338. break
  339. }
  340. b, err := json.Marshal(&JSONLog{Log: line, Stream: sw.stream, Created: time.Now().UTC()})
  341. if err != nil {
  342. // On error, evict the writer
  343. delete(w.writers, sw)
  344. continue
  345. }
  346. lp = append(lp, b...)
  347. lp = append(lp, '\n')
  348. }
  349. }
  350. if n, err := sw.wc.Write(lp); err != nil || n != len(lp) {
  351. // On error, evict the writer
  352. delete(w.writers, sw)
  353. }
  354. }
  355. return len(p), nil
  356. }
  357. func (w *WriteBroadcaster) CloseWriters() error {
  358. w.Lock()
  359. defer w.Unlock()
  360. for sw := range w.writers {
  361. sw.wc.Close()
  362. }
  363. w.writers = make(map[StreamWriter]bool)
  364. return nil
  365. }
  366. func NewWriteBroadcaster() *WriteBroadcaster {
  367. return &WriteBroadcaster{writers: make(map[StreamWriter]bool), buf: bytes.NewBuffer(nil)}
  368. }
  369. func GetTotalUsedFds() int {
  370. if fds, err := ioutil.ReadDir(fmt.Sprintf("/proc/%d/fd", os.Getpid())); err != nil {
  371. Errorf("Error opening /proc/%d/fd: %s", os.Getpid(), err)
  372. } else {
  373. return len(fds)
  374. }
  375. return -1
  376. }
  377. // TruncIndex allows the retrieval of string identifiers by any of their unique prefixes.
  378. // This is used to retrieve image and container IDs by more convenient shorthand prefixes.
  379. type TruncIndex struct {
  380. index *suffixarray.Index
  381. ids map[string]bool
  382. bytes []byte
  383. }
  384. func NewTruncIndex() *TruncIndex {
  385. return &TruncIndex{
  386. index: suffixarray.New([]byte{' '}),
  387. ids: make(map[string]bool),
  388. bytes: []byte{' '},
  389. }
  390. }
  391. func (idx *TruncIndex) Add(id string) error {
  392. if strings.Contains(id, " ") {
  393. return fmt.Errorf("Illegal character: ' '")
  394. }
  395. if _, exists := idx.ids[id]; exists {
  396. return fmt.Errorf("Id already exists: %s", id)
  397. }
  398. idx.ids[id] = true
  399. idx.bytes = append(idx.bytes, []byte(id+" ")...)
  400. idx.index = suffixarray.New(idx.bytes)
  401. return nil
  402. }
  403. func (idx *TruncIndex) Delete(id string) error {
  404. if _, exists := idx.ids[id]; !exists {
  405. return fmt.Errorf("No such id: %s", id)
  406. }
  407. before, after, err := idx.lookup(id)
  408. if err != nil {
  409. return err
  410. }
  411. delete(idx.ids, id)
  412. idx.bytes = append(idx.bytes[:before], idx.bytes[after:]...)
  413. idx.index = suffixarray.New(idx.bytes)
  414. return nil
  415. }
  416. func (idx *TruncIndex) lookup(s string) (int, int, error) {
  417. offsets := idx.index.Lookup([]byte(" "+s), -1)
  418. //log.Printf("lookup(%s): %v (index bytes: '%s')\n", s, offsets, idx.index.Bytes())
  419. if offsets == nil || len(offsets) == 0 || len(offsets) > 1 {
  420. return -1, -1, fmt.Errorf("No such id: %s", s)
  421. }
  422. offsetBefore := offsets[0] + 1
  423. offsetAfter := offsetBefore + strings.Index(string(idx.bytes[offsetBefore:]), " ")
  424. return offsetBefore, offsetAfter, nil
  425. }
  426. func (idx *TruncIndex) Get(s string) (string, error) {
  427. before, after, err := idx.lookup(s)
  428. //log.Printf("Get(%s) bytes=|%s| before=|%d| after=|%d|\n", s, idx.bytes, before, after)
  429. if err != nil {
  430. return "", err
  431. }
  432. return string(idx.bytes[before:after]), err
  433. }
  434. // TruncateID returns a shorthand version of a string identifier for convenience.
  435. // A collision with other shorthands is very unlikely, but possible.
  436. // In case of a collision a lookup with TruncIndex.Get() will fail, and the caller
  437. // will need to use a langer prefix, or the full-length Id.
  438. func TruncateID(id string) string {
  439. shortLen := 12
  440. if len(id) < shortLen {
  441. shortLen = len(id)
  442. }
  443. return id[:shortLen]
  444. }
  445. // Code c/c from io.Copy() modified to handle escape sequence
  446. func CopyEscapable(dst io.Writer, src io.ReadCloser) (written int64, err error) {
  447. buf := make([]byte, 32*1024)
  448. for {
  449. nr, er := src.Read(buf)
  450. if nr > 0 {
  451. // ---- Docker addition
  452. // char 16 is C-p
  453. if nr == 1 && buf[0] == 16 {
  454. nr, er = src.Read(buf)
  455. // char 17 is C-q
  456. if nr == 1 && buf[0] == 17 {
  457. if err := src.Close(); err != nil {
  458. return 0, err
  459. }
  460. return 0, nil
  461. }
  462. }
  463. // ---- End of docker
  464. nw, ew := dst.Write(buf[0:nr])
  465. if nw > 0 {
  466. written += int64(nw)
  467. }
  468. if ew != nil {
  469. err = ew
  470. break
  471. }
  472. if nr != nw {
  473. err = io.ErrShortWrite
  474. break
  475. }
  476. }
  477. if er == io.EOF {
  478. break
  479. }
  480. if er != nil {
  481. err = er
  482. break
  483. }
  484. }
  485. return written, err
  486. }
  487. func HashData(src io.Reader) (string, error) {
  488. h := sha256.New()
  489. if _, err := io.Copy(h, src); err != nil {
  490. return "", err
  491. }
  492. return "sha256:" + hex.EncodeToString(h.Sum(nil)), nil
  493. }
  494. type KernelVersionInfo struct {
  495. Kernel int
  496. Major int
  497. Minor int
  498. Flavor string
  499. }
  500. func (k *KernelVersionInfo) String() string {
  501. flavor := ""
  502. if len(k.Flavor) > 0 {
  503. flavor = fmt.Sprintf("-%s", k.Flavor)
  504. }
  505. return fmt.Sprintf("%d.%d.%d%s", k.Kernel, k.Major, k.Minor, flavor)
  506. }
  507. // Compare two KernelVersionInfo struct.
  508. // Returns -1 if a < b, = if a == b, 1 it a > b
  509. func CompareKernelVersion(a, b *KernelVersionInfo) int {
  510. if a.Kernel < b.Kernel {
  511. return -1
  512. } else if a.Kernel > b.Kernel {
  513. return 1
  514. }
  515. if a.Major < b.Major {
  516. return -1
  517. } else if a.Major > b.Major {
  518. return 1
  519. }
  520. if a.Minor < b.Minor {
  521. return -1
  522. } else if a.Minor > b.Minor {
  523. return 1
  524. }
  525. return 0
  526. }
  527. func GetKernelVersion() (*KernelVersionInfo, error) {
  528. var (
  529. err error
  530. )
  531. uts, err := uname()
  532. if err != nil {
  533. return nil, err
  534. }
  535. release := make([]byte, len(uts.Release))
  536. i := 0
  537. for _, c := range uts.Release {
  538. release[i] = byte(c)
  539. i++
  540. }
  541. // Remove the \x00 from the release for Atoi to parse correctly
  542. release = release[:bytes.IndexByte(release, 0)]
  543. return ParseRelease(string(release))
  544. }
  545. func ParseRelease(release string) (*KernelVersionInfo, error) {
  546. var (
  547. flavor string
  548. kernel, major, minor int
  549. err error
  550. )
  551. tmp := strings.SplitN(release, "-", 2)
  552. tmp2 := strings.Split(tmp[0], ".")
  553. if len(tmp2) > 0 {
  554. kernel, err = strconv.Atoi(tmp2[0])
  555. if err != nil {
  556. return nil, err
  557. }
  558. }
  559. if len(tmp2) > 1 {
  560. major, err = strconv.Atoi(tmp2[1])
  561. if err != nil {
  562. return nil, err
  563. }
  564. }
  565. if len(tmp2) > 2 {
  566. // Removes "+" because git kernels might set it
  567. minorUnparsed := strings.Trim(tmp2[2], "+")
  568. minor, err = strconv.Atoi(minorUnparsed)
  569. if err != nil {
  570. return nil, err
  571. }
  572. }
  573. if len(tmp) == 2 {
  574. flavor = tmp[1]
  575. } else {
  576. flavor = ""
  577. }
  578. return &KernelVersionInfo{
  579. Kernel: kernel,
  580. Major: major,
  581. Minor: minor,
  582. Flavor: flavor,
  583. }, nil
  584. }
  585. // FIXME: this is deprecated by CopyWithTar in archive.go
  586. func CopyDirectory(source, dest string) error {
  587. if output, err := exec.Command("cp", "-ra", source, dest).CombinedOutput(); err != nil {
  588. return fmt.Errorf("Error copy: %s (%s)", err, output)
  589. }
  590. return nil
  591. }
  592. type NopFlusher struct{}
  593. func (f *NopFlusher) Flush() {}
  594. type WriteFlusher struct {
  595. sync.Mutex
  596. w io.Writer
  597. flusher http.Flusher
  598. }
  599. func (wf *WriteFlusher) Write(b []byte) (n int, err error) {
  600. wf.Lock()
  601. defer wf.Unlock()
  602. n, err = wf.w.Write(b)
  603. wf.flusher.Flush()
  604. return n, err
  605. }
  606. // Flush the stream immediately.
  607. func (wf *WriteFlusher) Flush() {
  608. wf.Lock()
  609. defer wf.Unlock()
  610. wf.flusher.Flush()
  611. }
  612. func NewWriteFlusher(w io.Writer) *WriteFlusher {
  613. var flusher http.Flusher
  614. if f, ok := w.(http.Flusher); ok {
  615. flusher = f
  616. } else {
  617. flusher = &NopFlusher{}
  618. }
  619. return &WriteFlusher{w: w, flusher: flusher}
  620. }
  621. func NewHTTPRequestError(msg string, res *http.Response) error {
  622. return &JSONError{
  623. Message: msg,
  624. Code: res.StatusCode,
  625. }
  626. }
  627. func IsURL(str string) bool {
  628. return strings.HasPrefix(str, "http://") || strings.HasPrefix(str, "https://")
  629. }
  630. func IsGIT(str string) bool {
  631. return strings.HasPrefix(str, "git://") || strings.HasPrefix(str, "github.com/")
  632. }
  633. // GetResolvConf opens and read the content of /etc/resolv.conf.
  634. // It returns it as byte slice.
  635. func GetResolvConf() ([]byte, error) {
  636. resolv, err := ioutil.ReadFile("/etc/resolv.conf")
  637. if err != nil {
  638. Errorf("Error openning resolv.conf: %s", err)
  639. return nil, err
  640. }
  641. return resolv, nil
  642. }
  643. // CheckLocalDns looks into the /etc/resolv.conf,
  644. // it returns true if there is a local nameserver or if there is no nameserver.
  645. func CheckLocalDns(resolvConf []byte) bool {
  646. var parsedResolvConf = StripComments(resolvConf, []byte("#"))
  647. if !bytes.Contains(parsedResolvConf, []byte("nameserver")) {
  648. return true
  649. }
  650. for _, ip := range [][]byte{
  651. []byte("127.0.0.1"),
  652. []byte("127.0.1.1"),
  653. } {
  654. if bytes.Contains(parsedResolvConf, ip) {
  655. return true
  656. }
  657. }
  658. return false
  659. }
  660. // StripComments parses input into lines and strips away comments.
  661. func StripComments(input []byte, commentMarker []byte) []byte {
  662. lines := bytes.Split(input, []byte("\n"))
  663. var output []byte
  664. for _, currentLine := range lines {
  665. var commentIndex = bytes.Index(currentLine, commentMarker)
  666. if commentIndex == -1 {
  667. output = append(output, currentLine...)
  668. } else {
  669. output = append(output, currentLine[:commentIndex]...)
  670. }
  671. output = append(output, []byte("\n")...)
  672. }
  673. return output
  674. }
  675. // GetNameserversAsCIDR returns nameservers (if any) listed in
  676. // /etc/resolv.conf as CIDR blocks (e.g., "1.2.3.4/32")
  677. // This function's output is intended for net.ParseCIDR
  678. func GetNameserversAsCIDR(resolvConf []byte) []string {
  679. var parsedResolvConf = StripComments(resolvConf, []byte("#"))
  680. nameservers := []string{}
  681. re := regexp.MustCompile(`^\s*nameserver\s*(([0-9]+\.){3}([0-9]+))\s*$`)
  682. for _, line := range bytes.Split(parsedResolvConf, []byte("\n")) {
  683. var ns = re.FindSubmatch(line)
  684. if len(ns) > 0 {
  685. nameservers = append(nameservers, string(ns[1])+"/32")
  686. }
  687. }
  688. return nameservers
  689. }
  690. // FIXME: Change this not to receive default value as parameter
  691. func ParseHost(defaultHost string, defaultPort int, defaultUnix, addr string) (string, error) {
  692. var (
  693. proto string
  694. host string
  695. port int
  696. )
  697. addr = strings.TrimSpace(addr)
  698. switch {
  699. case strings.HasPrefix(addr, "unix://"):
  700. proto = "unix"
  701. addr = strings.TrimPrefix(addr, "unix://")
  702. if addr == "" {
  703. addr = defaultUnix
  704. }
  705. case strings.HasPrefix(addr, "tcp://"):
  706. proto = "tcp"
  707. addr = strings.TrimPrefix(addr, "tcp://")
  708. case addr == "":
  709. proto = "unix"
  710. addr = defaultUnix
  711. default:
  712. if strings.Contains(addr, "://") {
  713. return "", fmt.Errorf("Invalid bind address protocol: %s", addr)
  714. }
  715. proto = "tcp"
  716. }
  717. if proto != "unix" && strings.Contains(addr, ":") {
  718. hostParts := strings.Split(addr, ":")
  719. if len(hostParts) != 2 {
  720. return "", fmt.Errorf("Invalid bind address format: %s", addr)
  721. }
  722. if hostParts[0] != "" {
  723. host = hostParts[0]
  724. } else {
  725. host = defaultHost
  726. }
  727. if p, err := strconv.Atoi(hostParts[1]); err == nil && p != 0 {
  728. port = p
  729. } else {
  730. port = defaultPort
  731. }
  732. } else {
  733. host = addr
  734. port = defaultPort
  735. }
  736. if proto == "unix" {
  737. return fmt.Sprintf("%s://%s", proto, host), nil
  738. }
  739. return fmt.Sprintf("%s://%s:%d", proto, host, port), nil
  740. }
  741. func GetReleaseVersion() string {
  742. resp, err := http.Get("http://get.docker.io/latest")
  743. if err != nil {
  744. return ""
  745. }
  746. defer resp.Body.Close()
  747. if resp.ContentLength > 24 || resp.StatusCode != 200 {
  748. return ""
  749. }
  750. body, err := ioutil.ReadAll(resp.Body)
  751. if err != nil {
  752. return ""
  753. }
  754. return strings.TrimSpace(string(body))
  755. }
  756. // Get a repos name and returns the right reposName + tag
  757. // The tag can be confusing because of a port in a repository name.
  758. // Ex: localhost.localdomain:5000/samalba/hipache:latest
  759. func ParseRepositoryTag(repos string) (string, string) {
  760. n := strings.LastIndex(repos, ":")
  761. if n < 0 {
  762. return repos, ""
  763. }
  764. if tag := repos[n+1:]; !strings.Contains(tag, "/") {
  765. return repos[:n], tag
  766. }
  767. return repos, ""
  768. }
  769. type User struct {
  770. Uid string // user id
  771. Gid string // primary group id
  772. Username string
  773. Name string
  774. HomeDir string
  775. }
  776. // UserLookup check if the given username or uid is present in /etc/passwd
  777. // and returns the user struct.
  778. // If the username is not found, an error is returned.
  779. func UserLookup(uid string) (*User, error) {
  780. file, err := ioutil.ReadFile("/etc/passwd")
  781. if err != nil {
  782. return nil, err
  783. }
  784. for _, line := range strings.Split(string(file), "\n") {
  785. data := strings.Split(line, ":")
  786. if len(data) > 5 && (data[0] == uid || data[2] == uid) {
  787. return &User{
  788. Uid: data[2],
  789. Gid: data[3],
  790. Username: data[0],
  791. Name: data[4],
  792. HomeDir: data[5],
  793. }, nil
  794. }
  795. }
  796. return nil, fmt.Errorf("User not found in /etc/passwd")
  797. }
  798. // An StatusError reports an unsuccessful exit by a command.
  799. type StatusError struct {
  800. Status string
  801. StatusCode int
  802. }
  803. func (e *StatusError) Error() string {
  804. return fmt.Sprintf("Status: %s, Code: %d", e.Status, e.StatusCode)
  805. }
  806. func quote(word string, buf *bytes.Buffer) {
  807. // Bail out early for "simple" strings
  808. if word != "" && !strings.ContainsAny(word, "\\'\"`${[|&;<>()~*?! \t\n") {
  809. buf.WriteString(word)
  810. return
  811. }
  812. buf.WriteString("'")
  813. for i := 0; i < len(word); i++ {
  814. b := word[i]
  815. if b == '\'' {
  816. // Replace literal ' with a close ', a \', and a open '
  817. buf.WriteString("'\\''")
  818. } else {
  819. buf.WriteByte(b)
  820. }
  821. }
  822. buf.WriteString("'")
  823. }
  824. // Take a list of strings and escape them so they will be handled right
  825. // when passed as arguments to an program via a shell
  826. func ShellQuoteArguments(args []string) string {
  827. var buf bytes.Buffer
  828. for i, arg := range args {
  829. if i != 0 {
  830. buf.WriteByte(' ')
  831. }
  832. quote(arg, &buf)
  833. }
  834. return buf.String()
  835. }
  836. func IsClosedError(err error) bool {
  837. /* This comparison is ugly, but unfortunately, net.go doesn't export errClosing.
  838. * See:
  839. * http://golang.org/src/pkg/net/net.go
  840. * https://code.google.com/p/go/issues/detail?id=4337
  841. * https://groups.google.com/forum/#!msg/golang-nuts/0_aaCvBmOcM/SptmDyX1XJMJ
  842. */
  843. return strings.HasSuffix(err.Error(), "use of closed network connection")
  844. }
  845. func PartParser(template, data string) (map[string]string, error) {
  846. // ip:public:private
  847. var (
  848. templateParts = strings.Split(template, ":")
  849. parts = strings.Split(data, ":")
  850. out = make(map[string]string, len(templateParts))
  851. )
  852. if len(parts) != len(templateParts) {
  853. return nil, fmt.Errorf("Invalid format to parse. %s should match template %s", data, template)
  854. }
  855. for i, t := range templateParts {
  856. value := ""
  857. if len(parts) > i {
  858. value = parts[i]
  859. }
  860. out[t] = value
  861. }
  862. return out, nil
  863. }
  864. var globalTestID string
  865. // TestDirectory creates a new temporary directory and returns its path.
  866. // The contents of directory at path `templateDir` is copied into the
  867. // new directory.
  868. func TestDirectory(templateDir string) (dir string, err error) {
  869. if globalTestID == "" {
  870. globalTestID = RandomString()[:4]
  871. }
  872. prefix := fmt.Sprintf("docker-test%s-%s-", globalTestID, GetCallerName(2))
  873. if prefix == "" {
  874. prefix = "docker-test-"
  875. }
  876. dir, err = ioutil.TempDir("", prefix)
  877. if err = os.Remove(dir); err != nil {
  878. return
  879. }
  880. if templateDir != "" {
  881. if err = CopyDirectory(templateDir, dir); err != nil {
  882. return
  883. }
  884. }
  885. return
  886. }
  887. // GetCallerName introspects the call stack and returns the name of the
  888. // function `depth` levels down in the stack.
  889. func GetCallerName(depth int) string {
  890. // Use the caller function name as a prefix.
  891. // This helps trace temp directories back to their test.
  892. pc, _, _, _ := runtime.Caller(depth + 1)
  893. callerLongName := runtime.FuncForPC(pc).Name()
  894. parts := strings.Split(callerLongName, ".")
  895. callerShortName := parts[len(parts)-1]
  896. return callerShortName
  897. }
  898. func CopyFile(src, dst string) (int64, error) {
  899. if src == dst {
  900. return 0, nil
  901. }
  902. sf, err := os.Open(src)
  903. if err != nil {
  904. return 0, err
  905. }
  906. defer sf.Close()
  907. if err := os.Remove(dst); err != nil && !os.IsNotExist(err) {
  908. return 0, err
  909. }
  910. df, err := os.Create(dst)
  911. if err != nil {
  912. return 0, err
  913. }
  914. defer df.Close()
  915. return io.Copy(df, sf)
  916. }