daemon.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  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/libcontainerd/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. if err := os.Remove(fmt.Sprintf("%s/docker.pid", d.Folder)); err != nil {
  311. return err
  312. }
  313. return nil
  314. }
  315. // Pid returns the pid of the daemon
  316. func (d *Daemon) Pid() int {
  317. return d.cmd.Process.Pid
  318. }
  319. // Interrupt stops the daemon by sending it an Interrupt signal
  320. func (d *Daemon) Interrupt() error {
  321. return d.Signal(os.Interrupt)
  322. }
  323. // Signal sends the specified signal to the daemon if running
  324. func (d *Daemon) Signal(signal os.Signal) error {
  325. if d.cmd == nil || d.Wait == nil {
  326. return errDaemonNotStarted
  327. }
  328. return d.cmd.Process.Signal(signal)
  329. }
  330. // DumpStackAndQuit sends SIGQUIT to the daemon, which triggers it to dump its
  331. // stack to its log file and exit
  332. // This is used primarily for gathering debug information on test timeout
  333. func (d *Daemon) DumpStackAndQuit() {
  334. if d.cmd == nil || d.cmd.Process == nil {
  335. return
  336. }
  337. SignalDaemonDump(d.cmd.Process.Pid)
  338. }
  339. // Stop will send a SIGINT every second and wait for the daemon to stop.
  340. // If it times out, a SIGKILL is sent.
  341. // Stop will not delete the daemon directory. If a purged daemon is needed,
  342. // instantiate a new one with NewDaemon.
  343. // If an error occurs while starting the daemon, the test will fail.
  344. func (d *Daemon) Stop(t testingT) {
  345. err := d.StopWithError()
  346. if err != nil {
  347. if err != errDaemonNotStarted {
  348. t.Fatalf("Error while stopping the daemon %s : %v", d.id, err)
  349. } else {
  350. t.Logf("Daemon %s is not started", d.id)
  351. }
  352. }
  353. }
  354. // StopWithError will send a SIGINT every second and wait for the daemon to stop.
  355. // If it timeouts, a SIGKILL is sent.
  356. // Stop will not delete the daemon directory. If a purged daemon is needed,
  357. // instantiate a new one with NewDaemon.
  358. func (d *Daemon) StopWithError() error {
  359. if d.cmd == nil || d.Wait == nil {
  360. return errDaemonNotStarted
  361. }
  362. defer func() {
  363. d.logFile.Close()
  364. d.cmd = nil
  365. }()
  366. i := 1
  367. tick := time.Tick(time.Second)
  368. if err := d.cmd.Process.Signal(os.Interrupt); err != nil {
  369. if strings.Contains(err.Error(), "os: process already finished") {
  370. return errDaemonNotStarted
  371. }
  372. return errors.Errorf("could not send signal: %v", err)
  373. }
  374. out1:
  375. for {
  376. select {
  377. case err := <-d.Wait:
  378. return err
  379. case <-time.After(20 * time.Second):
  380. // time for stopping jobs and run onShutdown hooks
  381. d.log.Logf("[%s] daemon started", d.id)
  382. break out1
  383. }
  384. }
  385. out2:
  386. for {
  387. select {
  388. case err := <-d.Wait:
  389. return err
  390. case <-tick:
  391. i++
  392. if i > 5 {
  393. d.log.Logf("tried to interrupt daemon for %d times, now try to kill it", i)
  394. break out2
  395. }
  396. d.log.Logf("Attempt #%d: daemon is still running with pid %d", i, d.cmd.Process.Pid)
  397. if err := d.cmd.Process.Signal(os.Interrupt); err != nil {
  398. return errors.Errorf("could not send signal: %v", err)
  399. }
  400. }
  401. }
  402. if err := d.cmd.Process.Kill(); err != nil {
  403. d.log.Logf("Could not kill daemon: %v", err)
  404. return err
  405. }
  406. if err := os.Remove(fmt.Sprintf("%s/docker.pid", d.Folder)); err != nil {
  407. return err
  408. }
  409. return nil
  410. }
  411. // Restart will restart the daemon by first stopping it and the starting it.
  412. // If an error occurs while starting the daemon, the test will fail.
  413. func (d *Daemon) Restart(t testingT, args ...string) {
  414. d.Stop(t)
  415. d.handleUserns()
  416. d.Start(t, args...)
  417. }
  418. // RestartWithError will restart the daemon by first stopping it and then starting it.
  419. func (d *Daemon) RestartWithError(arg ...string) error {
  420. if err := d.StopWithError(); err != nil {
  421. return err
  422. }
  423. d.handleUserns()
  424. return d.StartWithError(arg...)
  425. }
  426. func (d *Daemon) handleUserns() {
  427. // in the case of tests running a user namespace-enabled daemon, we have resolved
  428. // d.Root to be the actual final path of the graph dir after the "uid.gid" of
  429. // remapped root is added--we need to subtract it from the path before calling
  430. // start or else we will continue making subdirectories rather than truly restarting
  431. // with the same location/root:
  432. if root := os.Getenv("DOCKER_REMAP_ROOT"); root != "" {
  433. d.Root = filepath.Dir(d.Root)
  434. }
  435. }
  436. // LoadBusybox image into the daemon
  437. func (d *Daemon) LoadBusybox(t testingT) {
  438. clientHost, err := client.NewEnvClient()
  439. require.NoError(t, err, "failed to create client")
  440. defer clientHost.Close()
  441. ctx := context.Background()
  442. reader, err := clientHost.ImageSave(ctx, []string{"busybox:latest"})
  443. require.NoError(t, err, "failed to download busybox")
  444. defer reader.Close()
  445. client, err := d.NewClient()
  446. require.NoError(t, err, "failed to create client")
  447. defer client.Close()
  448. resp, err := client.ImageLoad(ctx, reader, true)
  449. require.NoError(t, err, "failed to load busybox")
  450. defer resp.Body.Close()
  451. }
  452. func (d *Daemon) queryRootDir() (string, error) {
  453. // update daemon root by asking /info endpoint (to support user
  454. // namespaced daemon with root remapped uid.gid directory)
  455. clientConfig, err := d.getClientConfig()
  456. if err != nil {
  457. return "", err
  458. }
  459. client := &http.Client{
  460. Transport: clientConfig.transport,
  461. }
  462. req, err := http.NewRequest("GET", "/info", nil)
  463. if err != nil {
  464. return "", err
  465. }
  466. req.Header.Set("Content-Type", "application/json")
  467. req.URL.Host = clientConfig.addr
  468. req.URL.Scheme = clientConfig.scheme
  469. resp, err := client.Do(req)
  470. if err != nil {
  471. return "", err
  472. }
  473. body := ioutils.NewReadCloserWrapper(resp.Body, func() error {
  474. return resp.Body.Close()
  475. })
  476. type Info struct {
  477. DockerRootDir string
  478. }
  479. var b []byte
  480. var i Info
  481. b, err = request.ReadBody(body)
  482. if err == nil && resp.StatusCode == http.StatusOK {
  483. // read the docker root dir
  484. if err = json.Unmarshal(b, &i); err == nil {
  485. return i.DockerRootDir, nil
  486. }
  487. }
  488. return "", err
  489. }
  490. // Sock returns the socket path of the daemon
  491. func (d *Daemon) Sock() string {
  492. return fmt.Sprintf("unix://" + d.sockPath())
  493. }
  494. func (d *Daemon) sockPath() string {
  495. return filepath.Join(SockRoot, d.id+".sock")
  496. }
  497. // WaitRun waits for a container to be running for 10s
  498. func (d *Daemon) WaitRun(contID string) error {
  499. args := []string{"--host", d.Sock()}
  500. return WaitInspectWithArgs(d.dockerBinary, contID, "{{.State.Running}}", "true", 10*time.Second, args...)
  501. }
  502. // Info returns the info struct for this daemon
  503. func (d *Daemon) Info(t require.TestingT) types.Info {
  504. apiclient, err := request.NewClientForHost(d.Sock())
  505. require.NoError(t, err)
  506. info, err := apiclient.Info(context.Background())
  507. require.NoError(t, err)
  508. return info
  509. }
  510. // Cmd executes a docker CLI command against this daemon.
  511. // Example: d.Cmd("version") will run docker -H unix://path/to/unix.sock version
  512. func (d *Daemon) Cmd(args ...string) (string, error) {
  513. result := icmd.RunCmd(d.Command(args...))
  514. return result.Combined(), result.Error
  515. }
  516. // Command creates a docker CLI command against this daemon, to be executed later.
  517. // Example: d.Command("version") creates a command to run "docker -H unix://path/to/unix.sock version"
  518. func (d *Daemon) Command(args ...string) icmd.Cmd {
  519. return icmd.Command(d.dockerBinary, d.PrependHostArg(args)...)
  520. }
  521. // PrependHostArg prepend the specified arguments by the daemon host flags
  522. func (d *Daemon) PrependHostArg(args []string) []string {
  523. for _, arg := range args {
  524. if arg == "--host" || arg == "-H" {
  525. return args
  526. }
  527. }
  528. return append([]string{"--host", d.Sock()}, args...)
  529. }
  530. // SockRequest executes a socket request on a daemon and returns statuscode and output.
  531. func (d *Daemon) SockRequest(method, endpoint string, data interface{}) (int, []byte, error) {
  532. jsonData := bytes.NewBuffer(nil)
  533. if err := json.NewEncoder(jsonData).Encode(data); err != nil {
  534. return -1, nil, err
  535. }
  536. res, body, err := d.SockRequestRaw(method, endpoint, jsonData, "application/json")
  537. if err != nil {
  538. return -1, nil, err
  539. }
  540. b, err := request.ReadBody(body)
  541. return res.StatusCode, b, err
  542. }
  543. // SockRequestRaw executes a socket request on a daemon and returns an http
  544. // response and a reader for the output data.
  545. // Deprecated: use request package instead
  546. func (d *Daemon) SockRequestRaw(method, endpoint string, data io.Reader, ct string) (*http.Response, io.ReadCloser, error) {
  547. return request.SockRequestRaw(method, endpoint, data, ct, d.Sock())
  548. }
  549. // LogFileName returns the path the daemon's log file
  550. func (d *Daemon) LogFileName() string {
  551. return d.logFile.Name()
  552. }
  553. // GetIDByName returns the ID of an object (container, volume, …) given its name
  554. func (d *Daemon) GetIDByName(name string) (string, error) {
  555. return d.inspectFieldWithError(name, "Id")
  556. }
  557. // ActiveContainers returns the list of ids of the currently running containers
  558. func (d *Daemon) ActiveContainers() (ids []string) {
  559. // FIXME(vdemeester) shouldn't ignore the error
  560. out, _ := d.Cmd("ps", "-q")
  561. for _, id := range strings.Split(out, "\n") {
  562. if id = strings.TrimSpace(id); id != "" {
  563. ids = append(ids, id)
  564. }
  565. }
  566. return
  567. }
  568. // ReadLogFile returns the content of the daemon log file
  569. func (d *Daemon) ReadLogFile() ([]byte, error) {
  570. return ioutil.ReadFile(d.logFile.Name())
  571. }
  572. // InspectField returns the field filter by 'filter'
  573. func (d *Daemon) InspectField(name, filter string) (string, error) {
  574. return d.inspectFilter(name, filter)
  575. }
  576. func (d *Daemon) inspectFilter(name, filter string) (string, error) {
  577. format := fmt.Sprintf("{{%s}}", filter)
  578. out, err := d.Cmd("inspect", "-f", format, name)
  579. if err != nil {
  580. return "", errors.Errorf("failed to inspect %s: %s", name, out)
  581. }
  582. return strings.TrimSpace(out), nil
  583. }
  584. func (d *Daemon) inspectFieldWithError(name, field string) (string, error) {
  585. return d.inspectFilter(name, fmt.Sprintf(".%s", field))
  586. }
  587. // FindContainerIP returns the ip of the specified container
  588. func (d *Daemon) FindContainerIP(id string) (string, error) {
  589. out, err := d.Cmd("inspect", "--format='{{ .NetworkSettings.Networks.bridge.IPAddress }}'", id)
  590. if err != nil {
  591. return "", err
  592. }
  593. return strings.Trim(out, " \r\n'"), nil
  594. }
  595. // BuildImageWithOut builds an image with the specified dockerfile and options and returns the output
  596. func (d *Daemon) BuildImageWithOut(name, dockerfile string, useCache bool, buildFlags ...string) (string, int, error) {
  597. buildCmd := BuildImageCmdWithHost(d.dockerBinary, name, dockerfile, d.Sock(), useCache, buildFlags...)
  598. result := icmd.RunCmd(icmd.Cmd{
  599. Command: buildCmd.Args,
  600. Env: buildCmd.Env,
  601. Dir: buildCmd.Dir,
  602. Stdin: buildCmd.Stdin,
  603. Stdout: buildCmd.Stdout,
  604. })
  605. return result.Combined(), result.ExitCode, result.Error
  606. }
  607. // CheckActiveContainerCount returns the number of active containers
  608. // FIXME(vdemeester) should re-use ActivateContainers in some way
  609. func (d *Daemon) CheckActiveContainerCount(c *check.C) (interface{}, check.CommentInterface) {
  610. out, err := d.Cmd("ps", "-q")
  611. c.Assert(err, checker.IsNil)
  612. if len(strings.TrimSpace(out)) == 0 {
  613. return 0, nil
  614. }
  615. return len(strings.Split(strings.TrimSpace(out), "\n")), check.Commentf("output: %q", string(out))
  616. }
  617. // ReloadConfig asks the daemon to reload its configuration
  618. func (d *Daemon) ReloadConfig() error {
  619. if d.cmd == nil || d.cmd.Process == nil {
  620. return errors.New("daemon is not running")
  621. }
  622. errCh := make(chan error)
  623. started := make(chan struct{})
  624. go func() {
  625. _, body, err := request.DoOnHost(d.Sock(), "/events", request.Method(http.MethodGet))
  626. close(started)
  627. if err != nil {
  628. errCh <- err
  629. }
  630. defer body.Close()
  631. dec := json.NewDecoder(body)
  632. for {
  633. var e events.Message
  634. if err := dec.Decode(&e); err != nil {
  635. errCh <- err
  636. return
  637. }
  638. if e.Type != events.DaemonEventType {
  639. continue
  640. }
  641. if e.Action != "reload" {
  642. continue
  643. }
  644. close(errCh) // notify that we are done
  645. return
  646. }
  647. }()
  648. <-started
  649. if err := signalDaemonReload(d.cmd.Process.Pid); err != nil {
  650. return errors.Errorf("error signaling daemon reload: %v", err)
  651. }
  652. select {
  653. case err := <-errCh:
  654. if err != nil {
  655. return errors.Errorf("error waiting for daemon reload event: %v", err)
  656. }
  657. case <-time.After(30 * time.Second):
  658. return errors.New("timeout waiting for daemon reload event")
  659. }
  660. return nil
  661. }
  662. // NewClient creates new client based on daemon's socket path
  663. func (d *Daemon) NewClient() (*client.Client, error) {
  664. httpClient, err := request.NewHTTPClient(d.Sock())
  665. if err != nil {
  666. return nil, err
  667. }
  668. return client.NewClient(d.Sock(), api.DefaultVersion, httpClient, nil)
  669. }
  670. // WaitInspectWithArgs waits for the specified expression to be equals to the specified expected string in the given time.
  671. // Deprecated: use cli.WaitCmd instead
  672. func WaitInspectWithArgs(dockerBinary, name, expr, expected string, timeout time.Duration, arg ...string) error {
  673. after := time.After(timeout)
  674. args := append(arg, "inspect", "-f", expr, name)
  675. for {
  676. result := icmd.RunCommand(dockerBinary, args...)
  677. if result.Error != nil {
  678. if !strings.Contains(strings.ToLower(result.Stderr()), "no such") {
  679. return errors.Errorf("error executing docker inspect: %v\n%s",
  680. result.Stderr(), result.Stdout())
  681. }
  682. select {
  683. case <-after:
  684. return result.Error
  685. default:
  686. time.Sleep(10 * time.Millisecond)
  687. continue
  688. }
  689. }
  690. out := strings.TrimSpace(result.Stdout())
  691. if out == expected {
  692. break
  693. }
  694. select {
  695. case <-after:
  696. return errors.Errorf("condition \"%q == %q\" not true in time (%v)", out, expected, timeout)
  697. default:
  698. }
  699. time.Sleep(100 * time.Millisecond)
  700. }
  701. return nil
  702. }
  703. // BuildImageCmdWithHost create a build command with the specified arguments.
  704. // Deprecated
  705. // FIXME(vdemeester) move this away
  706. func BuildImageCmdWithHost(dockerBinary, name, dockerfile, host string, useCache bool, buildFlags ...string) *exec.Cmd {
  707. args := []string{}
  708. if host != "" {
  709. args = append(args, "--host", host)
  710. }
  711. args = append(args, "build", "-t", name)
  712. if !useCache {
  713. args = append(args, "--no-cache")
  714. }
  715. args = append(args, buildFlags...)
  716. args = append(args, "-")
  717. buildCmd := exec.Command(dockerBinary, args...)
  718. buildCmd.Stdin = strings.NewReader(dockerfile)
  719. return buildCmd
  720. }