utils.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. package docker
  2. import (
  3. "bytes"
  4. "crypto/sha256"
  5. "encoding/hex"
  6. "errors"
  7. "fmt"
  8. "github.com/dotcloud/docker/term"
  9. "index/suffixarray"
  10. "io"
  11. "io/ioutil"
  12. "net/http"
  13. "os"
  14. "os/exec"
  15. "os/signal"
  16. "path/filepath"
  17. "runtime"
  18. _ "strconv"
  19. "strings"
  20. "sync"
  21. "time"
  22. )
  23. // Go is a basic promise implementation: it wraps calls a function in a goroutine,
  24. // and returns a channel which will later return the function's return value.
  25. func Go(f func() error) chan error {
  26. ch := make(chan error)
  27. go func() {
  28. ch <- f()
  29. }()
  30. return ch
  31. }
  32. // Request a given URL and return an io.Reader
  33. func Download(url string, stderr io.Writer) (*http.Response, error) {
  34. var resp *http.Response
  35. var err error = nil
  36. if resp, err = http.Get(url); err != nil {
  37. return nil, err
  38. }
  39. if resp.StatusCode >= 400 {
  40. return nil, errors.New("Got HTTP status code >= 400: " + resp.Status)
  41. }
  42. return resp, nil
  43. }
  44. // Debug function, if the debug flag is set, then display. Do nothing otherwise
  45. // If Docker is in damon mode, also send the debug info on the socket
  46. func Debugf(format string, a ...interface{}) {
  47. if os.Getenv("DEBUG") != "" {
  48. // Retrieve the stack infos
  49. _, file, line, ok := runtime.Caller(1)
  50. if !ok {
  51. file = "<unknown>"
  52. line = -1
  53. } else {
  54. file = file[strings.LastIndex(file, "/")+1:]
  55. }
  56. fmt.Fprintf(os.Stderr, fmt.Sprintf("[debug] %s:%d %s\n", file, line, format), a...)
  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. // HumanSize returns a human-readabla approximation of a size
  126. // (eg. "44K", "17M")
  127. func HumanSize(size int64) string {
  128. i := 0
  129. var sizef float64
  130. sizef = float64(size)
  131. units := []string{"B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"}
  132. for sizef > 1024.0 {
  133. sizef = sizef / 1024.0
  134. i++
  135. }
  136. return fmt.Sprintf("%.*f %s", i, sizef, units[i])
  137. // sprintf(buf, "%.*f %s", i, size, units[i]);
  138. // if size/1024/1024 > 1000 {
  139. // return strconv.FormatFloat((float64)(size/1024/1024), 'f', 2, 32) + "G"
  140. // }
  141. // if size/1024 > 1024 {
  142. // return strconv.FormatInt(size/1024/1024, 10) + "M"
  143. // }
  144. // return strconv.FormatInt(size/1024, 10) + "K"
  145. }
  146. func Trunc(s string, maxlen int) string {
  147. if len(s) <= maxlen {
  148. return s
  149. }
  150. return s[:maxlen]
  151. }
  152. // Figure out the absolute path of our own binary
  153. func SelfPath() string {
  154. path, err := exec.LookPath(os.Args[0])
  155. if err != nil {
  156. panic(err)
  157. }
  158. path, err = filepath.Abs(path)
  159. if err != nil {
  160. panic(err)
  161. }
  162. return path
  163. }
  164. type nopWriter struct {
  165. }
  166. func (w *nopWriter) Write(buf []byte) (int, error) {
  167. return len(buf), nil
  168. }
  169. type nopWriteCloser struct {
  170. io.Writer
  171. }
  172. func (w *nopWriteCloser) Close() error { return nil }
  173. func NopWriteCloser(w io.Writer) io.WriteCloser {
  174. return &nopWriteCloser{w}
  175. }
  176. type bufReader struct {
  177. buf *bytes.Buffer
  178. reader io.Reader
  179. err error
  180. l sync.Mutex
  181. wait sync.Cond
  182. }
  183. func newBufReader(r io.Reader) *bufReader {
  184. reader := &bufReader{
  185. buf: &bytes.Buffer{},
  186. reader: r,
  187. }
  188. reader.wait.L = &reader.l
  189. go reader.drain()
  190. return reader
  191. }
  192. func (r *bufReader) drain() {
  193. buf := make([]byte, 1024)
  194. for {
  195. n, err := r.reader.Read(buf)
  196. r.l.Lock()
  197. if err != nil {
  198. r.err = err
  199. } else {
  200. r.buf.Write(buf[0:n])
  201. }
  202. r.wait.Signal()
  203. r.l.Unlock()
  204. if err != nil {
  205. break
  206. }
  207. }
  208. }
  209. func (r *bufReader) Read(p []byte) (n int, err error) {
  210. r.l.Lock()
  211. defer r.l.Unlock()
  212. for {
  213. n, err = r.buf.Read(p)
  214. if n > 0 {
  215. return n, err
  216. }
  217. if r.err != nil {
  218. return 0, r.err
  219. }
  220. r.wait.Wait()
  221. }
  222. panic("unreachable")
  223. }
  224. func (r *bufReader) Close() error {
  225. closer, ok := r.reader.(io.ReadCloser)
  226. if !ok {
  227. return nil
  228. }
  229. return closer.Close()
  230. }
  231. type writeBroadcaster struct {
  232. mu sync.Mutex
  233. writers map[io.WriteCloser]struct{}
  234. }
  235. func (w *writeBroadcaster) AddWriter(writer io.WriteCloser) {
  236. w.mu.Lock()
  237. w.writers[writer] = struct{}{}
  238. w.mu.Unlock()
  239. }
  240. // FIXME: Is that function used?
  241. // FIXME: This relies on the concrete writer type used having equality operator
  242. func (w *writeBroadcaster) RemoveWriter(writer io.WriteCloser) {
  243. w.mu.Lock()
  244. delete(w.writers, writer)
  245. w.mu.Unlock()
  246. }
  247. func (w *writeBroadcaster) Write(p []byte) (n int, err error) {
  248. w.mu.Lock()
  249. defer w.mu.Unlock()
  250. for writer := range w.writers {
  251. if n, err := writer.Write(p); err != nil || n != len(p) {
  252. // On error, evict the writer
  253. delete(w.writers, writer)
  254. }
  255. }
  256. return len(p), nil
  257. }
  258. func (w *writeBroadcaster) CloseWriters() error {
  259. w.mu.Lock()
  260. defer w.mu.Unlock()
  261. for writer := range w.writers {
  262. writer.Close()
  263. }
  264. w.writers = make(map[io.WriteCloser]struct{})
  265. return nil
  266. }
  267. func newWriteBroadcaster() *writeBroadcaster {
  268. return &writeBroadcaster{writers: make(map[io.WriteCloser]struct{})}
  269. }
  270. func getTotalUsedFds() int {
  271. if fds, err := ioutil.ReadDir(fmt.Sprintf("/proc/%d/fd", os.Getpid())); err != nil {
  272. Debugf("Error opening /proc/%d/fd: %s", os.Getpid(), err)
  273. } else {
  274. return len(fds)
  275. }
  276. return -1
  277. }
  278. // TruncIndex allows the retrieval of string identifiers by any of their unique prefixes.
  279. // This is used to retrieve image and container IDs by more convenient shorthand prefixes.
  280. type TruncIndex struct {
  281. index *suffixarray.Index
  282. ids map[string]bool
  283. bytes []byte
  284. }
  285. func NewTruncIndex() *TruncIndex {
  286. return &TruncIndex{
  287. index: suffixarray.New([]byte{' '}),
  288. ids: make(map[string]bool),
  289. bytes: []byte{' '},
  290. }
  291. }
  292. func (idx *TruncIndex) Add(id string) error {
  293. if strings.Contains(id, " ") {
  294. return fmt.Errorf("Illegal character: ' '")
  295. }
  296. if _, exists := idx.ids[id]; exists {
  297. return fmt.Errorf("Id already exists: %s", id)
  298. }
  299. idx.ids[id] = true
  300. idx.bytes = append(idx.bytes, []byte(id+" ")...)
  301. idx.index = suffixarray.New(idx.bytes)
  302. return nil
  303. }
  304. func (idx *TruncIndex) Delete(id string) error {
  305. if _, exists := idx.ids[id]; !exists {
  306. return fmt.Errorf("No such id: %s", id)
  307. }
  308. before, after, err := idx.lookup(id)
  309. if err != nil {
  310. return err
  311. }
  312. delete(idx.ids, id)
  313. idx.bytes = append(idx.bytes[:before], idx.bytes[after:]...)
  314. idx.index = suffixarray.New(idx.bytes)
  315. return nil
  316. }
  317. func (idx *TruncIndex) lookup(s string) (int, int, error) {
  318. offsets := idx.index.Lookup([]byte(" "+s), -1)
  319. //log.Printf("lookup(%s): %v (index bytes: '%s')\n", s, offsets, idx.index.Bytes())
  320. if offsets == nil || len(offsets) == 0 || len(offsets) > 1 {
  321. return -1, -1, fmt.Errorf("No such id: %s", s)
  322. }
  323. offsetBefore := offsets[0] + 1
  324. offsetAfter := offsetBefore + strings.Index(string(idx.bytes[offsetBefore:]), " ")
  325. return offsetBefore, offsetAfter, nil
  326. }
  327. func (idx *TruncIndex) Get(s string) (string, error) {
  328. before, after, err := idx.lookup(s)
  329. //log.Printf("Get(%s) bytes=|%s| before=|%d| after=|%d|\n", s, idx.bytes, before, after)
  330. if err != nil {
  331. return "", err
  332. }
  333. return string(idx.bytes[before:after]), err
  334. }
  335. // TruncateId returns a shorthand version of a string identifier for convenience.
  336. // A collision with other shorthands is very unlikely, but possible.
  337. // In case of a collision a lookup with TruncIndex.Get() will fail, and the caller
  338. // will need to use a langer prefix, or the full-length Id.
  339. func TruncateId(id string) string {
  340. shortLen := 12
  341. if len(id) < shortLen {
  342. shortLen = len(id)
  343. }
  344. return id[:shortLen]
  345. }
  346. // Code c/c from io.Copy() modified to handle escape sequence
  347. func CopyEscapable(dst io.Writer, src io.ReadCloser) (written int64, err error) {
  348. buf := make([]byte, 32*1024)
  349. for {
  350. nr, er := src.Read(buf)
  351. if nr > 0 {
  352. // ---- Docker addition
  353. // char 16 is C-p
  354. if nr == 1 && buf[0] == 16 {
  355. nr, er = src.Read(buf)
  356. // char 17 is C-q
  357. if nr == 1 && buf[0] == 17 {
  358. if err := src.Close(); err != nil {
  359. return 0, err
  360. }
  361. return 0, io.EOF
  362. }
  363. }
  364. // ---- End of docker
  365. nw, ew := dst.Write(buf[0:nr])
  366. if nw > 0 {
  367. written += int64(nw)
  368. }
  369. if ew != nil {
  370. err = ew
  371. break
  372. }
  373. if nr != nw {
  374. err = io.ErrShortWrite
  375. break
  376. }
  377. }
  378. if er == io.EOF {
  379. break
  380. }
  381. if er != nil {
  382. err = er
  383. break
  384. }
  385. }
  386. return written, err
  387. }
  388. func SetRawTerminal() (*term.State, error) {
  389. oldState, err := term.MakeRaw(int(os.Stdin.Fd()))
  390. if err != nil {
  391. return nil, err
  392. }
  393. c := make(chan os.Signal, 1)
  394. signal.Notify(c, os.Interrupt)
  395. go func() {
  396. _ = <-c
  397. term.Restore(int(os.Stdin.Fd()), oldState)
  398. os.Exit(0)
  399. }()
  400. return oldState, err
  401. }
  402. func RestoreTerminal(state *term.State) {
  403. term.Restore(int(os.Stdin.Fd()), state)
  404. }
  405. func HashData(src io.Reader) (string, error) {
  406. h := sha256.New()
  407. if _, err := io.Copy(h, src); err != nil {
  408. return "", err
  409. }
  410. return "sha256:" + hex.EncodeToString(h.Sum(nil)), nil
  411. }
  412. type KernelVersionInfo struct {
  413. Kernel int
  414. Major int
  415. Minor int
  416. Flavor string
  417. }
  418. // FIXME: this doens't build on Darwin
  419. func GetKernelVersion() (*KernelVersionInfo, error) {
  420. return getKernelVersion()
  421. }
  422. func (k *KernelVersionInfo) String() string {
  423. flavor := ""
  424. if len(k.Flavor) > 0 {
  425. flavor = fmt.Sprintf("-%s", k.Flavor)
  426. }
  427. return fmt.Sprintf("%d.%d.%d%s", k.Kernel, k.Major, k.Minor, flavor)
  428. }
  429. // Compare two KernelVersionInfo struct.
  430. // Returns -1 if a < b, = if a == b, 1 it a > b
  431. func CompareKernelVersion(a, b *KernelVersionInfo) int {
  432. if a.Kernel < b.Kernel {
  433. return -1
  434. } else if a.Kernel > b.Kernel {
  435. return 1
  436. }
  437. if a.Major < b.Major {
  438. return -1
  439. } else if a.Major > b.Major {
  440. return 1
  441. }
  442. if a.Minor < b.Minor {
  443. return -1
  444. } else if a.Minor > b.Minor {
  445. return 1
  446. }
  447. return 0
  448. }
  449. func FindCgroupMountpoint(cgroupType string) (string, error) {
  450. output, err := ioutil.ReadFile("/proc/mounts")
  451. if err != nil {
  452. return "", err
  453. }
  454. // /proc/mounts has 6 fields per line, one mount per line, e.g.
  455. // cgroup /sys/fs/cgroup/devices cgroup rw,relatime,devices 0 0
  456. for _, line := range strings.Split(string(output), "\n") {
  457. parts := strings.Split(line, " ")
  458. if len(parts) == 6 && parts[2] == "cgroup" {
  459. for _, opt := range strings.Split(parts[3], ",") {
  460. if opt == cgroupType {
  461. return parts[1], nil
  462. }
  463. }
  464. }
  465. }
  466. return "", fmt.Errorf("cgroup mountpoint not found for %s", cgroupType)
  467. }
  468. // Compare two Config struct. Do not compare the "Image" nor "Hostname" fields
  469. // If OpenStdin is set, then it differs
  470. func CompareConfig(a, b *Config) bool {
  471. if a == nil || b == nil ||
  472. a.OpenStdin || b.OpenStdin {
  473. return false
  474. }
  475. if a.AttachStdout != b.AttachStdout ||
  476. a.AttachStderr != b.AttachStderr ||
  477. a.User != b.User ||
  478. a.Memory != b.Memory ||
  479. a.MemorySwap != b.MemorySwap ||
  480. a.OpenStdin != b.OpenStdin ||
  481. a.Tty != b.Tty {
  482. return false
  483. }
  484. if len(a.Cmd) != len(b.Cmd) ||
  485. len(a.Dns) != len(b.Dns) ||
  486. len(a.Env) != len(b.Env) ||
  487. len(a.PortSpecs) != len(b.PortSpecs) {
  488. return false
  489. }
  490. for i := 0; i < len(a.Cmd); i++ {
  491. if a.Cmd[i] != b.Cmd[i] {
  492. return false
  493. }
  494. }
  495. for i := 0; i < len(a.Dns); i++ {
  496. if a.Dns[i] != b.Dns[i] {
  497. return false
  498. }
  499. }
  500. for i := 0; i < len(a.Env); i++ {
  501. if a.Env[i] != b.Env[i] {
  502. return false
  503. }
  504. }
  505. for i := 0; i < len(a.PortSpecs); i++ {
  506. if a.PortSpecs[i] != b.PortSpecs[i] {
  507. return false
  508. }
  509. }
  510. return true
  511. }