utils.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689
  1. package utils
  2. import (
  3. "bytes"
  4. "crypto/sha256"
  5. "encoding/hex"
  6. "encoding/json"
  7. "errors"
  8. "fmt"
  9. "index/suffixarray"
  10. "io"
  11. "io/ioutil"
  12. "log"
  13. "net/http"
  14. "os"
  15. "os/exec"
  16. "path/filepath"
  17. "runtime"
  18. "strconv"
  19. "strings"
  20. "sync"
  21. "time"
  22. )
  23. // Go is a basic promise implementation: it wraps calls a function in a goroutine,
  24. // and returns a channel which will later return the function's return value.
  25. func Go(f func() error) chan error {
  26. ch := make(chan error)
  27. go func() {
  28. ch <- f()
  29. }()
  30. return ch
  31. }
  32. // Request a given URL and return an io.Reader
  33. func Download(url string, stderr io.Writer) (*http.Response, error) {
  34. var resp *http.Response
  35. var err error
  36. if resp, err = http.Get(url); err != nil {
  37. return nil, err
  38. }
  39. if resp.StatusCode >= 400 {
  40. return nil, errors.New("Got HTTP status code >= 400: " + resp.Status)
  41. }
  42. return resp, nil
  43. }
  44. // Debug function, if the debug flag is set, then display. Do nothing otherwise
  45. // If Docker is in damon mode, also send the debug info on the socket
  46. func Debugf(format string, a ...interface{}) {
  47. if os.Getenv("DEBUG") != "" {
  48. // Retrieve the stack infos
  49. _, file, line, ok := runtime.Caller(1)
  50. if !ok {
  51. file = "<unknown>"
  52. line = -1
  53. } else {
  54. file = file[strings.LastIndex(file, "/")+1:]
  55. }
  56. fmt.Fprintf(os.Stderr, fmt.Sprintf("[debug] %s:%d %s\n", file, line, format), a...)
  57. }
  58. }
  59. // Reader with progress bar
  60. type progressReader struct {
  61. reader io.ReadCloser // Stream to read from
  62. output io.Writer // Where to send progress bar to
  63. readTotal int // Expected stream length (bytes)
  64. readProgress int // How much has been read so far (bytes)
  65. lastUpdate int // How many bytes read at least update
  66. template string // Template to print. Default "%v/%v (%v)"
  67. sf *StreamFormatter
  68. }
  69. func (r *progressReader) Read(p []byte) (n int, err error) {
  70. read, err := io.ReadCloser(r.reader).Read(p)
  71. r.readProgress += read
  72. updateEvery := 1024 * 512 //512kB
  73. if r.readTotal > 0 {
  74. // Update progress for every 1% read if 1% < 512kB
  75. if increment := int(0.01 * float64(r.readTotal)); increment < updateEvery {
  76. updateEvery = increment
  77. }
  78. }
  79. if r.readProgress-r.lastUpdate > updateEvery || err != nil {
  80. if r.readTotal > 0 {
  81. fmt.Fprintf(r.output, r.template, HumanSize(int64(r.readProgress)), HumanSize(int64(r.readTotal)), fmt.Sprintf("%2.0f%%", float64(r.readProgress)/float64(r.readTotal)*100))
  82. } else {
  83. fmt.Fprintf(r.output, r.template, r.readProgress, "?", "n/a")
  84. }
  85. r.lastUpdate = r.readProgress
  86. }
  87. // Send newline when complete
  88. if err != nil {
  89. r.output.Write(r.sf.FormatStatus(""))
  90. }
  91. return read, err
  92. }
  93. func (r *progressReader) Close() error {
  94. return io.ReadCloser(r.reader).Close()
  95. }
  96. func ProgressReader(r io.ReadCloser, size int, output io.Writer, template []byte, sf *StreamFormatter) *progressReader {
  97. tpl := string(template)
  98. if tpl == "" {
  99. tpl = string(sf.FormatProgress("", "%v/%v (%v)"))
  100. }
  101. return &progressReader{r, NewWriteFlusher(output), size, 0, 0, tpl, sf}
  102. }
  103. // HumanDuration returns a human-readable approximation of a duration
  104. // (eg. "About a minute", "4 hours ago", etc.)
  105. func HumanDuration(d time.Duration) string {
  106. if seconds := int(d.Seconds()); seconds < 1 {
  107. return "Less than a second"
  108. } else if seconds < 60 {
  109. return fmt.Sprintf("%d seconds", seconds)
  110. } else if minutes := int(d.Minutes()); minutes == 1 {
  111. return "About a minute"
  112. } else if minutes < 60 {
  113. return fmt.Sprintf("%d minutes", minutes)
  114. } else if hours := int(d.Hours()); hours == 1 {
  115. return "About an hour"
  116. } else if hours < 48 {
  117. return fmt.Sprintf("%d hours", hours)
  118. } else if hours < 24*7*2 {
  119. return fmt.Sprintf("%d days", hours/24)
  120. } else if hours < 24*30*3 {
  121. return fmt.Sprintf("%d weeks", hours/24/7)
  122. } else if hours < 24*365*2 {
  123. return fmt.Sprintf("%d months", hours/24/30)
  124. }
  125. return fmt.Sprintf("%f years", d.Hours()/24/365)
  126. }
  127. // HumanSize returns a human-readable approximation of a size
  128. // using SI standard (eg. "44kB", "17MB")
  129. func HumanSize(size int64) string {
  130. i := 0
  131. var sizef float64
  132. sizef = float64(size)
  133. units := []string{"B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"}
  134. for sizef >= 1000.0 {
  135. sizef = sizef / 1000.0
  136. i++
  137. }
  138. return fmt.Sprintf("%5.4g %s", sizef, units[i])
  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
  147. func SelfPath() string {
  148. path, err := exec.LookPath(os.Args[0])
  149. if err != nil {
  150. panic(err)
  151. }
  152. path, err = filepath.Abs(path)
  153. if err != nil {
  154. panic(err)
  155. }
  156. return path
  157. }
  158. type NopWriter struct {
  159. }
  160. func (w *NopWriter) Write(buf []byte) (int, error) {
  161. return len(buf), nil
  162. }
  163. type nopWriteCloser struct {
  164. io.Writer
  165. }
  166. func (w *nopWriteCloser) Close() error { return nil }
  167. func NopWriteCloser(w io.Writer) io.WriteCloser {
  168. return &nopWriteCloser{w}
  169. }
  170. type bufReader struct {
  171. buf *bytes.Buffer
  172. reader io.Reader
  173. err error
  174. l sync.Mutex
  175. wait sync.Cond
  176. }
  177. func NewBufReader(r io.Reader) *bufReader {
  178. reader := &bufReader{
  179. buf: &bytes.Buffer{},
  180. reader: r,
  181. }
  182. reader.wait.L = &reader.l
  183. go reader.drain()
  184. return reader
  185. }
  186. func (r *bufReader) drain() {
  187. buf := make([]byte, 1024)
  188. for {
  189. n, err := r.reader.Read(buf)
  190. r.l.Lock()
  191. if err != nil {
  192. r.err = err
  193. } else {
  194. r.buf.Write(buf[0:n])
  195. }
  196. r.wait.Signal()
  197. r.l.Unlock()
  198. if err != nil {
  199. break
  200. }
  201. }
  202. }
  203. func (r *bufReader) Read(p []byte) (n int, err error) {
  204. r.l.Lock()
  205. defer r.l.Unlock()
  206. for {
  207. n, err = r.buf.Read(p)
  208. if n > 0 {
  209. return n, err
  210. }
  211. if r.err != nil {
  212. return 0, r.err
  213. }
  214. r.wait.Wait()
  215. }
  216. }
  217. func (r *bufReader) Close() error {
  218. closer, ok := r.reader.(io.ReadCloser)
  219. if !ok {
  220. return nil
  221. }
  222. return closer.Close()
  223. }
  224. type WriteBroadcaster struct {
  225. mu sync.Mutex
  226. writers map[io.WriteCloser]struct{}
  227. }
  228. func (w *WriteBroadcaster) AddWriter(writer io.WriteCloser) {
  229. w.mu.Lock()
  230. w.writers[writer] = struct{}{}
  231. w.mu.Unlock()
  232. }
  233. // FIXME: Is that function used?
  234. // FIXME: This relies on the concrete writer type used having equality operator
  235. func (w *WriteBroadcaster) RemoveWriter(writer io.WriteCloser) {
  236. w.mu.Lock()
  237. delete(w.writers, writer)
  238. w.mu.Unlock()
  239. }
  240. func (w *WriteBroadcaster) Write(p []byte) (n int, err error) {
  241. w.mu.Lock()
  242. defer w.mu.Unlock()
  243. for writer := range w.writers {
  244. if n, err := writer.Write(p); err != nil || n != len(p) {
  245. // On error, evict the writer
  246. delete(w.writers, writer)
  247. }
  248. }
  249. return len(p), nil
  250. }
  251. func (w *WriteBroadcaster) CloseWriters() error {
  252. w.mu.Lock()
  253. defer w.mu.Unlock()
  254. for writer := range w.writers {
  255. writer.Close()
  256. }
  257. w.writers = make(map[io.WriteCloser]struct{})
  258. return nil
  259. }
  260. func NewWriteBroadcaster() *WriteBroadcaster {
  261. return &WriteBroadcaster{writers: make(map[io.WriteCloser]struct{})}
  262. }
  263. func GetTotalUsedFds() int {
  264. if fds, err := ioutil.ReadDir(fmt.Sprintf("/proc/%d/fd", os.Getpid())); err != nil {
  265. Debugf("Error opening /proc/%d/fd: %s", os.Getpid(), err)
  266. } else {
  267. return len(fds)
  268. }
  269. return -1
  270. }
  271. // TruncIndex allows the retrieval of string identifiers by any of their unique prefixes.
  272. // This is used to retrieve image and container IDs by more convenient shorthand prefixes.
  273. type TruncIndex struct {
  274. index *suffixarray.Index
  275. ids map[string]bool
  276. bytes []byte
  277. }
  278. func NewTruncIndex() *TruncIndex {
  279. return &TruncIndex{
  280. index: suffixarray.New([]byte{' '}),
  281. ids: make(map[string]bool),
  282. bytes: []byte{' '},
  283. }
  284. }
  285. func (idx *TruncIndex) Add(id string) error {
  286. if strings.Contains(id, " ") {
  287. return fmt.Errorf("Illegal character: ' '")
  288. }
  289. if _, exists := idx.ids[id]; exists {
  290. return fmt.Errorf("Id already exists: %s", id)
  291. }
  292. idx.ids[id] = true
  293. idx.bytes = append(idx.bytes, []byte(id+" ")...)
  294. idx.index = suffixarray.New(idx.bytes)
  295. return nil
  296. }
  297. func (idx *TruncIndex) Delete(id string) error {
  298. if _, exists := idx.ids[id]; !exists {
  299. return fmt.Errorf("No such id: %s", id)
  300. }
  301. before, after, err := idx.lookup(id)
  302. if err != nil {
  303. return err
  304. }
  305. delete(idx.ids, id)
  306. idx.bytes = append(idx.bytes[:before], idx.bytes[after:]...)
  307. idx.index = suffixarray.New(idx.bytes)
  308. return nil
  309. }
  310. func (idx *TruncIndex) lookup(s string) (int, int, error) {
  311. offsets := idx.index.Lookup([]byte(" "+s), -1)
  312. //log.Printf("lookup(%s): %v (index bytes: '%s')\n", s, offsets, idx.index.Bytes())
  313. if offsets == nil || len(offsets) == 0 || len(offsets) > 1 {
  314. return -1, -1, fmt.Errorf("No such id: %s", s)
  315. }
  316. offsetBefore := offsets[0] + 1
  317. offsetAfter := offsetBefore + strings.Index(string(idx.bytes[offsetBefore:]), " ")
  318. return offsetBefore, offsetAfter, nil
  319. }
  320. func (idx *TruncIndex) Get(s string) (string, error) {
  321. before, after, err := idx.lookup(s)
  322. //log.Printf("Get(%s) bytes=|%s| before=|%d| after=|%d|\n", s, idx.bytes, before, after)
  323. if err != nil {
  324. return "", err
  325. }
  326. return string(idx.bytes[before:after]), err
  327. }
  328. // TruncateID returns a shorthand version of a string identifier for convenience.
  329. // A collision with other shorthands is very unlikely, but possible.
  330. // In case of a collision a lookup with TruncIndex.Get() will fail, and the caller
  331. // will need to use a langer prefix, or the full-length Id.
  332. func TruncateID(id string) string {
  333. shortLen := 12
  334. if len(id) < shortLen {
  335. shortLen = len(id)
  336. }
  337. return id[:shortLen]
  338. }
  339. // Code c/c from io.Copy() modified to handle escape sequence
  340. func CopyEscapable(dst io.Writer, src io.ReadCloser) (written int64, err error) {
  341. buf := make([]byte, 32*1024)
  342. for {
  343. nr, er := src.Read(buf)
  344. if nr > 0 {
  345. // ---- Docker addition
  346. // char 16 is C-p
  347. if nr == 1 && buf[0] == 16 {
  348. nr, er = src.Read(buf)
  349. // char 17 is C-q
  350. if nr == 1 && buf[0] == 17 {
  351. if err := src.Close(); err != nil {
  352. return 0, err
  353. }
  354. return 0, io.EOF
  355. }
  356. }
  357. // ---- End of docker
  358. nw, ew := dst.Write(buf[0:nr])
  359. if nw > 0 {
  360. written += int64(nw)
  361. }
  362. if ew != nil {
  363. err = ew
  364. break
  365. }
  366. if nr != nw {
  367. err = io.ErrShortWrite
  368. break
  369. }
  370. }
  371. if er == io.EOF {
  372. break
  373. }
  374. if er != nil {
  375. err = er
  376. break
  377. }
  378. }
  379. return written, err
  380. }
  381. func HashData(src io.Reader) (string, error) {
  382. h := sha256.New()
  383. if _, err := io.Copy(h, src); err != nil {
  384. return "", err
  385. }
  386. return "sha256:" + hex.EncodeToString(h.Sum(nil)), nil
  387. }
  388. type KernelVersionInfo struct {
  389. Kernel int
  390. Major int
  391. Minor int
  392. Flavor string
  393. }
  394. func (k *KernelVersionInfo) String() string {
  395. flavor := ""
  396. if len(k.Flavor) > 0 {
  397. flavor = fmt.Sprintf("-%s", k.Flavor)
  398. }
  399. return fmt.Sprintf("%d.%d.%d%s", k.Kernel, k.Major, k.Minor, flavor)
  400. }
  401. // Compare two KernelVersionInfo struct.
  402. // Returns -1 if a < b, = if a == b, 1 it a > b
  403. func CompareKernelVersion(a, b *KernelVersionInfo) int {
  404. if a.Kernel < b.Kernel {
  405. return -1
  406. } else if a.Kernel > b.Kernel {
  407. return 1
  408. }
  409. if a.Major < b.Major {
  410. return -1
  411. } else if a.Major > b.Major {
  412. return 1
  413. }
  414. if a.Minor < b.Minor {
  415. return -1
  416. } else if a.Minor > b.Minor {
  417. return 1
  418. }
  419. return 0
  420. }
  421. func FindCgroupMountpoint(cgroupType string) (string, error) {
  422. output, err := ioutil.ReadFile("/proc/mounts")
  423. if err != nil {
  424. return "", err
  425. }
  426. // /proc/mounts has 6 fields per line, one mount per line, e.g.
  427. // cgroup /sys/fs/cgroup/devices cgroup rw,relatime,devices 0 0
  428. for _, line := range strings.Split(string(output), "\n") {
  429. parts := strings.Split(line, " ")
  430. if len(parts) == 6 && parts[2] == "cgroup" {
  431. for _, opt := range strings.Split(parts[3], ",") {
  432. if opt == cgroupType {
  433. return parts[1], nil
  434. }
  435. }
  436. }
  437. }
  438. return "", fmt.Errorf("cgroup mountpoint not found for %s", cgroupType)
  439. }
  440. func GetKernelVersion() (*KernelVersionInfo, error) {
  441. var (
  442. flavor string
  443. kernel, major, minor int
  444. err error
  445. )
  446. uts, err := uname()
  447. if err != nil {
  448. return nil, err
  449. }
  450. release := make([]byte, len(uts.Release))
  451. i := 0
  452. for _, c := range uts.Release {
  453. release[i] = byte(c)
  454. i++
  455. }
  456. // Remove the \x00 from the release for Atoi to parse correctly
  457. release = release[:bytes.IndexByte(release, 0)]
  458. tmp := strings.SplitN(string(release), "-", 2)
  459. tmp2 := strings.SplitN(tmp[0], ".", 3)
  460. if len(tmp2) > 0 {
  461. kernel, err = strconv.Atoi(tmp2[0])
  462. if err != nil {
  463. return nil, err
  464. }
  465. }
  466. if len(tmp2) > 1 {
  467. major, err = strconv.Atoi(tmp2[1])
  468. if err != nil {
  469. return nil, err
  470. }
  471. }
  472. if len(tmp2) > 2 {
  473. // Removes "+" because git kernels might set it
  474. minorUnparsed := strings.Trim(tmp2[2], "+")
  475. minor, err = strconv.Atoi(minorUnparsed)
  476. if err != nil {
  477. return nil, err
  478. }
  479. }
  480. if len(tmp) == 2 {
  481. flavor = tmp[1]
  482. } else {
  483. flavor = ""
  484. }
  485. return &KernelVersionInfo{
  486. Kernel: kernel,
  487. Major: major,
  488. Minor: minor,
  489. Flavor: flavor,
  490. }, nil
  491. }
  492. // FIXME: this is deprecated by CopyWithTar in archive.go
  493. func CopyDirectory(source, dest string) error {
  494. if output, err := exec.Command("cp", "-ra", source, dest).CombinedOutput(); err != nil {
  495. return fmt.Errorf("Error copy: %s (%s)", err, output)
  496. }
  497. return nil
  498. }
  499. type NopFlusher struct{}
  500. func (f *NopFlusher) Flush() {}
  501. type WriteFlusher struct {
  502. w io.Writer
  503. flusher http.Flusher
  504. }
  505. func (wf *WriteFlusher) Write(b []byte) (n int, err error) {
  506. n, err = wf.w.Write(b)
  507. wf.flusher.Flush()
  508. return n, err
  509. }
  510. func NewWriteFlusher(w io.Writer) *WriteFlusher {
  511. var flusher http.Flusher
  512. if f, ok := w.(http.Flusher); ok {
  513. flusher = f
  514. } else {
  515. flusher = &NopFlusher{}
  516. }
  517. return &WriteFlusher{w: w, flusher: flusher}
  518. }
  519. type JSONMessage struct {
  520. Status string `json:"status,omitempty"`
  521. Progress string `json:"progress,omitempty"`
  522. Error string `json:"error,omitempty"`
  523. }
  524. type StreamFormatter struct {
  525. json bool
  526. used bool
  527. }
  528. func NewStreamFormatter(json bool) *StreamFormatter {
  529. return &StreamFormatter{json, false}
  530. }
  531. func (sf *StreamFormatter) FormatStatus(format string, a ...interface{}) []byte {
  532. sf.used = true
  533. str := fmt.Sprintf(format, a...)
  534. if sf.json {
  535. b, err := json.Marshal(&JSONMessage{Status: str})
  536. if err != nil {
  537. return sf.FormatError(err)
  538. }
  539. return b
  540. }
  541. return []byte(str + "\r\n")
  542. }
  543. func (sf *StreamFormatter) FormatError(err error) []byte {
  544. sf.used = true
  545. if sf.json {
  546. if b, err := json.Marshal(&JSONMessage{Error: err.Error()}); err == nil {
  547. return b
  548. }
  549. return []byte("{\"error\":\"format error\"}")
  550. }
  551. return []byte("Error: " + err.Error() + "\r\n")
  552. }
  553. func (sf *StreamFormatter) FormatProgress(action, str string) []byte {
  554. sf.used = true
  555. if sf.json {
  556. b, err := json.Marshal(&JSONMessage{Status: action, Progress: str})
  557. if err != nil {
  558. return nil
  559. }
  560. return b
  561. }
  562. return []byte(action + " " + str + "\r")
  563. }
  564. func (sf *StreamFormatter) Used() bool {
  565. return sf.used
  566. }
  567. func IsURL(str string) bool {
  568. return strings.HasPrefix(str, "http://") || strings.HasPrefix(str, "https://")
  569. }
  570. func IsGIT(str string) bool {
  571. return strings.HasPrefix(str, "git://") || strings.HasPrefix(str, "github.com/")
  572. }
  573. func CheckLocalDns() bool {
  574. resolv, err := ioutil.ReadFile("/etc/resolv.conf")
  575. if err != nil {
  576. Debugf("Error openning resolv.conf: %s", err)
  577. return false
  578. }
  579. for _, ip := range []string{
  580. "127.0.0.1",
  581. "127.0.1.1",
  582. } {
  583. if strings.Contains(string(resolv), ip) {
  584. return true
  585. }
  586. }
  587. return false
  588. }
  589. func ParseHost(host string, port int, addr string) string {
  590. if strings.HasPrefix(addr, "unix://") {
  591. return addr
  592. }
  593. if strings.HasPrefix(addr, "tcp://") {
  594. addr = strings.TrimPrefix(addr, "tcp://")
  595. }
  596. if strings.Contains(addr, ":") {
  597. hostParts := strings.Split(addr, ":")
  598. if len(hostParts) != 2 {
  599. log.Fatal("Invalid bind address format.")
  600. os.Exit(-1)
  601. }
  602. if hostParts[0] != "" {
  603. host = hostParts[0]
  604. }
  605. if p, err := strconv.Atoi(hostParts[1]); err == nil {
  606. port = p
  607. }
  608. } else {
  609. host = addr
  610. }
  611. return fmt.Sprintf("tcp://%s:%d", host, port)
  612. }