utils.go 23 KB

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