etcd_runner_stresser.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. // Copyright 2017 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. "io/ioutil"
  18. "os/exec"
  19. "syscall"
  20. "golang.org/x/time/rate"
  21. )
  22. type runnerStresser struct {
  23. cmd *exec.Cmd
  24. cmdStr string
  25. args []string
  26. rl *rate.Limiter
  27. reqRate int
  28. errc chan error
  29. donec chan struct{}
  30. }
  31. func newRunnerStresser(cmdStr string, args []string, rl *rate.Limiter, reqRate int) *runnerStresser {
  32. rl.SetLimit(rl.Limit() - rate.Limit(reqRate))
  33. return &runnerStresser{
  34. cmdStr: cmdStr,
  35. args: args,
  36. rl: rl,
  37. reqRate: reqRate,
  38. errc: make(chan error, 1),
  39. donec: make(chan struct{}),
  40. }
  41. }
  42. func (rs *runnerStresser) setupOnce() (err error) {
  43. if rs.cmd != nil {
  44. return nil
  45. }
  46. rs.cmd = exec.Command(rs.cmdStr, rs.args...)
  47. stderr, err := rs.cmd.StderrPipe()
  48. if err != nil {
  49. return err
  50. }
  51. go func() {
  52. defer close(rs.donec)
  53. out, err := ioutil.ReadAll(stderr)
  54. if err != nil {
  55. rs.errc <- err
  56. } else {
  57. rs.errc <- fmt.Errorf("(%v %v) stderr %v", rs.cmdStr, rs.args, string(out))
  58. }
  59. }()
  60. return rs.cmd.Start()
  61. }
  62. func (rs *runnerStresser) Stress() (err error) {
  63. if err = rs.setupOnce(); err != nil {
  64. return err
  65. }
  66. return syscall.Kill(rs.cmd.Process.Pid, syscall.SIGCONT)
  67. }
  68. func (rs *runnerStresser) Pause() {
  69. syscall.Kill(rs.cmd.Process.Pid, syscall.SIGSTOP)
  70. }
  71. func (rs *runnerStresser) Close() {
  72. syscall.Kill(rs.cmd.Process.Pid, syscall.SIGINT)
  73. rs.cmd.Wait()
  74. <-rs.donec
  75. rs.rl.SetLimit(rs.rl.Limit() + rate.Limit(rs.reqRate))
  76. }
  77. func (rs *runnerStresser) ModifiedKeys() int64 {
  78. return 1
  79. }
  80. func (rs *runnerStresser) Checker() Checker {
  81. return &runnerChecker{rs.errc}
  82. }