daemon.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815
  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 $DOCKER_INTEGRATION_DAEMON_DEST or $DEST.
  70. // The daemon will not automatically start.
  71. func New(t testingT, dockerBinary string, dockerdBinary string, config Config) *Daemon {
  72. dest := os.Getenv("DOCKER_INTEGRATION_DAEMON_DEST")
  73. if dest == "" {
  74. dest = os.Getenv("DEST")
  75. }
  76. if dest == "" {
  77. t.Fatalf("Please set the DOCKER_INTEGRATION_DAEMON_DEST or the DEST environment variable")
  78. }
  79. if err := os.MkdirAll(SockRoot, 0700); err != nil {
  80. t.Fatalf("could not create daemon socket root")
  81. }
  82. id := fmt.Sprintf("d%s", stringid.TruncateID(stringid.GenerateRandomID()))
  83. dir := filepath.Join(dest, id)
  84. daemonFolder, err := filepath.Abs(dir)
  85. if err != nil {
  86. t.Fatalf("Could not make %q an absolute path", dir)
  87. }
  88. daemonRoot := filepath.Join(daemonFolder, "root")
  89. if err := os.MkdirAll(daemonRoot, 0755); err != nil {
  90. t.Fatalf("Could not create daemon root %q", dir)
  91. }
  92. userlandProxy := true
  93. if env := os.Getenv("DOCKER_USERLANDPROXY"); env != "" {
  94. if val, err := strconv.ParseBool(env); err != nil {
  95. userlandProxy = val
  96. }
  97. }
  98. return &Daemon{
  99. id: id,
  100. Folder: daemonFolder,
  101. Root: daemonRoot,
  102. storageDriver: os.Getenv("DOCKER_GRAPHDRIVER"),
  103. userlandProxy: userlandProxy,
  104. execRoot: filepath.Join(os.TempDir(), "docker-execroot", id),
  105. dockerBinary: dockerBinary,
  106. dockerdBinary: dockerdBinary,
  107. experimental: config.Experimental,
  108. log: t,
  109. }
  110. }
  111. // RootDir returns the root directory of the daemon.
  112. func (d *Daemon) RootDir() string {
  113. return d.Root
  114. }
  115. // ID returns the generated id of the daemon
  116. func (d *Daemon) ID() string {
  117. return d.id
  118. }
  119. // StorageDriver returns the configured storage driver of the daemon
  120. func (d *Daemon) StorageDriver() string {
  121. return d.storageDriver
  122. }
  123. // CleanupExecRoot cleans the daemon exec root (network namespaces, ...)
  124. func (d *Daemon) CleanupExecRoot(c *check.C) {
  125. cleanupExecRoot(c, d.execRoot)
  126. }
  127. func (d *Daemon) getClientConfig() (*clientConfig, error) {
  128. var (
  129. transport *http.Transport
  130. scheme string
  131. addr string
  132. proto string
  133. )
  134. if d.UseDefaultTLSHost {
  135. option := &tlsconfig.Options{
  136. CAFile: "fixtures/https/ca.pem",
  137. CertFile: "fixtures/https/client-cert.pem",
  138. KeyFile: "fixtures/https/client-key.pem",
  139. }
  140. tlsConfig, err := tlsconfig.Client(*option)
  141. if err != nil {
  142. return nil, err
  143. }
  144. transport = &http.Transport{
  145. TLSClientConfig: tlsConfig,
  146. }
  147. addr = fmt.Sprintf("%s:%d", opts.DefaultHTTPHost, opts.DefaultTLSHTTPPort)
  148. scheme = "https"
  149. proto = "tcp"
  150. } else if d.UseDefaultHost {
  151. addr = opts.DefaultUnixSocket
  152. proto = "unix"
  153. scheme = "http"
  154. transport = &http.Transport{}
  155. } else {
  156. addr = d.sockPath()
  157. proto = "unix"
  158. scheme = "http"
  159. transport = &http.Transport{}
  160. }
  161. if err := sockets.ConfigureTransport(transport, proto, addr); err != nil {
  162. return nil, err
  163. }
  164. transport.DisableKeepAlives = true
  165. return &clientConfig{
  166. transport: transport,
  167. scheme: scheme,
  168. addr: addr,
  169. }, nil
  170. }
  171. // Start starts the daemon and return once it is ready to receive requests.
  172. func (d *Daemon) Start(t testingT, args ...string) {
  173. if err := d.StartWithError(args...); err != nil {
  174. t.Fatalf("Error starting daemon with arguments: %v", args)
  175. }
  176. }
  177. // StartWithError starts the daemon and return once it is ready to receive requests.
  178. // It returns an error in case it couldn't start.
  179. func (d *Daemon) StartWithError(args ...string) error {
  180. logFile, err := os.OpenFile(filepath.Join(d.Folder, "docker.log"), os.O_RDWR|os.O_CREATE|os.O_APPEND, 0600)
  181. if err != nil {
  182. return errors.Wrapf(err, "[%s] Could not create %s/docker.log", d.id, d.Folder)
  183. }
  184. return d.StartWithLogFile(logFile, args...)
  185. }
  186. // StartWithLogFile will start the daemon and attach its streams to a given file.
  187. func (d *Daemon) StartWithLogFile(out *os.File, providedArgs ...string) error {
  188. dockerdBinary, err := exec.LookPath(d.dockerdBinary)
  189. if err != nil {
  190. return errors.Wrapf(err, "[%s] could not find docker binary in $PATH", d.id)
  191. }
  192. args := append(d.GlobalFlags,
  193. "--containerd", "/var/run/docker/libcontainerd/docker-containerd.sock",
  194. "--data-root", d.Root,
  195. "--exec-root", d.execRoot,
  196. "--pidfile", fmt.Sprintf("%s/docker.pid", d.Folder),
  197. fmt.Sprintf("--userland-proxy=%t", d.userlandProxy),
  198. )
  199. if d.experimental {
  200. args = append(args, "--experimental", "--init")
  201. }
  202. if !(d.UseDefaultHost || d.UseDefaultTLSHost) {
  203. args = append(args, []string{"--host", d.Sock()}...)
  204. }
  205. if root := os.Getenv("DOCKER_REMAP_ROOT"); root != "" {
  206. args = append(args, []string{"--userns-remap", root}...)
  207. }
  208. // If we don't explicitly set the log-level or debug flag(-D) then
  209. // turn on debug mode
  210. foundLog := false
  211. foundSd := false
  212. for _, a := range providedArgs {
  213. if strings.Contains(a, "--log-level") || strings.Contains(a, "-D") || strings.Contains(a, "--debug") {
  214. foundLog = true
  215. }
  216. if strings.Contains(a, "--storage-driver") {
  217. foundSd = true
  218. }
  219. }
  220. if !foundLog {
  221. args = append(args, "--debug")
  222. }
  223. if d.storageDriver != "" && !foundSd {
  224. args = append(args, "--storage-driver", d.storageDriver)
  225. }
  226. args = append(args, providedArgs...)
  227. d.cmd = exec.Command(dockerdBinary, args...)
  228. d.cmd.Env = append(os.Environ(), "DOCKER_SERVICE_PREFER_OFFLINE_IMAGE=1")
  229. d.cmd.Stdout = out
  230. d.cmd.Stderr = out
  231. d.logFile = out
  232. if err := d.cmd.Start(); err != nil {
  233. return errors.Errorf("[%s] could not start daemon container: %v", d.id, err)
  234. }
  235. wait := make(chan error)
  236. go func() {
  237. wait <- d.cmd.Wait()
  238. d.log.Logf("[%s] exiting daemon", d.id)
  239. close(wait)
  240. }()
  241. d.Wait = wait
  242. tick := time.Tick(500 * time.Millisecond)
  243. // make sure daemon is ready to receive requests
  244. startTime := time.Now().Unix()
  245. for {
  246. d.log.Logf("[%s] waiting for daemon to start", d.id)
  247. if time.Now().Unix()-startTime > 5 {
  248. // After 5 seconds, give up
  249. return errors.Errorf("[%s] Daemon exited and never started", d.id)
  250. }
  251. select {
  252. case <-time.After(2 * time.Second):
  253. return errors.Errorf("[%s] timeout: daemon does not respond", d.id)
  254. case <-tick:
  255. clientConfig, err := d.getClientConfig()
  256. if err != nil {
  257. return err
  258. }
  259. client := &http.Client{
  260. Transport: clientConfig.transport,
  261. }
  262. req, err := http.NewRequest("GET", "/_ping", nil)
  263. if err != nil {
  264. return errors.Wrapf(err, "[%s] could not create new request", d.id)
  265. }
  266. req.URL.Host = clientConfig.addr
  267. req.URL.Scheme = clientConfig.scheme
  268. resp, err := client.Do(req)
  269. if err != nil {
  270. continue
  271. }
  272. resp.Body.Close()
  273. if resp.StatusCode != http.StatusOK {
  274. d.log.Logf("[%s] received status != 200 OK: %s\n", d.id, resp.Status)
  275. }
  276. d.log.Logf("[%s] daemon started\n", d.id)
  277. d.Root, err = d.queryRootDir()
  278. if err != nil {
  279. return errors.Errorf("[%s] error querying daemon for root directory: %v", d.id, err)
  280. }
  281. return nil
  282. case <-d.Wait:
  283. return errors.Errorf("[%s] Daemon exited during startup", d.id)
  284. }
  285. }
  286. }
  287. // StartWithBusybox will first start the daemon with Daemon.Start()
  288. // then save the busybox image from the main daemon and load it into this Daemon instance.
  289. func (d *Daemon) StartWithBusybox(t testingT, arg ...string) {
  290. d.Start(t, arg...)
  291. if err := d.LoadBusybox(); err != nil {
  292. t.Fatalf("Error loading busybox image to current daemon: %s\n%v", d.id, err)
  293. }
  294. }
  295. // Kill will send a SIGKILL to the daemon
  296. func (d *Daemon) Kill() error {
  297. if d.cmd == nil || d.Wait == nil {
  298. return errDaemonNotStarted
  299. }
  300. defer func() {
  301. d.logFile.Close()
  302. d.cmd = nil
  303. }()
  304. if err := d.cmd.Process.Kill(); err != nil {
  305. return err
  306. }
  307. if err := os.Remove(fmt.Sprintf("%s/docker.pid", d.Folder)); err != nil {
  308. return err
  309. }
  310. return nil
  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. if err := os.Remove(fmt.Sprintf("%s/docker.pid", d.Folder)); err != nil {
  404. return err
  405. }
  406. return nil
  407. }
  408. // Restart will restart the daemon by first stopping it and the starting it.
  409. // If an error occurs while starting the daemon, the test will fail.
  410. func (d *Daemon) Restart(t testingT, args ...string) {
  411. d.Stop(t)
  412. d.handleUserns()
  413. d.Start(t, args...)
  414. }
  415. // RestartWithError will restart the daemon by first stopping it and then starting it.
  416. func (d *Daemon) RestartWithError(arg ...string) error {
  417. if err := d.StopWithError(); err != nil {
  418. return err
  419. }
  420. d.handleUserns()
  421. return d.StartWithError(arg...)
  422. }
  423. func (d *Daemon) handleUserns() {
  424. // in the case of tests running a user namespace-enabled daemon, we have resolved
  425. // d.Root to be the actual final path of the graph dir after the "uid.gid" of
  426. // remapped root is added--we need to subtract it from the path before calling
  427. // start or else we will continue making subdirectories rather than truly restarting
  428. // with the same location/root:
  429. if root := os.Getenv("DOCKER_REMAP_ROOT"); root != "" {
  430. d.Root = filepath.Dir(d.Root)
  431. }
  432. }
  433. // LoadBusybox will load the stored busybox into a newly started daemon
  434. func (d *Daemon) LoadBusybox() error {
  435. bb := filepath.Join(d.Folder, "busybox.tar")
  436. if _, err := os.Stat(bb); err != nil {
  437. if !os.IsNotExist(err) {
  438. return errors.Errorf("unexpected error on busybox.tar stat: %v", err)
  439. }
  440. // saving busybox image from main daemon
  441. if out, err := exec.Command(d.dockerBinary, "save", "--output", bb, "busybox:latest").CombinedOutput(); err != nil {
  442. imagesOut, _ := exec.Command(d.dockerBinary, "images", "--format", "{{ .Repository }}:{{ .Tag }}").CombinedOutput()
  443. return errors.Errorf("could not save busybox image: %s\n%s", string(out), strings.TrimSpace(string(imagesOut)))
  444. }
  445. }
  446. // loading busybox image to this daemon
  447. if out, err := d.Cmd("load", "--input", bb); err != nil {
  448. return errors.Errorf("could not load busybox image: %s", out)
  449. }
  450. if err := os.Remove(bb); err != nil {
  451. return err
  452. }
  453. return nil
  454. }
  455. func (d *Daemon) queryRootDir() (string, error) {
  456. // update daemon root by asking /info endpoint (to support user
  457. // namespaced daemon with root remapped uid.gid directory)
  458. clientConfig, err := d.getClientConfig()
  459. if err != nil {
  460. return "", err
  461. }
  462. client := &http.Client{
  463. Transport: clientConfig.transport,
  464. }
  465. req, err := http.NewRequest("GET", "/info", nil)
  466. if err != nil {
  467. return "", err
  468. }
  469. req.Header.Set("Content-Type", "application/json")
  470. req.URL.Host = clientConfig.addr
  471. req.URL.Scheme = clientConfig.scheme
  472. resp, err := client.Do(req)
  473. if err != nil {
  474. return "", err
  475. }
  476. body := ioutils.NewReadCloserWrapper(resp.Body, func() error {
  477. return resp.Body.Close()
  478. })
  479. type Info struct {
  480. DockerRootDir string
  481. }
  482. var b []byte
  483. var i Info
  484. b, err = testutil.ReadBody(body)
  485. if err == nil && resp.StatusCode == http.StatusOK {
  486. // read the docker root dir
  487. if err = json.Unmarshal(b, &i); err == nil {
  488. return i.DockerRootDir, nil
  489. }
  490. }
  491. return "", err
  492. }
  493. // Sock returns the socket path of the daemon
  494. func (d *Daemon) Sock() string {
  495. return fmt.Sprintf("unix://" + d.sockPath())
  496. }
  497. func (d *Daemon) sockPath() string {
  498. return filepath.Join(SockRoot, d.id+".sock")
  499. }
  500. // WaitRun waits for a container to be running for 10s
  501. func (d *Daemon) WaitRun(contID string) error {
  502. args := []string{"--host", d.Sock()}
  503. return WaitInspectWithArgs(d.dockerBinary, contID, "{{.State.Running}}", "true", 10*time.Second, args...)
  504. }
  505. // GetBaseDeviceSize returns the base device size of the daemon
  506. func (d *Daemon) GetBaseDeviceSize(c *check.C) int64 {
  507. infoCmdOutput, _, err := testutil.RunCommandPipelineWithOutput(
  508. exec.Command(d.dockerBinary, "-H", d.Sock(), "info"),
  509. exec.Command("grep", "Base Device Size"),
  510. )
  511. c.Assert(err, checker.IsNil)
  512. basesizeSlice := strings.Split(infoCmdOutput, ":")
  513. basesize := strings.Trim(basesizeSlice[1], " ")
  514. basesize = strings.Trim(basesize, "\n")[:len(basesize)-3]
  515. basesizeFloat, err := strconv.ParseFloat(strings.Trim(basesize, " "), 64)
  516. c.Assert(err, checker.IsNil)
  517. basesizeBytes := int64(basesizeFloat) * (1024 * 1024 * 1024)
  518. return basesizeBytes
  519. }
  520. // Cmd executes a docker CLI command against this daemon.
  521. // Example: d.Cmd("version") will run docker -H unix://path/to/unix.sock version
  522. func (d *Daemon) Cmd(args ...string) (string, error) {
  523. result := icmd.RunCmd(d.Command(args...))
  524. return result.Combined(), result.Error
  525. }
  526. // Command creates a docker CLI command against this daemon, to be executed later.
  527. // Example: d.Command("version") creates a command to run "docker -H unix://path/to/unix.sock version"
  528. func (d *Daemon) Command(args ...string) icmd.Cmd {
  529. return icmd.Command(d.dockerBinary, d.PrependHostArg(args)...)
  530. }
  531. // PrependHostArg prepend the specified arguments by the daemon host flags
  532. func (d *Daemon) PrependHostArg(args []string) []string {
  533. for _, arg := range args {
  534. if arg == "--host" || arg == "-H" {
  535. return args
  536. }
  537. }
  538. return append([]string{"--host", d.Sock()}, args...)
  539. }
  540. // SockRequest executes a socket request on a daemon and returns statuscode and output.
  541. func (d *Daemon) SockRequest(method, endpoint string, data interface{}) (int, []byte, error) {
  542. jsonData := bytes.NewBuffer(nil)
  543. if err := json.NewEncoder(jsonData).Encode(data); err != nil {
  544. return -1, nil, err
  545. }
  546. res, body, err := d.SockRequestRaw(method, endpoint, jsonData, "application/json")
  547. if err != nil {
  548. return -1, nil, err
  549. }
  550. b, err := testutil.ReadBody(body)
  551. return res.StatusCode, b, err
  552. }
  553. // SockRequestRaw executes a socket request on a daemon and returns an http
  554. // response and a reader for the output data.
  555. // Deprecated: use request package instead
  556. func (d *Daemon) SockRequestRaw(method, endpoint string, data io.Reader, ct string) (*http.Response, io.ReadCloser, error) {
  557. return request.SockRequestRaw(method, endpoint, data, ct, d.Sock())
  558. }
  559. // LogFileName returns the path the daemon's log file
  560. func (d *Daemon) LogFileName() string {
  561. return d.logFile.Name()
  562. }
  563. // GetIDByName returns the ID of an object (container, volume, …) given its name
  564. func (d *Daemon) GetIDByName(name string) (string, error) {
  565. return d.inspectFieldWithError(name, "Id")
  566. }
  567. // ActiveContainers returns the list of ids of the currently running containers
  568. func (d *Daemon) ActiveContainers() (ids []string) {
  569. // FIXME(vdemeester) shouldn't ignore the error
  570. out, _ := d.Cmd("ps", "-q")
  571. for _, id := range strings.Split(out, "\n") {
  572. if id = strings.TrimSpace(id); id != "" {
  573. ids = append(ids, id)
  574. }
  575. }
  576. return
  577. }
  578. // ReadLogFile returns the content of the daemon log file
  579. func (d *Daemon) ReadLogFile() ([]byte, error) {
  580. return ioutil.ReadFile(d.logFile.Name())
  581. }
  582. // InspectField returns the field filter by 'filter'
  583. func (d *Daemon) InspectField(name, filter string) (string, error) {
  584. return d.inspectFilter(name, filter)
  585. }
  586. func (d *Daemon) inspectFilter(name, filter string) (string, error) {
  587. format := fmt.Sprintf("{{%s}}", filter)
  588. out, err := d.Cmd("inspect", "-f", format, name)
  589. if err != nil {
  590. return "", errors.Errorf("failed to inspect %s: %s", name, out)
  591. }
  592. return strings.TrimSpace(out), nil
  593. }
  594. func (d *Daemon) inspectFieldWithError(name, field string) (string, error) {
  595. return d.inspectFilter(name, fmt.Sprintf(".%s", field))
  596. }
  597. // FindContainerIP returns the ip of the specified container
  598. func (d *Daemon) FindContainerIP(id string) (string, error) {
  599. out, err := d.Cmd("inspect", "--format='{{ .NetworkSettings.Networks.bridge.IPAddress }}'", id)
  600. if err != nil {
  601. return "", err
  602. }
  603. return strings.Trim(out, " \r\n'"), nil
  604. }
  605. // BuildImageWithOut builds an image with the specified dockerfile and options and returns the output
  606. func (d *Daemon) BuildImageWithOut(name, dockerfile string, useCache bool, buildFlags ...string) (string, int, error) {
  607. buildCmd := BuildImageCmdWithHost(d.dockerBinary, name, dockerfile, d.Sock(), useCache, buildFlags...)
  608. result := icmd.RunCmd(icmd.Cmd{
  609. Command: buildCmd.Args,
  610. Env: buildCmd.Env,
  611. Dir: buildCmd.Dir,
  612. Stdin: buildCmd.Stdin,
  613. Stdout: buildCmd.Stdout,
  614. })
  615. return result.Combined(), result.ExitCode, result.Error
  616. }
  617. // CheckActiveContainerCount returns the number of active containers
  618. // FIXME(vdemeester) should re-use ActivateContainers in some way
  619. func (d *Daemon) CheckActiveContainerCount(c *check.C) (interface{}, check.CommentInterface) {
  620. out, err := d.Cmd("ps", "-q")
  621. c.Assert(err, checker.IsNil)
  622. if len(strings.TrimSpace(out)) == 0 {
  623. return 0, nil
  624. }
  625. return len(strings.Split(strings.TrimSpace(out), "\n")), check.Commentf("output: %q", string(out))
  626. }
  627. // ReloadConfig asks the daemon to reload its configuration
  628. func (d *Daemon) ReloadConfig() error {
  629. if d.cmd == nil || d.cmd.Process == nil {
  630. return errors.New("daemon is not running")
  631. }
  632. errCh := make(chan error)
  633. started := make(chan struct{})
  634. go func() {
  635. _, body, err := request.DoOnHost(d.Sock(), "/events", request.Method(http.MethodGet))
  636. close(started)
  637. if err != nil {
  638. errCh <- err
  639. }
  640. defer body.Close()
  641. dec := json.NewDecoder(body)
  642. for {
  643. var e events.Message
  644. if err := dec.Decode(&e); err != nil {
  645. errCh <- err
  646. return
  647. }
  648. if e.Type != events.DaemonEventType {
  649. continue
  650. }
  651. if e.Action != "reload" {
  652. continue
  653. }
  654. close(errCh) // notify that we are done
  655. return
  656. }
  657. }()
  658. <-started
  659. if err := signalDaemonReload(d.cmd.Process.Pid); err != nil {
  660. return errors.Errorf("error signaling daemon reload: %v", err)
  661. }
  662. select {
  663. case err := <-errCh:
  664. if err != nil {
  665. return errors.Errorf("error waiting for daemon reload event: %v", err)
  666. }
  667. case <-time.After(30 * time.Second):
  668. return errors.New("timeout waiting for daemon reload event")
  669. }
  670. return nil
  671. }
  672. // WaitInspectWithArgs waits for the specified expression to be equals to the specified expected string in the given time.
  673. // Deprecated: use cli.WaitCmd instead
  674. func WaitInspectWithArgs(dockerBinary, name, expr, expected string, timeout time.Duration, arg ...string) error {
  675. after := time.After(timeout)
  676. args := append(arg, "inspect", "-f", expr, name)
  677. for {
  678. result := icmd.RunCommand(dockerBinary, args...)
  679. if result.Error != nil {
  680. if !strings.Contains(strings.ToLower(result.Stderr()), "no such") {
  681. return errors.Errorf("error executing docker inspect: %v\n%s",
  682. result.Stderr(), result.Stdout())
  683. }
  684. select {
  685. case <-after:
  686. return result.Error
  687. default:
  688. time.Sleep(10 * time.Millisecond)
  689. continue
  690. }
  691. }
  692. out := strings.TrimSpace(result.Stdout())
  693. if out == expected {
  694. break
  695. }
  696. select {
  697. case <-after:
  698. return errors.Errorf("condition \"%q == %q\" not true in time (%v)", out, expected, timeout)
  699. default:
  700. }
  701. time.Sleep(100 * time.Millisecond)
  702. }
  703. return nil
  704. }
  705. // BuildImageCmdWithHost create a build command with the specified arguments.
  706. // Deprecated
  707. // FIXME(vdemeester) move this away
  708. func BuildImageCmdWithHost(dockerBinary, name, dockerfile, host string, useCache bool, buildFlags ...string) *exec.Cmd {
  709. args := []string{}
  710. if host != "" {
  711. args = append(args, "--host", host)
  712. }
  713. args = append(args, "build", "-t", name)
  714. if !useCache {
  715. args = append(args, "--no-cache")
  716. }
  717. args = append(args, buildFlags...)
  718. args = append(args, "-")
  719. buildCmd := exec.Command(dockerBinary, args...)
  720. buildCmd.Stdin = strings.NewReader(dockerfile)
  721. return buildCmd
  722. }