utils.go 31 KB

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