utils.go 24 KB

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