How to use readinessCheck method of commands Package

Best Testkube code snippet using commands.readinessCheck

server.go

Source:server.go Github

copy

Full Screen

...80func (s *server) String() string {81 return fmt.Sprintf("server %q start-command: `%s`, kill-command: `%s`, restart-command: `%s`, health-check: %v, output-file: %q", s.name,82 commandToString(s.startCommand), commandToString(s.killCommand), commandToString(s.restartCommand), s.healthCheckUrls, s.outFilename)83}84// readinessCheck checks whether services are ready via the supplied health85// check URLs. Once there is an error in errCh, the function will stop waiting86// and return the error.87// TODO(random-liu): Move this to util88func readinessCheck(name string, urls []string, errCh <-chan error) error {89 glog.Infof("Running readiness check for service %q", name)90 endTime := time.Now().Add(*serverStartTimeout)91 blockCh := make(chan error)92 defer close(blockCh)93 for endTime.After(time.Now()) {94 select {95 // We *always* want to run the health check if there is no error on the channel.96 // With systemd, reads from errCh report nil because cmd.Run() waits97 // on systemd-run, rather than the service process. systemd-run quickly98 // exits with status 0, causing the channel to be closed with no error. In99 // this case, you want to wait for the health check to complete, rather100 // than returning from readinessCheck as soon as the channel is closed.101 case err, ok := <-errCh:102 if ok { // The channel is not closed, this is a real error103 if err != nil { // If there is an error, return it104 return err105 }106 // If not, keep checking readiness.107 } else { // The channel is closed, this is only a zero value.108 // Replace the errCh with blockCh to avoid busy loop,109 // and keep checking readiness.110 errCh = blockCh111 }112 case <-time.After(time.Second):113 ready := true114 for _, url := range urls {115 resp, err := http.Head(url)116 if err != nil || resp.StatusCode != http.StatusOK {117 ready = false118 break119 }120 }121 if ready {122 return nil123 }124 }125 }126 return fmt.Errorf("e2e service %q readiness check timeout %v", name, *serverStartTimeout)127}128// start starts the server by running its commands, monitors it with a health129// check, and ensures that it is restarted if applicable.130//131// Note: restartOnExit == true requires len(s.healthCheckUrls) > 0 to work properly.132func (s *server) start() error {133 glog.Infof("Starting server %q with command %q", s.name, commandToString(s.startCommand))134 errCh := make(chan error)135 // Set up restart channels if the server is configured for restart on exit.136 var stopRestartingCh, ackStopRestartingCh chan bool137 if s.restartOnExit {138 if len(s.healthCheckUrls) == 0 {139 return fmt.Errorf("Tried to start %s which has s.restartOnExit == true, but no health check urls provided.", s)140 }141 stopRestartingCh = make(chan bool)142 ackStopRestartingCh = make(chan bool)143 s.stopRestartingCh = stopRestartingCh144 s.ackStopRestartingCh = ackStopRestartingCh145 }146 // This goroutine actually runs the start command for the server.147 go func() {148 defer close(errCh)149 // Create the output filename150 outPath := path.Join(framework.TestContext.ReportDir, s.outFilename)151 outfile, err := os.Create(outPath)152 if err != nil {153 errCh <- fmt.Errorf("failed to create file %q for `%s` %v.", outPath, s, err)154 return155 } else {156 glog.Infof("Output file for server %q: %v", s.name, outfile.Name())157 }158 defer outfile.Close()159 defer outfile.Sync()160 // Set the command to write the output file161 s.startCommand.Stdout = outfile162 s.startCommand.Stderr = outfile163 // If monitorParent is set, set Pdeathsig when starting the server.164 if s.monitorParent {165 // Death of this test process should kill the server as well.166 attrs := &syscall.SysProcAttr{}167 // Hack to set linux-only field without build tags.168 deathSigField := reflect.ValueOf(attrs).Elem().FieldByName("Pdeathsig")169 if deathSigField.IsValid() {170 deathSigField.Set(reflect.ValueOf(syscall.SIGTERM))171 } else {172 errCh <- fmt.Errorf("failed to set Pdeathsig field (non-linux build)")173 return174 }175 s.startCommand.SysProcAttr = attrs176 }177 // Start the command178 err = s.startCommand.Start()179 if err != nil {180 errCh <- fmt.Errorf("failed to run %s: %v", s, err)181 return182 }183 if !s.restartOnExit {184 glog.Infof("Waiting for server %q start command to complete", s.name)185 // If we aren't planning on restarting, ok to Wait() here to release resources.186 // Otherwise, we Wait() in the restart loop.187 err = s.startCommand.Wait()188 if err != nil {189 errCh <- fmt.Errorf("failed to run start command for server %q: %v", s.name, err)190 return191 }192 } else {193 usedStartCmd := true194 for {195 glog.Infof("Running health check for service %q", s.name)196 // Wait for an initial health check to pass, so that we are sure the server started.197 err := readinessCheck(s.name, s.healthCheckUrls, nil)198 if err != nil {199 if usedStartCmd {200 glog.Infof("Waiting for server %q start command to complete after initial health check failed", s.name)201 s.startCommand.Wait() // Release resources if necessary.202 }203 // This should not happen, immediately stop the e2eService process.204 glog.Fatalf("Restart loop readinessCheck failed for %s", s)205 } else {206 glog.Infof("Initial health check passed for service %q", s.name)207 }208 // Initial health check passed, wait until a health check fails again.209 stillAlive:210 for {211 select {212 case <-stopRestartingCh:213 ackStopRestartingCh <- true214 return215 case <-time.After(time.Second):216 for _, url := range s.healthCheckUrls {217 resp, err := http.Head(url)218 if err != nil || resp.StatusCode != http.StatusOK {219 break stillAlive220 }221 }222 }223 }224 if usedStartCmd {225 s.startCommand.Wait() // Release resources from last cmd226 usedStartCmd = false227 }228 if s.restartCommand != nil {229 // Always make a fresh copy of restartCommand before230 // running, we may have to restart multiple times231 s.restartCommand = &exec.Cmd{232 Path: s.restartCommand.Path,233 Args: s.restartCommand.Args,234 Env: s.restartCommand.Env,235 Dir: s.restartCommand.Dir,236 Stdin: s.restartCommand.Stdin,237 Stdout: s.restartCommand.Stdout,238 Stderr: s.restartCommand.Stderr,239 ExtraFiles: s.restartCommand.ExtraFiles,240 SysProcAttr: s.restartCommand.SysProcAttr,241 }242 // Run and wait for exit. This command is assumed to have243 // short duration, e.g. systemctl restart244 glog.Infof("Restarting server %q with restart command", s.name)245 err = s.restartCommand.Run()246 if err != nil {247 // This should not happen, immediately stop the e2eService process.248 glog.Fatalf("Restarting server %s with restartCommand failed. Error: %v.", s, err)249 }250 } else {251 s.startCommand = &exec.Cmd{252 Path: s.startCommand.Path,253 Args: s.startCommand.Args,254 Env: s.startCommand.Env,255 Dir: s.startCommand.Dir,256 Stdin: s.startCommand.Stdin,257 Stdout: s.startCommand.Stdout,258 Stderr: s.startCommand.Stderr,259 ExtraFiles: s.startCommand.ExtraFiles,260 SysProcAttr: s.startCommand.SysProcAttr,261 }262 glog.Infof("Restarting server %q with start command", s.name)263 err = s.startCommand.Start()264 usedStartCmd = true265 if err != nil {266 // This should not happen, immediately stop the e2eService process.267 glog.Fatalf("Restarting server %s with startCommand failed. Error: %v.", s, err)268 }269 }270 }271 }272 }()273 return readinessCheck(s.name, s.healthCheckUrls, errCh)274}275// kill runs the server's kill command.276func (s *server) kill() error {277 glog.Infof("Kill server %q", s.name)278 name := s.name279 cmd := s.startCommand280 // If s has a restart loop, turn it off.281 if s.restartOnExit {282 s.stopRestartingCh <- true283 <-s.ackStopRestartingCh284 }285 if s.killCommand != nil {286 return s.killCommand.Run()287 }...

