utils.go 28 KB

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