Best Gauge code snippet using lang.killRunner
runner.go
Source:runner.go
...84 if done {85 return nil86 }87 case <-time.After(config.PluginKillTimeout()):88 return r.killRunner()89 }90 return nil91}92func (r *MultithreadedRunner) Connection() net.Conn {93 return r.r.connection94}95func (r *MultithreadedRunner) killRunner() error {96 if r.r.Cmd != nil && r.r.Cmd.Process != nil {97 logger.Warningf(true, "Killing runner with PID:%d forcefully", r.r.Cmd.Process.Pid)98 return r.r.Cmd.Process.Kill()99 }100 return nil101}102func (r *MultithreadedRunner) Pid() int {103 return -1104}105func (r *MultithreadedRunner) ExecuteAndGetStatus(message *gauge_messages.Message) *gauge_messages.ProtoExecutionResult {106 return r.r.ExecuteAndGetStatus(message)107}108func (r *MultithreadedRunner) ExecuteMessageWithTimeout(message *gauge_messages.Message) (*gauge_messages.Message, error) {109 r.r.EnsureConnected()110 return conn.GetResponseForMessageWithTimeout(message, r.r.Connection(), config.RunnerRequestTimeout())111}112type RunnerInfo struct {113 Id string114 Name string115 Version string116 Description string117 Run struct {118 Windows []string119 Linux []string120 Darwin []string121 }122 Init struct {123 Windows []string124 Linux []string125 Darwin []string126 }127 Lib string128 Multithreaded bool129 GaugeVersionSupport version.VersionSupport130 LspLangId string131}132func ExecuteInitHookForRunner(language string) error {133 if err := config.SetProjectRoot([]string{}); err != nil {134 return err135 }136 runnerInfo, err := GetRunnerInfo(language)137 if err != nil {138 return err139 }140 command := []string{}141 switch runtime.GOOS {142 case "windows":143 command = runnerInfo.Init.Windows144 break145 case "darwin":146 command = runnerInfo.Init.Darwin147 break148 default:149 command = runnerInfo.Init.Linux150 break151 }152 languageJSONFilePath, err := plugin.GetLanguageJSONFilePath(language)153 runnerDir := filepath.Dir(languageJSONFilePath)154 cmd, err := common.ExecuteCommand(command, runnerDir, os.Stdout, os.Stderr)155 if err != nil {156 return err157 }158 return cmd.Wait()159}160func GetRunnerInfo(language string) (*RunnerInfo, error) {161 runnerInfo := new(RunnerInfo)162 languageJSONFilePath, err := plugin.GetLanguageJSONFilePath(language)163 if err != nil {164 return nil, err165 }166 contents, err := common.ReadFileContents(languageJSONFilePath)167 if err != nil {168 return nil, err169 }170 err = json.Unmarshal([]byte(contents), &runnerInfo)171 if err != nil {172 return nil, err173 }174 return runnerInfo, nil175}176func (r *LanguageRunner) Alive() bool {177 r.mutex.Lock()178 ps := r.Cmd.ProcessState179 r.mutex.Unlock()180 return ps == nil || !ps.Exited()181}182func (r *LanguageRunner) EnsureConnected() bool {183 if r.lostContact {184 return false185 }186 c := r.connection187 c.SetReadDeadline(time.Now())188 var one []byte189 _, err := c.Read(one)190 if err == io.EOF {191 r.lostContact = true192 logger.Fatalf(true, "Connection to runner with Pid %d lost. The runner probably quit unexpectedly. Inspect logs for potential reasons. Error : %s", r.Cmd.Process.Pid, err.Error())193 }194 opErr, ok := err.(*net.OpError)195 if ok && !(opErr.Temporary() || opErr.Timeout()) {196 r.lostContact = true197 logger.Fatalf(true, "Connection to runner with Pid %d lost. The runner probably quit unexpectedly. Inspect logs for potential reasons. Error : %s", r.Cmd.Process.Pid, err.Error())198 }199 var zero time.Time200 c.SetReadDeadline(zero)201 return true202}203func (r *LanguageRunner) IsMultithreaded() bool {204 return r.multiThreaded205}206func (r *LanguageRunner) Kill() error {207 if r.Alive() {208 defer r.connection.Close()209 conn.SendProcessKillMessage(r.connection)210 exited := make(chan bool, 1)211 go func() {212 for {213 if r.Alive() {214 time.Sleep(100 * time.Millisecond)215 } else {216 exited <- true217 return218 }219 }220 }()221 select {222 case done := <-exited:223 if done {224 return nil225 }226 case <-time.After(config.PluginKillTimeout()):227 logger.Warningf(true, "Killing runner with PID:%d forcefully", r.Cmd.Process.Pid)228 return r.killRunner()229 }230 }231 return nil232}233func (r *LanguageRunner) Connection() net.Conn {234 return r.connection235}236func (r *LanguageRunner) killRunner() error {237 return r.Cmd.Process.Kill()238}239func (r *LanguageRunner) Pid() int {240 return r.Cmd.Process.Pid241}242// ExecuteAndGetStatus invokes the runner with a request and waits for response. error is thrown only when unable to connect to runner243func (r *LanguageRunner) ExecuteAndGetStatus(message *gauge_messages.Message) *gauge_messages.ProtoExecutionResult {244 if !r.EnsureConnected() {245 return nil246 }247 response, err := conn.GetResponseForMessageWithTimeout(message, r.connection, 0)248 if err != nil {249 return &gauge_messages.ProtoExecutionResult{Failed: true, ErrorMessage: err.Error()}250 }251 if response.GetMessageType() == gauge_messages.Message_ExecutionStatusResponse {252 executionResult := response.GetExecutionStatusResponse().GetExecutionResult()253 if executionResult == nil {254 errMsg := "ProtoExecutionResult obtained is nil"255 logger.Errorf(true, errMsg)256 return errorResult(errMsg)257 }258 return executionResult259 }260 errMsg := fmt.Sprintf("Expected ExecutionStatusResponse. Obtained: %s", response.GetMessageType())261 logger.Errorf(true, errMsg)262 return errorResult(errMsg)263}264func (r *LanguageRunner) ExecuteMessageWithTimeout(message *gauge_messages.Message) (*gauge_messages.Message, error) {265 r.EnsureConnected()266 return conn.GetResponseForMessageWithTimeout(message, r.Connection(), config.RunnerRequestTimeout())267}268func errorResult(message string) *gauge_messages.ProtoExecutionResult {269 return &gauge_messages.ProtoExecutionResult{Failed: true, ErrorMessage: message, RecoverableError: false}270}271func runRunnerCommand(manifest *manifest.Manifest, port string, debug bool, outputStreamWriter io.Writer) (*exec.Cmd, *RunnerInfo, error) {272 var r RunnerInfo273 runnerDir, err := getLanguageJSONFilePath(manifest, &r)274 if err != nil {275 return nil, nil, err276 }277 compatibilityErr := version.CheckCompatibility(version.CurrentGaugeVersion, &r.GaugeVersionSupport)278 if compatibilityErr != nil {279 return nil, nil, fmt.Errorf("Compatibility error. %s", compatibilityErr.Error())280 }281 command := getOsSpecificCommand(r)282 env := getCleanEnv(port, os.Environ(), debug, getPluginPaths())283 env = append(env, fmt.Sprintf("GAUGE_UNIQUE_INSTALLATION_ID=%s", config.UniqueID()))284 env = append(env, fmt.Sprintf("GAUGE_TELEMETRY_ENABLED=%v", config.TelemetryEnabled()))285 cmd, err := common.ExecuteCommandWithEnv(command, runnerDir, outputStreamWriter, outputStreamWriter, env)286 return cmd, &r, err287}288// Looks for a runner configuration inside the runner directory289// finds the runner configuration matching to the manifest and executes the commands for the current OS290func StartRunner(manifest *manifest.Manifest, port string, outputStreamWriter io.Writer, killChannel chan bool, debug bool) (*LanguageRunner, error) {291 cmd, r, err := runRunnerCommand(manifest, port, debug, outputStreamWriter)292 if err != nil {293 return nil, err294 }295 go func() {296 select {297 case <-killChannel:298 cmd.Process.Kill()299 }300 }()301 // Wait for the process to exit so we will get a detailed error message302 errChannel := make(chan error)303 testRunner := &LanguageRunner{Cmd: cmd, errorChannel: errChannel, mutex: &sync.Mutex{}, multiThreaded: r.Multithreaded}304 testRunner.waitAndGetErrorMessage()305 return testRunner, nil306}307func getPluginPaths() (paths []string) {308 for _, p := range plugin.PluginsWithoutScope() {309 paths = append(paths, p.Path)310 }311 return312}313func getLanguageJSONFilePath(manifest *manifest.Manifest, r *RunnerInfo) (string, error) {314 languageJSONFilePath, err := plugin.GetLanguageJSONFilePath(manifest.Language)315 if err != nil {316 return "", err317 }318 contents, err := common.ReadFileContents(languageJSONFilePath)319 if err != nil {320 return "", err321 }322 err = json.Unmarshal([]byte(contents), r)323 if err != nil {324 return "", err325 }326 return filepath.Dir(languageJSONFilePath), nil327}328func (r *LanguageRunner) waitAndGetErrorMessage() {329 go func() {330 pState, err := r.Cmd.Process.Wait()331 r.mutex.Lock()332 r.Cmd.ProcessState = pState333 r.mutex.Unlock()334 if err != nil {335 logger.Debugf(true, "Runner exited with error: %s", err)336 r.errorChannel <- fmt.Errorf("Runner exited with error: %s\n", err.Error())337 }338 if !pState.Success() {339 r.errorChannel <- fmt.Errorf("Runner with pid %d quit unexpectedly(%s).", pState.Pid(), pState.String())340 }341 }()342}343func getCleanEnv(port string, env []string, debug bool, pathToAdd []string) []string {344 isPresent := false345 for i, k := range env {346 key := strings.TrimSpace(strings.Split(k, "=")[0])347 //clear environment variable common.GaugeInternalPortEnvName348 if key == common.GaugeInternalPortEnvName {349 isPresent = true350 env[i] = common.GaugeInternalPortEnvName + "=" + port351 } else if strings.ToUpper(key) == "PATH" {352 path := os.Getenv("PATH")353 for _, p := range pathToAdd {354 path += string(os.PathListSeparator) + p355 }356 env[i] = "PATH=" + path357 }358 }359 if !isPresent {360 env = append(env, common.GaugeInternalPortEnvName+"="+port)361 }362 if debug {363 env = append(env, "debugging=true")364 }365 return env366}367func getOsSpecificCommand(r RunnerInfo) []string {368 command := []string{}369 switch runtime.GOOS {370 case "windows":371 command = r.Run.Windows372 break373 case "darwin":374 command = r.Run.Darwin375 break376 default:377 command = r.Run.Linux378 break379 }380 return command381}382type StartChannels struct {383 // this will hold the runner384 RunnerChan chan Runner385 // this will hold the error while creating runner386 ErrorChan chan error387 // this holds a flag based on which the runner is terminated388 KillChan chan bool389}390func Start(manifest *manifest.Manifest, outputStreamWriter io.Writer, killChannel chan bool, debug bool) (Runner, error) {391 port, err := conn.GetPortFromEnvironmentVariable(common.GaugePortEnvName)392 if err != nil {393 port = 0394 }395 handler, err := conn.NewGaugeConnectionHandler(port, nil)396 if err != nil {397 return nil, err398 }399 runner, err := StartRunner(manifest, strconv.Itoa(handler.ConnectionPortNumber()), outputStreamWriter, killChannel, debug)400 if err != nil {401 return nil, err402 }403 err = connect(handler, runner)404 return runner, err405}406func connect(h *conn.GaugeConnectionHandler, runner *LanguageRunner) error {407 connection, connErr := h.AcceptConnection(config.RunnerConnectionTimeout(), runner.errorChannel)408 if connErr != nil {409 logger.Debugf(true, "Runner connection error: %s", connErr)410 if err := runner.killRunner(); err != nil {411 logger.Debugf(true, "Error while killing runner: %s", err)412 }413 return connErr414 }415 runner.connection = connection416 return nil417}...
server.go
Source:server.go
...67 }68 go publishDiagnostics(ctx, conn)69 return nil, nil70 case "shutdown":71 return nil, killRunner()72 case "exit":73 if c, ok := conn.(*jsonrpc2.Conn); ok {74 err := c.Close()75 if err != nil {76 logError(req, err.Error())77 }78 os.Exit(0)79 }80 return nil, nil81 case "$/cancelRequest":82 return nil, nil83 case "textDocument/didOpen":84 err := documentOpened(req, ctx, conn)85 if err != nil {86 logDebug(req, err.Error())87 }88 return nil, err89 case "textDocument/didClose":90 err := documentClosed(req, ctx, conn)91 if err != nil {92 logDebug(req, err.Error())93 }94 return nil, err95 case "textDocument/didChange":96 err := documentChange(req, ctx, conn)97 if err != nil {98 logDebug(req, err.Error())99 }100 return nil, err101 case "workspace/didChangeWatchedFiles":102 err := documentChangeWatchedFiles(req, ctx, conn)103 if err != nil {104 logDebug(req, err.Error())105 }106 return nil, err107 case "textDocument/completion":108 val, err := completion(req)109 if err != nil {110 logDebug(req, err.Error())111 }112 return val, err113 case "completionItem/resolve":114 val, err := resolveCompletion(req)115 if err != nil {116 logDebug(req, err.Error())117 }118 return val, err119 case "textDocument/definition":120 val, err := definition(req)121 if err != nil {122 logDebug(req, err.Error())123 if e := showErrorMessageOnClient(ctx, conn, err); e != nil {124 return nil, fmt.Errorf("unable to send '%s' error to LSP server. %s", err.Error(), e.Error())125 }126 }127 return val, err128 case "textDocument/formatting":129 data, err := format(req)130 if err != nil {131 logDebug(req, err.Error())132 e := showErrorMessageOnClient(ctx, conn, err)133 if e != nil {134 return nil, fmt.Errorf("unable to send '%s' error to LSP server. %s", err.Error(), e.Error())135 }136 }137 return data, err138 case "textDocument/codeLens":139 val, err := codeLenses(req)140 if err != nil {141 logDebug(req, err.Error())142 }143 return val, err144 case "textDocument/codeAction":145 val, err := codeActions(req)146 if err != nil {147 logDebug(req, err.Error())148 }149 return val, err150 case "textDocument/rename":151 result, err := rename(ctx, conn, req)152 if err != nil {153 logDebug(req, err.Error())154 e := showErrorMessageOnClient(ctx, conn, err)155 if e != nil {156 return nil, fmt.Errorf("unable to send '%s' error to LSP server. %s", err.Error(), e.Error())157 }158 return nil, err159 }160 return result, nil161 case "textDocument/documentSymbol":162 val, err := documentSymbols(req)163 if err != nil {164 logDebug(req, err.Error())165 }166 return val, err167 case "workspace/symbol":168 val, err := workspaceSymbols(req)169 if err != nil {170 logDebug(req, err.Error())171 }172 return val, err173 case "gauge/stepReferences":174 val, err := stepReferences(req)175 if err != nil {176 logDebug(req, err.Error())177 }178 return val, err179 case "gauge/stepValueAt":180 val, err := stepValueAt(req)181 if err != nil {182 logDebug(req, err.Error())183 }184 return val, err185 case "gauge/scenarios":186 val, err := scenarios(req)187 if err != nil {188 logDebug(req, err.Error())189 }190 return val, err191 case "gauge/getImplFiles":192 val, err := getImplFiles(req)193 if err != nil {194 logDebug(req, err.Error())195 }196 return val, err197 case "gauge/putStubImpl":198 if err := sendSaveFilesRequest(ctx, conn); err != nil {199 logDebug(req, err.Error())200 e := showErrorMessageOnClient(ctx, conn, err)201 if e != nil {202 return nil, fmt.Errorf("unable to send '%s' error to LSP server. %s", err.Error(), e.Error())203 }204 return nil, err205 }206 val, err := putStubImpl(req)207 if err != nil {208 logDebug(req, err.Error())209 }210 return val, err211 case "gauge/specs":212 val, err := specs()213 if err != nil {214 logDebug(req, err.Error())215 }216 return val, err217 case "gauge/executionStatus":218 val, err := execution.ReadLastExecutionResult()219 if err != nil {220 logDebug(req, err.Error())221 }222 return val, err223 case "gauge/generateConcept":224 if err := sendSaveFilesRequest(ctx, conn); err != nil {225 e := showErrorMessageOnClient(ctx, conn, err)226 if e != nil {227 return nil, fmt.Errorf("unable to send '%s' error to LSP server. %s", err.Error(), e.Error())228 }229 return nil, err230 }231 return generateConcept(req)232 case "gauge/getRunnerLanguage":233 return lRunner.lspID, nil234 case "gauge/specDirs":235 return provider.GetSpecDirs(), nil236 default:237 return nil, nil238 }239}240func cacheInitializeParams(req *jsonrpc2.Request) error {241 var params InitializeParams242 var err error243 if err = json.Unmarshal(*req.Params, ¶ms); err != nil {244 return err245 }246 clientCapabilities = params.Capabilities247 return nil248}249func startLsp(logLevel string) (context.Context, *jsonrpc2.Conn) {250 logInfo(nil, "LangServer: reading on stdin, writing on stdout")251 var connOpt []jsonrpc2.ConnOpt252 if logLevel == "debug" {253 connOpt = append(connOpt, jsonrpc2.LogMessages(log.New(lspWriter{}, "", 0)))254 }255 ctx := context.Background()256 return ctx, jsonrpc2.NewConn(ctx, jsonrpc2.NewBufferedStream(stdRWC{}, jsonrpc2.VSCodeObjectCodec{}), newHandler(), connOpt...)257}258func initializeRunner() error {259 id, err := getLanguageIdentifier()260 if err != nil || id == "" {261 e := fmt.Errorf("There are version incompatibilities between Gauge and it's plugins in this project. Some features will not work as expected.")262 logDebug(nil, "%s", e.Error())263 return e264 }265 err = startRunner()266 if err != nil {267 logDebug(nil, "%s\nSome of the gauge lsp feature will not work as expected.", err.Error())268 return err269 }270 lRunner.lspID = id271 return nil272}273func Start(p infoProvider, logLevel string) {274 provider = p275 provider.Init()276 err := initializeRunner()277 ctx, conn := startLsp(logLevel)278 if err != nil {279 _ = showErrorMessageOnClient(ctx, conn, err)280 }281 initialize(ctx, conn)282 <-conn.DisconnectNotify()283 if killRunner() != nil {284 logInfo(nil, "failed to kill runner with pid %d", lRunner.runner.Pid())285 }286 logInfo(nil, "Connection closed")287}288func recoverPanic(req *jsonrpc2.Request) {289 if r := recover(); r != nil {290 logFatal(req, "%v\n%s", r, string(debug.Stack()))291 }292}...
killRunner
Using AI Code Generation
1import "fmt"2func main() {3 fmt.Println("Hello, world.")4}5import "fmt"6func main() {7 fmt.Println("Hello, world.")8}9import "fmt"10func main() {11 fmt.Println("Hello, world.")12}13import "fmt"14func main() {15 fmt.Println("Hello, world.")16}17import "fmt"18func main() {19 fmt.Println("Hello, world.")20}21import "fmt"22func main() {23 fmt.Println("Hello, world.")24}25import "fmt"26func main() {27 fmt.Println("Hello, world.")28}29import "fmt"30func main() {31 fmt.Println("Hello, world.")32}33import "fmt"34func main() {35 fmt.Println("Hello, world.")36}37import "fmt"38func main() {39 fmt.Println("Hello, world.")40}41import "fmt"42func main() {43 fmt.Println("Hello, world.")44}45import "fmt"46func main() {47 fmt.Println("Hello, world.")48}49import "fmt"50func main() {51 fmt.Println("Hello, world.")52}53import
killRunner
Using AI Code Generation
1import "fmt"2func main() {3 l.killRunner()4 fmt.Println("1.go")5}6import "fmt"7func main() {8 l.killRunner()9 fmt.Println("2.go")10}11import "fmt"12func main() {13 l.killRunner()14 fmt.Println("3.go")15}16import "fmt"17func main() {18 l.killRunner()19 fmt.Println("4.go")20}21import "fmt"22func main() {23 l.killRunner()24 fmt.Println("5.go")25}26import "fmt"27func main() {28 l.killRunner()29 fmt.Println("6.go")30}31import "fmt"32func main() {33 l.killRunner()34 fmt.Println("7.go")35}36import "fmt"37func main() {38 l.killRunner()39 fmt.Println("8.go")40}41import "fmt"42func main() {43 l.killRunner()44 fmt.Println("9.go")45}46import "fmt"47func main() {48 l.killRunner()49 fmt.Println("10.go")50}51import "fmt"52func main() {53 l.killRunner()54 fmt.Println("11.go")
killRunner
Using AI Code Generation
1import (2const (3var (4 red = color.RGBA{0xff, 0x00, 0x00, 0xff}5 green = color.RGBA{0x00, 0xff, 0x00, 0xff}6 blue = color.RGBA{0x00, 0x00, 0xff, 0xff}7 yellow = color.RGBA{0xff, 0xff, 0x00, 0xff}8 white = color.RGBA{0xff, 0xff, 0xff, 0xff}9 black = color.RGBA{0x00, 0x00, 0x00, 0xff}10type Game struct {
killRunner
Using AI Code Generation
1import (2func main() {3 langObj.killRunner()4}5import (6func main() {7 langObj.killRunner()8}9import (10func main() {11 langObj.killRunner()12}13import (14func main() {15 langObj.killRunner()16}17import (18func main() {19 langObj.killRunner()20}21import (22func main() {23 langObj.killRunner()24}25import (26func main() {27 langObj.killRunner()28}29import (30func main() {31 langObj.killRunner()32}33import (34func main() {35 langObj.killRunner()36}37import (
killRunner
Using AI Code Generation
1import (2func main() {3 lang := NewLang()4 lang.Start()5 lang.KillRunner()6 time.Sleep(2 * time.Second)7 lang.Start()8 time.Sleep(2 * time.Second)9 lang.KillRunner()10}11import (12type Lang struct {13}14func NewLang() *Lang {15 return &Lang{}16}17func (l *Lang) Start() {18 l.runner = NewRunner()19 l.cmd = exec.Command("go", "run", "2.go")20 l.cmd.Start()21}22func (l *Lang) KillRunner() {23 l.runner.Kill()24}25import (26type Runner struct {27}28func NewRunner() *Runner {29 return &Runner{}30}31func (r *Runner) Kill() {32 r.cmd.Process.Kill()33}34func (r *Runner) Write(p []byte) (n int, err error) {35 fmt.Println(string(p))36 return len(p), nil37}38import (39type Runner struct {40}41func NewRunner() *Runner {42 return &Runner{}43}44func (r *Runner) Kill() {45 r.cmd.Process.Kill()46}47func (r *Runner) Write(p []byte
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!!