utils.go 27 KB

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