utils.go 23 KB

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