utils.go 5.6 KB

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