utils.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. package docker
  2. import (
  3. "bytes"
  4. "container/list"
  5. "errors"
  6. "fmt"
  7. "github.com/dotcloud/docker/rcli"
  8. "io"
  9. "net/http"
  10. "os"
  11. "os/exec"
  12. "path/filepath"
  13. "runtime"
  14. "strings"
  15. "sync"
  16. "time"
  17. )
  18. // Go is a basic promise implementation: it wraps calls a function in a goroutine,
  19. // and returns a channel which will later return the function's return value.
  20. func Go(f func() error) chan error {
  21. ch := make(chan error)
  22. go func() {
  23. ch <- f()
  24. }()
  25. return ch
  26. }
  27. // Request a given URL and return an io.Reader
  28. func Download(url string, stderr io.Writer) (*http.Response, error) {
  29. var resp *http.Response
  30. var err error = nil
  31. if resp, err = http.Get(url); err != nil {
  32. return nil, err
  33. }
  34. if resp.StatusCode >= 400 {
  35. return nil, errors.New("Got HTTP status code >= 400: " + resp.Status)
  36. }
  37. return resp, nil
  38. }
  39. // Debug function, if the debug flag is set, then display. Do nothing otherwise
  40. // If Docker is in damon mode, also send the debug info on the socket
  41. func Debugf(format string, a ...interface{}) {
  42. if rcli.DEBUG_FLAG {
  43. // Retrieve the stack infos
  44. _, file, line, ok := runtime.Caller(1)
  45. if !ok {
  46. file = "<unknown>"
  47. line = -1
  48. } else {
  49. file = file[strings.LastIndex(file, "/")+1:]
  50. }
  51. fmt.Fprintf(os.Stderr, fmt.Sprintf("[debug] %s:%d %s\n", file, line, format), a...)
  52. if rcli.CLIENT_SOCKET != nil {
  53. fmt.Fprintf(rcli.CLIENT_SOCKET, fmt.Sprintf("[debug] %s:%d %s\n", file, line, format), a...)
  54. }
  55. }
  56. }
  57. // Reader with progress bar
  58. type progressReader struct {
  59. reader io.ReadCloser // Stream to read from
  60. output io.Writer // Where to send progress bar to
  61. readTotal int // Expected stream length (bytes)
  62. readProgress int // How much has been read so far (bytes)
  63. lastUpdate int // How many bytes read at least update
  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. // Only update progress for every 1% read
  69. updateEvery := int(0.01 * float64(r.readTotal))
  70. if r.readProgress-r.lastUpdate > updateEvery || r.readProgress == r.readTotal {
  71. fmt.Fprintf(r.output, "%d/%d (%.0f%%)\r",
  72. r.readProgress,
  73. r.readTotal,
  74. float64(r.readProgress)/float64(r.readTotal)*100)
  75. r.lastUpdate = r.readProgress
  76. }
  77. // Send newline when complete
  78. if err == io.EOF {
  79. fmt.Fprintf(r.output, "\n")
  80. }
  81. return read, err
  82. }
  83. func (r *progressReader) Close() error {
  84. return io.ReadCloser(r.reader).Close()
  85. }
  86. func ProgressReader(r io.ReadCloser, size int, output io.Writer) *progressReader {
  87. return &progressReader{r, output, size, 0, 0}
  88. }
  89. // HumanDuration returns a human-readable approximation of a duration
  90. // (eg. "About a minute", "4 hours ago", etc.)
  91. func HumanDuration(d time.Duration) string {
  92. if seconds := int(d.Seconds()); seconds < 1 {
  93. return "Less than a second"
  94. } else if seconds < 60 {
  95. return fmt.Sprintf("%d seconds", seconds)
  96. } else if minutes := int(d.Minutes()); minutes == 1 {
  97. return "About a minute"
  98. } else if minutes < 60 {
  99. return fmt.Sprintf("%d minutes", minutes)
  100. } else if hours := int(d.Hours()); hours == 1 {
  101. return "About an hour"
  102. } else if hours < 48 {
  103. return fmt.Sprintf("%d hours", hours)
  104. } else if hours < 24*7*2 {
  105. return fmt.Sprintf("%d days", hours/24)
  106. } else if hours < 24*30*3 {
  107. return fmt.Sprintf("%d weeks", hours/24/7)
  108. } else if hours < 24*365*2 {
  109. return fmt.Sprintf("%d months", hours/24/30)
  110. }
  111. return fmt.Sprintf("%d years", d.Hours()/24/365)
  112. }
  113. func Trunc(s string, maxlen int) string {
  114. if len(s) <= maxlen {
  115. return s
  116. }
  117. return s[:maxlen]
  118. }
  119. // Figure out the absolute path of our own binary
  120. func SelfPath() string {
  121. path, err := exec.LookPath(os.Args[0])
  122. if err != nil {
  123. panic(err)
  124. }
  125. path, err = filepath.Abs(path)
  126. if err != nil {
  127. panic(err)
  128. }
  129. return path
  130. }
  131. type nopWriteCloser struct {
  132. io.Writer
  133. }
  134. func (w *nopWriteCloser) Close() error { return nil }
  135. func NopWriteCloser(w io.Writer) io.WriteCloser {
  136. return &nopWriteCloser{w}
  137. }
  138. type bufReader struct {
  139. buf *bytes.Buffer
  140. reader io.Reader
  141. err error
  142. l sync.Mutex
  143. wait sync.Cond
  144. }
  145. func newBufReader(r io.Reader) *bufReader {
  146. reader := &bufReader{
  147. buf: &bytes.Buffer{},
  148. reader: r,
  149. }
  150. reader.wait.L = &reader.l
  151. go reader.drain()
  152. return reader
  153. }
  154. func (r *bufReader) drain() {
  155. buf := make([]byte, 1024)
  156. for {
  157. n, err := r.reader.Read(buf)
  158. if err != nil {
  159. r.err = err
  160. } else {
  161. r.buf.Write(buf[0:n])
  162. }
  163. r.l.Lock()
  164. r.wait.Signal()
  165. r.l.Unlock()
  166. if err != nil {
  167. break
  168. }
  169. }
  170. }
  171. func (r *bufReader) Read(p []byte) (n int, err error) {
  172. for {
  173. n, err = r.buf.Read(p)
  174. if n > 0 {
  175. return n, err
  176. }
  177. if r.err != nil {
  178. return 0, r.err
  179. }
  180. r.l.Lock()
  181. r.wait.Wait()
  182. r.l.Unlock()
  183. }
  184. return
  185. }
  186. func (r *bufReader) Close() error {
  187. closer, ok := r.reader.(io.ReadCloser)
  188. if !ok {
  189. return nil
  190. }
  191. return closer.Close()
  192. }
  193. type writeBroadcaster struct {
  194. writers *list.List
  195. }
  196. func (w *writeBroadcaster) AddWriter(writer io.WriteCloser) {
  197. w.writers.PushBack(writer)
  198. }
  199. func (w *writeBroadcaster) RemoveWriter(writer io.WriteCloser) {
  200. for e := w.writers.Front(); e != nil; e = e.Next() {
  201. v := e.Value.(io.Writer)
  202. if v == writer {
  203. w.writers.Remove(e)
  204. return
  205. }
  206. }
  207. }
  208. func (w *writeBroadcaster) Write(p []byte) (n int, err error) {
  209. failed := []*list.Element{}
  210. for e := w.writers.Front(); e != nil; e = e.Next() {
  211. writer := e.Value.(io.Writer)
  212. if n, err := writer.Write(p); err != nil || n != len(p) {
  213. // On error, evict the writer
  214. failed = append(failed, e)
  215. }
  216. }
  217. // We cannot remove while iterating, so it has to be done in
  218. // a separate step
  219. for _, e := range failed {
  220. w.writers.Remove(e)
  221. }
  222. return len(p), nil
  223. }
  224. func (w *writeBroadcaster) Close() error {
  225. for e := w.writers.Front(); e != nil; e = e.Next() {
  226. writer := e.Value.(io.WriteCloser)
  227. writer.Close()
  228. }
  229. return nil
  230. }
  231. func newWriteBroadcaster() *writeBroadcaster {
  232. return &writeBroadcaster{list.New()}
  233. }