utils.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. package docker
  2. import (
  3. "bytes"
  4. "container/list"
  5. "errors"
  6. "fmt"
  7. "github.com/dotcloud/docker/rcli"
  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 rcli.DEBUG_FLAG {
  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. if rcli.CLIENT_SOCKET != nil {
  55. fmt.Fprintf(rcli.CLIENT_SOCKET, fmt.Sprintf("[debug] %s:%d %s\n", file, line, format), a...)
  56. }
  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. }
  67. func (r *progressReader) Read(p []byte) (n int, err error) {
  68. read, err := io.ReadCloser(r.reader).Read(p)
  69. r.readProgress += read
  70. // Only update progress for every 1% read
  71. updateEvery := int(0.01 * float64(r.readTotal))
  72. if r.readProgress-r.lastUpdate > updateEvery || r.readProgress == r.readTotal {
  73. fmt.Fprintf(r.output, "%d/%d (%.0f%%)\r",
  74. r.readProgress,
  75. r.readTotal,
  76. float64(r.readProgress)/float64(r.readTotal)*100)
  77. r.lastUpdate = r.readProgress
  78. }
  79. // Send newline when complete
  80. if err == io.EOF {
  81. fmt.Fprintf(r.output, "\n")
  82. }
  83. return read, err
  84. }
  85. func (r *progressReader) Close() error {
  86. return io.ReadCloser(r.reader).Close()
  87. }
  88. func ProgressReader(r io.ReadCloser, size int, output io.Writer) *progressReader {
  89. return &progressReader{r, output, size, 0, 0}
  90. }
  91. // HumanDuration returns a human-readable approximation of a duration
  92. // (eg. "About a minute", "4 hours ago", etc.)
  93. func HumanDuration(d time.Duration) string {
  94. if seconds := int(d.Seconds()); seconds < 1 {
  95. return "Less than a second"
  96. } else if seconds < 60 {
  97. return fmt.Sprintf("%d seconds", seconds)
  98. } else if minutes := int(d.Minutes()); minutes == 1 {
  99. return "About a minute"
  100. } else if minutes < 60 {
  101. return fmt.Sprintf("%d minutes", minutes)
  102. } else if hours := int(d.Hours()); hours == 1 {
  103. return "About an hour"
  104. } else if hours < 48 {
  105. return fmt.Sprintf("%d hours", hours)
  106. } else if hours < 24*7*2 {
  107. return fmt.Sprintf("%d days", hours/24)
  108. } else if hours < 24*30*3 {
  109. return fmt.Sprintf("%d weeks", hours/24/7)
  110. } else if hours < 24*365*2 {
  111. return fmt.Sprintf("%d months", hours/24/30)
  112. }
  113. return fmt.Sprintf("%d years", d.Hours()/24/365)
  114. }
  115. func Trunc(s string, maxlen int) string {
  116. if len(s) <= maxlen {
  117. return s
  118. }
  119. return s[:maxlen]
  120. }
  121. // Figure out the absolute path of our own binary
  122. func SelfPath() string {
  123. path, err := exec.LookPath(os.Args[0])
  124. if err != nil {
  125. panic(err)
  126. }
  127. path, err = filepath.Abs(path)
  128. if err != nil {
  129. panic(err)
  130. }
  131. return path
  132. }
  133. type nopWriteCloser struct {
  134. io.Writer
  135. }
  136. func (w *nopWriteCloser) Close() error { return nil }
  137. func NopWriteCloser(w io.Writer) io.WriteCloser {
  138. return &nopWriteCloser{w}
  139. }
  140. type bufReader struct {
  141. buf *bytes.Buffer
  142. reader io.Reader
  143. err error
  144. l sync.Mutex
  145. wait sync.Cond
  146. }
  147. func newBufReader(r io.Reader) *bufReader {
  148. reader := &bufReader{
  149. buf: &bytes.Buffer{},
  150. reader: r,
  151. }
  152. reader.wait.L = &reader.l
  153. go reader.drain()
  154. return reader
  155. }
  156. func (r *bufReader) drain() {
  157. buf := make([]byte, 1024)
  158. for {
  159. n, err := r.reader.Read(buf)
  160. r.l.Lock()
  161. if err != nil {
  162. r.err = err
  163. } else {
  164. r.buf.Write(buf[0:n])
  165. }
  166. r.wait.Signal()
  167. r.l.Unlock()
  168. if err != nil {
  169. break
  170. }
  171. }
  172. }
  173. func (r *bufReader) Read(p []byte) (n int, err error) {
  174. r.l.Lock()
  175. defer r.l.Unlock()
  176. for {
  177. n, err = r.buf.Read(p)
  178. if n > 0 {
  179. return n, err
  180. }
  181. if r.err != nil {
  182. return 0, r.err
  183. }
  184. r.wait.Wait()
  185. }
  186. return
  187. }
  188. func (r *bufReader) Close() error {
  189. closer, ok := r.reader.(io.ReadCloser)
  190. if !ok {
  191. return nil
  192. }
  193. return closer.Close()
  194. }
  195. type writeBroadcaster struct {
  196. writers *list.List
  197. }
  198. func (w *writeBroadcaster) AddWriter(writer io.WriteCloser) {
  199. w.writers.PushBack(writer)
  200. }
  201. // FIXME: Is that function used?
  202. func (w *writeBroadcaster) RemoveWriter(writer io.WriteCloser) {
  203. for e := w.writers.Front(); e != nil; e = e.Next() {
  204. v := e.Value.(io.Writer)
  205. if v == writer {
  206. w.writers.Remove(e)
  207. return
  208. }
  209. }
  210. }
  211. func (w *writeBroadcaster) Write(p []byte) (n int, err error) {
  212. failed := []*list.Element{}
  213. for e := w.writers.Front(); e != nil; e = e.Next() {
  214. writer := e.Value.(io.Writer)
  215. if n, err := writer.Write(p); err != nil || n != len(p) {
  216. // On error, evict the writer
  217. failed = append(failed, e)
  218. }
  219. }
  220. // We cannot remove while iterating, so it has to be done in
  221. // a separate step
  222. for _, e := range failed {
  223. w.writers.Remove(e)
  224. }
  225. return len(p), nil
  226. }
  227. func (w *writeBroadcaster) Close() error {
  228. for e := w.writers.Front(); e != nil; e = e.Next() {
  229. writer := e.Value.(io.WriteCloser)
  230. writer.Close()
  231. }
  232. w.writers.Init()
  233. return nil
  234. }
  235. func newWriteBroadcaster() *writeBroadcaster {
  236. return &writeBroadcaster{list.New()}
  237. }
  238. func getTotalUsedFds() int {
  239. if fds, err := ioutil.ReadDir(fmt.Sprintf("/proc/%d/fd", os.Getpid())); err != nil {
  240. Debugf("Error opening /proc/%d/fd: %s", os.Getpid(), err)
  241. } else {
  242. return len(fds)
  243. }
  244. return -1
  245. }
  246. // TruncIndex allows the retrieval of string identifiers by any of their unique prefixes.
  247. // This is used to retrieve image and container IDs by more convenient shorthand prefixes.
  248. type TruncIndex struct {
  249. index *suffixarray.Index
  250. ids map[string]bool
  251. bytes []byte
  252. }
  253. func NewTruncIndex() *TruncIndex {
  254. return &TruncIndex{
  255. index: suffixarray.New([]byte{' '}),
  256. ids: make(map[string]bool),
  257. bytes: []byte{' '},
  258. }
  259. }
  260. func (idx *TruncIndex) Add(id string) error {
  261. if strings.Contains(id, " ") {
  262. return fmt.Errorf("Illegal character: ' '")
  263. }
  264. if _, exists := idx.ids[id]; exists {
  265. return fmt.Errorf("Id already exists: %s", id)
  266. }
  267. idx.ids[id] = true
  268. idx.bytes = append(idx.bytes, []byte(id+" ")...)
  269. idx.index = suffixarray.New(idx.bytes)
  270. return nil
  271. }
  272. func (idx *TruncIndex) Delete(id string) error {
  273. if _, exists := idx.ids[id]; !exists {
  274. return fmt.Errorf("No such id: %s", id)
  275. }
  276. before, after, err := idx.lookup(id)
  277. if err != nil {
  278. return err
  279. }
  280. delete(idx.ids, id)
  281. idx.bytes = append(idx.bytes[:before], idx.bytes[after:]...)
  282. idx.index = suffixarray.New(idx.bytes)
  283. return nil
  284. }
  285. func (idx *TruncIndex) lookup(s string) (int, int, error) {
  286. offsets := idx.index.Lookup([]byte(" "+s), -1)
  287. //log.Printf("lookup(%s): %v (index bytes: '%s')\n", s, offsets, idx.index.Bytes())
  288. if offsets == nil || len(offsets) == 0 || len(offsets) > 1 {
  289. return -1, -1, fmt.Errorf("No such id: %s", s)
  290. }
  291. offsetBefore := offsets[0] + 1
  292. offsetAfter := offsetBefore + strings.Index(string(idx.bytes[offsetBefore:]), " ")
  293. return offsetBefore, offsetAfter, nil
  294. }
  295. func (idx *TruncIndex) Get(s string) (string, error) {
  296. before, after, err := idx.lookup(s)
  297. //log.Printf("Get(%s) bytes=|%s| before=|%d| after=|%d|\n", s, idx.bytes, before, after)
  298. if err != nil {
  299. return "", err
  300. }
  301. return string(idx.bytes[before:after]), err
  302. }
  303. // TruncateId returns a shorthand version of a string identifier for convenience.
  304. // A collision with other shorthands is very unlikely, but possible.
  305. // In case of a collision a lookup with TruncIndex.Get() will fail, and the caller
  306. // will need to use a langer prefix, or the full-length Id.
  307. func TruncateId(id string) string {
  308. shortLen := 12
  309. if len(id) < shortLen {
  310. shortLen = len(id)
  311. }
  312. return id[:shortLen]
  313. }