daemon.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836
  1. package daemon
  2. import (
  3. "bytes"
  4. "crypto/tls"
  5. "encoding/json"
  6. "fmt"
  7. "io"
  8. "io/ioutil"
  9. "net"
  10. "net/http"
  11. "net/http/httputil"
  12. "net/url"
  13. "os"
  14. "os/exec"
  15. "path/filepath"
  16. "strconv"
  17. "strings"
  18. "time"
  19. "github.com/docker/docker/api/types/events"
  20. "github.com/docker/docker/opts"
  21. "github.com/docker/docker/pkg/integration"
  22. "github.com/docker/docker/pkg/integration/checker"
  23. icmd "github.com/docker/docker/pkg/integration/cmd"
  24. "github.com/docker/docker/pkg/ioutils"
  25. "github.com/docker/docker/pkg/stringid"
  26. "github.com/docker/go-connections/sockets"
  27. "github.com/docker/go-connections/tlsconfig"
  28. "github.com/go-check/check"
  29. "github.com/pkg/errors"
  30. )
  31. // SockRoot holds the path of the default docker integration daemon socket
  32. var SockRoot = filepath.Join(os.TempDir(), "docker-integration")
  33. // Daemon represents a Docker daemon for the testing framework.
  34. type Daemon struct {
  35. GlobalFlags []string
  36. Root string
  37. Folder string
  38. Wait chan error
  39. UseDefaultHost bool
  40. UseDefaultTLSHost bool
  41. id string
  42. logFile *os.File
  43. stdin io.WriteCloser
  44. stdout, stderr io.ReadCloser
  45. cmd *exec.Cmd
  46. storageDriver string
  47. userlandProxy bool
  48. execRoot string
  49. experimental bool
  50. dockerBinary string
  51. dockerdBinary string
  52. }
  53. // Config holds docker daemon integration configuration
  54. type Config struct {
  55. Experimental bool
  56. }
  57. type clientConfig struct {
  58. transport *http.Transport
  59. scheme string
  60. addr string
  61. }
  62. // New returns a Daemon instance to be used for testing.
  63. // This will create a directory such as d123456789 in the folder specified by $DEST.
  64. // The daemon will not automatically start.
  65. func New(c *check.C, dockerBinary string, dockerdBinary string, config Config) *Daemon {
  66. dest := os.Getenv("DEST")
  67. c.Assert(dest, check.Not(check.Equals), "", check.Commentf("Please set the DEST environment variable"))
  68. err := os.MkdirAll(SockRoot, 0700)
  69. c.Assert(err, checker.IsNil, check.Commentf("could not create daemon socket root"))
  70. id := fmt.Sprintf("d%s", stringid.TruncateID(stringid.GenerateRandomID()))
  71. dir := filepath.Join(dest, id)
  72. daemonFolder, err := filepath.Abs(dir)
  73. c.Assert(err, check.IsNil, check.Commentf("Could not make %q an absolute path", dir))
  74. daemonRoot := filepath.Join(daemonFolder, "root")
  75. c.Assert(os.MkdirAll(daemonRoot, 0755), check.IsNil, check.Commentf("Could not create daemon root %q", dir))
  76. userlandProxy := true
  77. if env := os.Getenv("DOCKER_USERLANDPROXY"); env != "" {
  78. if val, err := strconv.ParseBool(env); err != nil {
  79. userlandProxy = val
  80. }
  81. }
  82. return &Daemon{
  83. id: id,
  84. Folder: daemonFolder,
  85. Root: daemonRoot,
  86. storageDriver: os.Getenv("DOCKER_GRAPHDRIVER"),
  87. userlandProxy: userlandProxy,
  88. execRoot: filepath.Join(os.TempDir(), "docker-execroot", id),
  89. dockerBinary: dockerBinary,
  90. dockerdBinary: dockerdBinary,
  91. experimental: config.Experimental,
  92. }
  93. }
  94. // RootDir returns the root directory of the daemon.
  95. func (d *Daemon) RootDir() string {
  96. return d.Root
  97. }
  98. // ID returns the generated id of the daemon
  99. func (d *Daemon) ID() string {
  100. return d.id
  101. }
  102. // StorageDriver returns the configured storage driver of the daemon
  103. func (d *Daemon) StorageDriver() string {
  104. return d.storageDriver
  105. }
  106. // CleanupExecRoot cleans the daemon exec root (network namespaces, ...)
  107. func (d *Daemon) CleanupExecRoot(c *check.C) {
  108. cleanupExecRoot(c, d.execRoot)
  109. }
  110. func (d *Daemon) getClientConfig() (*clientConfig, error) {
  111. var (
  112. transport *http.Transport
  113. scheme string
  114. addr string
  115. proto string
  116. )
  117. if d.UseDefaultTLSHost {
  118. option := &tlsconfig.Options{
  119. CAFile: "fixtures/https/ca.pem",
  120. CertFile: "fixtures/https/client-cert.pem",
  121. KeyFile: "fixtures/https/client-key.pem",
  122. }
  123. tlsConfig, err := tlsconfig.Client(*option)
  124. if err != nil {
  125. return nil, err
  126. }
  127. transport = &http.Transport{
  128. TLSClientConfig: tlsConfig,
  129. }
  130. addr = fmt.Sprintf("%s:%d", opts.DefaultHTTPHost, opts.DefaultTLSHTTPPort)
  131. scheme = "https"
  132. proto = "tcp"
  133. } else if d.UseDefaultHost {
  134. addr = opts.DefaultUnixSocket
  135. proto = "unix"
  136. scheme = "http"
  137. transport = &http.Transport{}
  138. } else {
  139. addr = d.sockPath()
  140. proto = "unix"
  141. scheme = "http"
  142. transport = &http.Transport{}
  143. }
  144. if err := sockets.ConfigureTransport(transport, proto, addr); err != nil {
  145. return nil, err
  146. }
  147. return &clientConfig{
  148. transport: transport,
  149. scheme: scheme,
  150. addr: addr,
  151. }, nil
  152. }
  153. // Start will start the daemon and return once it is ready to receive requests.
  154. // You can specify additional daemon flags.
  155. func (d *Daemon) Start(args ...string) error {
  156. logFile, err := os.OpenFile(filepath.Join(d.Folder, "docker.log"), os.O_RDWR|os.O_CREATE|os.O_APPEND, 0600)
  157. if err != nil {
  158. return errors.Wrapf(err, "[%s] Could not create %s/docker.log", d.id, d.Folder)
  159. }
  160. return d.StartWithLogFile(logFile, args...)
  161. }
  162. // StartWithLogFile will start the daemon and attach its streams to a given file.
  163. func (d *Daemon) StartWithLogFile(out *os.File, providedArgs ...string) error {
  164. dockerdBinary, err := exec.LookPath(d.dockerdBinary)
  165. if err != nil {
  166. return errors.Wrapf(err, "[%s] could not find docker binary in $PATH", d.id)
  167. }
  168. args := append(d.GlobalFlags,
  169. "--containerd", "/var/run/docker/libcontainerd/docker-containerd.sock",
  170. "--graph", d.Root,
  171. "--exec-root", d.execRoot,
  172. "--pidfile", fmt.Sprintf("%s/docker.pid", d.Folder),
  173. fmt.Sprintf("--userland-proxy=%t", d.userlandProxy),
  174. )
  175. if d.experimental {
  176. args = append(args, "--experimental", "--init")
  177. }
  178. if !(d.UseDefaultHost || d.UseDefaultTLSHost) {
  179. args = append(args, []string{"--host", d.Sock()}...)
  180. }
  181. if root := os.Getenv("DOCKER_REMAP_ROOT"); root != "" {
  182. args = append(args, []string{"--userns-remap", root}...)
  183. }
  184. // If we don't explicitly set the log-level or debug flag(-D) then
  185. // turn on debug mode
  186. foundLog := false
  187. foundSd := false
  188. for _, a := range providedArgs {
  189. if strings.Contains(a, "--log-level") || strings.Contains(a, "-D") || strings.Contains(a, "--debug") {
  190. foundLog = true
  191. }
  192. if strings.Contains(a, "--storage-driver") {
  193. foundSd = true
  194. }
  195. }
  196. if !foundLog {
  197. args = append(args, "--debug")
  198. }
  199. if d.storageDriver != "" && !foundSd {
  200. args = append(args, "--storage-driver", d.storageDriver)
  201. }
  202. args = append(args, providedArgs...)
  203. d.cmd = exec.Command(dockerdBinary, args...)
  204. d.cmd.Env = append(os.Environ(), "DOCKER_SERVICE_PREFER_OFFLINE_IMAGE=1")
  205. d.cmd.Stdout = out
  206. d.cmd.Stderr = out
  207. d.logFile = out
  208. if err := d.cmd.Start(); err != nil {
  209. return errors.Errorf("[%s] could not start daemon container: %v", d.id, err)
  210. }
  211. wait := make(chan error)
  212. go func() {
  213. wait <- d.cmd.Wait()
  214. fmt.Printf("[%s] exiting daemon\n", d.id)
  215. close(wait)
  216. }()
  217. d.Wait = wait
  218. tick := time.Tick(500 * time.Millisecond)
  219. // make sure daemon is ready to receive requests
  220. startTime := time.Now().Unix()
  221. for {
  222. fmt.Printf("[%s] waiting for daemon to start\n", d.id)
  223. if time.Now().Unix()-startTime > 5 {
  224. // After 5 seconds, give up
  225. return errors.Errorf("[%s] Daemon exited and never started", d.id)
  226. }
  227. select {
  228. case <-time.After(2 * time.Second):
  229. return errors.Errorf("[%s] timeout: daemon does not respond", d.id)
  230. case <-tick:
  231. clientConfig, err := d.getClientConfig()
  232. if err != nil {
  233. return err
  234. }
  235. client := &http.Client{
  236. Transport: clientConfig.transport,
  237. }
  238. req, err := http.NewRequest("GET", "/_ping", nil)
  239. if err != nil {
  240. return errors.Wrapf(err, "[%s] could not create new request", d.id)
  241. }
  242. req.URL.Host = clientConfig.addr
  243. req.URL.Scheme = clientConfig.scheme
  244. resp, err := client.Do(req)
  245. if err != nil {
  246. continue
  247. }
  248. if resp.StatusCode != http.StatusOK {
  249. fmt.Printf("[%s] received status != 200 OK: %s\n", d.id, resp.Status)
  250. }
  251. fmt.Printf("[%s] daemon started\n", d.id)
  252. d.Root, err = d.queryRootDir()
  253. if err != nil {
  254. return errors.Errorf("[%s] error querying daemon for root directory: %v", d.id, err)
  255. }
  256. return nil
  257. case <-d.Wait:
  258. return errors.Errorf("[%s] Daemon exited during startup", d.id)
  259. }
  260. }
  261. }
  262. // StartWithBusybox will first start the daemon with Daemon.Start()
  263. // then save the busybox image from the main daemon and load it into this Daemon instance.
  264. func (d *Daemon) StartWithBusybox(arg ...string) error {
  265. if err := d.Start(arg...); err != nil {
  266. return err
  267. }
  268. return d.LoadBusybox()
  269. }
  270. // Kill will send a SIGKILL to the daemon
  271. func (d *Daemon) Kill() error {
  272. if d.cmd == nil || d.Wait == nil {
  273. return errors.New("daemon not started")
  274. }
  275. defer func() {
  276. d.logFile.Close()
  277. d.cmd = nil
  278. }()
  279. if err := d.cmd.Process.Kill(); err != nil {
  280. return err
  281. }
  282. if err := os.Remove(fmt.Sprintf("%s/docker.pid", d.Folder)); err != nil {
  283. return err
  284. }
  285. return nil
  286. }
  287. // Pid returns the pid of the daemon
  288. func (d *Daemon) Pid() int {
  289. return d.cmd.Process.Pid
  290. }
  291. // Interrupt stops the daemon by sending it an Interrupt signal
  292. func (d *Daemon) Interrupt() error {
  293. return d.Signal(os.Interrupt)
  294. }
  295. // Signal sends the specified signal to the daemon if running
  296. func (d *Daemon) Signal(signal os.Signal) error {
  297. if d.cmd == nil || d.Wait == nil {
  298. return errors.New("daemon not started")
  299. }
  300. return d.cmd.Process.Signal(signal)
  301. }
  302. // DumpStackAndQuit sends SIGQUIT to the daemon, which triggers it to dump its
  303. // stack to its log file and exit
  304. // This is used primarily for gathering debug information on test timeout
  305. func (d *Daemon) DumpStackAndQuit() {
  306. if d.cmd == nil || d.cmd.Process == nil {
  307. return
  308. }
  309. SignalDaemonDump(d.cmd.Process.Pid)
  310. }
  311. // Stop will send a SIGINT every second and wait for the daemon to stop.
  312. // If it timeouts, a SIGKILL is sent.
  313. // Stop will not delete the daemon directory. If a purged daemon is needed,
  314. // instantiate a new one with NewDaemon.
  315. func (d *Daemon) Stop() error {
  316. if d.cmd == nil || d.Wait == nil {
  317. return errors.New("daemon not started")
  318. }
  319. defer func() {
  320. d.logFile.Close()
  321. d.cmd = nil
  322. }()
  323. i := 1
  324. tick := time.Tick(time.Second)
  325. if err := d.cmd.Process.Signal(os.Interrupt); err != nil {
  326. return errors.Errorf("could not send signal: %v", err)
  327. }
  328. out1:
  329. for {
  330. select {
  331. case err := <-d.Wait:
  332. return err
  333. case <-time.After(20 * time.Second):
  334. // time for stopping jobs and run onShutdown hooks
  335. fmt.Printf("timeout: %v\n", d.id)
  336. break out1
  337. }
  338. }
  339. out2:
  340. for {
  341. select {
  342. case err := <-d.Wait:
  343. return err
  344. case <-tick:
  345. i++
  346. if i > 5 {
  347. fmt.Printf("tried to interrupt daemon for %d times, now try to kill it\n", i)
  348. break out2
  349. }
  350. fmt.Printf("Attempt #%d: daemon is still running with pid %d\n", i, d.cmd.Process.Pid)
  351. if err := d.cmd.Process.Signal(os.Interrupt); err != nil {
  352. return errors.Errorf("could not send signal: %v", err)
  353. }
  354. }
  355. }
  356. if err := d.cmd.Process.Kill(); err != nil {
  357. fmt.Printf("Could not kill daemon: %v\n", err)
  358. return err
  359. }
  360. if err := os.Remove(fmt.Sprintf("%s/docker.pid", d.Folder)); err != nil {
  361. return err
  362. }
  363. return nil
  364. }
  365. // Restart will restart the daemon by first stopping it and then starting it.
  366. func (d *Daemon) Restart(arg ...string) error {
  367. d.Stop()
  368. // in the case of tests running a user namespace-enabled daemon, we have resolved
  369. // d.Root to be the actual final path of the graph dir after the "uid.gid" of
  370. // remapped root is added--we need to subtract it from the path before calling
  371. // start or else we will continue making subdirectories rather than truly restarting
  372. // with the same location/root:
  373. if root := os.Getenv("DOCKER_REMAP_ROOT"); root != "" {
  374. d.Root = filepath.Dir(d.Root)
  375. }
  376. return d.Start(arg...)
  377. }
  378. // LoadBusybox will load the stored busybox into a newly started daemon
  379. func (d *Daemon) LoadBusybox() error {
  380. bb := filepath.Join(d.Folder, "busybox.tar")
  381. if _, err := os.Stat(bb); err != nil {
  382. if !os.IsNotExist(err) {
  383. return errors.Errorf("unexpected error on busybox.tar stat: %v", err)
  384. }
  385. // saving busybox image from main daemon
  386. if out, err := exec.Command(d.dockerBinary, "save", "--output", bb, "busybox:latest").CombinedOutput(); err != nil {
  387. imagesOut, _ := exec.Command(d.dockerBinary, "images", "--format", "{{ .Repository }}:{{ .Tag }}").CombinedOutput()
  388. return errors.Errorf("could not save busybox image: %s\n%s", string(out), strings.TrimSpace(string(imagesOut)))
  389. }
  390. }
  391. // loading busybox image to this daemon
  392. if out, err := d.Cmd("load", "--input", bb); err != nil {
  393. return errors.Errorf("could not load busybox image: %s", out)
  394. }
  395. if err := os.Remove(bb); err != nil {
  396. return err
  397. }
  398. return nil
  399. }
  400. func (d *Daemon) queryRootDir() (string, error) {
  401. // update daemon root by asking /info endpoint (to support user
  402. // namespaced daemon with root remapped uid.gid directory)
  403. clientConfig, err := d.getClientConfig()
  404. if err != nil {
  405. return "", err
  406. }
  407. client := &http.Client{
  408. Transport: clientConfig.transport,
  409. }
  410. req, err := http.NewRequest("GET", "/info", nil)
  411. if err != nil {
  412. return "", err
  413. }
  414. req.Header.Set("Content-Type", "application/json")
  415. req.URL.Host = clientConfig.addr
  416. req.URL.Scheme = clientConfig.scheme
  417. resp, err := client.Do(req)
  418. if err != nil {
  419. return "", err
  420. }
  421. body := ioutils.NewReadCloserWrapper(resp.Body, func() error {
  422. return resp.Body.Close()
  423. })
  424. type Info struct {
  425. DockerRootDir string
  426. }
  427. var b []byte
  428. var i Info
  429. b, err = integration.ReadBody(body)
  430. if err == nil && resp.StatusCode == http.StatusOK {
  431. // read the docker root dir
  432. if err = json.Unmarshal(b, &i); err == nil {
  433. return i.DockerRootDir, nil
  434. }
  435. }
  436. return "", err
  437. }
  438. // Sock returns the socket path of the daemon
  439. func (d *Daemon) Sock() string {
  440. return fmt.Sprintf("unix://" + d.sockPath())
  441. }
  442. func (d *Daemon) sockPath() string {
  443. return filepath.Join(SockRoot, d.id+".sock")
  444. }
  445. // WaitRun waits for a container to be running for 10s
  446. func (d *Daemon) WaitRun(contID string) error {
  447. args := []string{"--host", d.Sock()}
  448. return WaitInspectWithArgs(d.dockerBinary, contID, "{{.State.Running}}", "true", 10*time.Second, args...)
  449. }
  450. // GetBaseDeviceSize returns the base device size of the daemon
  451. func (d *Daemon) GetBaseDeviceSize(c *check.C) int64 {
  452. infoCmdOutput, _, err := integration.RunCommandPipelineWithOutput(
  453. exec.Command(d.dockerBinary, "-H", d.Sock(), "info"),
  454. exec.Command("grep", "Base Device Size"),
  455. )
  456. c.Assert(err, checker.IsNil)
  457. basesizeSlice := strings.Split(infoCmdOutput, ":")
  458. basesize := strings.Trim(basesizeSlice[1], " ")
  459. basesize = strings.Trim(basesize, "\n")[:len(basesize)-3]
  460. basesizeFloat, err := strconv.ParseFloat(strings.Trim(basesize, " "), 64)
  461. c.Assert(err, checker.IsNil)
  462. basesizeBytes := int64(basesizeFloat) * (1024 * 1024 * 1024)
  463. return basesizeBytes
  464. }
  465. // Cmd will execute a docker CLI command against this Daemon.
  466. // Example: d.Cmd("version") will run docker -H unix://path/to/unix.sock version
  467. func (d *Daemon) Cmd(args ...string) (string, error) {
  468. b, err := d.Command(args...).CombinedOutput()
  469. return string(b), err
  470. }
  471. // Command will create a docker CLI command against this Daeomn.
  472. func (d *Daemon) Command(args ...string) *exec.Cmd {
  473. return exec.Command(d.dockerBinary, d.PrependHostArg(args)...)
  474. }
  475. // PrependHostArg prepend the specified arguments by the daemon host flags
  476. func (d *Daemon) PrependHostArg(args []string) []string {
  477. for _, arg := range args {
  478. if arg == "--host" || arg == "-H" {
  479. return args
  480. }
  481. }
  482. return append([]string{"--host", d.Sock()}, args...)
  483. }
  484. // SockRequest executes a socket request on a daemon and returns statuscode and output.
  485. func (d *Daemon) SockRequest(method, endpoint string, data interface{}) (int, []byte, error) {
  486. jsonData := bytes.NewBuffer(nil)
  487. if err := json.NewEncoder(jsonData).Encode(data); err != nil {
  488. return -1, nil, err
  489. }
  490. res, body, err := d.SockRequestRaw(method, endpoint, jsonData, "application/json")
  491. if err != nil {
  492. return -1, nil, err
  493. }
  494. b, err := integration.ReadBody(body)
  495. return res.StatusCode, b, err
  496. }
  497. // SockRequestRaw executes a socket request on a daemon and returns an http
  498. // response and a reader for the output data.
  499. func (d *Daemon) SockRequestRaw(method, endpoint string, data io.Reader, ct string) (*http.Response, io.ReadCloser, error) {
  500. return SockRequestRawToDaemon(method, endpoint, data, ct, d.Sock())
  501. }
  502. // LogFileName returns the path the the daemon's log file
  503. func (d *Daemon) LogFileName() string {
  504. return d.logFile.Name()
  505. }
  506. // GetIDByName returns the ID of an object (container, volume, …) given its name
  507. func (d *Daemon) GetIDByName(name string) (string, error) {
  508. return d.inspectFieldWithError(name, "Id")
  509. }
  510. // ActiveContainers returns the list of ids of the currently running containers
  511. func (d *Daemon) ActiveContainers() (ids []string) {
  512. // FIXME(vdemeester) shouldn't ignore the error
  513. out, _ := d.Cmd("ps", "-q")
  514. for _, id := range strings.Split(out, "\n") {
  515. if id = strings.TrimSpace(id); id != "" {
  516. ids = append(ids, id)
  517. }
  518. }
  519. return
  520. }
  521. // ReadLogFile returns the content of the daemon log file
  522. func (d *Daemon) ReadLogFile() ([]byte, error) {
  523. return ioutil.ReadFile(d.logFile.Name())
  524. }
  525. func (d *Daemon) inspectFilter(name, filter string) (string, error) {
  526. format := fmt.Sprintf("{{%s}}", filter)
  527. out, err := d.Cmd("inspect", "-f", format, name)
  528. if err != nil {
  529. return "", errors.Errorf("failed to inspect %s: %s", name, out)
  530. }
  531. return strings.TrimSpace(out), nil
  532. }
  533. func (d *Daemon) inspectFieldWithError(name, field string) (string, error) {
  534. return d.inspectFilter(name, fmt.Sprintf(".%s", field))
  535. }
  536. // FindContainerIP returns the ip of the specified container
  537. func (d *Daemon) FindContainerIP(id string) (string, error) {
  538. out, err := d.Cmd("inspect", "--format='{{ .NetworkSettings.Networks.bridge.IPAddress }}'", id)
  539. if err != nil {
  540. return "", err
  541. }
  542. return strings.Trim(out, " \r\n'"), nil
  543. }
  544. // BuildImageWithOut builds an image with the specified dockerfile and options and returns the output
  545. func (d *Daemon) BuildImageWithOut(name, dockerfile string, useCache bool, buildFlags ...string) (string, int, error) {
  546. buildCmd := BuildImageCmdWithHost(d.dockerBinary, name, dockerfile, d.Sock(), useCache, buildFlags...)
  547. result := icmd.RunCmd(icmd.Cmd{
  548. Command: buildCmd.Args,
  549. Env: buildCmd.Env,
  550. Dir: buildCmd.Dir,
  551. Stdin: buildCmd.Stdin,
  552. Stdout: buildCmd.Stdout,
  553. })
  554. return result.Combined(), result.ExitCode, result.Error
  555. }
  556. // CheckActiveContainerCount returns the number of active containers
  557. // FIXME(vdemeester) should re-use ActivateContainers in some way
  558. func (d *Daemon) CheckActiveContainerCount(c *check.C) (interface{}, check.CommentInterface) {
  559. out, err := d.Cmd("ps", "-q")
  560. c.Assert(err, checker.IsNil)
  561. if len(strings.TrimSpace(out)) == 0 {
  562. return 0, nil
  563. }
  564. return len(strings.Split(strings.TrimSpace(out), "\n")), check.Commentf("output: %q", string(out))
  565. }
  566. // ReloadConfig asks the daemon to reload its configuration
  567. func (d *Daemon) ReloadConfig() error {
  568. if d.cmd == nil || d.cmd.Process == nil {
  569. return errors.New("daemon is not running")
  570. }
  571. errCh := make(chan error)
  572. started := make(chan struct{})
  573. go func() {
  574. _, body, err := SockRequestRawToDaemon("GET", "/events", nil, "", d.Sock())
  575. close(started)
  576. if err != nil {
  577. errCh <- err
  578. }
  579. defer body.Close()
  580. dec := json.NewDecoder(body)
  581. for {
  582. var e events.Message
  583. if err := dec.Decode(&e); err != nil {
  584. errCh <- err
  585. return
  586. }
  587. if e.Type != events.DaemonEventType {
  588. continue
  589. }
  590. if e.Action != "reload" {
  591. continue
  592. }
  593. close(errCh) // notify that we are done
  594. return
  595. }
  596. }()
  597. <-started
  598. if err := signalDaemonReload(d.cmd.Process.Pid); err != nil {
  599. return errors.Errorf("error signaling daemon reload: %v", err)
  600. }
  601. select {
  602. case err := <-errCh:
  603. if err != nil {
  604. return errors.Errorf("error waiting for daemon reload event: %v", err)
  605. }
  606. case <-time.After(30 * time.Second):
  607. return errors.New("timeout waiting for daemon reload event")
  608. }
  609. return nil
  610. }
  611. // WaitInspectWithArgs waits for the specified expression to be equals to the specified expected string in the given time.
  612. // FIXME(vdemeester) Attach this to the Daemon struct
  613. func WaitInspectWithArgs(dockerBinary, name, expr, expected string, timeout time.Duration, arg ...string) error {
  614. after := time.After(timeout)
  615. args := append(arg, "inspect", "-f", expr, name)
  616. for {
  617. result := icmd.RunCommand(dockerBinary, args...)
  618. if result.Error != nil {
  619. if !strings.Contains(result.Stderr(), "No such") {
  620. return errors.Errorf("error executing docker inspect: %v\n%s",
  621. result.Stderr(), result.Stdout())
  622. }
  623. select {
  624. case <-after:
  625. return result.Error
  626. default:
  627. time.Sleep(10 * time.Millisecond)
  628. continue
  629. }
  630. }
  631. out := strings.TrimSpace(result.Stdout())
  632. if out == expected {
  633. break
  634. }
  635. select {
  636. case <-after:
  637. return errors.Errorf("condition \"%q == %q\" not true in time (%v)", out, expected, timeout)
  638. default:
  639. }
  640. time.Sleep(100 * time.Millisecond)
  641. }
  642. return nil
  643. }
  644. // SockRequestRawToDaemon creates an http request against the specified daemon socket
  645. // FIXME(vdemeester) attach this to daemon ?
  646. func SockRequestRawToDaemon(method, endpoint string, data io.Reader, ct, daemon string) (*http.Response, io.ReadCloser, error) {
  647. req, client, err := newRequestClient(method, endpoint, data, ct, daemon)
  648. if err != nil {
  649. return nil, nil, err
  650. }
  651. resp, err := client.Do(req)
  652. if err != nil {
  653. client.Close()
  654. return nil, nil, err
  655. }
  656. body := ioutils.NewReadCloserWrapper(resp.Body, func() error {
  657. defer resp.Body.Close()
  658. return client.Close()
  659. })
  660. return resp, body, nil
  661. }
  662. func getTLSConfig() (*tls.Config, error) {
  663. dockerCertPath := os.Getenv("DOCKER_CERT_PATH")
  664. if dockerCertPath == "" {
  665. return nil, errors.New("DOCKER_TLS_VERIFY specified, but no DOCKER_CERT_PATH environment variable")
  666. }
  667. option := &tlsconfig.Options{
  668. CAFile: filepath.Join(dockerCertPath, "ca.pem"),
  669. CertFile: filepath.Join(dockerCertPath, "cert.pem"),
  670. KeyFile: filepath.Join(dockerCertPath, "key.pem"),
  671. }
  672. tlsConfig, err := tlsconfig.Client(*option)
  673. if err != nil {
  674. return nil, err
  675. }
  676. return tlsConfig, nil
  677. }
  678. // SockConn opens a connection on the specified socket
  679. func SockConn(timeout time.Duration, daemon string) (net.Conn, error) {
  680. daemonURL, err := url.Parse(daemon)
  681. if err != nil {
  682. return nil, errors.Wrapf(err, "could not parse url %q", daemon)
  683. }
  684. var c net.Conn
  685. switch daemonURL.Scheme {
  686. case "npipe":
  687. return npipeDial(daemonURL.Path, timeout)
  688. case "unix":
  689. return net.DialTimeout(daemonURL.Scheme, daemonURL.Path, timeout)
  690. case "tcp":
  691. if os.Getenv("DOCKER_TLS_VERIFY") != "" {
  692. // Setup the socket TLS configuration.
  693. tlsConfig, err := getTLSConfig()
  694. if err != nil {
  695. return nil, err
  696. }
  697. dialer := &net.Dialer{Timeout: timeout}
  698. return tls.DialWithDialer(dialer, daemonURL.Scheme, daemonURL.Host, tlsConfig)
  699. }
  700. return net.DialTimeout(daemonURL.Scheme, daemonURL.Host, timeout)
  701. default:
  702. return c, errors.Errorf("unknown scheme %v (%s)", daemonURL.Scheme, daemon)
  703. }
  704. }
  705. func newRequestClient(method, endpoint string, data io.Reader, ct, daemon string) (*http.Request, *httputil.ClientConn, error) {
  706. c, err := SockConn(time.Duration(10*time.Second), daemon)
  707. if err != nil {
  708. return nil, nil, errors.Errorf("could not dial docker daemon: %v", err)
  709. }
  710. client := httputil.NewClientConn(c, nil)
  711. req, err := http.NewRequest(method, endpoint, data)
  712. if err != nil {
  713. client.Close()
  714. return nil, nil, errors.Errorf("could not create new request: %v", err)
  715. }
  716. if ct != "" {
  717. req.Header.Set("Content-Type", ct)
  718. }
  719. return req, client, nil
  720. }
  721. // BuildImageCmdWithHost create a build command with the specified arguments.
  722. // FIXME(vdemeester) move this away
  723. func BuildImageCmdWithHost(dockerBinary, name, dockerfile, host string, useCache bool, buildFlags ...string) *exec.Cmd {
  724. args := []string{}
  725. if host != "" {
  726. args = append(args, "--host", host)
  727. }
  728. args = append(args, "build", "-t", name)
  729. if !useCache {
  730. args = append(args, "--no-cache")
  731. }
  732. args = append(args, buildFlags...)
  733. args = append(args, "-")
  734. buildCmd := exec.Command(dockerBinary, args...)
  735. buildCmd.Stdin = strings.NewReader(dockerfile)
  736. return buildCmd
  737. }