Full Screen

Full Screen

readinessCheck

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 app := cli.NewApp()4 app.Commands = []cli.Command{5 {6 Aliases: []string{"rc"},7 Action: func(c *cli.Context) error {8 fmt.Println("Checking readiness")9 },10 },11 }12 app.Run(os.Args)13}

Full Screen

Full Screen

readinessCheck

Using AI Code Generation

copy

Full Screen

1import (2type Command struct {3}4func (c *Command) readinessCheck() bool {5 cmd := exec.Command(c.Path, c.Args...)6 env := os.Environ()7 cmd.Env = append(env, c.Env...)8 err := cmd.Run()9 if err != nil {10 }11}12func main() {13 cmd := &Command{14 Args: []string{"-la"},15 Env: []string{"PATH=/bin:/sbin:/usr/bin:/usr/sbin"},16 }17 fmt.Println(cmd.readinessCheck())18}

Full Screen

Full Screen

readinessCheck

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 app := cli.NewApp()4 app.Action = func(c *cli.Context) error {5 fmt.Println("Readiness check")6 }7 app.Commands = []cli.Command{8 {9 Aliases: []string{"r"},10 Action: func(c *cli.Context) error {11 fmt.Println("Readiness check")12 },13 },14 }15 app.Run(os.Args)16}17import (18func main() {19 app := cli.NewApp()20 app.Action = func(c *cli.Context) error {21 fmt.Println("Readiness check")22 }23 app.Commands = []cli.Command{24 {25 Aliases: []string{"r"},26 Action: func(c *cli.Context) error {27 fmt.Println("Readiness check")28 },29 },30 }31 app.Run(os.Args)32}33import (34func main() {35 app := cli.NewApp()36 app.Action = func(c *cli.Context) error {37 fmt.Println("Readiness check")38 }39 app.Commands = []cli.Command{40 {41 Aliases: []string{"r"},42 Action: func(c *cli.Context) error {43 fmt.Println("Readiness check")44 },45 },46 }47 app.Run(os.Args)48}49import (

Full Screen

Full Screen

readinessCheck

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 cmd := exec.Command("ping", "google.com")4 err := cmd.Start()5 if err != nil {6 fmt.Println(err)7 }8 fmt.Println("Waiting for command to finish...")

Full Screen

Full Screen

readinessCheck

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 cmd := &cobra.Command{4 Run: func(cmd *cobra.Command, args []string) {5 fmt.Println("readinessCheck")6 },7 }8 if err := cmd.Execute(); err != nil {9 fmt.Println(err)10 }11}12import (13func main() {14 cmd := &cobra.Command{15 Run: func(cmd *cobra.Command, args []string) {16 fmt.Println("readinessCheck")17 },18 }19 if err := cmd.Execute(); err != nil {20 fmt.Println(err)21 }22}23import (24func main() {25 cmd := &cobra.Command{26 Run: func(cmd *cobra.Command, args []string) {27 fmt.Println("readinessCheck")28 },29 }30 if err := cmd.Execute(); err != nil {31 fmt.Println(err)32 }33}34import (35func main() {36 cmd := &cobra.Command{37 Run: func(cmd *cobra.Command, args []string) {38 fmt.Println("readinessCheck")39 },40 }41 if err := cmd.Execute(); err != nil {42 fmt.Println(err)43 }44}45import (46func main() {47 cmd := &cobra.Command{48 Run: func(cmd *cobra

Full Screen

Full Screen

readinessCheck

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 cmd := exec.Command("cmd", "/C", "echo hello")4 err := cmd.Start()5 if err != nil {6 fmt.Println(err)7 }8 output, err := cmd.Output()9 if err != nil {10 fmt.Println(err)11 }12 fmt.Println(string(output))13}14Go | os/exec CommandOutput()15Go | os/exec CommandContext()16Go | os/exec CommandContext()

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful