utils.go 28 KB

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