utils.go 19 KB

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