utils.go 24 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030
  1. package utils
  2. import (
  3. "bytes"
  4. "crypto/sha256"
  5. "encoding/hex"
  6. "encoding/json"
  7. "errors"
  8. "fmt"
  9. "index/suffixarray"
  10. "io"
  11. "io/ioutil"
  12. "log"
  13. "net/http"
  14. "os"
  15. "os/exec"
  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
  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. func logf(level string, format string, a ...interface{}) {
  45. // Retrieve the stack infos
  46. _, file, line, ok := runtime.Caller(2)
  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("[%s] %s:%d %s\n", level, file, line, format), a...)
  54. }
  55. // Debug function, if the debug flag is set, then display. Do nothing otherwise
  56. // If Docker is in damon mode, also send the debug info on the socket
  57. func Debugf(format string, a ...interface{}) {
  58. if os.Getenv("DEBUG") != "" {
  59. logf("debug", format, a...)
  60. }
  61. }
  62. func Errorf(format string, a ...interface{}) {
  63. logf("error", format, a...)
  64. }
  65. // Reader with progress bar
  66. type progressReader struct {
  67. reader io.ReadCloser // Stream to read from
  68. output io.Writer // Where to send progress bar to
  69. readTotal int // Expected stream length (bytes)
  70. readProgress int // How much has been read so far (bytes)
  71. lastUpdate int // How many bytes read at least update
  72. template string // Template to print. Default "%v/%v (%v)"
  73. sf *StreamFormatter
  74. newLine bool
  75. }
  76. func (r *progressReader) Read(p []byte) (n int, err error) {
  77. read, err := io.ReadCloser(r.reader).Read(p)
  78. r.readProgress += read
  79. updateEvery := 1024 * 512 //512kB
  80. if r.readTotal > 0 {
  81. // Update progress for every 1% read if 1% < 512kB
  82. if increment := int(0.01 * float64(r.readTotal)); increment < updateEvery {
  83. updateEvery = increment
  84. }
  85. }
  86. if r.readProgress-r.lastUpdate > updateEvery || err != nil {
  87. if r.readTotal > 0 {
  88. fmt.Fprintf(r.output, r.template, HumanSize(int64(r.readProgress)), HumanSize(int64(r.readTotal)), fmt.Sprintf("%.0f%%", float64(r.readProgress)/float64(r.readTotal)*100))
  89. } else {
  90. fmt.Fprintf(r.output, r.template, r.readProgress, "?", "n/a")
  91. }
  92. r.lastUpdate = r.readProgress
  93. }
  94. // Send newline when complete
  95. if r.newLine && err != nil {
  96. r.output.Write(r.sf.FormatStatus("", ""))
  97. }
  98. return read, err
  99. }
  100. func (r *progressReader) Close() error {
  101. return io.ReadCloser(r.reader).Close()
  102. }
  103. func ProgressReader(r io.ReadCloser, size int, output io.Writer, tpl []byte, sf *StreamFormatter, newline bool) *progressReader {
  104. return &progressReader{
  105. reader: r,
  106. output: NewWriteFlusher(output),
  107. readTotal: size,
  108. template: string(tpl),
  109. sf: sf,
  110. newLine: newline,
  111. }
  112. }
  113. // HumanDuration returns a human-readable approximation of a duration
  114. // (eg. "About a minute", "4 hours ago", etc.)
  115. func HumanDuration(d time.Duration) string {
  116. if seconds := int(d.Seconds()); seconds < 1 {
  117. return "Less than a second"
  118. } else if seconds < 60 {
  119. return fmt.Sprintf("%d seconds", seconds)
  120. } else if minutes := int(d.Minutes()); minutes == 1 {
  121. return "About a minute"
  122. } else if minutes < 60 {
  123. return fmt.Sprintf("%d minutes", minutes)
  124. } else if hours := int(d.Hours()); hours == 1 {
  125. return "About an hour"
  126. } else if hours < 48 {
  127. return fmt.Sprintf("%d hours", hours)
  128. } else if hours < 24*7*2 {
  129. return fmt.Sprintf("%d days", hours/24)
  130. } else if hours < 24*30*3 {
  131. return fmt.Sprintf("%d weeks", hours/24/7)
  132. } else if hours < 24*365*2 {
  133. return fmt.Sprintf("%d months", hours/24/30)
  134. }
  135. return fmt.Sprintf("%f years", d.Hours()/24/365)
  136. }
  137. // HumanSize returns a human-readable approximation of a size
  138. // using SI standard (eg. "44kB", "17MB")
  139. func HumanSize(size int64) string {
  140. i := 0
  141. var sizef float64
  142. sizef = float64(size)
  143. units := []string{"B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"}
  144. for sizef >= 1000.0 {
  145. sizef = sizef / 1000.0
  146. i++
  147. }
  148. return fmt.Sprintf("%.4g %s", sizef, units[i])
  149. }
  150. func Trunc(s string, maxlen int) string {
  151. if len(s) <= maxlen {
  152. return s
  153. }
  154. return s[:maxlen]
  155. }
  156. // Figure out the absolute path of our own binary
  157. func SelfPath() string {
  158. path, err := exec.LookPath(os.Args[0])
  159. if err != nil {
  160. panic(err)
  161. }
  162. path, err = filepath.Abs(path)
  163. if err != nil {
  164. panic(err)
  165. }
  166. return path
  167. }
  168. type NopWriter struct{}
  169. func (*NopWriter) Write(buf []byte) (int, error) {
  170. return len(buf), nil
  171. }
  172. type nopWriteCloser struct {
  173. io.Writer
  174. }
  175. func (w *nopWriteCloser) Close() error { return nil }
  176. func NopWriteCloser(w io.Writer) io.WriteCloser {
  177. return &nopWriteCloser{w}
  178. }
  179. type bufReader struct {
  180. sync.Mutex
  181. buf *bytes.Buffer
  182. reader io.Reader
  183. err error
  184. wait sync.Cond
  185. }
  186. func NewBufReader(r io.Reader) *bufReader {
  187. reader := &bufReader{
  188. buf: &bytes.Buffer{},
  189. reader: r,
  190. }
  191. reader.wait.L = &reader.Mutex
  192. go reader.drain()
  193. return reader
  194. }
  195. func (r *bufReader) drain() {
  196. buf := make([]byte, 1024)
  197. for {
  198. n, err := r.reader.Read(buf)
  199. r.Lock()
  200. if err != nil {
  201. r.err = err
  202. } else {
  203. r.buf.Write(buf[0:n])
  204. }
  205. r.wait.Signal()
  206. r.Unlock()
  207. if err != nil {
  208. break
  209. }
  210. }
  211. }
  212. func (r *bufReader) Read(p []byte) (n int, err error) {
  213. r.Lock()
  214. defer r.Unlock()
  215. for {
  216. n, err = r.buf.Read(p)
  217. if n > 0 {
  218. return n, err
  219. }
  220. if r.err != nil {
  221. return 0, r.err
  222. }
  223. r.wait.Wait()
  224. }
  225. }
  226. func (r *bufReader) Close() error {
  227. closer, ok := r.reader.(io.ReadCloser)
  228. if !ok {
  229. return nil
  230. }
  231. return closer.Close()
  232. }
  233. type WriteBroadcaster struct {
  234. sync.Mutex
  235. buf *bytes.Buffer
  236. writers map[StreamWriter]bool
  237. }
  238. type StreamWriter struct {
  239. wc io.WriteCloser
  240. stream string
  241. }
  242. func (w *WriteBroadcaster) AddWriter(writer io.WriteCloser, stream string) {
  243. w.Lock()
  244. sw := StreamWriter{wc: writer, stream: stream}
  245. w.writers[sw] = true
  246. w.Unlock()
  247. }
  248. type JSONLog struct {
  249. Log string `json:"log,omitempty"`
  250. Stream string `json:"stream,omitempty"`
  251. Created time.Time `json:"time"`
  252. }
  253. func (w *WriteBroadcaster) Write(p []byte) (n int, err error) {
  254. w.Lock()
  255. defer w.Unlock()
  256. w.buf.Write(p)
  257. for sw := range w.writers {
  258. lp := p
  259. if sw.stream != "" {
  260. lp = nil
  261. for {
  262. line, err := w.buf.ReadString('\n')
  263. if err != nil {
  264. w.buf.Write([]byte(line))
  265. break
  266. }
  267. b, err := json.Marshal(&JSONLog{Log: line, Stream: sw.stream, Created: time.Now()})
  268. if err != nil {
  269. // On error, evict the writer
  270. delete(w.writers, sw)
  271. continue
  272. }
  273. lp = append(lp, b...)
  274. lp = append(lp, '\n')
  275. }
  276. }
  277. if n, err := sw.wc.Write(lp); err != nil || n != len(lp) {
  278. // On error, evict the writer
  279. delete(w.writers, sw)
  280. }
  281. }
  282. return len(p), nil
  283. }
  284. func (w *WriteBroadcaster) CloseWriters() error {
  285. w.Lock()
  286. defer w.Unlock()
  287. for sw := range w.writers {
  288. sw.wc.Close()
  289. }
  290. w.writers = make(map[StreamWriter]bool)
  291. return nil
  292. }
  293. func NewWriteBroadcaster() *WriteBroadcaster {
  294. return &WriteBroadcaster{writers: make(map[StreamWriter]bool), buf: bytes.NewBuffer(nil)}
  295. }
  296. func GetTotalUsedFds() int {
  297. if fds, err := ioutil.ReadDir(fmt.Sprintf("/proc/%d/fd", os.Getpid())); err != nil {
  298. Errorf("Error opening /proc/%d/fd: %s", os.Getpid(), err)
  299. } else {
  300. return len(fds)
  301. }
  302. return -1
  303. }
  304. // TruncIndex allows the retrieval of string identifiers by any of their unique prefixes.
  305. // This is used to retrieve image and container IDs by more convenient shorthand prefixes.
  306. type TruncIndex struct {
  307. index *suffixarray.Index
  308. ids map[string]bool
  309. bytes []byte
  310. }
  311. func NewTruncIndex() *TruncIndex {
  312. return &TruncIndex{
  313. index: suffixarray.New([]byte{' '}),
  314. ids: make(map[string]bool),
  315. bytes: []byte{' '},
  316. }
  317. }
  318. func (idx *TruncIndex) Add(id string) error {
  319. if strings.Contains(id, " ") {
  320. return fmt.Errorf("Illegal character: ' '")
  321. }
  322. if _, exists := idx.ids[id]; exists {
  323. return fmt.Errorf("Id already exists: %s", id)
  324. }
  325. idx.ids[id] = true
  326. idx.bytes = append(idx.bytes, []byte(id+" ")...)
  327. idx.index = suffixarray.New(idx.bytes)
  328. return nil
  329. }
  330. func (idx *TruncIndex) Delete(id string) error {
  331. if _, exists := idx.ids[id]; !exists {
  332. return fmt.Errorf("No such id: %s", id)
  333. }
  334. before, after, err := idx.lookup(id)
  335. if err != nil {
  336. return err
  337. }
  338. delete(idx.ids, id)
  339. idx.bytes = append(idx.bytes[:before], idx.bytes[after:]...)
  340. idx.index = suffixarray.New(idx.bytes)
  341. return nil
  342. }
  343. func (idx *TruncIndex) lookup(s string) (int, int, error) {
  344. offsets := idx.index.Lookup([]byte(" "+s), -1)
  345. //log.Printf("lookup(%s): %v (index bytes: '%s')\n", s, offsets, idx.index.Bytes())
  346. if offsets == nil || len(offsets) == 0 || len(offsets) > 1 {
  347. return -1, -1, fmt.Errorf("No such id: %s", s)
  348. }
  349. offsetBefore := offsets[0] + 1
  350. offsetAfter := offsetBefore + strings.Index(string(idx.bytes[offsetBefore:]), " ")
  351. return offsetBefore, offsetAfter, nil
  352. }
  353. func (idx *TruncIndex) Get(s string) (string, error) {
  354. before, after, err := idx.lookup(s)
  355. //log.Printf("Get(%s) bytes=|%s| before=|%d| after=|%d|\n", s, idx.bytes, before, after)
  356. if err != nil {
  357. return "", err
  358. }
  359. return string(idx.bytes[before:after]), err
  360. }
  361. // TruncateID returns a shorthand version of a string identifier for convenience.
  362. // A collision with other shorthands is very unlikely, but possible.
  363. // In case of a collision a lookup with TruncIndex.Get() will fail, and the caller
  364. // will need to use a langer prefix, or the full-length Id.
  365. func TruncateID(id string) string {
  366. shortLen := 12
  367. if len(id) < shortLen {
  368. shortLen = len(id)
  369. }
  370. return id[:shortLen]
  371. }
  372. // Code c/c from io.Copy() modified to handle escape sequence
  373. func CopyEscapable(dst io.Writer, src io.ReadCloser) (written int64, err error) {
  374. buf := make([]byte, 32*1024)
  375. for {
  376. nr, er := src.Read(buf)
  377. if nr > 0 {
  378. // ---- Docker addition
  379. // char 16 is C-p
  380. if nr == 1 && buf[0] == 16 {
  381. nr, er = src.Read(buf)
  382. // char 17 is C-q
  383. if nr == 1 && buf[0] == 17 {
  384. if err := src.Close(); err != nil {
  385. return 0, err
  386. }
  387. return 0, io.EOF
  388. }
  389. }
  390. // ---- End of docker
  391. nw, ew := dst.Write(buf[0:nr])
  392. if nw > 0 {
  393. written += int64(nw)
  394. }
  395. if ew != nil {
  396. err = ew
  397. break
  398. }
  399. if nr != nw {
  400. err = io.ErrShortWrite
  401. break
  402. }
  403. }
  404. if er == io.EOF {
  405. break
  406. }
  407. if er != nil {
  408. err = er
  409. break
  410. }
  411. }
  412. return written, err
  413. }
  414. func HashData(src io.Reader) (string, error) {
  415. h := sha256.New()
  416. if _, err := io.Copy(h, src); err != nil {
  417. return "", err
  418. }
  419. return "sha256:" + hex.EncodeToString(h.Sum(nil)), nil
  420. }
  421. type KernelVersionInfo struct {
  422. Kernel int
  423. Major int
  424. Minor int
  425. Flavor string
  426. }
  427. func (k *KernelVersionInfo) String() string {
  428. flavor := ""
  429. if len(k.Flavor) > 0 {
  430. flavor = fmt.Sprintf("-%s", k.Flavor)
  431. }
  432. return fmt.Sprintf("%d.%d.%d%s", k.Kernel, k.Major, k.Minor, flavor)
  433. }
  434. // Compare two KernelVersionInfo struct.
  435. // Returns -1 if a < b, = if a == b, 1 it a > b
  436. func CompareKernelVersion(a, b *KernelVersionInfo) int {
  437. if a.Kernel < b.Kernel {
  438. return -1
  439. } else if a.Kernel > b.Kernel {
  440. return 1
  441. }
  442. if a.Major < b.Major {
  443. return -1
  444. } else if a.Major > b.Major {
  445. return 1
  446. }
  447. if a.Minor < b.Minor {
  448. return -1
  449. } else if a.Minor > b.Minor {
  450. return 1
  451. }
  452. return 0
  453. }
  454. func FindCgroupMountpoint(cgroupType string) (string, error) {
  455. output, err := ioutil.ReadFile("/proc/mounts")
  456. if err != nil {
  457. return "", err
  458. }
  459. // /proc/mounts has 6 fields per line, one mount per line, e.g.
  460. // cgroup /sys/fs/cgroup/devices cgroup rw,relatime,devices 0 0
  461. for _, line := range strings.Split(string(output), "\n") {
  462. parts := strings.Split(line, " ")
  463. if len(parts) == 6 && parts[2] == "cgroup" {
  464. for _, opt := range strings.Split(parts[3], ",") {
  465. if opt == cgroupType {
  466. return parts[1], nil
  467. }
  468. }
  469. }
  470. }
  471. return "", fmt.Errorf("cgroup mountpoint not found for %s", cgroupType)
  472. }
  473. func GetKernelVersion() (*KernelVersionInfo, error) {
  474. var (
  475. err error
  476. )
  477. uts, err := uname()
  478. if err != nil {
  479. return nil, err
  480. }
  481. release := make([]byte, len(uts.Release))
  482. i := 0
  483. for _, c := range uts.Release {
  484. release[i] = byte(c)
  485. i++
  486. }
  487. // Remove the \x00 from the release for Atoi to parse correctly
  488. release = release[:bytes.IndexByte(release, 0)]
  489. return ParseRelease(string(release))
  490. }
  491. func ParseRelease(release string) (*KernelVersionInfo, error) {
  492. var (
  493. flavor string
  494. kernel, major, minor int
  495. err error
  496. )
  497. tmp := strings.SplitN(release, "-", 2)
  498. tmp2 := strings.Split(tmp[0], ".")
  499. if len(tmp2) > 0 {
  500. kernel, err = strconv.Atoi(tmp2[0])
  501. if err != nil {
  502. return nil, err
  503. }
  504. }
  505. if len(tmp2) > 1 {
  506. major, err = strconv.Atoi(tmp2[1])
  507. if err != nil {
  508. return nil, err
  509. }
  510. }
  511. if len(tmp2) > 2 {
  512. // Removes "+" because git kernels might set it
  513. minorUnparsed := strings.Trim(tmp2[2], "+")
  514. minor, err = strconv.Atoi(minorUnparsed)
  515. if err != nil {
  516. return nil, err
  517. }
  518. }
  519. if len(tmp) == 2 {
  520. flavor = tmp[1]
  521. } else {
  522. flavor = ""
  523. }
  524. return &KernelVersionInfo{
  525. Kernel: kernel,
  526. Major: major,
  527. Minor: minor,
  528. Flavor: flavor,
  529. }, nil
  530. }
  531. // FIXME: this is deprecated by CopyWithTar in archive.go
  532. func CopyDirectory(source, dest string) error {
  533. if output, err := exec.Command("cp", "-ra", source, dest).CombinedOutput(); err != nil {
  534. return fmt.Errorf("Error copy: %s (%s)", err, output)
  535. }
  536. return nil
  537. }
  538. type NopFlusher struct{}
  539. func (f *NopFlusher) Flush() {}
  540. type WriteFlusher struct {
  541. sync.Mutex
  542. w io.Writer
  543. flusher http.Flusher
  544. }
  545. func (wf *WriteFlusher) Write(b []byte) (n int, err error) {
  546. wf.Lock()
  547. defer wf.Unlock()
  548. n, err = wf.w.Write(b)
  549. wf.flusher.Flush()
  550. return n, err
  551. }
  552. func NewWriteFlusher(w io.Writer) *WriteFlusher {
  553. var flusher http.Flusher
  554. if f, ok := w.(http.Flusher); ok {
  555. flusher = f
  556. } else {
  557. flusher = &NopFlusher{}
  558. }
  559. return &WriteFlusher{w: w, flusher: flusher}
  560. }
  561. type JSONError struct {
  562. Code int `json:"code,omitempty"`
  563. Message string `json:"message,omitempty"`
  564. }
  565. type JSONMessage struct {
  566. Status string `json:"status,omitempty"`
  567. Progress string `json:"progress,omitempty"`
  568. ErrorMessage string `json:"error,omitempty"` //deprecated
  569. ID string `json:"id,omitempty"`
  570. From string `json:"from,omitempty"`
  571. Time int64 `json:"time,omitempty"`
  572. Error *JSONError `json:"errorDetail,omitempty"`
  573. }
  574. func (e *JSONError) Error() string {
  575. return e.Message
  576. }
  577. func NewHTTPRequestError(msg string, res *http.Response) error {
  578. return &JSONError{
  579. Message: msg,
  580. Code: res.StatusCode,
  581. }
  582. }
  583. func (jm *JSONMessage) Display(out io.Writer) error {
  584. if jm.Error != nil {
  585. if jm.Error.Code == 401 {
  586. return fmt.Errorf("Authentication is required.")
  587. }
  588. return jm.Error
  589. }
  590. fmt.Fprintf(out, "%c[2K\r", 27)
  591. if jm.Time != 0 {
  592. fmt.Fprintf(out, "[%s] ", time.Unix(jm.Time, 0))
  593. }
  594. if jm.ID != "" {
  595. fmt.Fprintf(out, "%s: ", jm.ID)
  596. }
  597. if jm.From != "" {
  598. fmt.Fprintf(out, "(from %s) ", jm.From)
  599. }
  600. if jm.Progress != "" {
  601. fmt.Fprintf(out, "%s %s\r", jm.Status, jm.Progress)
  602. } else {
  603. fmt.Fprintf(out, "%s\r\n", jm.Status)
  604. }
  605. return nil
  606. }
  607. func DisplayJSONMessagesStream(in io.Reader, out io.Writer) error {
  608. dec := json.NewDecoder(in)
  609. ids := make(map[string]int)
  610. diff := 0
  611. for {
  612. jm := JSONMessage{}
  613. if err := dec.Decode(&jm); err == io.EOF {
  614. break
  615. } else if err != nil {
  616. return err
  617. }
  618. if jm.Progress != "" && jm.ID != "" {
  619. line, ok := ids[jm.ID]
  620. if !ok {
  621. line = len(ids)
  622. ids[jm.ID] = line
  623. fmt.Fprintf(out, "\n")
  624. diff = 0
  625. } else {
  626. diff = len(ids) - line
  627. }
  628. fmt.Fprintf(out, "%c[%dA", 27, diff)
  629. }
  630. err := jm.Display(out)
  631. if jm.ID != "" {
  632. fmt.Fprintf(out, "%c[%dB", 27, diff)
  633. }
  634. if err != nil {
  635. return err
  636. }
  637. }
  638. return nil
  639. }
  640. type StreamFormatter struct {
  641. json bool
  642. used bool
  643. }
  644. func NewStreamFormatter(json bool) *StreamFormatter {
  645. return &StreamFormatter{json, false}
  646. }
  647. func (sf *StreamFormatter) FormatStatus(id, format string, a ...interface{}) []byte {
  648. sf.used = true
  649. str := fmt.Sprintf(format, a...)
  650. if sf.json {
  651. b, err := json.Marshal(&JSONMessage{ID: id, Status: str})
  652. if err != nil {
  653. return sf.FormatError(err)
  654. }
  655. return b
  656. }
  657. return []byte(str + "\r\n")
  658. }
  659. func (sf *StreamFormatter) FormatError(err error) []byte {
  660. sf.used = true
  661. if sf.json {
  662. jsonError, ok := err.(*JSONError)
  663. if !ok {
  664. jsonError = &JSONError{Message: err.Error()}
  665. }
  666. if b, err := json.Marshal(&JSONMessage{Error: jsonError, ErrorMessage: err.Error()}); err == nil {
  667. return b
  668. }
  669. return []byte("{\"error\":\"format error\"}")
  670. }
  671. return []byte("Error: " + err.Error() + "\r\n")
  672. }
  673. func (sf *StreamFormatter) FormatProgress(id, action, progress string) []byte {
  674. sf.used = true
  675. if sf.json {
  676. b, err := json.Marshal(&JSONMessage{Status: action, Progress: progress, ID: id})
  677. if err != nil {
  678. return nil
  679. }
  680. return b
  681. }
  682. return []byte(action + " " + progress + "\r")
  683. }
  684. func (sf *StreamFormatter) Used() bool {
  685. return sf.used
  686. }
  687. func IsURL(str string) bool {
  688. return strings.HasPrefix(str, "http://") || strings.HasPrefix(str, "https://")
  689. }
  690. func IsGIT(str string) bool {
  691. return strings.HasPrefix(str, "git://") || strings.HasPrefix(str, "github.com/")
  692. }
  693. // GetResolvConf opens and read the content of /etc/resolv.conf.
  694. // It returns it as byte slice.
  695. func GetResolvConf() ([]byte, error) {
  696. resolv, err := ioutil.ReadFile("/etc/resolv.conf")
  697. if err != nil {
  698. Errorf("Error openning resolv.conf: %s", err)
  699. return nil, err
  700. }
  701. return resolv, nil
  702. }
  703. // CheckLocalDns looks into the /etc/resolv.conf,
  704. // it returns true if there is a local nameserver or if there is no nameserver.
  705. func CheckLocalDns(resolvConf []byte) bool {
  706. var parsedResolvConf = StripComments(resolvConf, []byte("#"))
  707. if !bytes.Contains(parsedResolvConf, []byte("nameserver")) {
  708. return true
  709. }
  710. for _, ip := range [][]byte{
  711. []byte("127.0.0.1"),
  712. []byte("127.0.1.1"),
  713. } {
  714. if bytes.Contains(parsedResolvConf, ip) {
  715. return true
  716. }
  717. }
  718. return false
  719. }
  720. // StripComments parses input into lines and strips away comments.
  721. func StripComments(input []byte, commentMarker []byte) []byte {
  722. lines := bytes.Split(input, []byte("\n"))
  723. var output []byte
  724. for _, currentLine := range lines {
  725. var commentIndex = bytes.Index(currentLine, commentMarker)
  726. if commentIndex == -1 {
  727. output = append(output, currentLine...)
  728. } else {
  729. output = append(output, currentLine[:commentIndex]...)
  730. }
  731. output = append(output, []byte("\n")...)
  732. }
  733. return output
  734. }
  735. func ParseHost(host string, port int, addr string) string {
  736. if strings.HasPrefix(addr, "unix://") {
  737. return addr
  738. }
  739. if strings.HasPrefix(addr, "tcp://") {
  740. addr = strings.TrimPrefix(addr, "tcp://")
  741. }
  742. if strings.Contains(addr, ":") {
  743. hostParts := strings.Split(addr, ":")
  744. if len(hostParts) != 2 {
  745. log.Fatal("Invalid bind address format.")
  746. os.Exit(-1)
  747. }
  748. if hostParts[0] != "" {
  749. host = hostParts[0]
  750. }
  751. if p, err := strconv.Atoi(hostParts[1]); err == nil {
  752. port = p
  753. }
  754. } else {
  755. host = addr
  756. }
  757. return fmt.Sprintf("tcp://%s:%d", host, port)
  758. }
  759. func GetReleaseVersion() string {
  760. resp, err := http.Get("http://get.docker.io/latest")
  761. if err != nil {
  762. return ""
  763. }
  764. defer resp.Body.Close()
  765. if resp.ContentLength > 24 || resp.StatusCode != 200 {
  766. return ""
  767. }
  768. body, err := ioutil.ReadAll(resp.Body)
  769. if err != nil {
  770. return ""
  771. }
  772. return strings.TrimSpace(string(body))
  773. }
  774. // Get a repos name and returns the right reposName + tag
  775. // The tag can be confusing because of a port in a repository name.
  776. // Ex: localhost.localdomain:5000/samalba/hipache:latest
  777. func ParseRepositoryTag(repos string) (string, string) {
  778. n := strings.LastIndex(repos, ":")
  779. if n < 0 {
  780. return repos, ""
  781. }
  782. if tag := repos[n+1:]; !strings.Contains(tag, "/") {
  783. return repos[:n], tag
  784. }
  785. return repos, ""
  786. }
  787. type User struct {
  788. Uid string // user id
  789. Gid string // primary group id
  790. Username string
  791. Name string
  792. HomeDir string
  793. }
  794. // UserLookup check if the given username or uid is present in /etc/passwd
  795. // and returns the user struct.
  796. // If the username is not found, an error is returned.
  797. func UserLookup(uid string) (*User, error) {
  798. file, err := ioutil.ReadFile("/etc/passwd")
  799. if err != nil {
  800. return nil, err
  801. }
  802. for _, line := range strings.Split(string(file), "\n") {
  803. data := strings.Split(line, ":")
  804. if len(data) > 5 && (data[0] == uid || data[2] == uid) {
  805. return &User{
  806. Uid: data[2],
  807. Gid: data[3],
  808. Username: data[0],
  809. Name: data[4],
  810. HomeDir: data[5],
  811. }, nil
  812. }
  813. }
  814. return nil, fmt.Errorf("User not found in /etc/passwd")
  815. }
  816. type DependencyGraph struct {
  817. nodes map[string]*DependencyNode
  818. }
  819. type DependencyNode struct {
  820. id string
  821. deps map[*DependencyNode]bool
  822. }
  823. func NewDependencyGraph() DependencyGraph {
  824. return DependencyGraph{
  825. nodes: map[string]*DependencyNode{},
  826. }
  827. }
  828. func (graph *DependencyGraph) addNode(node *DependencyNode) string {
  829. if graph.nodes[node.id] == nil {
  830. graph.nodes[node.id] = node
  831. }
  832. return node.id
  833. }
  834. func (graph *DependencyGraph) NewNode(id string) string {
  835. if graph.nodes[id] != nil {
  836. return id
  837. }
  838. nd := &DependencyNode{
  839. id: id,
  840. deps: map[*DependencyNode]bool{},
  841. }
  842. graph.addNode(nd)
  843. return id
  844. }
  845. func (graph *DependencyGraph) AddDependency(node, to string) error {
  846. if graph.nodes[node] == nil {
  847. return fmt.Errorf("Node %s does not belong to this graph", node)
  848. }
  849. if graph.nodes[to] == nil {
  850. return fmt.Errorf("Node %s does not belong to this graph", to)
  851. }
  852. if node == to {
  853. return fmt.Errorf("Dependency loops are forbidden!")
  854. }
  855. graph.nodes[node].addDependency(graph.nodes[to])
  856. return nil
  857. }
  858. func (node *DependencyNode) addDependency(to *DependencyNode) bool {
  859. node.deps[to] = true
  860. return node.deps[to]
  861. }
  862. func (node *DependencyNode) Degree() int {
  863. return len(node.deps)
  864. }
  865. // The magic happens here ::
  866. func (graph *DependencyGraph) GenerateTraversalMap() ([][]string, error) {
  867. Debugf("Generating traversal map. Nodes: %d", len(graph.nodes))
  868. result := [][]string{}
  869. processed := map[*DependencyNode]bool{}
  870. // As long as we haven't processed all nodes...
  871. for len(processed) < len(graph.nodes) {
  872. // Use a temporary buffer for processed nodes, otherwise
  873. // nodes that depend on each other could end up in the same round.
  874. tmp_processed := []*DependencyNode{}
  875. for _, node := range graph.nodes {
  876. // If the node has more dependencies than what we have cleared,
  877. // it won't be valid for this round.
  878. if node.Degree() > len(processed) {
  879. continue
  880. }
  881. // If it's already processed, get to the next one
  882. if processed[node] {
  883. continue
  884. }
  885. // It's not been processed yet and has 0 deps. Add it!
  886. // (this is a shortcut for what we're doing below)
  887. if node.Degree() == 0 {
  888. tmp_processed = append(tmp_processed, node)
  889. continue
  890. }
  891. // If at least one dep hasn't been processed yet, we can't
  892. // add it.
  893. ok := true
  894. for dep := range node.deps {
  895. if !processed[dep] {
  896. ok = false
  897. break
  898. }
  899. }
  900. // All deps have already been processed. Add it!
  901. if ok {
  902. tmp_processed = append(tmp_processed, node)
  903. }
  904. }
  905. Debugf("Round %d: found %d available nodes", len(result), len(tmp_processed))
  906. // If no progress has been made this round,
  907. // that means we have circular dependencies.
  908. if len(tmp_processed) == 0 {
  909. return nil, fmt.Errorf("Could not find a solution to this dependency graph")
  910. }
  911. round := []string{}
  912. for _, nd := range tmp_processed {
  913. round = append(round, nd.id)
  914. processed[nd] = true
  915. }
  916. result = append(result, round)
  917. }
  918. return result, nil
  919. }
  920. // An StatusError reports an unsuccessful exit by a command.
  921. type StatusError struct {
  922. Status int
  923. }
  924. func (e *StatusError) Error() string {
  925. return fmt.Sprintf("Status: %d", e.Status)
  926. }