utils.go 31 KB

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