utils.go 19 KB

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