daemon.go 23 KB

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