utils.go 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244
  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 quote(word string, buf *bytes.Buffer) {
  1059. // Bail out early for "simple" strings
  1060. if word != "" && !strings.ContainsAny(word, "\\'\"`${[|&;<>()~*?! \t\n") {
  1061. buf.WriteString(word)
  1062. return
  1063. }
  1064. buf.WriteString("'")
  1065. for i := 0; i < len(word); i++ {
  1066. b := word[i]
  1067. if b == '\'' {
  1068. // Replace literal ' with a close ', a \', and a open '
  1069. buf.WriteString("'\\''")
  1070. } else {
  1071. buf.WriteByte(b)
  1072. }
  1073. }
  1074. buf.WriteString("'")
  1075. }
  1076. // Take a list of strings and escape them so they will be handled right
  1077. // when passed as arguments to an program via a shell
  1078. func ShellQuoteArguments(args []string) string {
  1079. var buf bytes.Buffer
  1080. for i, arg := range args {
  1081. if i != 0 {
  1082. buf.WriteByte(' ')
  1083. }
  1084. quote(arg, &buf)
  1085. }
  1086. return buf.String()
  1087. }
  1088. func IsClosedError(err error) bool {
  1089. /* This comparison is ugly, but unfortunately, net.go doesn't export errClosing.
  1090. * See:
  1091. * http://golang.org/src/pkg/net/net.go
  1092. * https://code.google.com/p/go/issues/detail?id=4337
  1093. * https://groups.google.com/forum/#!msg/golang-nuts/0_aaCvBmOcM/SptmDyX1XJMJ
  1094. */
  1095. return strings.HasSuffix(err.Error(), "use of closed network connection")
  1096. }
  1097. func PartParser(template, data string) (map[string]string, error) {
  1098. // ip:public:private
  1099. templateParts := strings.Split(template, ":")
  1100. parts := strings.Split(data, ":")
  1101. if len(parts) != len(templateParts) {
  1102. return nil, fmt.Errorf("Invalid format to parse. %s should match template %s", data, template)
  1103. }
  1104. out := make(map[string]string, len(templateParts))
  1105. for i, t := range templateParts {
  1106. value := ""
  1107. if len(parts) > i {
  1108. value = parts[i]
  1109. }
  1110. out[t] = value
  1111. }
  1112. return out, nil
  1113. }