utils.go 28 KB

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