Best Gauge code snippet using runner.Pid
runner_test.go
Source:runner_test.go
1package agent_test2import (3 "errors"4 "fmt"5 "io/ioutil"6 "math/rand"7 "os"8 "path/filepath"9 "runtime"10 "code.cloudfoundry.org/lager"11 "github.com/cloudfoundry-incubator/consul-release/src/confab/agent"12 "github.com/cloudfoundry-incubator/consul-release/src/confab/fakes"13 . "github.com/onsi/ginkgo"14 . "github.com/onsi/gomega"15 . "github.com/pivotal-cf-experimental/gomegamatchers"16)17var _ = Describe("Runner", func() {18 var (19 runner *agent.Runner20 logger *fakes.Logger21 )22 BeforeEach(func() {23 var err error24 configDir, err := ioutil.TempDir("", "fake-agent-config-dir")25 Expect(err).NotTo(HaveOccurred())26 pidFile, err := ioutil.TempFile("", "fake-agent-pid")27 Expect(err).NotTo(HaveOccurred())28 pidFile.Close()29 os.Remove(pidFile.Name()) // so that the pid file doesn't exist at all30 pidFileName := pidFile.Name()31 logger = &fakes.Logger{}32 runner = &agent.Runner{33 Path: pathToFakeProcess,34 ConfigDir: configDir,35 Recursors: []string{"8.8.8.8", "10.0.2.3"},36 PIDFile: pidFileName,37 Logger: logger,38 // Stdout: os.Stdout, // uncomment this to see output from test agent39 // Stderr: os.Stderr,40 }41 })42 AfterEach(func() {43 os.Remove(runner.PIDFile)44 os.RemoveAll(runner.ConfigDir)45 })46 Describe("Cleanup", func() {47 It("deletes the PID file for the consul agent", func() {48 _, err := os.Stat(runner.PIDFile)49 Expect(err).To(BeAnOsIsNotExistError())50 file, err := os.Create(runner.PIDFile)51 Expect(err).NotTo(HaveOccurred())52 file.Close()53 _, err = os.Stat(runner.PIDFile)54 Expect(err).NotTo(HaveOccurred())55 err = runner.Cleanup()56 Expect(err).NotTo(HaveOccurred())57 _, err = os.Stat(runner.PIDFile)58 Expect(err).To(BeAnOsIsNotExistError())59 Expect(logger.Messages()).To(ContainSequence([]fakes.LoggerMessage{60 {61 Action: "agent-runner.cleanup.remove",62 Data: []lager.Data{{63 "pidfile": runner.PIDFile,64 }},65 },66 {67 Action: "agent-runner.cleanup.success",68 },69 }))70 })71 Context("when the PIDFile does not exist", func() {72 It("returns the error", func() {73 err := runner.Cleanup()74 Expect(err).To(BeAnOsIsNotExistError())75 Expect(logger.Messages()).To(ContainSequence([]fakes.LoggerMessage{76 {77 Action: "agent-runner.cleanup.remove",78 Data: []lager.Data{{79 "pidfile": runner.PIDFile,80 }},81 },82 {83 Action: "agent-runner.cleanup.remove.failed",84 Error: errors.New(err.Error()),85 Data: []lager.Data{{86 "pidfile": runner.PIDFile,87 }},88 },89 }))90 })91 })92 })93 Describe("Stop", func() {94 It("kills the process", func() {95 By("launching the process, configured to spin", func() {96 Expect(ioutil.WriteFile(filepath.Join(runner.ConfigDir, "options.json"), []byte(`{ "WaitForHUP": true }`), 0600)).To(Succeed())97 Expect(runner.Run()).To(Succeed())98 Expect(runner.WritePID()).To(Succeed())99 })100 By("waiting for the process to start enough that it has ignored signals", func() {101 Eventually(func() error {102 _, err := os.Stat(filepath.Join(runner.ConfigDir, "fake-output.json"))103 return err104 }).Should(Succeed())105 })106 By("calling stop", func() {107 pid, err := getPID(runner)108 Expect(err).NotTo(HaveOccurred())109 Expect(runner.Stop()).To(Succeed())110 Expect(logger.Messages()).To(ContainSequence([]fakes.LoggerMessage{111 {112 Action: "agent-runner.stop.get-process",113 },114 {115 Action: "agent-runner.stop.get-process.result",116 Data: []lager.Data{{117 "pid": pid,118 }},119 },120 {121 Action: "agent-runner.stop.signal",122 Data: []lager.Data{{123 "pid": pid,124 }},125 },126 {127 Action: "agent-runner.stop.success",128 },129 }))130 })131 By("checking that the process no longer exists", func() {132 Eventually(runner.Exited).Should(BeTrue())133 })134 })135 Context("when the PID file cannot be read", func() {136 It("returns an error", func() {137 runner.PIDFile = "/tmp/nope-i-do-not-exist"138 err := runner.Stop()139 Expect(err).To(BeAnOsIsNotExistError())140 Expect(logger.Messages()).To(ContainSequence([]fakes.LoggerMessage{141 {142 Action: "agent-runner.stop.get-process",143 },144 {145 Action: "agent-runner.stop.get-process.failed",146 Error: errors.New(err.Error()),147 },148 }))149 })150 })151 Context("when the PID file contains nonsense", func() {152 It("returns an error", func() {153 Expect(ioutil.WriteFile(runner.PIDFile, []byte("nonsense"), 0644)).To(Succeed())154 Expect(runner.Stop()).To(MatchError(ContainSubstring("ParseInt")))155 })156 })157 Context("when the PID file has the wrong PID", func() {158 It("returns an error", func() {159 Expect(ioutil.WriteFile(runner.PIDFile, []byte("-1"), 0644)).To(Succeed())160 Expect(runner.Stop()).To(HaveOccurred())161 })162 })163 })164 Describe("stop & wait", func() {165 It("stops the process / waits until it exits", func() {166 By("launching the process, configured to spin", func() {167 Expect(ioutil.WriteFile(filepath.Join(runner.ConfigDir, "options.json"), []byte(`{ "WaitForHUP": true }`), 0600)).To(Succeed())168 Expect(runner.Run()).To(Succeed())169 Expect(runner.WritePID()).To(Succeed())170 })171 By("waiting for the process to get started", func() {172 Eventually(func() error {173 _, err := os.Stat(filepath.Join(runner.ConfigDir, "fake-output.json"))174 return err175 }).Should(Succeed())176 })177 By("checking that the process has not exited", func() {178 Expect(runner.Exited()).To(BeFalse())179 })180 done := make(chan struct{})181 By("checking that Wait() blocks", func() {182 go func() {183 if err := runner.Wait(); err != nil {184 panic(fmt.Sprintf("%#v\n", err))185 }186 done <- struct{}{}187 }()188 Consistently(done, "100ms").ShouldNot(Receive())189 })190 By("stopping the process", func() {191 Expect(runner.Stop()).To(Succeed())192 })193 By("checking that Wait returns", func() {194 pid, err := getPID(runner)195 Expect(err).NotTo(HaveOccurred())196 Expect(runner.Wait()).To(Succeed())197 Expect(logger.Messages()).To(ContainSequence([]fakes.LoggerMessage{198 {199 Action: "agent-runner.wait.get-process",200 },201 {202 Action: "agent-runner.wait.get-process.result",203 Data: []lager.Data{{204 "pid": pid,205 }},206 },207 {208 Action: "agent-runner.wait.signal",209 Data: []lager.Data{{210 "pid": pid,211 }},212 },213 {214 Action: "agent-runner.wait.success",215 },216 }))217 })218 By("checking that the process no longer exists", func() {219 Eventually(runner.Exited).Should(BeTrue())220 })221 Eventually(done).Should(Receive())222 })223 Context("when the PID file cannot be read", func() {224 It("returns an error", func() {225 runner.PIDFile = "/tmp/nope-i-do-not-exist"226 err := runner.Wait()227 Expect(err).To(BeAnOsIsNotExistError())228 Expect(logger.Messages()).To(ContainSequence([]fakes.LoggerMessage{229 {230 Action: "agent-runner.wait.get-process",231 },232 {233 Action: "agent-runner.wait.get-process.failed",234 Error: errors.New(err.Error()),235 },236 }))237 })238 })239 Context("when the PID file contains nonsense", func() {240 It("returns an error", func() {241 Expect(ioutil.WriteFile(runner.PIDFile, []byte("nonsense"), 0644)).To(Succeed())242 Expect(runner.Wait()).To(MatchError(ContainSubstring("ParseInt")))243 })244 })245 })246 Describe("WritePID", func() {247 BeforeEach(func() {248 Expect(runner.Run()).To(Succeed())249 })250 It("writes the pid of the agent process to the pid file", func() {251 Expect(runner.WritePID()).To(Succeed())252 pid, err := getPID(runner)253 Expect(err).NotTo(HaveOccurred())254 Expect(logger.Messages()).To(ContainSequence([]fakes.LoggerMessage{255 {256 Action: "agent-runner.run.write-pidfile",257 Data: []lager.Data{{258 "pid": pid,259 "path": runner.PIDFile,260 }},261 },262 }))263 Expect(runner.Wait()).To(Succeed())264 })265 It("makes the pid file world readable", func() {266 Expect(runner.WritePID()).To(Succeed())267 fileInfo, err := os.Stat(runner.PIDFile)268 Expect(err).NotTo(HaveOccurred())269 if runtime.GOOS == "windows" {270 //Windows doesn't honor unix file permissions271 Expect(fileInfo.Mode().Perm()).To(BeEquivalentTo(0666))272 } else {273 Expect(fileInfo.Mode().Perm()).To(BeEquivalentTo(0644))274 }275 Expect(runner.Wait()).To(Succeed())276 })277 Context("when writing the PID file errors", func() {278 It("returns the error", func() {279 Expect(os.Mkdir(runner.PIDFile, os.ModeDir)).To(Succeed())280 err := runner.WritePID()281 Expect(err).To(MatchError(ContainSubstring("error writing PID file")))282 Expect(runner.WritePID()).To(MatchError(ContainSubstring("is a directory")))283 })284 })285 })286 Describe("Run", func() {287 It("starts the process", func() {288 Expect(runner.Run()).To(Succeed())289 Expect(runner.WritePID()).To(Succeed())290 pid, err := getPID(runner)291 Expect(err).NotTo(HaveOccurred())292 Expect(logger.Messages()).To(ContainSequence([]fakes.LoggerMessage{293 {294 Action: "agent-runner.run.start",295 Data: []lager.Data{{296 "cmd": runner.Path,297 "args": []string{298 "agent",299 fmt.Sprintf("-config-dir=%s", runner.ConfigDir),300 "-recursor=8.8.8.8",301 "-recursor=10.0.2.3",302 },303 }},304 },305 {306 Action: "agent-runner.run.success",307 },308 }))309 Expect(runner.Wait()).To(Succeed())310 pid, err = getPID(runner)311 Expect(err).NotTo(HaveOccurred())312 outputs := getFakeAgentOutput(runner)313 Expect(pid).To(Equal(outputs.PID))314 })315 It("sets the arguments correctly", func() {316 Expect(runner.Run()).To(Succeed())317 Expect(runner.WritePID()).To(Succeed())318 Expect(runner.Wait()).To(Succeed())319 Expect(getFakeAgentOutput(runner).Args).To(Equal([]string{320 "agent",321 fmt.Sprintf("-config-dir=%s", runner.ConfigDir),322 fmt.Sprintf("-recursor=%s", "8.8.8.8"),323 fmt.Sprintf("-recursor=%s", "10.0.2.3"),324 }))325 })326 It("returns without waiting for the process to exit", func() {327 Expect(ioutil.WriteFile(filepath.Join(runner.ConfigDir, "options.json"), []byte(`{ "WaitForHUP": true }`), 0600)).To(Succeed())328 done := make(chan struct{})329 go func() {330 runner.Run()331 Expect(runner.WritePID()).To(Succeed())332 done <- struct{}{}333 }()334 Eventually(done, "1s").Should(Receive())335 Expect(runner.Exited()).To(BeFalse())336 err := runner.Stop()337 Expect(err).NotTo(HaveOccurred())338 })339 It("wires up the stdout and stderr pipes", func() {340 stdoutBytes := newConcurrentSafeBuffer()341 stderrBytes := newConcurrentSafeBuffer()342 runner.Stdout = stdoutBytes343 runner.Stderr = stderrBytes344 Expect(runner.Run()).To(Succeed())345 Expect(runner.WritePID()).To(Succeed())346 Expect(runner.Wait()).To(Succeed())347 Expect(stdoutBytes.String()).To(Equal("some standard out"))348 Expect(stderrBytes.String()).To(Equal("some standard error"))349 })350 Context("when starting the process fails", func() {351 It("returns the error", func() {352 runner.Path = "/tmp/not-a-thing-we-can-launch"353 // If the command cannot start the354 // returned error type is undefined.355 err := runner.Run()356 Expect(err).ToNot(BeNil())357 Expect(logger.Messages()).To(ContainSequence([]fakes.LoggerMessage{358 {359 Action: "agent-runner.run.start",360 Data: []lager.Data{{361 "cmd": runner.Path,362 "args": []string{363 "agent",364 fmt.Sprintf("-config-dir=%s", runner.ConfigDir),365 "-recursor=8.8.8.8",366 "-recursor=10.0.2.3",367 },368 }},369 },370 {371 Action: "agent-runner.run.start.failed",372 Error: errors.New(err.Error()),373 Data: []lager.Data{{374 "cmd": runner.Path,375 "args": []string{376 "agent",377 fmt.Sprintf("-config-dir=%s", runner.ConfigDir),378 "-recursor=8.8.8.8",379 "-recursor=10.0.2.3",380 },381 }},382 },383 }))384 })385 })386 Context("when the ConfigDir is missing", func() {387 It("returns an error immediately, without starting a process", func() {388 runner.ConfigDir = fmt.Sprintf("/tmp/this-directory-does-not-existi-%x", rand.Int31())389 Expect(runner.Run()).To(MatchError(ContainSubstring("config dir does not exist")))390 Expect(logger.Messages()).To(ContainSequence([]fakes.LoggerMessage{391 {392 Action: "agent-runner.run.config-dir-missing",393 Error: fmt.Errorf("config dir does not exist: %s", runner.ConfigDir),394 },395 }))396 })397 })398 })399})...
runner.go
Source:runner.go
...63}64func (r *Runner) Exited() bool { return atomic.LoadInt32(&r.exited) == 1 }65func (r *Runner) WritePID() error {66 r.Logger.Info("agent-runner.run.write-pidfile", lager.Data{67 "pid": r.cmd.Process.Pid,68 "path": r.PIDFile,69 })70 if err := ioutil.WriteFile(r.PIDFile, []byte(fmt.Sprintf("%d", r.cmd.Process.Pid)), 0644); err != nil {71 err = fmt.Errorf("error writing PID file: %s", err)72 r.Logger.Error("agent-runner.run.write-pidfile.failed", err, lager.Data{73 "pid": r.cmd.Process.Pid,74 "path": r.PIDFile,75 })76 return err77 }78 return nil79}80func (r *Runner) getProcess() (*os.Process, error) {81 if r.cmd != nil && r.cmd.Process != nil {82 return r.cmd.Process, nil83 }84 pidFileContents, err := ioutil.ReadFile(r.PIDFile)85 if err != nil {86 return nil, err87 }88 pid, err := strconv.Atoi(string(pidFileContents))89 if err != nil {90 return nil, err91 }92 process, err := os.FindProcess(pid)93 if err != nil {94 return nil, err // not tested. As of Go 1.5, FindProcess never errors95 }96 return process, nil97}98func (r *Runner) Wait() error {99 r.Logger.Info("agent-runner.wait.get-process")100 process, err := r.getProcess()101 if err != nil {102 r.Logger.Error("agent-runner.wait.get-process.failed", errors.New(err.Error()))103 return err104 }105 r.Logger.Info("agent-runner.wait.get-process.result", lager.Data{106 "pid": process.Pid,107 })108 r.Logger.Info("agent-runner.wait.signal", lager.Data{109 "pid": process.Pid,110 })111 r.wg.Wait()112 r.Logger.Info("agent-runner.wait.success")113 return nil114}115func (r *Runner) Stop() error {116 r.Logger.Info("agent-runner.stop.get-process")117 process, err := r.getProcess()118 if err != nil {119 r.Logger.Error("agent-runner.stop.get-process.failed", errors.New(err.Error()))120 return err121 }122 r.Logger.Info("agent-runner.stop.get-process.result", lager.Data{123 "pid": process.Pid,124 })125 r.Logger.Info("agent-runner.stop.signal", lager.Data{126 "pid": process.Pid,127 })128 err = process.Signal(syscall.Signal(syscall.SIGKILL))129 if err != nil {130 r.Logger.Error("agent-runner.stop.signal.failed", err)131 return err132 }133 r.Logger.Info("agent-runner.stop.success")134 return nil135}136func (r *Runner) Cleanup() error {137 r.Logger.Info("agent-runner.cleanup.remove", lager.Data{138 "pidfile": r.PIDFile,139 })140 if err := os.Remove(r.PIDFile); err != nil {...
Pid
Using AI Code Generation
1import (2func main() {3 cmd := exec.Command("ls", "-l")4 err := cmd.Start()5 if err != nil {6 fmt.Println(err)7 os.Exit(1)8 }9 fmt.Println("Process id: ", cmd.Process.Pid)10 err = cmd.Wait()11 if err != nil {12 fmt.Println(err)13 os.Exit(1)14 }15}16import (17func main() {18 cmd := exec.Command("sleep", "10")19 err := cmd.Start()20 if err != nil {21 fmt.Println(err)22 os.Exit(1)23 }24 fmt.Println("Process id: ", cmd.Process.Pid)25 err = cmd.Process.Kill()26 if err != nil {27 fmt.Println(err)28 os.Exit(1)29 }30 fmt.Println("Process killed")31 err = cmd.Wait()32 if err != nil {
Pid
Using AI Code Generation
1import (2func main() {3 cmd := exec.Command("go", "run", "2.go")4 cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}5 err := cmd.Start()6 if err != nil {7 fmt.Println(err)8 os.Exit(1)9 }10 fmt.Println("Process ID:", cmd.Process.Pid)11 fmt.Println("Process Group ID:", cmd.Process.Pid)12 err = cmd.Wait()13 fmt.Println(err)14}15import (16func main() {17 cmd := exec.Command("go", "run", "3.go")18 cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}19 err := cmd.Start()20 if err != nil {21 fmt.Println(err)22 os.Exit(1)23 }24 fmt.Println("Process ID:", cmd.Process.Pid)25 fmt.Println("Process Group ID:", cmd.Process.Pid)26 err = cmd.Wait()27 fmt.Println(err)28}29import (30func main() {31 cmd := exec.Command("go", "run", "4.go")32 cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}33 err := cmd.Start()34 if err != nil {35 fmt.Println(err)36 os.Exit(1)37 }38 fmt.Println("Process ID:", cmd.Process.Pid)39 fmt.Println("Process Group ID:", cmd.Process.Pid)40 err = cmd.Wait()41 fmt.Println(err)42}43import (44func main() {45 cmd := exec.Command("go", "run", "5.go")46 cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}47 err := cmd.Start()48 if err != nil {49 fmt.Println(err)50 os.Exit(1)51 }52 fmt.Println("Process ID:", cmd.Process.Pid)53 fmt.Println("Process Group ID:", cmd.Process.Pid)54 err = cmd.Wait()55 fmt.Println(err)56}
Pid
Using AI Code Generation
1import (2func main() {3 r := runner.New(3 * time.Second)4 r.Add(createTask(), createTask(), createTask())5 if err := r.Start(); err != nil {6 switch err {7 fmt.Println("Terminating due to timeout.")8 os.Exit(1)9 fmt.Println("Terminating due to interrupt.")10 os.Exit(2)11 }12 }13 fmt.Println("Process ended.")14}15import (16var ErrTimeout = errors.New("received timeout")17var ErrInterrupt = errors.New("received interrupt")18type Runner struct {19 tasks []func(int)20}21func New(d time.Duration) *Runner {22 return &Runner{23 interrupt: make(chan os.Signal, 1),24 complete: make(chan error),25 timeout: time.After(d),26 }27}28func (r *Runner) Add(tasks ...func(int)) {29 r.tasks = append(r.tasks, tasks...)30}31func (r *Runner) Start() error {32 signal.Notify(r.interrupt, os.Interrupt)33 go func() {34 r.complete <- r.run()35 }()36 select {
Pid
Using AI Code Generation
1import (2func main() {3 r := runner.New(10 * time.Second)4 go func() {5 time.Sleep(5 * time.Second)6 fmt.Printf("Terminating now...")7 r.Terminate()8 }()9 err := r.Start(func(interrupt <-chan os.Signal) error {10 fmt.Println("Starting...")11 select {12 case <-time.After(3 * time.Second):13 fmt.Println("Done.")14 fmt.Println("Interrupted.")15 return errors.New("Terminated.")16 }17 })18 if err != nil {19 fmt.Printf("Error: %s20 }21}
Pid
Using AI Code Generation
1import (2func main() {3 runner := golrunner.Runner{}4 pid := runner.Pid("tail", "-f", "/var/log/messages")5 fmt.Println(pid)6}7import (8func main() {9 runner := golrunner.Runner{}10 pid := runner.Pid("tail", "-f", "/var/log/messages")11 fmt.Println(pid)12}13import (14func main() {15 runner := golrunner.Runner{}16 pid := runner.Pid("tail", "-f", "/var/log/messages")17 fmt.Println(pid)18}19import (20func main() {21 runner := golrunner.Runner{}22 pid := runner.Pid("tail", "-f", "/var/log/messages")23 fmt.Println(pid)24}25import (26func main() {27 runner := golrunner.Runner{}28 pid := runner.Pid("tail", "-f", "/var/log/messages")29 fmt.Println(pid)30}31import (32func main() {33 runner := golrunner.Runner{}34 pid := runner.Pid("tail", "-f", "/var/log/messages")35 fmt.Println(pid)36}37import (38func main() {
Pid
Using AI Code Generation
1import (2func main() {3 r := bufio.NewReader(os.Stdin)4 fmt.Print("Enter a command: ")5 cmdString, _ := r.ReadString('6 cmdString = strings.TrimSuffix(cmdString, "7 cmd := exec.Command(cmdString)8 cmd.Start()9 fmt.Printf("The pid of the process is %d", pid)10}
Pid
Using AI Code Generation
1import (2func main() {3 r := runner.New(3 * time.Second)4 r.Add(createTask(), createTask(), createTask())5 if err := r.Start(); err != nil {6 switch err {7 fmt.Println("Terminating due to interrupt")8 os.Exit(2)9 fmt.Println("Terminating due to timeout")10 os.Exit(1)11 }12 }13 fmt.Println("Process ended")14}15func createTask() func(int) {16 return func(id int) {17 time.Sleep(time.Duration(id) * time.Second)18 }19}20import (21type Runner struct {22 tasks []func(int)23}24const (25var ErrTimeout = errors.New("received timeout")26var ErrInterrupt = errors.New("received interrupt")27func New(d time.Duration) *Runner {28 return &Runner{29 complete: make(chan error),30 timeout: time.After(d),31 }32}33func (r *Runner) Add(tasks ...func(int)) {34 r.tasks = append(r.tasks, tasks...)35}36func (r *Runner) Start() error {37 go func() {38 r.complete <- r.run()39 }()40 select {
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!