utils.go 25 KB

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