utils.go 26 KB

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