utils.go 9.0 KB

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