utils.go 11 KB

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