utils.go 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249
  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() 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. filepath.Join(filepath.Dir(selfPath), "dockerinit"),
  253. // "/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."
  254. "/usr/libexec/docker/dockerinit",
  255. "/usr/local/libexec/docker/dockerinit",
  256. }
  257. for _, dockerInit := range possibleInits {
  258. path, err := exec.LookPath(dockerInit)
  259. if err == nil {
  260. path, err = filepath.Abs(path)
  261. if err != nil {
  262. // LookPath already validated that this file exists and is executable (following symlinks), so how could Abs fail?
  263. panic(err)
  264. }
  265. if isValidDockerInitPath(path, selfPath) {
  266. return path
  267. }
  268. }
  269. }
  270. return ""
  271. }
  272. type NopWriter struct{}
  273. func (*NopWriter) Write(buf []byte) (int, error) {
  274. return len(buf), nil
  275. }
  276. type nopWriteCloser struct {
  277. io.Writer
  278. }
  279. func (w *nopWriteCloser) Close() error { return nil }
  280. func NopWriteCloser(w io.Writer) io.WriteCloser {
  281. return &nopWriteCloser{w}
  282. }
  283. type bufReader struct {
  284. sync.Mutex
  285. buf *bytes.Buffer
  286. reader io.Reader
  287. err error
  288. wait sync.Cond
  289. }
  290. func NewBufReader(r io.Reader) *bufReader {
  291. reader := &bufReader{
  292. buf: &bytes.Buffer{},
  293. reader: r,
  294. }
  295. reader.wait.L = &reader.Mutex
  296. go reader.drain()
  297. return reader
  298. }
  299. func (r *bufReader) drain() {
  300. buf := make([]byte, 1024)
  301. for {
  302. n, err := r.reader.Read(buf)
  303. r.Lock()
  304. if err != nil {
  305. r.err = err
  306. } else {
  307. r.buf.Write(buf[0:n])
  308. }
  309. r.wait.Signal()
  310. r.Unlock()
  311. if err != nil {
  312. break
  313. }
  314. }
  315. }
  316. func (r *bufReader) Read(p []byte) (n int, err error) {
  317. r.Lock()
  318. defer r.Unlock()
  319. for {
  320. n, err = r.buf.Read(p)
  321. if n > 0 {
  322. return n, err
  323. }
  324. if r.err != nil {
  325. return 0, r.err
  326. }
  327. r.wait.Wait()
  328. }
  329. }
  330. func (r *bufReader) Close() error {
  331. closer, ok := r.reader.(io.ReadCloser)
  332. if !ok {
  333. return nil
  334. }
  335. return closer.Close()
  336. }
  337. type WriteBroadcaster struct {
  338. sync.Mutex
  339. buf *bytes.Buffer
  340. writers map[StreamWriter]bool
  341. }
  342. type StreamWriter struct {
  343. wc io.WriteCloser
  344. stream string
  345. }
  346. func (w *WriteBroadcaster) AddWriter(writer io.WriteCloser, stream string) {
  347. w.Lock()
  348. sw := StreamWriter{wc: writer, stream: stream}
  349. w.writers[sw] = true
  350. w.Unlock()
  351. }
  352. type JSONLog struct {
  353. Log string `json:"log,omitempty"`
  354. Stream string `json:"stream,omitempty"`
  355. Created time.Time `json:"time"`
  356. }
  357. func (w *WriteBroadcaster) Write(p []byte) (n int, err error) {
  358. w.Lock()
  359. defer w.Unlock()
  360. w.buf.Write(p)
  361. for sw := range w.writers {
  362. lp := p
  363. if sw.stream != "" {
  364. lp = nil
  365. for {
  366. line, err := w.buf.ReadString('\n')
  367. if err != nil {
  368. w.buf.Write([]byte(line))
  369. break
  370. }
  371. b, err := json.Marshal(&JSONLog{Log: line, Stream: sw.stream, Created: time.Now()})
  372. if err != nil {
  373. // On error, evict the writer
  374. delete(w.writers, sw)
  375. continue
  376. }
  377. lp = append(lp, b...)
  378. lp = append(lp, '\n')
  379. }
  380. }
  381. if n, err := sw.wc.Write(lp); err != nil || n != len(lp) {
  382. // On error, evict the writer
  383. delete(w.writers, sw)
  384. }
  385. }
  386. return len(p), nil
  387. }
  388. func (w *WriteBroadcaster) CloseWriters() error {
  389. w.Lock()
  390. defer w.Unlock()
  391. for sw := range w.writers {
  392. sw.wc.Close()
  393. }
  394. w.writers = make(map[StreamWriter]bool)
  395. return nil
  396. }
  397. func NewWriteBroadcaster() *WriteBroadcaster {
  398. return &WriteBroadcaster{writers: make(map[StreamWriter]bool), buf: bytes.NewBuffer(nil)}
  399. }
  400. func GetTotalUsedFds() int {
  401. if fds, err := ioutil.ReadDir(fmt.Sprintf("/proc/%d/fd", os.Getpid())); err != nil {
  402. Errorf("Error opening /proc/%d/fd: %s", os.Getpid(), err)
  403. } else {
  404. return len(fds)
  405. }
  406. return -1
  407. }
  408. // TruncIndex allows the retrieval of string identifiers by any of their unique prefixes.
  409. // This is used to retrieve image and container IDs by more convenient shorthand prefixes.
  410. type TruncIndex struct {
  411. index *suffixarray.Index
  412. ids map[string]bool
  413. bytes []byte
  414. }
  415. func NewTruncIndex() *TruncIndex {
  416. return &TruncIndex{
  417. index: suffixarray.New([]byte{' '}),
  418. ids: make(map[string]bool),
  419. bytes: []byte{' '},
  420. }
  421. }
  422. func (idx *TruncIndex) Add(id string) error {
  423. if strings.Contains(id, " ") {
  424. return fmt.Errorf("Illegal character: ' '")
  425. }
  426. if _, exists := idx.ids[id]; exists {
  427. return fmt.Errorf("Id already exists: %s", id)
  428. }
  429. idx.ids[id] = true
  430. idx.bytes = append(idx.bytes, []byte(id+" ")...)
  431. idx.index = suffixarray.New(idx.bytes)
  432. return nil
  433. }
  434. func (idx *TruncIndex) Delete(id string) error {
  435. if _, exists := idx.ids[id]; !exists {
  436. return fmt.Errorf("No such id: %s", id)
  437. }
  438. before, after, err := idx.lookup(id)
  439. if err != nil {
  440. return err
  441. }
  442. delete(idx.ids, id)
  443. idx.bytes = append(idx.bytes[:before], idx.bytes[after:]...)
  444. idx.index = suffixarray.New(idx.bytes)
  445. return nil
  446. }
  447. func (idx *TruncIndex) lookup(s string) (int, int, error) {
  448. offsets := idx.index.Lookup([]byte(" "+s), -1)
  449. //log.Printf("lookup(%s): %v (index bytes: '%s')\n", s, offsets, idx.index.Bytes())
  450. if offsets == nil || len(offsets) == 0 || len(offsets) > 1 {
  451. return -1, -1, fmt.Errorf("No such id: %s", s)
  452. }
  453. offsetBefore := offsets[0] + 1
  454. offsetAfter := offsetBefore + strings.Index(string(idx.bytes[offsetBefore:]), " ")
  455. return offsetBefore, offsetAfter, nil
  456. }
  457. func (idx *TruncIndex) Get(s string) (string, error) {
  458. before, after, err := idx.lookup(s)
  459. //log.Printf("Get(%s) bytes=|%s| before=|%d| after=|%d|\n", s, idx.bytes, before, after)
  460. if err != nil {
  461. return "", err
  462. }
  463. return string(idx.bytes[before:after]), err
  464. }
  465. // TruncateID returns a shorthand version of a string identifier for convenience.
  466. // A collision with other shorthands is very unlikely, but possible.
  467. // In case of a collision a lookup with TruncIndex.Get() will fail, and the caller
  468. // will need to use a langer prefix, or the full-length Id.
  469. func TruncateID(id string) string {
  470. shortLen := 12
  471. if len(id) < shortLen {
  472. shortLen = len(id)
  473. }
  474. return id[:shortLen]
  475. }
  476. // Code c/c from io.Copy() modified to handle escape sequence
  477. func CopyEscapable(dst io.Writer, src io.ReadCloser) (written int64, err error) {
  478. buf := make([]byte, 32*1024)
  479. for {
  480. nr, er := src.Read(buf)
  481. if nr > 0 {
  482. // ---- Docker addition
  483. // char 16 is C-p
  484. if nr == 1 && buf[0] == 16 {
  485. nr, er = src.Read(buf)
  486. // char 17 is C-q
  487. if nr == 1 && buf[0] == 17 {
  488. if err := src.Close(); err != nil {
  489. return 0, err
  490. }
  491. return 0, io.EOF
  492. }
  493. }
  494. // ---- End of docker
  495. nw, ew := dst.Write(buf[0:nr])
  496. if nw > 0 {
  497. written += int64(nw)
  498. }
  499. if ew != nil {
  500. err = ew
  501. break
  502. }
  503. if nr != nw {
  504. err = io.ErrShortWrite
  505. break
  506. }
  507. }
  508. if er == io.EOF {
  509. break
  510. }
  511. if er != nil {
  512. err = er
  513. break
  514. }
  515. }
  516. return written, err
  517. }
  518. func HashData(src io.Reader) (string, error) {
  519. h := sha256.New()
  520. if _, err := io.Copy(h, src); err != nil {
  521. return "", err
  522. }
  523. return "sha256:" + hex.EncodeToString(h.Sum(nil)), nil
  524. }
  525. type KernelVersionInfo struct {
  526. Kernel int
  527. Major int
  528. Minor int
  529. Flavor string
  530. }
  531. func (k *KernelVersionInfo) String() string {
  532. flavor := ""
  533. if len(k.Flavor) > 0 {
  534. flavor = fmt.Sprintf("-%s", k.Flavor)
  535. }
  536. return fmt.Sprintf("%d.%d.%d%s", k.Kernel, k.Major, k.Minor, flavor)
  537. }
  538. // Compare two KernelVersionInfo struct.
  539. // Returns -1 if a < b, = if a == b, 1 it a > b
  540. func CompareKernelVersion(a, b *KernelVersionInfo) int {
  541. if a.Kernel < b.Kernel {
  542. return -1
  543. } else if a.Kernel > b.Kernel {
  544. return 1
  545. }
  546. if a.Major < b.Major {
  547. return -1
  548. } else if a.Major > b.Major {
  549. return 1
  550. }
  551. if a.Minor < b.Minor {
  552. return -1
  553. } else if a.Minor > b.Minor {
  554. return 1
  555. }
  556. return 0
  557. }
  558. func FindCgroupMountpoint(cgroupType string) (string, error) {
  559. output, err := ioutil.ReadFile("/proc/mounts")
  560. if err != nil {
  561. return "", err
  562. }
  563. // /proc/mounts has 6 fields per line, one mount per line, e.g.
  564. // cgroup /sys/fs/cgroup/devices cgroup rw,relatime,devices 0 0
  565. for _, line := range strings.Split(string(output), "\n") {
  566. parts := strings.Split(line, " ")
  567. if len(parts) == 6 && parts[2] == "cgroup" {
  568. for _, opt := range strings.Split(parts[3], ",") {
  569. if opt == cgroupType {
  570. return parts[1], nil
  571. }
  572. }
  573. }
  574. }
  575. return "", fmt.Errorf("cgroup mountpoint not found for %s", cgroupType)
  576. }
  577. func GetKernelVersion() (*KernelVersionInfo, error) {
  578. var (
  579. err error
  580. )
  581. uts, err := uname()
  582. if err != nil {
  583. return nil, err
  584. }
  585. release := make([]byte, len(uts.Release))
  586. i := 0
  587. for _, c := range uts.Release {
  588. release[i] = byte(c)
  589. i++
  590. }
  591. // Remove the \x00 from the release for Atoi to parse correctly
  592. release = release[:bytes.IndexByte(release, 0)]
  593. return ParseRelease(string(release))
  594. }
  595. func ParseRelease(release string) (*KernelVersionInfo, error) {
  596. var (
  597. flavor string
  598. kernel, major, minor int
  599. err error
  600. )
  601. tmp := strings.SplitN(release, "-", 2)
  602. tmp2 := strings.Split(tmp[0], ".")
  603. if len(tmp2) > 0 {
  604. kernel, err = strconv.Atoi(tmp2[0])
  605. if err != nil {
  606. return nil, err
  607. }
  608. }
  609. if len(tmp2) > 1 {
  610. major, err = strconv.Atoi(tmp2[1])
  611. if err != nil {
  612. return nil, err
  613. }
  614. }
  615. if len(tmp2) > 2 {
  616. // Removes "+" because git kernels might set it
  617. minorUnparsed := strings.Trim(tmp2[2], "+")
  618. minor, err = strconv.Atoi(minorUnparsed)
  619. if err != nil {
  620. return nil, err
  621. }
  622. }
  623. if len(tmp) == 2 {
  624. flavor = tmp[1]
  625. } else {
  626. flavor = ""
  627. }
  628. return &KernelVersionInfo{
  629. Kernel: kernel,
  630. Major: major,
  631. Minor: minor,
  632. Flavor: flavor,
  633. }, nil
  634. }
  635. // FIXME: this is deprecated by CopyWithTar in archive.go
  636. func CopyDirectory(source, dest string) error {
  637. if output, err := exec.Command("cp", "-ra", source, dest).CombinedOutput(); err != nil {
  638. return fmt.Errorf("Error copy: %s (%s)", err, output)
  639. }
  640. return nil
  641. }
  642. type NopFlusher struct{}
  643. func (f *NopFlusher) Flush() {}
  644. type WriteFlusher struct {
  645. sync.Mutex
  646. w io.Writer
  647. flusher http.Flusher
  648. }
  649. func (wf *WriteFlusher) Write(b []byte) (n int, err error) {
  650. wf.Lock()
  651. defer wf.Unlock()
  652. n, err = wf.w.Write(b)
  653. wf.flusher.Flush()
  654. return n, err
  655. }
  656. // Flush the stream immediately.
  657. func (wf *WriteFlusher) Flush() {
  658. wf.Lock()
  659. defer wf.Unlock()
  660. wf.flusher.Flush()
  661. }
  662. func NewWriteFlusher(w io.Writer) *WriteFlusher {
  663. var flusher http.Flusher
  664. if f, ok := w.(http.Flusher); ok {
  665. flusher = f
  666. } else {
  667. flusher = &NopFlusher{}
  668. }
  669. return &WriteFlusher{w: w, flusher: flusher}
  670. }
  671. type JSONError struct {
  672. Code int `json:"code,omitempty"`
  673. Message string `json:"message,omitempty"`
  674. }
  675. type JSONMessage struct {
  676. Status string `json:"status,omitempty"`
  677. Progress string `json:"progress,omitempty"`
  678. ErrorMessage string `json:"error,omitempty"` //deprecated
  679. ID string `json:"id,omitempty"`
  680. From string `json:"from,omitempty"`
  681. Time int64 `json:"time,omitempty"`
  682. Error *JSONError `json:"errorDetail,omitempty"`
  683. }
  684. func (e *JSONError) Error() string {
  685. return e.Message
  686. }
  687. func NewHTTPRequestError(msg string, res *http.Response) error {
  688. return &JSONError{
  689. Message: msg,
  690. Code: res.StatusCode,
  691. }
  692. }
  693. func (jm *JSONMessage) Display(out io.Writer) error {
  694. if jm.Error != nil {
  695. if jm.Error.Code == 401 {
  696. return fmt.Errorf("Authentication is required.")
  697. }
  698. return jm.Error
  699. }
  700. fmt.Fprintf(out, "%c[2K\r", 27)
  701. if jm.Time != 0 {
  702. fmt.Fprintf(out, "[%s] ", time.Unix(jm.Time, 0))
  703. }
  704. if jm.ID != "" {
  705. fmt.Fprintf(out, "%s: ", jm.ID)
  706. }
  707. if jm.From != "" {
  708. fmt.Fprintf(out, "(from %s) ", jm.From)
  709. }
  710. if jm.Progress != "" {
  711. fmt.Fprintf(out, "%s %s\r", jm.Status, jm.Progress)
  712. } else {
  713. fmt.Fprintf(out, "%s\r\n", jm.Status)
  714. }
  715. return nil
  716. }
  717. func DisplayJSONMessagesStream(in io.Reader, out io.Writer) error {
  718. dec := json.NewDecoder(in)
  719. ids := make(map[string]int)
  720. diff := 0
  721. for {
  722. jm := JSONMessage{}
  723. if err := dec.Decode(&jm); err == io.EOF {
  724. break
  725. } else if err != nil {
  726. return err
  727. }
  728. if jm.Progress != "" && jm.ID != "" {
  729. line, ok := ids[jm.ID]
  730. if !ok {
  731. line = len(ids)
  732. ids[jm.ID] = line
  733. fmt.Fprintf(out, "\n")
  734. diff = 0
  735. } else {
  736. diff = len(ids) - line
  737. }
  738. fmt.Fprintf(out, "%c[%dA", 27, diff)
  739. }
  740. err := jm.Display(out)
  741. if jm.ID != "" {
  742. fmt.Fprintf(out, "%c[%dB", 27, diff)
  743. }
  744. if err != nil {
  745. return err
  746. }
  747. }
  748. return nil
  749. }
  750. type StreamFormatter struct {
  751. json bool
  752. used bool
  753. }
  754. func NewStreamFormatter(json bool) *StreamFormatter {
  755. return &StreamFormatter{json, false}
  756. }
  757. func (sf *StreamFormatter) FormatStatus(id, format string, a ...interface{}) []byte {
  758. sf.used = true
  759. str := fmt.Sprintf(format, a...)
  760. if sf.json {
  761. b, err := json.Marshal(&JSONMessage{ID: id, Status: str})
  762. if err != nil {
  763. return sf.FormatError(err)
  764. }
  765. return b
  766. }
  767. return []byte(str + "\r\n")
  768. }
  769. func (sf *StreamFormatter) FormatError(err error) []byte {
  770. sf.used = true
  771. if sf.json {
  772. jsonError, ok := err.(*JSONError)
  773. if !ok {
  774. jsonError = &JSONError{Message: err.Error()}
  775. }
  776. if b, err := json.Marshal(&JSONMessage{Error: jsonError, ErrorMessage: err.Error()}); err == nil {
  777. return b
  778. }
  779. return []byte("{\"error\":\"format error\"}")
  780. }
  781. return []byte("Error: " + err.Error() + "\r\n")
  782. }
  783. func (sf *StreamFormatter) FormatProgress(id, action, progress string) []byte {
  784. sf.used = true
  785. if sf.json {
  786. b, err := json.Marshal(&JSONMessage{Status: action, Progress: progress, ID: id})
  787. if err != nil {
  788. return nil
  789. }
  790. return b
  791. }
  792. return []byte(action + " " + progress + "\r")
  793. }
  794. func (sf *StreamFormatter) Used() bool {
  795. return sf.used
  796. }
  797. func IsURL(str string) bool {
  798. return strings.HasPrefix(str, "http://") || strings.HasPrefix(str, "https://")
  799. }
  800. func IsGIT(str string) bool {
  801. return strings.HasPrefix(str, "git://") || strings.HasPrefix(str, "github.com/")
  802. }
  803. // GetResolvConf opens and read the content of /etc/resolv.conf.
  804. // It returns it as byte slice.
  805. func GetResolvConf() ([]byte, error) {
  806. resolv, err := ioutil.ReadFile("/etc/resolv.conf")
  807. if err != nil {
  808. Errorf("Error openning resolv.conf: %s", err)
  809. return nil, err
  810. }
  811. return resolv, nil
  812. }
  813. // CheckLocalDns looks into the /etc/resolv.conf,
  814. // it returns true if there is a local nameserver or if there is no nameserver.
  815. func CheckLocalDns(resolvConf []byte) bool {
  816. var parsedResolvConf = StripComments(resolvConf, []byte("#"))
  817. if !bytes.Contains(parsedResolvConf, []byte("nameserver")) {
  818. return true
  819. }
  820. for _, ip := range [][]byte{
  821. []byte("127.0.0.1"),
  822. []byte("127.0.1.1"),
  823. } {
  824. if bytes.Contains(parsedResolvConf, ip) {
  825. return true
  826. }
  827. }
  828. return false
  829. }
  830. // StripComments parses input into lines and strips away comments.
  831. func StripComments(input []byte, commentMarker []byte) []byte {
  832. lines := bytes.Split(input, []byte("\n"))
  833. var output []byte
  834. for _, currentLine := range lines {
  835. var commentIndex = bytes.Index(currentLine, commentMarker)
  836. if commentIndex == -1 {
  837. output = append(output, currentLine...)
  838. } else {
  839. output = append(output, currentLine[:commentIndex]...)
  840. }
  841. output = append(output, []byte("\n")...)
  842. }
  843. return output
  844. }
  845. // GetNameserversAsCIDR returns nameservers (if any) listed in
  846. // /etc/resolv.conf as CIDR blocks (e.g., "1.2.3.4/32")
  847. // This function's output is intended for net.ParseCIDR
  848. func GetNameserversAsCIDR(resolvConf []byte) []string {
  849. var parsedResolvConf = StripComments(resolvConf, []byte("#"))
  850. nameservers := []string{}
  851. re := regexp.MustCompile(`^\s*nameserver\s*(([0-9]+\.){3}([0-9]+))\s*$`)
  852. for _, line := range bytes.Split(parsedResolvConf, []byte("\n")) {
  853. var ns = re.FindSubmatch(line)
  854. if len(ns) > 0 {
  855. nameservers = append(nameservers, string(ns[1])+"/32")
  856. }
  857. }
  858. return nameservers
  859. }
  860. func ParseHost(host string, port int, addr string) (string, error) {
  861. var proto string
  862. switch {
  863. case strings.HasPrefix(addr, "unix://"):
  864. return addr, nil
  865. case strings.HasPrefix(addr, "tcp://"):
  866. proto = "tcp"
  867. addr = strings.TrimPrefix(addr, "tcp://")
  868. default:
  869. if strings.Contains(addr, "://") {
  870. return "", fmt.Errorf("Invalid bind address protocol: %s", addr)
  871. }
  872. proto = "tcp"
  873. }
  874. if strings.Contains(addr, ":") {
  875. hostParts := strings.Split(addr, ":")
  876. if len(hostParts) != 2 {
  877. return "", fmt.Errorf("Invalid bind address format: %s", addr)
  878. }
  879. if hostParts[0] != "" {
  880. host = hostParts[0]
  881. }
  882. if p, err := strconv.Atoi(hostParts[1]); err == nil {
  883. port = p
  884. }
  885. } else {
  886. host = addr
  887. }
  888. return fmt.Sprintf("%s://%s:%d", proto, host, port), nil
  889. }
  890. func GetReleaseVersion() string {
  891. resp, err := http.Get("http://get.docker.io/latest")
  892. if err != nil {
  893. return ""
  894. }
  895. defer resp.Body.Close()
  896. if resp.ContentLength > 24 || resp.StatusCode != 200 {
  897. return ""
  898. }
  899. body, err := ioutil.ReadAll(resp.Body)
  900. if err != nil {
  901. return ""
  902. }
  903. return strings.TrimSpace(string(body))
  904. }
  905. // Get a repos name and returns the right reposName + tag
  906. // The tag can be confusing because of a port in a repository name.
  907. // Ex: localhost.localdomain:5000/samalba/hipache:latest
  908. func ParseRepositoryTag(repos string) (string, string) {
  909. n := strings.LastIndex(repos, ":")
  910. if n < 0 {
  911. return repos, ""
  912. }
  913. if tag := repos[n+1:]; !strings.Contains(tag, "/") {
  914. return repos[:n], tag
  915. }
  916. return repos, ""
  917. }
  918. type User struct {
  919. Uid string // user id
  920. Gid string // primary group id
  921. Username string
  922. Name string
  923. HomeDir string
  924. }
  925. // UserLookup check if the given username or uid is present in /etc/passwd
  926. // and returns the user struct.
  927. // If the username is not found, an error is returned.
  928. func UserLookup(uid string) (*User, error) {
  929. file, err := ioutil.ReadFile("/etc/passwd")
  930. if err != nil {
  931. return nil, err
  932. }
  933. for _, line := range strings.Split(string(file), "\n") {
  934. data := strings.Split(line, ":")
  935. if len(data) > 5 && (data[0] == uid || data[2] == uid) {
  936. return &User{
  937. Uid: data[2],
  938. Gid: data[3],
  939. Username: data[0],
  940. Name: data[4],
  941. HomeDir: data[5],
  942. }, nil
  943. }
  944. }
  945. return nil, fmt.Errorf("User not found in /etc/passwd")
  946. }
  947. type DependencyGraph struct {
  948. nodes map[string]*DependencyNode
  949. }
  950. type DependencyNode struct {
  951. id string
  952. deps map[*DependencyNode]bool
  953. }
  954. func NewDependencyGraph() DependencyGraph {
  955. return DependencyGraph{
  956. nodes: map[string]*DependencyNode{},
  957. }
  958. }
  959. func (graph *DependencyGraph) addNode(node *DependencyNode) string {
  960. if graph.nodes[node.id] == nil {
  961. graph.nodes[node.id] = node
  962. }
  963. return node.id
  964. }
  965. func (graph *DependencyGraph) NewNode(id string) string {
  966. if graph.nodes[id] != nil {
  967. return id
  968. }
  969. nd := &DependencyNode{
  970. id: id,
  971. deps: map[*DependencyNode]bool{},
  972. }
  973. graph.addNode(nd)
  974. return id
  975. }
  976. func (graph *DependencyGraph) AddDependency(node, to string) error {
  977. if graph.nodes[node] == nil {
  978. return fmt.Errorf("Node %s does not belong to this graph", node)
  979. }
  980. if graph.nodes[to] == nil {
  981. return fmt.Errorf("Node %s does not belong to this graph", to)
  982. }
  983. if node == to {
  984. return fmt.Errorf("Dependency loops are forbidden!")
  985. }
  986. graph.nodes[node].addDependency(graph.nodes[to])
  987. return nil
  988. }
  989. func (node *DependencyNode) addDependency(to *DependencyNode) bool {
  990. node.deps[to] = true
  991. return node.deps[to]
  992. }
  993. func (node *DependencyNode) Degree() int {
  994. return len(node.deps)
  995. }
  996. // The magic happens here ::
  997. func (graph *DependencyGraph) GenerateTraversalMap() ([][]string, error) {
  998. Debugf("Generating traversal map. Nodes: %d", len(graph.nodes))
  999. result := [][]string{}
  1000. processed := map[*DependencyNode]bool{}
  1001. // As long as we haven't processed all nodes...
  1002. for len(processed) < len(graph.nodes) {
  1003. // Use a temporary buffer for processed nodes, otherwise
  1004. // nodes that depend on each other could end up in the same round.
  1005. tmp_processed := []*DependencyNode{}
  1006. for _, node := range graph.nodes {
  1007. // If the node has more dependencies than what we have cleared,
  1008. // it won't be valid for this round.
  1009. if node.Degree() > len(processed) {
  1010. continue
  1011. }
  1012. // If it's already processed, get to the next one
  1013. if processed[node] {
  1014. continue
  1015. }
  1016. // It's not been processed yet and has 0 deps. Add it!
  1017. // (this is a shortcut for what we're doing below)
  1018. if node.Degree() == 0 {
  1019. tmp_processed = append(tmp_processed, node)
  1020. continue
  1021. }
  1022. // If at least one dep hasn't been processed yet, we can't
  1023. // add it.
  1024. ok := true
  1025. for dep := range node.deps {
  1026. if !processed[dep] {
  1027. ok = false
  1028. break
  1029. }
  1030. }
  1031. // All deps have already been processed. Add it!
  1032. if ok {
  1033. tmp_processed = append(tmp_processed, node)
  1034. }
  1035. }
  1036. Debugf("Round %d: found %d available nodes", len(result), len(tmp_processed))
  1037. // If no progress has been made this round,
  1038. // that means we have circular dependencies.
  1039. if len(tmp_processed) == 0 {
  1040. return nil, fmt.Errorf("Could not find a solution to this dependency graph")
  1041. }
  1042. round := []string{}
  1043. for _, nd := range tmp_processed {
  1044. round = append(round, nd.id)
  1045. processed[nd] = true
  1046. }
  1047. result = append(result, round)
  1048. }
  1049. return result, nil
  1050. }
  1051. // An StatusError reports an unsuccessful exit by a command.
  1052. type StatusError struct {
  1053. Status int
  1054. }
  1055. func (e *StatusError) Error() string {
  1056. return fmt.Sprintf("Status: %d", e.Status)
  1057. }
  1058. func IsClosedError(err error) bool {
  1059. /* This comparison is ugly, but unfortunately, net.go doesn't export errClosing.
  1060. * See:
  1061. * http://golang.org/src/pkg/net/net.go
  1062. * https://code.google.com/p/go/issues/detail?id=4337
  1063. * https://groups.google.com/forum/#!msg/golang-nuts/0_aaCvBmOcM/SptmDyX1XJMJ
  1064. */
  1065. return strings.HasSuffix(err.Error(), "use of closed network connection")
  1066. }
  1067. func PartParser(template, data string) (map[string]string, error) {
  1068. // ip:public:private
  1069. templateParts := strings.Split(template, ":")
  1070. parts := strings.Split(data, ":")
  1071. if len(parts) != len(templateParts) {
  1072. return nil, fmt.Errorf("Invalid format to parse. %s should match template %s", data, template)
  1073. }
  1074. out := make(map[string]string, len(templateParts))
  1075. for i, t := range templateParts {
  1076. value := ""
  1077. if len(parts) > i {
  1078. value = parts[i]
  1079. }
  1080. out[t] = value
  1081. }
  1082. return out, nil
  1083. }
  1084. var globalTestID string
  1085. // TestDirectory creates a new temporary directory and returns its path.
  1086. // The contents of directory at path `templateDir` is copied into the
  1087. // new directory.
  1088. func TestDirectory(templateDir string) (dir string, err error) {
  1089. if globalTestID == "" {
  1090. globalTestID = RandomString()[:4]
  1091. }
  1092. prefix := fmt.Sprintf("docker-test%s-%s-", globalTestID, GetCallerName(2))
  1093. if prefix == "" {
  1094. prefix = "docker-test-"
  1095. }
  1096. dir, err = ioutil.TempDir("", prefix)
  1097. if err = os.Remove(dir); err != nil {
  1098. return
  1099. }
  1100. if templateDir != "" {
  1101. if err = CopyDirectory(templateDir, dir); err != nil {
  1102. return
  1103. }
  1104. }
  1105. return
  1106. }
  1107. // GetCallerName introspects the call stack and returns the name of the
  1108. // function `depth` levels down in the stack.
  1109. func GetCallerName(depth int) string {
  1110. // Use the caller function name as a prefix.
  1111. // This helps trace temp directories back to their test.
  1112. pc, _, _, _ := runtime.Caller(depth + 1)
  1113. callerLongName := runtime.FuncForPC(pc).Name()
  1114. parts := strings.Split(callerLongName, ".")
  1115. callerShortName := parts[len(parts)-1]
  1116. return callerShortName
  1117. }