utils.go 11 KB

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