utils.go 27 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160
  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. sync.RWMutex
  378. index *suffixarray.Index
  379. ids map[string]bool
  380. bytes []byte
  381. }
  382. func NewTruncIndex() *TruncIndex {
  383. return &TruncIndex{
  384. index: suffixarray.New([]byte{' '}),
  385. ids: make(map[string]bool),
  386. bytes: []byte{' '},
  387. }
  388. }
  389. func (idx *TruncIndex) Add(id string) error {
  390. idx.Lock()
  391. defer idx.Unlock()
  392. if strings.Contains(id, " ") {
  393. return fmt.Errorf("Illegal character: ' '")
  394. }
  395. if _, exists := idx.ids[id]; exists {
  396. return fmt.Errorf("Id already exists: %s", id)
  397. }
  398. idx.ids[id] = true
  399. idx.bytes = append(idx.bytes, []byte(id+" ")...)
  400. idx.index = suffixarray.New(idx.bytes)
  401. return nil
  402. }
  403. func (idx *TruncIndex) Delete(id string) error {
  404. idx.Lock()
  405. defer idx.Unlock()
  406. if _, exists := idx.ids[id]; !exists {
  407. return fmt.Errorf("No such id: %s", id)
  408. }
  409. before, after, err := idx.lookup(id)
  410. if err != nil {
  411. return err
  412. }
  413. delete(idx.ids, id)
  414. idx.bytes = append(idx.bytes[:before], idx.bytes[after:]...)
  415. idx.index = suffixarray.New(idx.bytes)
  416. return nil
  417. }
  418. func (idx *TruncIndex) lookup(s string) (int, int, error) {
  419. offsets := idx.index.Lookup([]byte(" "+s), -1)
  420. //log.Printf("lookup(%s): %v (index bytes: '%s')\n", s, offsets, idx.index.Bytes())
  421. if offsets == nil || len(offsets) == 0 || len(offsets) > 1 {
  422. return -1, -1, fmt.Errorf("No such id: %s", s)
  423. }
  424. offsetBefore := offsets[0] + 1
  425. offsetAfter := offsetBefore + strings.Index(string(idx.bytes[offsetBefore:]), " ")
  426. return offsetBefore, offsetAfter, nil
  427. }
  428. func (idx *TruncIndex) Get(s string) (string, error) {
  429. idx.RLock()
  430. defer idx.RUnlock()
  431. before, after, err := idx.lookup(s)
  432. //log.Printf("Get(%s) bytes=|%s| before=|%d| after=|%d|\n", s, idx.bytes, before, after)
  433. if err != nil {
  434. return "", err
  435. }
  436. return string(idx.bytes[before:after]), err
  437. }
  438. // TruncateID returns a shorthand version of a string identifier for convenience.
  439. // A collision with other shorthands is very unlikely, but possible.
  440. // In case of a collision a lookup with TruncIndex.Get() will fail, and the caller
  441. // will need to use a langer prefix, or the full-length Id.
  442. func TruncateID(id string) string {
  443. shortLen := 12
  444. if len(id) < shortLen {
  445. shortLen = len(id)
  446. }
  447. return id[:shortLen]
  448. }
  449. // Code c/c from io.Copy() modified to handle escape sequence
  450. func CopyEscapable(dst io.Writer, src io.ReadCloser) (written int64, err error) {
  451. buf := make([]byte, 32*1024)
  452. for {
  453. nr, er := src.Read(buf)
  454. if nr > 0 {
  455. // ---- Docker addition
  456. // char 16 is C-p
  457. if nr == 1 && buf[0] == 16 {
  458. nr, er = src.Read(buf)
  459. // char 17 is C-q
  460. if nr == 1 && buf[0] == 17 {
  461. if err := src.Close(); err != nil {
  462. return 0, err
  463. }
  464. return 0, nil
  465. }
  466. }
  467. // ---- End of docker
  468. nw, ew := dst.Write(buf[0:nr])
  469. if nw > 0 {
  470. written += int64(nw)
  471. }
  472. if ew != nil {
  473. err = ew
  474. break
  475. }
  476. if nr != nw {
  477. err = io.ErrShortWrite
  478. break
  479. }
  480. }
  481. if er == io.EOF {
  482. break
  483. }
  484. if er != nil {
  485. err = er
  486. break
  487. }
  488. }
  489. return written, err
  490. }
  491. func HashData(src io.Reader) (string, error) {
  492. h := sha256.New()
  493. if _, err := io.Copy(h, src); err != nil {
  494. return "", err
  495. }
  496. return "sha256:" + hex.EncodeToString(h.Sum(nil)), nil
  497. }
  498. type KernelVersionInfo struct {
  499. Kernel int
  500. Major int
  501. Minor int
  502. Flavor string
  503. }
  504. func (k *KernelVersionInfo) String() string {
  505. flavor := ""
  506. if len(k.Flavor) > 0 {
  507. flavor = fmt.Sprintf("-%s", k.Flavor)
  508. }
  509. return fmt.Sprintf("%d.%d.%d%s", k.Kernel, k.Major, k.Minor, flavor)
  510. }
  511. // Compare two KernelVersionInfo struct.
  512. // Returns -1 if a < b, = if a == b, 1 it a > b
  513. func CompareKernelVersion(a, b *KernelVersionInfo) int {
  514. if a.Kernel < b.Kernel {
  515. return -1
  516. } else if a.Kernel > b.Kernel {
  517. return 1
  518. }
  519. if a.Major < b.Major {
  520. return -1
  521. } else if a.Major > b.Major {
  522. return 1
  523. }
  524. if a.Minor < b.Minor {
  525. return -1
  526. } else if a.Minor > b.Minor {
  527. return 1
  528. }
  529. return 0
  530. }
  531. func GetKernelVersion() (*KernelVersionInfo, error) {
  532. var (
  533. err error
  534. )
  535. uts, err := uname()
  536. if err != nil {
  537. return nil, err
  538. }
  539. release := make([]byte, len(uts.Release))
  540. i := 0
  541. for _, c := range uts.Release {
  542. release[i] = byte(c)
  543. i++
  544. }
  545. // Remove the \x00 from the release for Atoi to parse correctly
  546. release = release[:bytes.IndexByte(release, 0)]
  547. return ParseRelease(string(release))
  548. }
  549. func ParseRelease(release string) (*KernelVersionInfo, error) {
  550. var (
  551. flavor string
  552. kernel, major, minor int
  553. err error
  554. )
  555. tmp := strings.SplitN(release, "-", 2)
  556. tmp2 := strings.Split(tmp[0], ".")
  557. if len(tmp2) > 0 {
  558. kernel, err = strconv.Atoi(tmp2[0])
  559. if err != nil {
  560. return nil, err
  561. }
  562. }
  563. if len(tmp2) > 1 {
  564. major, err = strconv.Atoi(tmp2[1])
  565. if err != nil {
  566. return nil, err
  567. }
  568. }
  569. if len(tmp2) > 2 {
  570. // Removes "+" because git kernels might set it
  571. minorUnparsed := strings.Trim(tmp2[2], "+")
  572. minor, err = strconv.Atoi(minorUnparsed)
  573. if err != nil {
  574. return nil, err
  575. }
  576. }
  577. if len(tmp) == 2 {
  578. flavor = tmp[1]
  579. } else {
  580. flavor = ""
  581. }
  582. return &KernelVersionInfo{
  583. Kernel: kernel,
  584. Major: major,
  585. Minor: minor,
  586. Flavor: flavor,
  587. }, nil
  588. }
  589. // FIXME: this is deprecated by CopyWithTar in archive.go
  590. func CopyDirectory(source, dest string) error {
  591. if output, err := exec.Command("cp", "-ra", source, dest).CombinedOutput(); err != nil {
  592. return fmt.Errorf("Error copy: %s (%s)", err, output)
  593. }
  594. return nil
  595. }
  596. type NopFlusher struct{}
  597. func (f *NopFlusher) Flush() {}
  598. type WriteFlusher struct {
  599. sync.Mutex
  600. w io.Writer
  601. flusher http.Flusher
  602. }
  603. func (wf *WriteFlusher) Write(b []byte) (n int, err error) {
  604. wf.Lock()
  605. defer wf.Unlock()
  606. n, err = wf.w.Write(b)
  607. wf.flusher.Flush()
  608. return n, err
  609. }
  610. // Flush the stream immediately.
  611. func (wf *WriteFlusher) Flush() {
  612. wf.Lock()
  613. defer wf.Unlock()
  614. wf.flusher.Flush()
  615. }
  616. func NewWriteFlusher(w io.Writer) *WriteFlusher {
  617. var flusher http.Flusher
  618. if f, ok := w.(http.Flusher); ok {
  619. flusher = f
  620. } else {
  621. flusher = &NopFlusher{}
  622. }
  623. return &WriteFlusher{w: w, flusher: flusher}
  624. }
  625. func NewHTTPRequestError(msg string, res *http.Response) error {
  626. return &JSONError{
  627. Message: msg,
  628. Code: res.StatusCode,
  629. }
  630. }
  631. func IsURL(str string) bool {
  632. return strings.HasPrefix(str, "http://") || strings.HasPrefix(str, "https://")
  633. }
  634. func IsGIT(str string) bool {
  635. return strings.HasPrefix(str, "git://") || strings.HasPrefix(str, "github.com/")
  636. }
  637. // GetResolvConf opens and read the content of /etc/resolv.conf.
  638. // It returns it as byte slice.
  639. func GetResolvConf() ([]byte, error) {
  640. resolv, err := ioutil.ReadFile("/etc/resolv.conf")
  641. if err != nil {
  642. Errorf("Error openning resolv.conf: %s", err)
  643. return nil, err
  644. }
  645. return resolv, nil
  646. }
  647. // CheckLocalDns looks into the /etc/resolv.conf,
  648. // it returns true if there is a local nameserver or if there is no nameserver.
  649. func CheckLocalDns(resolvConf []byte) bool {
  650. var parsedResolvConf = StripComments(resolvConf, []byte("#"))
  651. if !bytes.Contains(parsedResolvConf, []byte("nameserver")) {
  652. return true
  653. }
  654. for _, ip := range [][]byte{
  655. []byte("127.0.0.1"),
  656. []byte("127.0.1.1"),
  657. } {
  658. if bytes.Contains(parsedResolvConf, ip) {
  659. return true
  660. }
  661. }
  662. return false
  663. }
  664. // StripComments parses input into lines and strips away comments.
  665. func StripComments(input []byte, commentMarker []byte) []byte {
  666. lines := bytes.Split(input, []byte("\n"))
  667. var output []byte
  668. for _, currentLine := range lines {
  669. var commentIndex = bytes.Index(currentLine, commentMarker)
  670. if commentIndex == -1 {
  671. output = append(output, currentLine...)
  672. } else {
  673. output = append(output, currentLine[:commentIndex]...)
  674. }
  675. output = append(output, []byte("\n")...)
  676. }
  677. return output
  678. }
  679. // GetNameserversAsCIDR returns nameservers (if any) listed in
  680. // /etc/resolv.conf as CIDR blocks (e.g., "1.2.3.4/32")
  681. // This function's output is intended for net.ParseCIDR
  682. func GetNameserversAsCIDR(resolvConf []byte) []string {
  683. var parsedResolvConf = StripComments(resolvConf, []byte("#"))
  684. nameservers := []string{}
  685. re := regexp.MustCompile(`^\s*nameserver\s*(([0-9]+\.){3}([0-9]+))\s*$`)
  686. for _, line := range bytes.Split(parsedResolvConf, []byte("\n")) {
  687. var ns = re.FindSubmatch(line)
  688. if len(ns) > 0 {
  689. nameservers = append(nameservers, string(ns[1])+"/32")
  690. }
  691. }
  692. return nameservers
  693. }
  694. // FIXME: Change this not to receive default value as parameter
  695. func ParseHost(defaultHost string, defaultPort int, defaultUnix, addr string) (string, error) {
  696. var (
  697. proto string
  698. host string
  699. port int
  700. )
  701. addr = strings.TrimSpace(addr)
  702. switch {
  703. case strings.HasPrefix(addr, "unix://"):
  704. proto = "unix"
  705. addr = strings.TrimPrefix(addr, "unix://")
  706. if addr == "" {
  707. addr = defaultUnix
  708. }
  709. case strings.HasPrefix(addr, "tcp://"):
  710. proto = "tcp"
  711. addr = strings.TrimPrefix(addr, "tcp://")
  712. case addr == "":
  713. proto = "unix"
  714. addr = defaultUnix
  715. default:
  716. if strings.Contains(addr, "://") {
  717. return "", fmt.Errorf("Invalid bind address protocol: %s", addr)
  718. }
  719. proto = "tcp"
  720. }
  721. if proto != "unix" && strings.Contains(addr, ":") {
  722. hostParts := strings.Split(addr, ":")
  723. if len(hostParts) != 2 {
  724. return "", fmt.Errorf("Invalid bind address format: %s", addr)
  725. }
  726. if hostParts[0] != "" {
  727. host = hostParts[0]
  728. } else {
  729. host = defaultHost
  730. }
  731. if p, err := strconv.Atoi(hostParts[1]); err == nil && p != 0 {
  732. port = p
  733. } else {
  734. port = defaultPort
  735. }
  736. } else {
  737. host = addr
  738. port = defaultPort
  739. }
  740. if proto == "unix" {
  741. return fmt.Sprintf("%s://%s", proto, host), nil
  742. }
  743. return fmt.Sprintf("%s://%s:%d", proto, host, port), nil
  744. }
  745. func GetReleaseVersion() string {
  746. resp, err := http.Get("https://get.docker.io/latest")
  747. if err != nil {
  748. return ""
  749. }
  750. defer resp.Body.Close()
  751. if resp.ContentLength > 24 || resp.StatusCode != 200 {
  752. return ""
  753. }
  754. body, err := ioutil.ReadAll(resp.Body)
  755. if err != nil {
  756. return ""
  757. }
  758. return strings.TrimSpace(string(body))
  759. }
  760. // Get a repos name and returns the right reposName + tag
  761. // The tag can be confusing because of a port in a repository name.
  762. // Ex: localhost.localdomain:5000/samalba/hipache:latest
  763. func ParseRepositoryTag(repos string) (string, string) {
  764. n := strings.LastIndex(repos, ":")
  765. if n < 0 {
  766. return repos, ""
  767. }
  768. if tag := repos[n+1:]; !strings.Contains(tag, "/") {
  769. return repos[:n], tag
  770. }
  771. return repos, ""
  772. }
  773. type User struct {
  774. Uid string // user id
  775. Gid string // primary group id
  776. Username string
  777. Name string
  778. HomeDir string
  779. }
  780. // UserLookup check if the given username or uid is present in /etc/passwd
  781. // and returns the user struct.
  782. // If the username is not found, an error is returned.
  783. func UserLookup(uid string) (*User, error) {
  784. file, err := ioutil.ReadFile("/etc/passwd")
  785. if err != nil {
  786. return nil, err
  787. }
  788. for _, line := range strings.Split(string(file), "\n") {
  789. data := strings.Split(line, ":")
  790. if len(data) > 5 && (data[0] == uid || data[2] == uid) {
  791. return &User{
  792. Uid: data[2],
  793. Gid: data[3],
  794. Username: data[0],
  795. Name: data[4],
  796. HomeDir: data[5],
  797. }, nil
  798. }
  799. }
  800. return nil, fmt.Errorf("User not found in /etc/passwd")
  801. }
  802. type DependencyGraph struct {
  803. nodes map[string]*DependencyNode
  804. }
  805. type DependencyNode struct {
  806. id string
  807. deps map[*DependencyNode]bool
  808. }
  809. func NewDependencyGraph() DependencyGraph {
  810. return DependencyGraph{
  811. nodes: map[string]*DependencyNode{},
  812. }
  813. }
  814. func (graph *DependencyGraph) addNode(node *DependencyNode) string {
  815. if graph.nodes[node.id] == nil {
  816. graph.nodes[node.id] = node
  817. }
  818. return node.id
  819. }
  820. func (graph *DependencyGraph) NewNode(id string) string {
  821. if graph.nodes[id] != nil {
  822. return id
  823. }
  824. nd := &DependencyNode{
  825. id: id,
  826. deps: map[*DependencyNode]bool{},
  827. }
  828. graph.addNode(nd)
  829. return id
  830. }
  831. func (graph *DependencyGraph) AddDependency(node, to string) error {
  832. if graph.nodes[node] == nil {
  833. return fmt.Errorf("Node %s does not belong to this graph", node)
  834. }
  835. if graph.nodes[to] == nil {
  836. return fmt.Errorf("Node %s does not belong to this graph", to)
  837. }
  838. if node == to {
  839. return fmt.Errorf("Dependency loops are forbidden!")
  840. }
  841. graph.nodes[node].addDependency(graph.nodes[to])
  842. return nil
  843. }
  844. func (node *DependencyNode) addDependency(to *DependencyNode) bool {
  845. node.deps[to] = true
  846. return node.deps[to]
  847. }
  848. func (node *DependencyNode) Degree() int {
  849. return len(node.deps)
  850. }
  851. // The magic happens here ::
  852. func (graph *DependencyGraph) GenerateTraversalMap() ([][]string, error) {
  853. Debugf("Generating traversal map. Nodes: %d", len(graph.nodes))
  854. result := [][]string{}
  855. processed := map[*DependencyNode]bool{}
  856. // As long as we haven't processed all nodes...
  857. for len(processed) < len(graph.nodes) {
  858. // Use a temporary buffer for processed nodes, otherwise
  859. // nodes that depend on each other could end up in the same round.
  860. tmpProcessed := []*DependencyNode{}
  861. for _, node := range graph.nodes {
  862. // If the node has more dependencies than what we have cleared,
  863. // it won't be valid for this round.
  864. if node.Degree() > len(processed) {
  865. continue
  866. }
  867. // If it's already processed, get to the next one
  868. if processed[node] {
  869. continue
  870. }
  871. // It's not been processed yet and has 0 deps. Add it!
  872. // (this is a shortcut for what we're doing below)
  873. if node.Degree() == 0 {
  874. tmpProcessed = append(tmpProcessed, node)
  875. continue
  876. }
  877. // If at least one dep hasn't been processed yet, we can't
  878. // add it.
  879. ok := true
  880. for dep := range node.deps {
  881. if !processed[dep] {
  882. ok = false
  883. break
  884. }
  885. }
  886. // All deps have already been processed. Add it!
  887. if ok {
  888. tmpProcessed = append(tmpProcessed, node)
  889. }
  890. }
  891. Debugf("Round %d: found %d available nodes", len(result), len(tmpProcessed))
  892. // If no progress has been made this round,
  893. // that means we have circular dependencies.
  894. if len(tmpProcessed) == 0 {
  895. return nil, fmt.Errorf("Could not find a solution to this dependency graph")
  896. }
  897. round := []string{}
  898. for _, nd := range tmpProcessed {
  899. round = append(round, nd.id)
  900. processed[nd] = true
  901. }
  902. result = append(result, round)
  903. }
  904. return result, nil
  905. }
  906. // An StatusError reports an unsuccessful exit by a command.
  907. type StatusError struct {
  908. Status string
  909. StatusCode int
  910. }
  911. func (e *StatusError) Error() string {
  912. return fmt.Sprintf("Status: %s, Code: %d", e.Status, e.StatusCode)
  913. }
  914. func quote(word string, buf *bytes.Buffer) {
  915. // Bail out early for "simple" strings
  916. if word != "" && !strings.ContainsAny(word, "\\'\"`${[|&;<>()~*?! \t\n") {
  917. buf.WriteString(word)
  918. return
  919. }
  920. buf.WriteString("'")
  921. for i := 0; i < len(word); i++ {
  922. b := word[i]
  923. if b == '\'' {
  924. // Replace literal ' with a close ', a \', and a open '
  925. buf.WriteString("'\\''")
  926. } else {
  927. buf.WriteByte(b)
  928. }
  929. }
  930. buf.WriteString("'")
  931. }
  932. // Take a list of strings and escape them so they will be handled right
  933. // when passed as arguments to an program via a shell
  934. func ShellQuoteArguments(args []string) string {
  935. var buf bytes.Buffer
  936. for i, arg := range args {
  937. if i != 0 {
  938. buf.WriteByte(' ')
  939. }
  940. quote(arg, &buf)
  941. }
  942. return buf.String()
  943. }
  944. func IsClosedError(err error) bool {
  945. /* This comparison is ugly, but unfortunately, net.go doesn't export errClosing.
  946. * See:
  947. * http://golang.org/src/pkg/net/net.go
  948. * https://code.google.com/p/go/issues/detail?id=4337
  949. * https://groups.google.com/forum/#!msg/golang-nuts/0_aaCvBmOcM/SptmDyX1XJMJ
  950. */
  951. return strings.HasSuffix(err.Error(), "use of closed network connection")
  952. }
  953. func PartParser(template, data string) (map[string]string, error) {
  954. // ip:public:private
  955. var (
  956. templateParts = strings.Split(template, ":")
  957. parts = strings.Split(data, ":")
  958. out = make(map[string]string, len(templateParts))
  959. )
  960. if len(parts) != len(templateParts) {
  961. return nil, fmt.Errorf("Invalid format to parse. %s should match template %s", data, template)
  962. }
  963. for i, t := range templateParts {
  964. value := ""
  965. if len(parts) > i {
  966. value = parts[i]
  967. }
  968. out[t] = value
  969. }
  970. return out, nil
  971. }
  972. var globalTestID string
  973. // TestDirectory creates a new temporary directory and returns its path.
  974. // The contents of directory at path `templateDir` is copied into the
  975. // new directory.
  976. func TestDirectory(templateDir string) (dir string, err error) {
  977. if globalTestID == "" {
  978. globalTestID = RandomString()[:4]
  979. }
  980. prefix := fmt.Sprintf("docker-test%s-%s-", globalTestID, GetCallerName(2))
  981. if prefix == "" {
  982. prefix = "docker-test-"
  983. }
  984. dir, err = ioutil.TempDir("", prefix)
  985. if err = os.Remove(dir); err != nil {
  986. return
  987. }
  988. if templateDir != "" {
  989. if err = CopyDirectory(templateDir, dir); err != nil {
  990. return
  991. }
  992. }
  993. return
  994. }
  995. // GetCallerName introspects the call stack and returns the name of the
  996. // function `depth` levels down in the stack.
  997. func GetCallerName(depth int) string {
  998. // Use the caller function name as a prefix.
  999. // This helps trace temp directories back to their test.
  1000. pc, _, _, _ := runtime.Caller(depth + 1)
  1001. callerLongName := runtime.FuncForPC(pc).Name()
  1002. parts := strings.Split(callerLongName, ".")
  1003. callerShortName := parts[len(parts)-1]
  1004. return callerShortName
  1005. }
  1006. func CopyFile(src, dst string) (int64, error) {
  1007. if src == dst {
  1008. return 0, nil
  1009. }
  1010. sf, err := os.Open(src)
  1011. if err != nil {
  1012. return 0, err
  1013. }
  1014. defer sf.Close()
  1015. if err := os.Remove(dst); err != nil && !os.IsNotExist(err) {
  1016. return 0, err
  1017. }
  1018. df, err := os.Create(dst)
  1019. if err != nil {
  1020. return 0, err
  1021. }
  1022. defer df.Close()
  1023. return io.Copy(df, sf)
  1024. }
  1025. type readCloserWrapper struct {
  1026. io.Reader
  1027. closer func() error
  1028. }
  1029. func (r *readCloserWrapper) Close() error {
  1030. return r.closer()
  1031. }
  1032. func NewReadCloserWrapper(r io.Reader, closer func() error) io.ReadCloser {
  1033. return &readCloserWrapper{
  1034. Reader: r,
  1035. closer: closer,
  1036. }
  1037. }