utils.go 9.5 KB

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