utils.go 28 KB

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