utils.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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. template string // Template to print. Default "%v/%v (%v)"
  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. updateEvery := 4096
  71. if r.readTotal > 0 {
  72. // Only update progress for every 1% read
  73. if increment := int(0.01 * float64(r.readTotal)); increment > updateEvery {
  74. updateEvery = increment
  75. }
  76. }
  77. if r.readProgress-r.lastUpdate > updateEvery || err != nil {
  78. if r.readTotal > 0 {
  79. fmt.Fprintf(r.output, r.template+"\r", r.readProgress, r.readTotal, fmt.Sprintf("%.0f%%", float64(r.readProgress)/float64(r.readTotal)*100))
  80. } else {
  81. fmt.Fprintf(r.output, r.template+"\r", r.readProgress, "?", "n/a")
  82. }
  83. r.lastUpdate = r.readProgress
  84. }
  85. // Send newline when complete
  86. if err != nil {
  87. fmt.Fprintf(r.output, "\n")
  88. }
  89. return read, err
  90. }
  91. func (r *progressReader) Close() error {
  92. return io.ReadCloser(r.reader).Close()
  93. }
  94. func ProgressReader(r io.ReadCloser, size int, output io.Writer, template string) *progressReader {
  95. if template == "" {
  96. template = "%v/%v (%v)"
  97. }
  98. return &progressReader{r, output, size, 0, 0, template}
  99. }
  100. // HumanDuration returns a human-readable approximation of a duration
  101. // (eg. "About a minute", "4 hours ago", etc.)
  102. func HumanDuration(d time.Duration) string {
  103. if seconds := int(d.Seconds()); seconds < 1 {
  104. return "Less than a second"
  105. } else if seconds < 60 {
  106. return fmt.Sprintf("%d seconds", seconds)
  107. } else if minutes := int(d.Minutes()); minutes == 1 {
  108. return "About a minute"
  109. } else if minutes < 60 {
  110. return fmt.Sprintf("%d minutes", minutes)
  111. } else if hours := int(d.Hours()); hours == 1 {
  112. return "About an hour"
  113. } else if hours < 48 {
  114. return fmt.Sprintf("%d hours", hours)
  115. } else if hours < 24*7*2 {
  116. return fmt.Sprintf("%d days", hours/24)
  117. } else if hours < 24*30*3 {
  118. return fmt.Sprintf("%d weeks", hours/24/7)
  119. } else if hours < 24*365*2 {
  120. return fmt.Sprintf("%d months", hours/24/30)
  121. }
  122. return fmt.Sprintf("%d years", d.Hours()/24/365)
  123. }
  124. func Trunc(s string, maxlen int) string {
  125. if len(s) <= maxlen {
  126. return s
  127. }
  128. return s[:maxlen]
  129. }
  130. // Figure out the absolute path of our own binary
  131. func SelfPath() string {
  132. path, err := exec.LookPath(os.Args[0])
  133. if err != nil {
  134. panic(err)
  135. }
  136. path, err = filepath.Abs(path)
  137. if err != nil {
  138. panic(err)
  139. }
  140. return path
  141. }
  142. type nopWriteCloser struct {
  143. io.Writer
  144. }
  145. func (w *nopWriteCloser) Close() error { return nil }
  146. func NopWriteCloser(w io.Writer) io.WriteCloser {
  147. return &nopWriteCloser{w}
  148. }
  149. type bufReader struct {
  150. buf *bytes.Buffer
  151. reader io.Reader
  152. err error
  153. l sync.Mutex
  154. wait sync.Cond
  155. }
  156. func newBufReader(r io.Reader) *bufReader {
  157. reader := &bufReader{
  158. buf: &bytes.Buffer{},
  159. reader: r,
  160. }
  161. reader.wait.L = &reader.l
  162. go reader.drain()
  163. return reader
  164. }
  165. func (r *bufReader) drain() {
  166. buf := make([]byte, 1024)
  167. for {
  168. n, err := r.reader.Read(buf)
  169. r.l.Lock()
  170. if err != nil {
  171. r.err = err
  172. } else {
  173. r.buf.Write(buf[0:n])
  174. }
  175. r.wait.Signal()
  176. r.l.Unlock()
  177. if err != nil {
  178. break
  179. }
  180. }
  181. }
  182. func (r *bufReader) Read(p []byte) (n int, err error) {
  183. r.l.Lock()
  184. defer r.l.Unlock()
  185. for {
  186. n, err = r.buf.Read(p)
  187. if n > 0 {
  188. return n, err
  189. }
  190. if r.err != nil {
  191. return 0, r.err
  192. }
  193. r.wait.Wait()
  194. }
  195. panic("unreachable")
  196. }
  197. func (r *bufReader) Close() error {
  198. closer, ok := r.reader.(io.ReadCloser)
  199. if !ok {
  200. return nil
  201. }
  202. return closer.Close()
  203. }
  204. type writeBroadcaster struct {
  205. mu sync.Mutex
  206. writers map[io.WriteCloser]struct{}
  207. }
  208. func (w *writeBroadcaster) AddWriter(writer io.WriteCloser) {
  209. w.mu.Lock()
  210. w.writers[writer] = struct{}{}
  211. w.mu.Unlock()
  212. }
  213. // FIXME: Is that function used?
  214. // FIXME: This relies on the concrete writer type used having equality operator
  215. func (w *writeBroadcaster) RemoveWriter(writer io.WriteCloser) {
  216. w.mu.Lock()
  217. delete(w.writers, writer)
  218. w.mu.Unlock()
  219. }
  220. func (w *writeBroadcaster) Write(p []byte) (n int, err error) {
  221. w.mu.Lock()
  222. defer w.mu.Unlock()
  223. for writer := range w.writers {
  224. if n, err := writer.Write(p); err != nil || n != len(p) {
  225. // On error, evict the writer
  226. delete(w.writers, writer)
  227. }
  228. }
  229. return len(p), nil
  230. }
  231. func (w *writeBroadcaster) CloseWriters() error {
  232. w.mu.Lock()
  233. defer w.mu.Unlock()
  234. for writer := range w.writers {
  235. writer.Close()
  236. }
  237. w.writers = make(map[io.WriteCloser]struct{})
  238. return nil
  239. }
  240. func newWriteBroadcaster() *writeBroadcaster {
  241. return &writeBroadcaster{writers: make(map[io.WriteCloser]struct{})}
  242. }
  243. func getTotalUsedFds() int {
  244. if fds, err := ioutil.ReadDir(fmt.Sprintf("/proc/%d/fd", os.Getpid())); err != nil {
  245. Debugf("Error opening /proc/%d/fd: %s", os.Getpid(), err)
  246. } else {
  247. return len(fds)
  248. }
  249. return -1
  250. }
  251. // TruncIndex allows the retrieval of string identifiers by any of their unique prefixes.
  252. // This is used to retrieve image and container IDs by more convenient shorthand prefixes.
  253. type TruncIndex struct {
  254. index *suffixarray.Index
  255. ids map[string]bool
  256. bytes []byte
  257. }
  258. func NewTruncIndex() *TruncIndex {
  259. return &TruncIndex{
  260. index: suffixarray.New([]byte{' '}),
  261. ids: make(map[string]bool),
  262. bytes: []byte{' '},
  263. }
  264. }
  265. func (idx *TruncIndex) Add(id string) error {
  266. if strings.Contains(id, " ") {
  267. return fmt.Errorf("Illegal character: ' '")
  268. }
  269. if _, exists := idx.ids[id]; exists {
  270. return fmt.Errorf("Id already exists: %s", id)
  271. }
  272. idx.ids[id] = true
  273. idx.bytes = append(idx.bytes, []byte(id+" ")...)
  274. idx.index = suffixarray.New(idx.bytes)
  275. return nil
  276. }
  277. func (idx *TruncIndex) Delete(id string) error {
  278. if _, exists := idx.ids[id]; !exists {
  279. return fmt.Errorf("No such id: %s", id)
  280. }
  281. before, after, err := idx.lookup(id)
  282. if err != nil {
  283. return err
  284. }
  285. delete(idx.ids, id)
  286. idx.bytes = append(idx.bytes[:before], idx.bytes[after:]...)
  287. idx.index = suffixarray.New(idx.bytes)
  288. return nil
  289. }
  290. func (idx *TruncIndex) lookup(s string) (int, int, error) {
  291. offsets := idx.index.Lookup([]byte(" "+s), -1)
  292. //log.Printf("lookup(%s): %v (index bytes: '%s')\n", s, offsets, idx.index.Bytes())
  293. if offsets == nil || len(offsets) == 0 || len(offsets) > 1 {
  294. return -1, -1, fmt.Errorf("No such id: %s", s)
  295. }
  296. offsetBefore := offsets[0] + 1
  297. offsetAfter := offsetBefore + strings.Index(string(idx.bytes[offsetBefore:]), " ")
  298. return offsetBefore, offsetAfter, nil
  299. }
  300. func (idx *TruncIndex) Get(s string) (string, error) {
  301. before, after, err := idx.lookup(s)
  302. //log.Printf("Get(%s) bytes=|%s| before=|%d| after=|%d|\n", s, idx.bytes, before, after)
  303. if err != nil {
  304. return "", err
  305. }
  306. return string(idx.bytes[before:after]), err
  307. }
  308. // TruncateId returns a shorthand version of a string identifier for convenience.
  309. // A collision with other shorthands is very unlikely, but possible.
  310. // In case of a collision a lookup with TruncIndex.Get() will fail, and the caller
  311. // will need to use a langer prefix, or the full-length Id.
  312. func TruncateId(id string) string {
  313. shortLen := 12
  314. if len(id) < shortLen {
  315. shortLen = len(id)
  316. }
  317. return id[:shortLen]
  318. }
  319. // Code c/c from io.Copy() modified to handle escape sequence
  320. func CopyEscapable(dst io.Writer, src io.ReadCloser) (written int64, err error) {
  321. buf := make([]byte, 32*1024)
  322. for {
  323. nr, er := src.Read(buf)
  324. if nr > 0 {
  325. // ---- Docker addition
  326. // char 16 is C-p
  327. if nr == 1 && buf[0] == 16 {
  328. nr, er = src.Read(buf)
  329. // char 17 is C-q
  330. if nr == 1 && buf[0] == 17 {
  331. if err := src.Close(); err != nil {
  332. return 0, err
  333. }
  334. return 0, io.EOF
  335. }
  336. }
  337. // ---- End of docker
  338. nw, ew := dst.Write(buf[0:nr])
  339. if nw > 0 {
  340. written += int64(nw)
  341. }
  342. if ew != nil {
  343. err = ew
  344. break
  345. }
  346. if nr != nw {
  347. err = io.ErrShortWrite
  348. break
  349. }
  350. }
  351. if er == io.EOF {
  352. break
  353. }
  354. if er != nil {
  355. err = er
  356. break
  357. }
  358. }
  359. return written, err
  360. }
  361. type KernelVersionInfo struct {
  362. Kernel int
  363. Major int
  364. Minor int
  365. Flavor string
  366. }
  367. // FIXME: this doens't build on Darwin
  368. func GetKernelVersion() (*KernelVersionInfo, error) {
  369. return getKernelVersion()
  370. }
  371. func (k *KernelVersionInfo) String() string {
  372. return fmt.Sprintf("%d.%d.%d-%s", k.Kernel, k.Major, k.Minor, k.Flavor)
  373. }
  374. // Compare two KernelVersionInfo struct.
  375. // Returns -1 if a < b, = if a == b, 1 it a > b
  376. func CompareKernelVersion(a, b *KernelVersionInfo) int {
  377. if a.Kernel < b.Kernel {
  378. return -1
  379. } else if a.Kernel > b.Kernel {
  380. return 1
  381. }
  382. if a.Major < b.Major {
  383. return -1
  384. } else if a.Major > b.Major {
  385. return 1
  386. }
  387. if a.Minor < b.Minor {
  388. return -1
  389. } else if a.Minor > b.Minor {
  390. return 1
  391. }
  392. return 0
  393. }
  394. func FindCgroupMountpoint(cgroupType string) (string, error) {
  395. output, err := ioutil.ReadFile("/proc/mounts")
  396. if err != nil {
  397. return "", err
  398. }
  399. // /proc/mounts has 6 fields per line, one mount per line, e.g.
  400. // cgroup /sys/fs/cgroup/devices cgroup rw,relatime,devices 0 0
  401. for _, line := range strings.Split(string(output), "\n") {
  402. parts := strings.Split(line, " ")
  403. if len(parts) > 1 && parts[2] == "cgroup" {
  404. for _, opt := range strings.Split(parts[3], ",") {
  405. if opt == cgroupType {
  406. return parts[1], nil
  407. }
  408. }
  409. }
  410. }
  411. return "", fmt.Errorf("cgroup mountpoint not found for %s", cgroupType)
  412. }