utils.go 12 KB

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