daemon.go 23 KB

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