utils.go 25 KB

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