utils.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. package utils
  2. import (
  3. "bytes"
  4. "crypto/sha256"
  5. "encoding/hex"
  6. "errors"
  7. "fmt"
  8. "index/suffixarray"
  9. "io"
  10. "io/ioutil"
  11. "net/http"
  12. "os"
  13. "os/exec"
  14. "path/filepath"
  15. "runtime"
  16. "strings"
  17. "sync"
  18. "time"
  19. )
  20. // Go is a basic promise implementation: it wraps calls a function in a goroutine,
  21. // and returns a channel which will later return the function's return value.
  22. func Go(f func() error) chan error {
  23. ch := make(chan error)
  24. go func() {
  25. ch <- f()
  26. }()
  27. return ch
  28. }
  29. // Request a given URL and return an io.Reader
  30. func Download(url string, stderr io.Writer) (*http.Response, error) {
  31. var resp *http.Response
  32. var err error = nil
  33. if resp, err = http.Get(url); err != nil {
  34. return nil, err
  35. }
  36. if resp.StatusCode >= 400 {
  37. return nil, errors.New("Got HTTP status code >= 400: " + resp.Status)
  38. }
  39. return resp, nil
  40. }
  41. // Debug function, if the debug flag is set, then display. Do nothing otherwise
  42. // If Docker is in damon mode, also send the debug info on the socket
  43. func Debugf(format string, a ...interface{}) {
  44. if os.Getenv("DEBUG") != "" {
  45. // Retrieve the stack infos
  46. _, file, line, ok := runtime.Caller(1)
  47. if !ok {
  48. file = "<unknown>"
  49. line = -1
  50. } else {
  51. file = file[strings.LastIndex(file, "/")+1:]
  52. }
  53. fmt.Fprintf(os.Stderr, fmt.Sprintf("[debug] %s:%d %s\n", file, line, format), a...)
  54. }
  55. }
  56. // Reader with progress bar
  57. type progressReader struct {
  58. reader io.ReadCloser // Stream to read from
  59. output io.Writer // Where to send progress bar to
  60. readTotal int // Expected stream length (bytes)
  61. readProgress int // How much has been read so far (bytes)
  62. lastUpdate int // How many bytes read at least update
  63. template string // Template to print. Default "%v/%v (%v)"
  64. }
  65. func (r *progressReader) Read(p []byte) (n int, err error) {
  66. read, err := io.ReadCloser(r.reader).Read(p)
  67. r.readProgress += read
  68. updateEvery := 4096
  69. if r.readTotal > 0 {
  70. // Only update progress for every 1% read
  71. if increment := int(0.01 * float64(r.readTotal)); increment > updateEvery {
  72. updateEvery = increment
  73. }
  74. }
  75. if r.readProgress-r.lastUpdate > updateEvery || err != nil {
  76. if r.readTotal > 0 {
  77. fmt.Fprintf(r.output, r.template+"\r", r.readProgress, r.readTotal, fmt.Sprintf("%.0f%%", float64(r.readProgress)/float64(r.readTotal)*100))
  78. } else {
  79. fmt.Fprintf(r.output, r.template+"\r", r.readProgress, "?", "n/a")
  80. }
  81. r.lastUpdate = r.readProgress
  82. }
  83. // Send newline when complete
  84. if err != nil {
  85. fmt.Fprintf(r.output, "\n")
  86. }
  87. return read, err
  88. }
  89. func (r *progressReader) Close() error {
  90. return io.ReadCloser(r.reader).Close()
  91. }
  92. func ProgressReader(r io.ReadCloser, size int, output io.Writer, template string) *progressReader {
  93. if template == "" {
  94. template = "%v/%v (%v)"
  95. }
  96. return &progressReader{r, output, size, 0, 0, template}
  97. }
  98. // HumanDuration returns a human-readable approximation of a duration
  99. // (eg. "About a minute", "4 hours ago", etc.)
  100. func HumanDuration(d time.Duration) string {
  101. if seconds := int(d.Seconds()); seconds < 1 {
  102. return "Less than a second"
  103. } else if seconds < 60 {
  104. return fmt.Sprintf("%d seconds", seconds)
  105. } else if minutes := int(d.Minutes()); minutes == 1 {
  106. return "About a minute"
  107. } else if minutes < 60 {
  108. return fmt.Sprintf("%d minutes", minutes)
  109. } else if hours := int(d.Hours()); hours == 1 {
  110. return "About an hour"
  111. } else if hours < 48 {
  112. return fmt.Sprintf("%d hours", hours)
  113. } else if hours < 24*7*2 {
  114. return fmt.Sprintf("%d days", hours/24)
  115. } else if hours < 24*30*3 {
  116. return fmt.Sprintf("%d weeks", hours/24/7)
  117. } else if hours < 24*365*2 {
  118. return fmt.Sprintf("%d months", hours/24/30)
  119. }
  120. return fmt.Sprintf("%d years", d.Hours()/24/365)
  121. }
  122. func Trunc(s string, maxlen int) string {
  123. if len(s) <= maxlen {
  124. return s
  125. }
  126. return s[:maxlen]
  127. }
  128. // Figure out the absolute path of our own binary
  129. func SelfPath() string {
  130. path, err := exec.LookPath(os.Args[0])
  131. if err != nil {
  132. panic(err)
  133. }
  134. path, err = filepath.Abs(path)
  135. if err != nil {
  136. panic(err)
  137. }
  138. return path
  139. }
  140. type nopWriter struct {
  141. }
  142. func (w *nopWriter) Write(buf []byte) (int, error) {
  143. return len(buf), nil
  144. }
  145. type nopWriteCloser struct {
  146. io.Writer
  147. }
  148. func (w *nopWriteCloser) Close() error { return nil }
  149. func NopWriteCloser(w io.Writer) io.WriteCloser {
  150. return &nopWriteCloser{w}
  151. }
  152. type bufReader struct {
  153. buf *bytes.Buffer
  154. reader io.Reader
  155. err error
  156. l sync.Mutex
  157. wait sync.Cond
  158. }
  159. func NewBufReader(r io.Reader) *bufReader {
  160. reader := &bufReader{
  161. buf: &bytes.Buffer{},
  162. reader: r,
  163. }
  164. reader.wait.L = &reader.l
  165. go reader.drain()
  166. return reader
  167. }
  168. func (r *bufReader) drain() {
  169. buf := make([]byte, 1024)
  170. for {
  171. n, err := r.reader.Read(buf)
  172. r.l.Lock()
  173. if err != nil {
  174. r.err = err
  175. } else {
  176. r.buf.Write(buf[0:n])
  177. }
  178. r.wait.Signal()
  179. r.l.Unlock()
  180. if err != nil {
  181. break
  182. }
  183. }
  184. }
  185. func (r *bufReader) Read(p []byte) (n int, err error) {
  186. r.l.Lock()
  187. defer r.l.Unlock()
  188. for {
  189. n, err = r.buf.Read(p)
  190. if n > 0 {
  191. return n, err
  192. }
  193. if r.err != nil {
  194. return 0, r.err
  195. }
  196. r.wait.Wait()
  197. }
  198. panic("unreachable")
  199. }
  200. func (r *bufReader) Close() error {
  201. closer, ok := r.reader.(io.ReadCloser)
  202. if !ok {
  203. return nil
  204. }
  205. return closer.Close()
  206. }
  207. type WriteBroadcaster struct {
  208. mu sync.Mutex
  209. writers map[io.WriteCloser]struct{}
  210. }
  211. func (w *WriteBroadcaster) AddWriter(writer io.WriteCloser) {
  212. w.mu.Lock()
  213. w.writers[writer] = struct{}{}
  214. w.mu.Unlock()
  215. }
  216. // FIXME: Is that function used?
  217. // FIXME: This relies on the concrete writer type used having equality operator
  218. func (w *WriteBroadcaster) RemoveWriter(writer io.WriteCloser) {
  219. w.mu.Lock()
  220. delete(w.writers, writer)
  221. w.mu.Unlock()
  222. }
  223. func (w *WriteBroadcaster) Write(p []byte) (n int, err error) {
  224. w.mu.Lock()
  225. defer w.mu.Unlock()
  226. for writer := range w.writers {
  227. if n, err := writer.Write(p); err != nil || n != len(p) {
  228. // On error, evict the writer
  229. delete(w.writers, writer)
  230. }
  231. }
  232. return len(p), nil
  233. }
  234. func (w *WriteBroadcaster) CloseWriters() error {
  235. w.mu.Lock()
  236. defer w.mu.Unlock()
  237. for writer := range w.writers {
  238. writer.Close()
  239. }
  240. w.writers = make(map[io.WriteCloser]struct{})
  241. return nil
  242. }
  243. func NewWriteBroadcaster() *WriteBroadcaster {
  244. return &WriteBroadcaster{writers: make(map[io.WriteCloser]struct{})}
  245. }
  246. func GetTotalUsedFds() int {
  247. if fds, err := ioutil.ReadDir(fmt.Sprintf("/proc/%d/fd", os.Getpid())); err != nil {
  248. Debugf("Error opening /proc/%d/fd: %s", os.Getpid(), err)
  249. } else {
  250. return len(fds)
  251. }
  252. return -1
  253. }
  254. // TruncIndex allows the retrieval of string identifiers by any of their unique prefixes.
  255. // This is used to retrieve image and container IDs by more convenient shorthand prefixes.
  256. type TruncIndex struct {
  257. index *suffixarray.Index
  258. ids map[string]bool
  259. bytes []byte
  260. }
  261. func NewTruncIndex() *TruncIndex {
  262. return &TruncIndex{
  263. index: suffixarray.New([]byte{' '}),
  264. ids: make(map[string]bool),
  265. bytes: []byte{' '},
  266. }
  267. }
  268. func (idx *TruncIndex) Add(id string) error {
  269. if strings.Contains(id, " ") {
  270. return fmt.Errorf("Illegal character: ' '")
  271. }
  272. if _, exists := idx.ids[id]; exists {
  273. return fmt.Errorf("Id already exists: %s", id)
  274. }
  275. idx.ids[id] = true
  276. idx.bytes = append(idx.bytes, []byte(id+" ")...)
  277. idx.index = suffixarray.New(idx.bytes)
  278. return nil
  279. }
  280. func (idx *TruncIndex) Delete(id string) error {
  281. if _, exists := idx.ids[id]; !exists {
  282. return fmt.Errorf("No such id: %s", id)
  283. }
  284. before, after, err := idx.lookup(id)
  285. if err != nil {
  286. return err
  287. }
  288. delete(idx.ids, id)
  289. idx.bytes = append(idx.bytes[:before], idx.bytes[after:]...)
  290. idx.index = suffixarray.New(idx.bytes)
  291. return nil
  292. }
  293. func (idx *TruncIndex) lookup(s string) (int, int, error) {
  294. offsets := idx.index.Lookup([]byte(" "+s), -1)
  295. //log.Printf("lookup(%s): %v (index bytes: '%s')\n", s, offsets, idx.index.Bytes())
  296. if offsets == nil || len(offsets) == 0 || len(offsets) > 1 {
  297. return -1, -1, fmt.Errorf("No such id: %s", s)
  298. }
  299. offsetBefore := offsets[0] + 1
  300. offsetAfter := offsetBefore + strings.Index(string(idx.bytes[offsetBefore:]), " ")
  301. return offsetBefore, offsetAfter, nil
  302. }
  303. func (idx *TruncIndex) Get(s string) (string, error) {
  304. before, after, err := idx.lookup(s)
  305. //log.Printf("Get(%s) bytes=|%s| before=|%d| after=|%d|\n", s, idx.bytes, before, after)
  306. if err != nil {
  307. return "", err
  308. }
  309. return string(idx.bytes[before:after]), err
  310. }
  311. // TruncateId returns a shorthand version of a string identifier for convenience.
  312. // A collision with other shorthands is very unlikely, but possible.
  313. // In case of a collision a lookup with TruncIndex.Get() will fail, and the caller
  314. // will need to use a langer prefix, or the full-length Id.
  315. func TruncateId(id string) string {
  316. shortLen := 12
  317. if len(id) < shortLen {
  318. shortLen = len(id)
  319. }
  320. return id[:shortLen]
  321. }
  322. // Code c/c from io.Copy() modified to handle escape sequence
  323. func CopyEscapable(dst io.Writer, src io.ReadCloser) (written int64, err error) {
  324. buf := make([]byte, 32*1024)
  325. for {
  326. nr, er := src.Read(buf)
  327. if nr > 0 {
  328. // ---- Docker addition
  329. // char 16 is C-p
  330. if nr == 1 && buf[0] == 16 {
  331. nr, er = src.Read(buf)
  332. // char 17 is C-q
  333. if nr == 1 && buf[0] == 17 {
  334. if err := src.Close(); err != nil {
  335. return 0, err
  336. }
  337. return 0, io.EOF
  338. }
  339. }
  340. // ---- End of docker
  341. nw, ew := dst.Write(buf[0:nr])
  342. if nw > 0 {
  343. written += int64(nw)
  344. }
  345. if ew != nil {
  346. err = ew
  347. break
  348. }
  349. if nr != nw {
  350. err = io.ErrShortWrite
  351. break
  352. }
  353. }
  354. if er == io.EOF {
  355. break
  356. }
  357. if er != nil {
  358. err = er
  359. break
  360. }
  361. }
  362. return written, err
  363. }
  364. func HashData(src io.Reader) (string, error) {
  365. h := sha256.New()
  366. if _, err := io.Copy(h, src); err != nil {
  367. return "", err
  368. }
  369. return "sha256:" + hex.EncodeToString(h.Sum(nil)), nil
  370. }
  371. type KernelVersionInfo struct {
  372. Kernel int
  373. Major int
  374. Minor int
  375. Flavor string
  376. }
  377. func (k *KernelVersionInfo) String() string {
  378. flavor := ""
  379. if len(k.Flavor) > 0 {
  380. flavor = fmt.Sprintf("-%s", k.Flavor)
  381. }
  382. return fmt.Sprintf("%d.%d.%d%s", k.Kernel, k.Major, k.Minor, flavor)
  383. }
  384. // Compare two KernelVersionInfo struct.
  385. // Returns -1 if a < b, = if a == b, 1 it a > b
  386. func CompareKernelVersion(a, b *KernelVersionInfo) int {
  387. if a.Kernel < b.Kernel {
  388. return -1
  389. } else if a.Kernel > b.Kernel {
  390. return 1
  391. }
  392. if a.Major < b.Major {
  393. return -1
  394. } else if a.Major > b.Major {
  395. return 1
  396. }
  397. if a.Minor < b.Minor {
  398. return -1
  399. } else if a.Minor > b.Minor {
  400. return 1
  401. }
  402. return 0
  403. }
  404. func FindCgroupMountpoint(cgroupType string) (string, error) {
  405. output, err := ioutil.ReadFile("/proc/mounts")
  406. if err != nil {
  407. return "", err
  408. }
  409. // /proc/mounts has 6 fields per line, one mount per line, e.g.
  410. // cgroup /sys/fs/cgroup/devices cgroup rw,relatime,devices 0 0
  411. for _, line := range strings.Split(string(output), "\n") {
  412. parts := strings.Split(line, " ")
  413. if len(parts) == 6 && parts[2] == "cgroup" {
  414. for _, opt := range strings.Split(parts[3], ",") {
  415. if opt == cgroupType {
  416. return parts[1], nil
  417. }
  418. }
  419. }
  420. }
  421. return "", fmt.Errorf("cgroup mountpoint not found for %s", cgroupType)
  422. }