agent.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. // Copyright 2015 The etcd Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package main
  15. import (
  16. "fmt"
  17. "os"
  18. "os/exec"
  19. "path/filepath"
  20. "syscall"
  21. "time"
  22. "github.com/coreos/etcd/pkg/fileutil"
  23. "github.com/coreos/etcd/pkg/netutil"
  24. "github.com/coreos/etcd/tools/functional-tester/etcd-agent/client"
  25. )
  26. const (
  27. stateUninitialized = "uninitialized"
  28. stateStarted = "started"
  29. stateStopped = "stopped"
  30. stateTerminated = "terminated"
  31. )
  32. type Agent struct {
  33. state string // the state of etcd process
  34. cmd *exec.Cmd
  35. logfile *os.File
  36. logDir string
  37. }
  38. func newAgent(etcd, logDir string) (*Agent, error) {
  39. // check if the file exists
  40. _, err := os.Stat(etcd)
  41. if err != nil {
  42. return nil, err
  43. }
  44. c := exec.Command(etcd)
  45. err = fileutil.TouchDirAll(logDir)
  46. if err != nil {
  47. return nil, err
  48. }
  49. var f *os.File
  50. f, err = os.Create(filepath.Join(logDir, "etcd.log"))
  51. if err != nil {
  52. return nil, err
  53. }
  54. return &Agent{state: stateUninitialized, cmd: c, logfile: f, logDir: logDir}, nil
  55. }
  56. // start starts a new etcd process with the given args.
  57. func (a *Agent) start(args ...string) error {
  58. a.cmd = exec.Command(a.cmd.Path, args...)
  59. a.cmd.Env = []string{"GOFAIL_HTTP=:2381"}
  60. a.cmd.Stdout = a.logfile
  61. a.cmd.Stderr = a.logfile
  62. err := a.cmd.Start()
  63. if err != nil {
  64. return err
  65. }
  66. a.state = stateStarted
  67. return nil
  68. }
  69. // stop stops the existing etcd process the agent started.
  70. func (a *Agent) stopWithSig(sig os.Signal) error {
  71. if a.state != stateStarted {
  72. return nil
  73. }
  74. err := stopWithSig(a.cmd, sig)
  75. if err != nil {
  76. return err
  77. }
  78. a.state = stateStopped
  79. return nil
  80. }
  81. func stopWithSig(cmd *exec.Cmd, sig os.Signal) error {
  82. err := cmd.Process.Signal(sig)
  83. if err != nil {
  84. return err
  85. }
  86. errc := make(chan error)
  87. go func() {
  88. _, ew := cmd.Process.Wait()
  89. errc <- ew
  90. close(errc)
  91. }()
  92. select {
  93. case <-time.After(5 * time.Second):
  94. cmd.Process.Kill()
  95. case e := <-errc:
  96. return e
  97. }
  98. err = <-errc
  99. return err
  100. }
  101. // restart restarts the stopped etcd process.
  102. func (a *Agent) restart() error {
  103. return a.start(a.cmd.Args[1:]...)
  104. }
  105. func (a *Agent) cleanup() error {
  106. // exit with stackstrace
  107. if err := a.stopWithSig(syscall.SIGQUIT); err != nil {
  108. return err
  109. }
  110. a.state = stateUninitialized
  111. a.logfile.Close()
  112. if err := archiveLogAndDataDir(a.logDir, a.dataDir()); err != nil {
  113. return err
  114. }
  115. if err := fileutil.TouchDirAll(a.logDir); err != nil {
  116. return err
  117. }
  118. f, err := os.Create(filepath.Join(a.logDir, "etcd.log"))
  119. if err != nil {
  120. return err
  121. }
  122. a.logfile = f
  123. // https://www.kernel.org/doc/Documentation/sysctl/vm.txt
  124. // https://github.com/torvalds/linux/blob/master/fs/drop_caches.c
  125. cmd := exec.Command("/bin/sh", "-c", `echo "echo 1 > /proc/sys/vm/drop_caches" | sudo sh`)
  126. if err := cmd.Run(); err != nil {
  127. plog.Printf("error when cleaning page cache (%v)", err)
  128. }
  129. return nil
  130. }
  131. // terminate stops the exiting etcd process the agent started
  132. // and removes the data dir.
  133. func (a *Agent) terminate() error {
  134. err := a.stopWithSig(syscall.SIGTERM)
  135. if err != nil {
  136. return err
  137. }
  138. err = os.RemoveAll(a.dataDir())
  139. if err != nil {
  140. return err
  141. }
  142. a.state = stateTerminated
  143. return nil
  144. }
  145. func (a *Agent) dropPort(port int) error {
  146. return netutil.DropPort(port)
  147. }
  148. func (a *Agent) recoverPort(port int) error {
  149. return netutil.RecoverPort(port)
  150. }
  151. func (a *Agent) setLatency(ms, rv int) error {
  152. if ms == 0 {
  153. return netutil.RemoveLatency()
  154. }
  155. return netutil.SetLatency(ms, rv)
  156. }
  157. func (a *Agent) status() client.Status {
  158. return client.Status{State: a.state}
  159. }
  160. func (a *Agent) dataDir() string {
  161. datadir := filepath.Join(a.cmd.Path, "*.etcd")
  162. args := a.cmd.Args
  163. // only parse the simple case like "--data-dir /var/lib/etcd"
  164. for i, arg := range args {
  165. if arg == "--data-dir" {
  166. datadir = args[i+1]
  167. break
  168. }
  169. }
  170. return datadir
  171. }
  172. func existDir(fpath string) bool {
  173. st, err := os.Stat(fpath)
  174. if err != nil {
  175. if os.IsNotExist(err) {
  176. return false
  177. }
  178. } else {
  179. return st.IsDir()
  180. }
  181. return false
  182. }
  183. func archiveLogAndDataDir(logDir string, datadir string) error {
  184. dir := filepath.Join("failure_archive", fmt.Sprint(time.Now().Format(time.RFC3339)))
  185. if existDir(dir) {
  186. dir = filepath.Join("failure_archive", fmt.Sprint(time.Now().Add(time.Second).Format(time.RFC3339)))
  187. }
  188. if err := fileutil.TouchDirAll(dir); err != nil {
  189. return err
  190. }
  191. if err := os.Rename(logDir, filepath.Join(dir, filepath.Base(logDir))); err != nil {
  192. if !os.IsNotExist(err) {
  193. return err
  194. }
  195. }
  196. if err := os.Rename(datadir, filepath.Join(dir, filepath.Base(datadir))); err != nil {
  197. if !os.IsNotExist(err) {
  198. return err
  199. }
  200. }
  201. return nil
  202. }