utils.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702
  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. func (*NopWriter) Write(buf []byte) (int, error) {
  160. return len(buf), nil
  161. }
  162. type nopWriteCloser struct {
  163. io.Writer
  164. }
  165. func (w *nopWriteCloser) Close() error { return nil }
  166. func NopWriteCloser(w io.Writer) io.WriteCloser {
  167. return &nopWriteCloser{w}
  168. }
  169. type bufReader struct {
  170. sync.Mutex
  171. buf *bytes.Buffer
  172. reader io.Reader
  173. err error
  174. wait sync.Cond
  175. }
  176. func NewBufReader(r io.Reader) *bufReader {
  177. reader := &bufReader{
  178. buf: &bytes.Buffer{},
  179. reader: r,
  180. }
  181. reader.wait.L = &reader.Mutex
  182. go reader.drain()
  183. return reader
  184. }
  185. func (r *bufReader) drain() {
  186. buf := make([]byte, 1024)
  187. for {
  188. n, err := r.reader.Read(buf)
  189. r.Lock()
  190. if err != nil {
  191. r.err = err
  192. } else {
  193. r.buf.Write(buf[0:n])
  194. }
  195. r.wait.Signal()
  196. r.Unlock()
  197. if err != nil {
  198. break
  199. }
  200. }
  201. }
  202. func (r *bufReader) Read(p []byte) (n int, err error) {
  203. r.Lock()
  204. defer r.Unlock()
  205. for {
  206. n, err = r.buf.Read(p)
  207. if n > 0 {
  208. return n, err
  209. }
  210. if r.err != nil {
  211. return 0, r.err
  212. }
  213. r.wait.Wait()
  214. }
  215. }
  216. func (r *bufReader) Close() error {
  217. closer, ok := r.reader.(io.ReadCloser)
  218. if !ok {
  219. return nil
  220. }
  221. return closer.Close()
  222. }
  223. type WriteBroadcaster struct {
  224. sync.Mutex
  225. writers map[io.WriteCloser]struct{}
  226. }
  227. func (w *WriteBroadcaster) AddWriter(writer io.WriteCloser) {
  228. w.Lock()
  229. w.writers[writer] = struct{}{}
  230. w.Unlock()
  231. }
  232. // FIXME: Is that function used?
  233. // FIXME: This relies on the concrete writer type used having equality operator
  234. func (w *WriteBroadcaster) RemoveWriter(writer io.WriteCloser) {
  235. w.Lock()
  236. delete(w.writers, writer)
  237. w.Unlock()
  238. }
  239. func (w *WriteBroadcaster) Write(p []byte) (n int, err error) {
  240. w.Lock()
  241. defer w.Unlock()
  242. for writer := range w.writers {
  243. if n, err := writer.Write(p); err != nil || n != len(p) {
  244. // On error, evict the writer
  245. delete(w.writers, writer)
  246. }
  247. }
  248. return len(p), nil
  249. }
  250. func (w *WriteBroadcaster) CloseWriters() error {
  251. w.Lock()
  252. defer w.Unlock()
  253. for writer := range w.writers {
  254. writer.Close()
  255. }
  256. w.writers = make(map[io.WriteCloser]struct{})
  257. return nil
  258. }
  259. func NewWriteBroadcaster() *WriteBroadcaster {
  260. return &WriteBroadcaster{writers: make(map[io.WriteCloser]struct{})}
  261. }
  262. func GetTotalUsedFds() int {
  263. if fds, err := ioutil.ReadDir(fmt.Sprintf("/proc/%d/fd", os.Getpid())); err != nil {
  264. Debugf("Error opening /proc/%d/fd: %s", os.Getpid(), err)
  265. } else {
  266. return len(fds)
  267. }
  268. return -1
  269. }
  270. // TruncIndex allows the retrieval of string identifiers by any of their unique prefixes.
  271. // This is used to retrieve image and container IDs by more convenient shorthand prefixes.
  272. type TruncIndex struct {
  273. index *suffixarray.Index
  274. ids map[string]bool
  275. bytes []byte
  276. }
  277. func NewTruncIndex() *TruncIndex {
  278. return &TruncIndex{
  279. index: suffixarray.New([]byte{' '}),
  280. ids: make(map[string]bool),
  281. bytes: []byte{' '},
  282. }
  283. }
  284. func (idx *TruncIndex) Add(id string) error {
  285. if strings.Contains(id, " ") {
  286. return fmt.Errorf("Illegal character: ' '")
  287. }
  288. if _, exists := idx.ids[id]; exists {
  289. return fmt.Errorf("Id already exists: %s", id)
  290. }
  291. idx.ids[id] = true
  292. idx.bytes = append(idx.bytes, []byte(id+" ")...)
  293. idx.index = suffixarray.New(idx.bytes)
  294. return nil
  295. }
  296. func (idx *TruncIndex) Delete(id string) error {
  297. if _, exists := idx.ids[id]; !exists {
  298. return fmt.Errorf("No such id: %s", id)
  299. }
  300. before, after, err := idx.lookup(id)
  301. if err != nil {
  302. return err
  303. }
  304. delete(idx.ids, id)
  305. idx.bytes = append(idx.bytes[:before], idx.bytes[after:]...)
  306. idx.index = suffixarray.New(idx.bytes)
  307. return nil
  308. }
  309. func (idx *TruncIndex) lookup(s string) (int, int, error) {
  310. offsets := idx.index.Lookup([]byte(" "+s), -1)
  311. //log.Printf("lookup(%s): %v (index bytes: '%s')\n", s, offsets, idx.index.Bytes())
  312. if offsets == nil || len(offsets) == 0 || len(offsets) > 1 {
  313. return -1, -1, fmt.Errorf("No such id: %s", s)
  314. }
  315. offsetBefore := offsets[0] + 1
  316. offsetAfter := offsetBefore + strings.Index(string(idx.bytes[offsetBefore:]), " ")
  317. return offsetBefore, offsetAfter, nil
  318. }
  319. func (idx *TruncIndex) Get(s string) (string, error) {
  320. before, after, err := idx.lookup(s)
  321. //log.Printf("Get(%s) bytes=|%s| before=|%d| after=|%d|\n", s, idx.bytes, before, after)
  322. if err != nil {
  323. return "", err
  324. }
  325. return string(idx.bytes[before:after]), err
  326. }
  327. // TruncateID returns a shorthand version of a string identifier for convenience.
  328. // A collision with other shorthands is very unlikely, but possible.
  329. // In case of a collision a lookup with TruncIndex.Get() will fail, and the caller
  330. // will need to use a langer prefix, or the full-length Id.
  331. func TruncateID(id string) string {
  332. shortLen := 12
  333. if len(id) < shortLen {
  334. shortLen = len(id)
  335. }
  336. return id[:shortLen]
  337. }
  338. // Code c/c from io.Copy() modified to handle escape sequence
  339. func CopyEscapable(dst io.Writer, src io.ReadCloser) (written int64, err error) {
  340. buf := make([]byte, 32*1024)
  341. for {
  342. nr, er := src.Read(buf)
  343. if nr > 0 {
  344. // ---- Docker addition
  345. // char 16 is C-p
  346. if nr == 1 && buf[0] == 16 {
  347. nr, er = src.Read(buf)
  348. // char 17 is C-q
  349. if nr == 1 && buf[0] == 17 {
  350. if err := src.Close(); err != nil {
  351. return 0, err
  352. }
  353. return 0, io.EOF
  354. }
  355. }
  356. // ---- End of docker
  357. nw, ew := dst.Write(buf[0:nr])
  358. if nw > 0 {
  359. written += int64(nw)
  360. }
  361. if ew != nil {
  362. err = ew
  363. break
  364. }
  365. if nr != nw {
  366. err = io.ErrShortWrite
  367. break
  368. }
  369. }
  370. if er == io.EOF {
  371. break
  372. }
  373. if er != nil {
  374. err = er
  375. break
  376. }
  377. }
  378. return written, err
  379. }
  380. func HashData(src io.Reader) (string, error) {
  381. h := sha256.New()
  382. if _, err := io.Copy(h, src); err != nil {
  383. return "", err
  384. }
  385. return "sha256:" + hex.EncodeToString(h.Sum(nil)), nil
  386. }
  387. type KernelVersionInfo struct {
  388. Kernel int
  389. Major int
  390. Minor int
  391. Flavor string
  392. }
  393. func (k *KernelVersionInfo) String() string {
  394. flavor := ""
  395. if len(k.Flavor) > 0 {
  396. flavor = fmt.Sprintf("-%s", k.Flavor)
  397. }
  398. return fmt.Sprintf("%d.%d.%d%s", k.Kernel, k.Major, k.Minor, flavor)
  399. }
  400. // Compare two KernelVersionInfo struct.
  401. // Returns -1 if a < b, = if a == b, 1 it a > b
  402. func CompareKernelVersion(a, b *KernelVersionInfo) int {
  403. if a.Kernel < b.Kernel {
  404. return -1
  405. } else if a.Kernel > b.Kernel {
  406. return 1
  407. }
  408. if a.Major < b.Major {
  409. return -1
  410. } else if a.Major > b.Major {
  411. return 1
  412. }
  413. if a.Minor < b.Minor {
  414. return -1
  415. } else if a.Minor > b.Minor {
  416. return 1
  417. }
  418. return 0
  419. }
  420. func FindCgroupMountpoint(cgroupType string) (string, error) {
  421. output, err := ioutil.ReadFile("/proc/mounts")
  422. if err != nil {
  423. return "", err
  424. }
  425. // /proc/mounts has 6 fields per line, one mount per line, e.g.
  426. // cgroup /sys/fs/cgroup/devices cgroup rw,relatime,devices 0 0
  427. for _, line := range strings.Split(string(output), "\n") {
  428. parts := strings.Split(line, " ")
  429. if len(parts) == 6 && parts[2] == "cgroup" {
  430. for _, opt := range strings.Split(parts[3], ",") {
  431. if opt == cgroupType {
  432. return parts[1], nil
  433. }
  434. }
  435. }
  436. }
  437. return "", fmt.Errorf("cgroup mountpoint not found for %s", cgroupType)
  438. }
  439. func GetKernelVersion() (*KernelVersionInfo, error) {
  440. var (
  441. flavor string
  442. kernel, major, minor int
  443. err error
  444. )
  445. uts, err := uname()
  446. if err != nil {
  447. return nil, err
  448. }
  449. release := make([]byte, len(uts.Release))
  450. i := 0
  451. for _, c := range uts.Release {
  452. release[i] = byte(c)
  453. i++
  454. }
  455. // Remove the \x00 from the release for Atoi to parse correctly
  456. release = release[:bytes.IndexByte(release, 0)]
  457. tmp := strings.SplitN(string(release), "-", 2)
  458. tmp2 := strings.SplitN(tmp[0], ".", 3)
  459. if len(tmp2) > 0 {
  460. kernel, err = strconv.Atoi(tmp2[0])
  461. if err != nil {
  462. return nil, err
  463. }
  464. }
  465. if len(tmp2) > 1 {
  466. major, err = strconv.Atoi(tmp2[1])
  467. if err != nil {
  468. return nil, err
  469. }
  470. }
  471. if len(tmp2) > 2 {
  472. // Removes "+" because git kernels might set it
  473. minorUnparsed := strings.Trim(tmp2[2], "+")
  474. minor, err = strconv.Atoi(minorUnparsed)
  475. if err != nil {
  476. return nil, err
  477. }
  478. }
  479. if len(tmp) == 2 {
  480. flavor = tmp[1]
  481. } else {
  482. flavor = ""
  483. }
  484. return &KernelVersionInfo{
  485. Kernel: kernel,
  486. Major: major,
  487. Minor: minor,
  488. Flavor: flavor,
  489. }, nil
  490. }
  491. // FIXME: this is deprecated by CopyWithTar in archive.go
  492. func CopyDirectory(source, dest string) error {
  493. if output, err := exec.Command("cp", "-ra", source, dest).CombinedOutput(); err != nil {
  494. return fmt.Errorf("Error copy: %s (%s)", err, output)
  495. }
  496. return nil
  497. }
  498. type NopFlusher struct{}
  499. func (f *NopFlusher) Flush() {}
  500. type WriteFlusher struct {
  501. w io.Writer
  502. flusher http.Flusher
  503. }
  504. func (wf *WriteFlusher) Write(b []byte) (n int, err error) {
  505. n, err = wf.w.Write(b)
  506. wf.flusher.Flush()
  507. return n, err
  508. }
  509. func NewWriteFlusher(w io.Writer) *WriteFlusher {
  510. var flusher http.Flusher
  511. if f, ok := w.(http.Flusher); ok {
  512. flusher = f
  513. } else {
  514. flusher = &NopFlusher{}
  515. }
  516. return &WriteFlusher{w: w, flusher: flusher}
  517. }
  518. type JSONMessage struct {
  519. Status string `json:"status,omitempty"`
  520. Progress string `json:"progress,omitempty"`
  521. Error string `json:"error,omitempty"`
  522. }
  523. type StreamFormatter struct {
  524. json bool
  525. used bool
  526. }
  527. func NewStreamFormatter(json bool) *StreamFormatter {
  528. return &StreamFormatter{json, false}
  529. }
  530. func (sf *StreamFormatter) FormatStatus(format string, a ...interface{}) []byte {
  531. sf.used = true
  532. str := fmt.Sprintf(format, a...)
  533. if sf.json {
  534. b, err := json.Marshal(&JSONMessage{Status: str})
  535. if err != nil {
  536. return sf.FormatError(err)
  537. }
  538. return b
  539. }
  540. return []byte(str + "\r\n")
  541. }
  542. func (sf *StreamFormatter) FormatError(err error) []byte {
  543. sf.used = true
  544. if sf.json {
  545. if b, err := json.Marshal(&JSONMessage{Error: err.Error()}); err == nil {
  546. return b
  547. }
  548. return []byte("{\"error\":\"format error\"}")
  549. }
  550. return []byte("Error: " + err.Error() + "\r\n")
  551. }
  552. func (sf *StreamFormatter) FormatProgress(action, str string) []byte {
  553. sf.used = true
  554. if sf.json {
  555. b, err := json.Marshal(&JSONMessage{Status: action, Progress: str})
  556. if err != nil {
  557. return nil
  558. }
  559. return b
  560. }
  561. return []byte(action + " " + str + "\r")
  562. }
  563. func (sf *StreamFormatter) Used() bool {
  564. return sf.used
  565. }
  566. func IsURL(str string) bool {
  567. return strings.HasPrefix(str, "http://") || strings.HasPrefix(str, "https://")
  568. }
  569. func IsGIT(str string) bool {
  570. return strings.HasPrefix(str, "git://") || strings.HasPrefix(str, "github.com/")
  571. }
  572. func CheckLocalDns() bool {
  573. resolv, err := ioutil.ReadFile("/etc/resolv.conf")
  574. if err != nil {
  575. Debugf("Error openning resolv.conf: %s", err)
  576. return false
  577. }
  578. for _, ip := range []string{
  579. "127.0.0.1",
  580. "127.0.1.1",
  581. } {
  582. if strings.Contains(string(resolv), ip) {
  583. return true
  584. }
  585. }
  586. return false
  587. }
  588. func ParseHost(host string, port int, addr string) string {
  589. if strings.HasPrefix(addr, "unix://") {
  590. return addr
  591. }
  592. if strings.HasPrefix(addr, "tcp://") {
  593. addr = strings.TrimPrefix(addr, "tcp://")
  594. }
  595. if strings.Contains(addr, ":") {
  596. hostParts := strings.Split(addr, ":")
  597. if len(hostParts) != 2 {
  598. log.Fatal("Invalid bind address format.")
  599. os.Exit(-1)
  600. }
  601. if hostParts[0] != "" {
  602. host = hostParts[0]
  603. }
  604. if p, err := strconv.Atoi(hostParts[1]); err == nil {
  605. port = p
  606. }
  607. } else {
  608. host = addr
  609. }
  610. return fmt.Sprintf("tcp://%s:%d", host, port)
  611. }
  612. // Get a repos name and returns the right reposName + tag
  613. // The tag can be confusing because of a port in a repository name.
  614. // Ex: localhost.localdomain:5000/samalba/hipache:latest
  615. func ParseRepositoryTag(repos string) (string, string) {
  616. n := strings.LastIndex(repos, ":")
  617. if n < 0 {
  618. return repos, ""
  619. }
  620. if tag := repos[n+1:]; !strings.Contains(tag, "/") {
  621. return repos[:n], tag
  622. }
  623. return repos, ""
  624. }