utils.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143
  1. package utils
  2. import (
  3. "bytes"
  4. "crypto/rand"
  5. "crypto/sha1"
  6. "crypto/sha256"
  7. "encoding/hex"
  8. "encoding/json"
  9. "errors"
  10. "fmt"
  11. "github.com/dotcloud/docker/dockerversion"
  12. "index/suffixarray"
  13. "io"
  14. "io/ioutil"
  15. "net/http"
  16. "os"
  17. "os/exec"
  18. "path/filepath"
  19. "regexp"
  20. "runtime"
  21. "strconv"
  22. "strings"
  23. "sync"
  24. "time"
  25. )
  26. type KeyValuePair struct {
  27. Key string
  28. Value string
  29. }
  30. // A common interface to access the Fatal method of
  31. // both testing.B and testing.T.
  32. type Fataler interface {
  33. Fatal(args ...interface{})
  34. }
  35. // Go is a basic promise implementation: it wraps calls a function in a goroutine,
  36. // and returns a channel which will later return the function's return value.
  37. func Go(f func() error) chan error {
  38. ch := make(chan error, 1)
  39. go func() {
  40. ch <- f()
  41. }()
  42. return ch
  43. }
  44. // Request a given URL and return an io.Reader
  45. func Download(url string) (resp *http.Response, err error) {
  46. if resp, err = http.Get(url); err != nil {
  47. return nil, err
  48. }
  49. if resp.StatusCode >= 400 {
  50. return nil, fmt.Errorf("Got HTTP status code >= 400: %s", 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 (if it's still around).
  146. func SelfPath() string {
  147. path, err := exec.LookPath(os.Args[0])
  148. if err != nil {
  149. if os.IsNotExist(err) {
  150. return ""
  151. }
  152. if execErr, ok := err.(*exec.Error); ok && os.IsNotExist(execErr.Err) {
  153. return ""
  154. }
  155. panic(err)
  156. }
  157. path, err = filepath.Abs(path)
  158. if err != nil {
  159. if os.IsNotExist(err) {
  160. return ""
  161. }
  162. panic(err)
  163. }
  164. return path
  165. }
  166. func dockerInitSha1(target string) string {
  167. f, err := os.Open(target)
  168. if err != nil {
  169. return ""
  170. }
  171. defer f.Close()
  172. h := sha1.New()
  173. _, err = io.Copy(h, f)
  174. if err != nil {
  175. return ""
  176. }
  177. return hex.EncodeToString(h.Sum(nil))
  178. }
  179. func isValidDockerInitPath(target string, selfPath string) bool { // target and selfPath should be absolute (InitPath and SelfPath already do this)
  180. if target == "" {
  181. return false
  182. }
  183. if dockerversion.IAMSTATIC {
  184. if selfPath == "" {
  185. return false
  186. }
  187. if target == selfPath {
  188. return true
  189. }
  190. targetFileInfo, err := os.Lstat(target)
  191. if err != nil {
  192. return false
  193. }
  194. selfPathFileInfo, err := os.Lstat(selfPath)
  195. if err != nil {
  196. return false
  197. }
  198. return os.SameFile(targetFileInfo, selfPathFileInfo)
  199. }
  200. return dockerversion.INITSHA1 != "" && dockerInitSha1(target) == dockerversion.INITSHA1
  201. }
  202. // Figure out the path of our dockerinit (which may be SelfPath())
  203. func DockerInitPath(localCopy string) string {
  204. selfPath := SelfPath()
  205. if isValidDockerInitPath(selfPath, selfPath) {
  206. // if we're valid, don't bother checking anything else
  207. return selfPath
  208. }
  209. var possibleInits = []string{
  210. localCopy,
  211. dockerversion.INITPATH,
  212. filepath.Join(filepath.Dir(selfPath), "dockerinit"),
  213. // 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."
  214. // http://www.linuxbase.org/betaspecs/fhs/fhs.html#usrlibexec
  215. "/usr/libexec/docker/dockerinit",
  216. "/usr/local/libexec/docker/dockerinit",
  217. // 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."
  218. // http://refspecs.linuxfoundation.org/FHS_2.3/fhs-2.3.html#USRLIBLIBRARIESFORPROGRAMMINGANDPA
  219. "/usr/lib/docker/dockerinit",
  220. "/usr/local/lib/docker/dockerinit",
  221. }
  222. for _, dockerInit := range possibleInits {
  223. if dockerInit == "" {
  224. continue
  225. }
  226. path, err := exec.LookPath(dockerInit)
  227. if err == nil {
  228. path, err = filepath.Abs(path)
  229. if err != nil {
  230. // LookPath already validated that this file exists and is executable (following symlinks), so how could Abs fail?
  231. panic(err)
  232. }
  233. if isValidDockerInitPath(path, selfPath) {
  234. return path
  235. }
  236. }
  237. }
  238. return ""
  239. }
  240. type NopWriter struct{}
  241. func (*NopWriter) Write(buf []byte) (int, error) {
  242. return len(buf), nil
  243. }
  244. type nopWriteCloser struct {
  245. io.Writer
  246. }
  247. func (w *nopWriteCloser) Close() error { return nil }
  248. func NopWriteCloser(w io.Writer) io.WriteCloser {
  249. return &nopWriteCloser{w}
  250. }
  251. type bufReader struct {
  252. sync.Mutex
  253. buf *bytes.Buffer
  254. reader io.Reader
  255. err error
  256. wait sync.Cond
  257. }
  258. func NewBufReader(r io.Reader) *bufReader {
  259. reader := &bufReader{
  260. buf: &bytes.Buffer{},
  261. reader: r,
  262. }
  263. reader.wait.L = &reader.Mutex
  264. go reader.drain()
  265. return reader
  266. }
  267. func (r *bufReader) drain() {
  268. buf := make([]byte, 1024)
  269. for {
  270. n, err := r.reader.Read(buf)
  271. r.Lock()
  272. if err != nil {
  273. r.err = err
  274. } else {
  275. r.buf.Write(buf[0:n])
  276. }
  277. r.wait.Signal()
  278. r.Unlock()
  279. if err != nil {
  280. break
  281. }
  282. }
  283. }
  284. func (r *bufReader) Read(p []byte) (n int, err error) {
  285. r.Lock()
  286. defer r.Unlock()
  287. for {
  288. n, err = r.buf.Read(p)
  289. if n > 0 {
  290. return n, err
  291. }
  292. if r.err != nil {
  293. return 0, r.err
  294. }
  295. r.wait.Wait()
  296. }
  297. }
  298. func (r *bufReader) Close() error {
  299. closer, ok := r.reader.(io.ReadCloser)
  300. if !ok {
  301. return nil
  302. }
  303. return closer.Close()
  304. }
  305. type WriteBroadcaster struct {
  306. sync.Mutex
  307. buf *bytes.Buffer
  308. streams map[string](map[io.WriteCloser]struct{})
  309. }
  310. func (w *WriteBroadcaster) AddWriter(writer io.WriteCloser, stream string) {
  311. w.Lock()
  312. if _, ok := w.streams[stream]; !ok {
  313. w.streams[stream] = make(map[io.WriteCloser]struct{})
  314. }
  315. w.streams[stream][writer] = struct{}{}
  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 (jl *JSONLog) Format(format string) (string, error) {
  324. if format == "" {
  325. return jl.Log, nil
  326. }
  327. if format == "json" {
  328. m, err := json.Marshal(jl)
  329. return string(m), err
  330. }
  331. return fmt.Sprintf("[%s] %s", jl.Created.Format(format), jl.Log), nil
  332. }
  333. func WriteLog(src io.Reader, dst io.WriteCloser, format string) error {
  334. dec := json.NewDecoder(src)
  335. for {
  336. l := &JSONLog{}
  337. if err := dec.Decode(l); err == io.EOF {
  338. return nil
  339. } else if err != nil {
  340. Errorf("Error streaming logs: %s", err)
  341. return err
  342. }
  343. line, err := l.Format(format)
  344. if err != nil {
  345. return err
  346. }
  347. fmt.Fprintf(dst, "%s", line)
  348. }
  349. }
  350. type LogFormatter struct {
  351. wc io.WriteCloser
  352. timeFormat string
  353. }
  354. func (w *WriteBroadcaster) Write(p []byte) (n int, err error) {
  355. created := time.Now().UTC()
  356. w.Lock()
  357. defer w.Unlock()
  358. if writers, ok := w.streams[""]; ok {
  359. for sw := range writers {
  360. if n, err := sw.Write(p); err != nil || n != len(p) {
  361. // On error, evict the writer
  362. delete(writers, sw)
  363. }
  364. }
  365. }
  366. w.buf.Write(p)
  367. lines := []string{}
  368. for {
  369. line, err := w.buf.ReadString('\n')
  370. if err != nil {
  371. w.buf.Write([]byte(line))
  372. break
  373. }
  374. lines = append(lines, line)
  375. }
  376. if len(lines) != 0 {
  377. for stream, writers := range w.streams {
  378. if stream == "" {
  379. continue
  380. }
  381. var lp []byte
  382. for _, line := range lines {
  383. b, err := json.Marshal(&JSONLog{Log: line, Stream: stream, Created: created})
  384. if err != nil {
  385. Errorf("Error making JSON log line: %s", err)
  386. }
  387. lp = append(lp, b...)
  388. lp = append(lp, '\n')
  389. }
  390. for sw := range writers {
  391. if _, err := sw.Write(lp); err != nil {
  392. delete(writers, sw)
  393. }
  394. }
  395. }
  396. }
  397. return len(p), nil
  398. }
  399. func (w *WriteBroadcaster) CloseWriters() error {
  400. w.Lock()
  401. defer w.Unlock()
  402. for _, writers := range w.streams {
  403. for w := range writers {
  404. w.Close()
  405. }
  406. }
  407. w.streams = make(map[string](map[io.WriteCloser]struct{}))
  408. return nil
  409. }
  410. func NewWriteBroadcaster() *WriteBroadcaster {
  411. return &WriteBroadcaster{
  412. streams: make(map[string](map[io.WriteCloser]struct{})),
  413. buf: bytes.NewBuffer(nil),
  414. }
  415. }
  416. func GetTotalUsedFds() int {
  417. if fds, err := ioutil.ReadDir(fmt.Sprintf("/proc/%d/fd", os.Getpid())); err != nil {
  418. Errorf("Error opening /proc/%d/fd: %s", os.Getpid(), err)
  419. } else {
  420. return len(fds)
  421. }
  422. return -1
  423. }
  424. // TruncIndex allows the retrieval of string identifiers by any of their unique prefixes.
  425. // This is used to retrieve image and container IDs by more convenient shorthand prefixes.
  426. type TruncIndex struct {
  427. sync.RWMutex
  428. index *suffixarray.Index
  429. ids map[string]bool
  430. bytes []byte
  431. }
  432. func NewTruncIndex(ids []string) (idx *TruncIndex) {
  433. idx = &TruncIndex{
  434. ids: make(map[string]bool),
  435. bytes: []byte{' '},
  436. }
  437. for _, id := range ids {
  438. idx.ids[id] = true
  439. idx.bytes = append(idx.bytes, []byte(id+" ")...)
  440. }
  441. idx.index = suffixarray.New(idx.bytes)
  442. return
  443. }
  444. func (idx *TruncIndex) Add(id string) error {
  445. idx.Lock()
  446. defer idx.Unlock()
  447. if strings.Contains(id, " ") {
  448. return fmt.Errorf("Illegal character: ' '")
  449. }
  450. if _, exists := idx.ids[id]; exists {
  451. return fmt.Errorf("Id already exists: %s", id)
  452. }
  453. idx.ids[id] = true
  454. idx.bytes = append(idx.bytes, []byte(id+" ")...)
  455. idx.index = suffixarray.New(idx.bytes)
  456. return nil
  457. }
  458. func (idx *TruncIndex) Delete(id string) error {
  459. idx.Lock()
  460. defer idx.Unlock()
  461. if _, exists := idx.ids[id]; !exists {
  462. return fmt.Errorf("No such id: %s", id)
  463. }
  464. before, after, err := idx.lookup(id)
  465. if err != nil {
  466. return err
  467. }
  468. delete(idx.ids, id)
  469. idx.bytes = append(idx.bytes[:before], idx.bytes[after:]...)
  470. idx.index = suffixarray.New(idx.bytes)
  471. return nil
  472. }
  473. func (idx *TruncIndex) lookup(s string) (int, int, error) {
  474. offsets := idx.index.Lookup([]byte(" "+s), -1)
  475. //log.Printf("lookup(%s): %v (index bytes: '%s')\n", s, offsets, idx.index.Bytes())
  476. if offsets == nil || len(offsets) == 0 || len(offsets) > 1 {
  477. return -1, -1, fmt.Errorf("No such id: %s", s)
  478. }
  479. offsetBefore := offsets[0] + 1
  480. offsetAfter := offsetBefore + strings.Index(string(idx.bytes[offsetBefore:]), " ")
  481. return offsetBefore, offsetAfter, nil
  482. }
  483. func (idx *TruncIndex) Get(s string) (string, error) {
  484. idx.RLock()
  485. defer idx.RUnlock()
  486. before, after, err := idx.lookup(s)
  487. //log.Printf("Get(%s) bytes=|%s| before=|%d| after=|%d|\n", s, idx.bytes, before, after)
  488. if err != nil {
  489. return "", err
  490. }
  491. return string(idx.bytes[before:after]), err
  492. }
  493. // TruncateID returns a shorthand version of a string identifier for convenience.
  494. // A collision with other shorthands is very unlikely, but possible.
  495. // In case of a collision a lookup with TruncIndex.Get() will fail, and the caller
  496. // will need to use a langer prefix, or the full-length Id.
  497. func TruncateID(id string) string {
  498. shortLen := 12
  499. if len(id) < shortLen {
  500. shortLen = len(id)
  501. }
  502. return id[:shortLen]
  503. }
  504. // GenerateRandomID returns an unique id
  505. func GenerateRandomID() string {
  506. for {
  507. id := make([]byte, 32)
  508. if _, err := io.ReadFull(rand.Reader, id); err != nil {
  509. panic(err) // This shouldn't happen
  510. }
  511. value := hex.EncodeToString(id)
  512. // if we try to parse the truncated for as an int and we don't have
  513. // an error then the value is all numberic and causes issues when
  514. // used as a hostname. ref #3869
  515. if _, err := strconv.Atoi(TruncateID(value)); err == nil {
  516. continue
  517. }
  518. return value
  519. }
  520. }
  521. func ValidateID(id string) error {
  522. if id == "" {
  523. return fmt.Errorf("Id can't be empty")
  524. }
  525. if strings.Contains(id, ":") {
  526. return fmt.Errorf("Invalid character in id: ':'")
  527. }
  528. return nil
  529. }
  530. // Code c/c from io.Copy() modified to handle escape sequence
  531. func CopyEscapable(dst io.Writer, src io.ReadCloser) (written int64, err error) {
  532. buf := make([]byte, 32*1024)
  533. for {
  534. nr, er := src.Read(buf)
  535. if nr > 0 {
  536. // ---- Docker addition
  537. // char 16 is C-p
  538. if nr == 1 && buf[0] == 16 {
  539. nr, er = src.Read(buf)
  540. // char 17 is C-q
  541. if nr == 1 && buf[0] == 17 {
  542. if err := src.Close(); err != nil {
  543. return 0, err
  544. }
  545. return 0, nil
  546. }
  547. }
  548. // ---- End of docker
  549. nw, ew := dst.Write(buf[0:nr])
  550. if nw > 0 {
  551. written += int64(nw)
  552. }
  553. if ew != nil {
  554. err = ew
  555. break
  556. }
  557. if nr != nw {
  558. err = io.ErrShortWrite
  559. break
  560. }
  561. }
  562. if er == io.EOF {
  563. break
  564. }
  565. if er != nil {
  566. err = er
  567. break
  568. }
  569. }
  570. return written, err
  571. }
  572. func HashData(src io.Reader) (string, error) {
  573. h := sha256.New()
  574. if _, err := io.Copy(h, src); err != nil {
  575. return "", err
  576. }
  577. return "sha256:" + hex.EncodeToString(h.Sum(nil)), nil
  578. }
  579. type KernelVersionInfo struct {
  580. Kernel int
  581. Major int
  582. Minor int
  583. Flavor string
  584. }
  585. func (k *KernelVersionInfo) String() string {
  586. return fmt.Sprintf("%d.%d.%d%s", k.Kernel, k.Major, k.Minor, k.Flavor)
  587. }
  588. // Compare two KernelVersionInfo struct.
  589. // Returns -1 if a < b, 0 if a == b, 1 it a > b
  590. func CompareKernelVersion(a, b *KernelVersionInfo) int {
  591. if a.Kernel < b.Kernel {
  592. return -1
  593. } else if a.Kernel > b.Kernel {
  594. return 1
  595. }
  596. if a.Major < b.Major {
  597. return -1
  598. } else if a.Major > b.Major {
  599. return 1
  600. }
  601. if a.Minor < b.Minor {
  602. return -1
  603. } else if a.Minor > b.Minor {
  604. return 1
  605. }
  606. return 0
  607. }
  608. func GetKernelVersion() (*KernelVersionInfo, error) {
  609. var (
  610. err error
  611. )
  612. uts, err := uname()
  613. if err != nil {
  614. return nil, err
  615. }
  616. release := make([]byte, len(uts.Release))
  617. i := 0
  618. for _, c := range uts.Release {
  619. release[i] = byte(c)
  620. i++
  621. }
  622. // Remove the \x00 from the release for Atoi to parse correctly
  623. release = release[:bytes.IndexByte(release, 0)]
  624. return ParseRelease(string(release))
  625. }
  626. func ParseRelease(release string) (*KernelVersionInfo, error) {
  627. var (
  628. kernel, major, minor, parsed int
  629. flavor, partial string
  630. )
  631. // Ignore error from Sscanf to allow an empty flavor. Instead, just
  632. // make sure we got all the version numbers.
  633. parsed, _ = fmt.Sscanf(release, "%d.%d%s", &kernel, &major, &partial)
  634. if parsed < 2 {
  635. return nil, errors.New("Can't parse kernel version " + release)
  636. }
  637. // sometimes we have 3.12.25-gentoo, but sometimes we just have 3.12-1-amd64
  638. parsed, _ = fmt.Sscanf(partial, ".%d%s", &minor, &flavor)
  639. if parsed < 1 {
  640. flavor = partial
  641. }
  642. return &KernelVersionInfo{
  643. Kernel: kernel,
  644. Major: major,
  645. Minor: minor,
  646. Flavor: flavor,
  647. }, nil
  648. }
  649. // FIXME: this is deprecated by CopyWithTar in archive.go
  650. func CopyDirectory(source, dest string) error {
  651. if output, err := exec.Command("cp", "-ra", source, dest).CombinedOutput(); err != nil {
  652. return fmt.Errorf("Error copy: %s (%s)", err, output)
  653. }
  654. return nil
  655. }
  656. type NopFlusher struct{}
  657. func (f *NopFlusher) Flush() {}
  658. type WriteFlusher struct {
  659. sync.Mutex
  660. w io.Writer
  661. flusher http.Flusher
  662. }
  663. func (wf *WriteFlusher) Write(b []byte) (n int, err error) {
  664. wf.Lock()
  665. defer wf.Unlock()
  666. n, err = wf.w.Write(b)
  667. wf.flusher.Flush()
  668. return n, err
  669. }
  670. // Flush the stream immediately.
  671. func (wf *WriteFlusher) Flush() {
  672. wf.Lock()
  673. defer wf.Unlock()
  674. wf.flusher.Flush()
  675. }
  676. func NewWriteFlusher(w io.Writer) *WriteFlusher {
  677. var flusher http.Flusher
  678. if f, ok := w.(http.Flusher); ok {
  679. flusher = f
  680. } else {
  681. flusher = &NopFlusher{}
  682. }
  683. return &WriteFlusher{w: w, flusher: flusher}
  684. }
  685. func NewHTTPRequestError(msg string, res *http.Response) error {
  686. return &JSONError{
  687. Message: msg,
  688. Code: res.StatusCode,
  689. }
  690. }
  691. func IsURL(str string) bool {
  692. return strings.HasPrefix(str, "http://") || strings.HasPrefix(str, "https://")
  693. }
  694. func IsGIT(str string) bool {
  695. return strings.HasPrefix(str, "git://") || strings.HasPrefix(str, "github.com/") || strings.HasPrefix(str, "git@github.com:") || (strings.HasSuffix(str, ".git") && IsURL(str))
  696. }
  697. // GetResolvConf opens and read the content of /etc/resolv.conf.
  698. // It returns it as byte slice.
  699. func GetResolvConf() ([]byte, error) {
  700. resolv, err := ioutil.ReadFile("/etc/resolv.conf")
  701. if err != nil {
  702. Errorf("Error openning resolv.conf: %s", err)
  703. return nil, err
  704. }
  705. return resolv, nil
  706. }
  707. // CheckLocalDns looks into the /etc/resolv.conf,
  708. // it returns true if there is a local nameserver or if there is no nameserver.
  709. func CheckLocalDns(resolvConf []byte) bool {
  710. for _, line := range GetLines(resolvConf, []byte("#")) {
  711. if !bytes.Contains(line, []byte("nameserver")) {
  712. continue
  713. }
  714. for _, ip := range [][]byte{
  715. []byte("127.0.0.1"),
  716. []byte("127.0.1.1"),
  717. } {
  718. if bytes.Contains(line, ip) {
  719. return true
  720. }
  721. }
  722. return false
  723. }
  724. return true
  725. }
  726. // GetLines parses input into lines and strips away comments.
  727. func GetLines(input []byte, commentMarker []byte) [][]byte {
  728. lines := bytes.Split(input, []byte("\n"))
  729. var output [][]byte
  730. for _, currentLine := range lines {
  731. var commentIndex = bytes.Index(currentLine, commentMarker)
  732. if commentIndex == -1 {
  733. output = append(output, currentLine)
  734. } else {
  735. output = append(output, currentLine[:commentIndex])
  736. }
  737. }
  738. return output
  739. }
  740. // GetNameservers returns nameservers (if any) listed in /etc/resolv.conf
  741. func GetNameservers(resolvConf []byte) []string {
  742. nameservers := []string{}
  743. re := regexp.MustCompile(`^\s*nameserver\s*(([0-9]+\.){3}([0-9]+))\s*$`)
  744. for _, line := range GetLines(resolvConf, []byte("#")) {
  745. var ns = re.FindSubmatch(line)
  746. if len(ns) > 0 {
  747. nameservers = append(nameservers, string(ns[1]))
  748. }
  749. }
  750. return nameservers
  751. }
  752. // GetNameserversAsCIDR returns nameservers (if any) listed in
  753. // /etc/resolv.conf as CIDR blocks (e.g., "1.2.3.4/32")
  754. // This function's output is intended for net.ParseCIDR
  755. func GetNameserversAsCIDR(resolvConf []byte) []string {
  756. nameservers := []string{}
  757. for _, nameserver := range GetNameservers(resolvConf) {
  758. nameservers = append(nameservers, nameserver+"/32")
  759. }
  760. return nameservers
  761. }
  762. // GetSearchDomains returns search domains (if any) listed in /etc/resolv.conf
  763. // If more than one search line is encountered, only the contents of the last
  764. // one is returned.
  765. func GetSearchDomains(resolvConf []byte) []string {
  766. re := regexp.MustCompile(`^\s*search\s*(([^\s]+\s*)*)$`)
  767. domains := []string{}
  768. for _, line := range GetLines(resolvConf, []byte("#")) {
  769. match := re.FindSubmatch(line)
  770. if match == nil {
  771. continue
  772. }
  773. domains = strings.Fields(string(match[1]))
  774. }
  775. return domains
  776. }
  777. // FIXME: Change this not to receive default value as parameter
  778. func ParseHost(defaultHost string, defaultUnix, addr string) (string, error) {
  779. var (
  780. proto string
  781. host string
  782. port int
  783. )
  784. addr = strings.TrimSpace(addr)
  785. switch {
  786. case addr == "tcp://":
  787. return "", fmt.Errorf("Invalid bind address format: %s", addr)
  788. case strings.HasPrefix(addr, "unix://"):
  789. proto = "unix"
  790. addr = strings.TrimPrefix(addr, "unix://")
  791. if addr == "" {
  792. addr = defaultUnix
  793. }
  794. case strings.HasPrefix(addr, "tcp://"):
  795. proto = "tcp"
  796. addr = strings.TrimPrefix(addr, "tcp://")
  797. case strings.HasPrefix(addr, "fd://"):
  798. return addr, nil
  799. case addr == "":
  800. proto = "unix"
  801. addr = defaultUnix
  802. default:
  803. if strings.Contains(addr, "://") {
  804. return "", fmt.Errorf("Invalid bind address protocol: %s", addr)
  805. }
  806. proto = "tcp"
  807. }
  808. if proto != "unix" && strings.Contains(addr, ":") {
  809. hostParts := strings.Split(addr, ":")
  810. if len(hostParts) != 2 {
  811. return "", fmt.Errorf("Invalid bind address format: %s", addr)
  812. }
  813. if hostParts[0] != "" {
  814. host = hostParts[0]
  815. } else {
  816. host = defaultHost
  817. }
  818. if p, err := strconv.Atoi(hostParts[1]); err == nil && p != 0 {
  819. port = p
  820. } else {
  821. return "", fmt.Errorf("Invalid bind address format: %s", addr)
  822. }
  823. } else if proto == "tcp" && !strings.Contains(addr, ":") {
  824. return "", fmt.Errorf("Invalid bind address format: %s", addr)
  825. } else {
  826. host = addr
  827. }
  828. if proto == "unix" {
  829. return fmt.Sprintf("%s://%s", proto, host), nil
  830. }
  831. return fmt.Sprintf("%s://%s:%d", proto, host, port), nil
  832. }
  833. func GetReleaseVersion() string {
  834. resp, err := http.Get("https://get.docker.io/latest")
  835. if err != nil {
  836. return ""
  837. }
  838. defer resp.Body.Close()
  839. if resp.ContentLength > 24 || resp.StatusCode != 200 {
  840. return ""
  841. }
  842. body, err := ioutil.ReadAll(resp.Body)
  843. if err != nil {
  844. return ""
  845. }
  846. return strings.TrimSpace(string(body))
  847. }
  848. // Get a repos name and returns the right reposName + tag
  849. // The tag can be confusing because of a port in a repository name.
  850. // Ex: localhost.localdomain:5000/samalba/hipache:latest
  851. func ParseRepositoryTag(repos string) (string, string) {
  852. n := strings.LastIndex(repos, ":")
  853. if n < 0 {
  854. return repos, ""
  855. }
  856. if tag := repos[n+1:]; !strings.Contains(tag, "/") {
  857. return repos[:n], tag
  858. }
  859. return repos, ""
  860. }
  861. // An StatusError reports an unsuccessful exit by a command.
  862. type StatusError struct {
  863. Status string
  864. StatusCode int
  865. }
  866. func (e *StatusError) Error() string {
  867. return fmt.Sprintf("Status: %s, Code: %d", e.Status, e.StatusCode)
  868. }
  869. func quote(word string, buf *bytes.Buffer) {
  870. // Bail out early for "simple" strings
  871. if word != "" && !strings.ContainsAny(word, "\\'\"`${[|&;<>()~*?! \t\n") {
  872. buf.WriteString(word)
  873. return
  874. }
  875. buf.WriteString("'")
  876. for i := 0; i < len(word); i++ {
  877. b := word[i]
  878. if b == '\'' {
  879. // Replace literal ' with a close ', a \', and a open '
  880. buf.WriteString("'\\''")
  881. } else {
  882. buf.WriteByte(b)
  883. }
  884. }
  885. buf.WriteString("'")
  886. }
  887. // Take a list of strings and escape them so they will be handled right
  888. // when passed as arguments to an program via a shell
  889. func ShellQuoteArguments(args []string) string {
  890. var buf bytes.Buffer
  891. for i, arg := range args {
  892. if i != 0 {
  893. buf.WriteByte(' ')
  894. }
  895. quote(arg, &buf)
  896. }
  897. return buf.String()
  898. }
  899. func PartParser(template, data string) (map[string]string, error) {
  900. // ip:public:private
  901. var (
  902. templateParts = strings.Split(template, ":")
  903. parts = strings.Split(data, ":")
  904. out = make(map[string]string, len(templateParts))
  905. )
  906. if len(parts) != len(templateParts) {
  907. return nil, fmt.Errorf("Invalid format to parse. %s should match template %s", data, template)
  908. }
  909. for i, t := range templateParts {
  910. value := ""
  911. if len(parts) > i {
  912. value = parts[i]
  913. }
  914. out[t] = value
  915. }
  916. return out, nil
  917. }
  918. var globalTestID string
  919. // TestDirectory creates a new temporary directory and returns its path.
  920. // The contents of directory at path `templateDir` is copied into the
  921. // new directory.
  922. func TestDirectory(templateDir string) (dir string, err error) {
  923. if globalTestID == "" {
  924. globalTestID = RandomString()[:4]
  925. }
  926. prefix := fmt.Sprintf("docker-test%s-%s-", globalTestID, GetCallerName(2))
  927. if prefix == "" {
  928. prefix = "docker-test-"
  929. }
  930. dir, err = ioutil.TempDir("", prefix)
  931. if err = os.Remove(dir); err != nil {
  932. return
  933. }
  934. if templateDir != "" {
  935. if err = CopyDirectory(templateDir, dir); err != nil {
  936. return
  937. }
  938. }
  939. return
  940. }
  941. // GetCallerName introspects the call stack and returns the name of the
  942. // function `depth` levels down in the stack.
  943. func GetCallerName(depth int) string {
  944. // Use the caller function name as a prefix.
  945. // This helps trace temp directories back to their test.
  946. pc, _, _, _ := runtime.Caller(depth + 1)
  947. callerLongName := runtime.FuncForPC(pc).Name()
  948. parts := strings.Split(callerLongName, ".")
  949. callerShortName := parts[len(parts)-1]
  950. return callerShortName
  951. }
  952. func CopyFile(src, dst string) (int64, error) {
  953. if src == dst {
  954. return 0, nil
  955. }
  956. sf, err := os.Open(src)
  957. if err != nil {
  958. return 0, err
  959. }
  960. defer sf.Close()
  961. if err := os.Remove(dst); err != nil && !os.IsNotExist(err) {
  962. return 0, err
  963. }
  964. df, err := os.Create(dst)
  965. if err != nil {
  966. return 0, err
  967. }
  968. defer df.Close()
  969. return io.Copy(df, sf)
  970. }
  971. type readCloserWrapper struct {
  972. io.Reader
  973. closer func() error
  974. }
  975. func (r *readCloserWrapper) Close() error {
  976. return r.closer()
  977. }
  978. func NewReadCloserWrapper(r io.Reader, closer func() error) io.ReadCloser {
  979. return &readCloserWrapper{
  980. Reader: r,
  981. closer: closer,
  982. }
  983. }
  984. // ReplaceOrAppendValues returns the defaults with the overrides either
  985. // replaced by env key or appended to the list
  986. func ReplaceOrAppendEnvValues(defaults, overrides []string) []string {
  987. cache := make(map[string]int, len(defaults))
  988. for i, e := range defaults {
  989. parts := strings.SplitN(e, "=", 2)
  990. cache[parts[0]] = i
  991. }
  992. for _, value := range overrides {
  993. parts := strings.SplitN(value, "=", 2)
  994. if i, exists := cache[parts[0]]; exists {
  995. defaults[i] = value
  996. } else {
  997. defaults = append(defaults, value)
  998. }
  999. }
  1000. return defaults
  1001. }
  1002. // ReadSymlinkedDirectory returns the target directory of a symlink.
  1003. // The target of the symbolic link may not be a file.
  1004. func ReadSymlinkedDirectory(path string) (string, error) {
  1005. var realPath string
  1006. var err error
  1007. if realPath, err = filepath.Abs(path); err != nil {
  1008. return "", fmt.Errorf("unable to get absolute path for %s: %s", path, err)
  1009. }
  1010. if realPath, err = filepath.EvalSymlinks(realPath); err != nil {
  1011. return "", fmt.Errorf("failed to canonicalise path for %s: %s", path, err)
  1012. }
  1013. realPathInfo, err := os.Stat(realPath)
  1014. if err != nil {
  1015. return "", fmt.Errorf("failed to stat target '%s' of '%s': %s", realPath, path, err)
  1016. }
  1017. if !realPathInfo.Mode().IsDir() {
  1018. return "", fmt.Errorf("canonical path points to a file '%s'", realPath)
  1019. }
  1020. return realPath, nil
  1021. }
  1022. func ParseKeyValueOpt(opt string) (string, string, error) {
  1023. parts := strings.SplitN(opt, "=", 2)
  1024. if len(parts) != 2 {
  1025. return "", "", fmt.Errorf("Unable to parse key/value option: %s", opt)
  1026. }
  1027. return strings.TrimSpace(parts[0]), strings.TrimSpace(parts[1]), nil
  1028. }