How to use killGrpcProcess method of plugin Package

Best Gauge code snippet using plugin.killGrpcProcess

plugin.go

Source:plugin.go Github

copy

Full Screen

...54 ps := p.pluginCmd.ProcessState55 p.mutex.Unlock()56 return ps == nil || !ps.Exited()57}58func (p *plugin) killGrpcProcess() error {59 var m *gauge_messages.Empty60 var err error61 if p.ReporterClient != nil {62 m, err = p.ReporterClient.Kill(context.Background(), &gauge_messages.KillProcessRequest{})63 } else if p.DocumenterClient != nil {64 m, err = p.DocumenterClient.Kill(context.Background(), &gauge_messages.KillProcessRequest{})65 }66 if m == nil || err != nil {67 errStatus, _ := status.FromError(err)68 if errStatus.Code() == codes.Unavailable {69 // Ref https://www.grpc.io/docs/guides/error/#general-errors70 // GRPC_STATUS_UNAVAILABLE is thrown when Server is shutting down. Ignore it here.71 return nil72 }73 return err74 }75 if p.gRPCConn == nil && p.pluginCmd == nil {76 return nil77 }78 defer p.gRPCConn.Close()79 if isProcessRunning(p) {80 exited := make(chan bool, 1)81 go func() {82 for {83 if isProcessRunning(p) {84 time.Sleep(100 * time.Millisecond)85 } else {86 exited <- true87 return88 }89 }90 }()91 select {92 case done := <-exited:93 if done {94 logger.Debugf(true, "Runner with PID:%d has exited", p.pluginCmd.Process.Pid)95 return nil96 }97 case <-time.After(config.PluginKillTimeout()):98 logger.Warningf(true, "Killing runner with PID:%d forcefully", p.pluginCmd.Process.Pid)99 return p.pluginCmd.Process.Kill()100 }101 }102 return nil103}104func (p *plugin) kill(wg *sync.WaitGroup) error {105 defer wg.Done()106 if p.gRPCConn != nil && p.ReporterClient != nil {107 return p.killGrpcProcess()108 }109 if isProcessRunning(p) {110 defer p.connection.Close()111 p.killTimer = time.NewTimer(config.PluginKillTimeout())112 err := conn.SendProcessKillMessage(p.connection)113 if err != nil {114 logger.Warningf(true, "Error while killing plugin %s : %s ", p.descriptor.Name, err.Error())115 }116 exited := make(chan bool, 1)117 go func() {118 for {119 if isProcessRunning(p) {120 time.Sleep(100 * time.Millisecond)121 } else {122 exited <- true123 return124 }125 }126 }()127 select {128 case <-exited:129 if !p.killTimer.Stop() {130 <-p.killTimer.C131 }132 logger.Debugf(true, "Plugin [%s] with pid [%d] has exited", p.descriptor.Name, p.pluginCmd.Process.Pid)133 case <-p.killTimer.C:134 logger.Warningf(true, "Plugin [%s] with pid [%d] did not exit after %.2f seconds. Forcefully killing it.", p.descriptor.Name, p.pluginCmd.Process.Pid, config.PluginKillTimeout().Seconds())135 err := p.pluginCmd.Process.Kill()136 if err != nil {137 logger.Warningf(true, "Error while killing plugin %s : %s ", p.descriptor.Name, err.Error())138 }139 return err140 }141 }142 return nil143}144// IsPluginInstalled checks if given plugin with specific version is installed or not.145func IsPluginInstalled(pluginName, pluginVersion string) bool {146 pluginsInstallDir, err := common.GetPluginsInstallDir(pluginName)147 if err != nil {148 return false149 }150 thisPluginDir := filepath.Join(pluginsInstallDir, pluginName)151 if !common.DirExists(thisPluginDir) {152 return false153 }154 if pluginVersion != "" {155 return common.FileExists(filepath.Join(thisPluginDir, pluginVersion, common.PluginJSONFile))156 }157 return true158}159func getPluginJSONPath(pluginName, pluginVersion string) (string, error) {160 if !IsPluginInstalled(pluginName, pluginVersion) {161 plugin := strings.TrimSpace(fmt.Sprintf("%s %s", pluginName, pluginVersion))162 return "", fmt.Errorf("Plugin %s is not installed", plugin)163 }164 pluginInstallDir, err := GetInstallDir(pluginName, "")165 if err != nil {166 return "", err167 }168 return filepath.Join(pluginInstallDir, common.PluginJSONFile), nil169}170// GetPluginDescriptor return the information about the plugin including name, id, commands to start etc.171func GetPluginDescriptor(pluginID, pluginVersion string) (*PluginDescriptor, error) {172 pluginJSON, err := getPluginJSONPath(pluginID, pluginVersion)173 if err != nil {174 return nil, err175 }176 return GetPluginDescriptorFromJSON(pluginJSON)177}178func GetPluginDescriptorFromJSON(pluginJSON string) (*PluginDescriptor, error) {179 pluginJSONContents, err := common.ReadFileContents(pluginJSON)180 if err != nil {181 return nil, err182 }183 var pd PluginDescriptor184 if err = json.Unmarshal([]byte(pluginJSONContents), &pd); err != nil {185 return nil, fmt.Errorf("%s: %s", pluginJSON, err.Error())186 }187 pd.pluginPath = filepath.Dir(pluginJSON)188 return &pd, nil189}190func startPlugin(pd *PluginDescriptor, action pluginScope) (*plugin, error) {191 var command []string192 switch runtime.GOOS {193 case "windows":194 command = pd.Command.Windows195 case "darwin":196 command = pd.Command.Darwin197 default:198 command = pd.Command.Linux199 }200 if len(command) == 0 {201 return nil, fmt.Errorf("Platform specific command not specified: %s.", runtime.GOOS)202 }203 if pd.hasCapability(gRPCSupportCapability) {204 return startGRPCPlugin(pd, command)205 }206 return startLegacyPlugin(pd, command)207}208func startGRPCPlugin(pd *PluginDescriptor, command []string) (*plugin, error) {209 portChan := make(chan string)210 writer := &logger.LogWriter{211 Stderr: logger.NewCustomWriter(portChan, os.Stderr, pd.ID, true),212 Stdout: logger.NewCustomWriter(portChan, os.Stdout, pd.ID, false),213 }214 cmd, err := common.ExecuteCommand(command, pd.pluginPath, writer.Stdout, writer.Stderr)215 go func() {216 err = cmd.Wait()217 if err != nil {218 logger.Errorf(true, "Error occurred while waiting for plugin process to finish.\nError : %s", err.Error())219 }220 }()221 if err != nil {222 return nil, err223 }224 var port string225 select {226 case port = <-portChan:227 close(portChan)228 case <-time.After(config.PluginConnectionTimeout()):229 return nil, fmt.Errorf("timed out connecting to %s", pd.ID)230 }231 logger.Debugf(true, "Attempting to connect to grpc server at port: %s", port)232 gRPCConn, err := grpc.Dial(fmt.Sprintf("%s:%s", "127.0.0.1", port),233 grpc.WithTransportCredentials(insecure.NewCredentials()),234 grpc.WithDefaultCallOptions(grpc.MaxCallSendMsgSize(1024*1024*1024), grpc.MaxCallRecvMsgSize(1024*1024*1024)),235 grpc.WithBlock())236 if err != nil {237 return nil, err238 }239 plugin := &plugin{240 pluginCmd: cmd,241 descriptor: pd,242 gRPCConn: gRPCConn,243 mutex: &sync.Mutex{},244 }245 if pd.hasScope(docScope) {246 plugin.DocumenterClient = gauge_messages.NewDocumenterClient(gRPCConn)247 } else {248 plugin.ReporterClient = gauge_messages.NewReporterClient(gRPCConn)249 }250 logger.Debugf(true, "Successfully made the connection with plugin with port: %s", port)251 return plugin, nil252}253func startLegacyPlugin(pd *PluginDescriptor, command []string) (*plugin, error) {254 writer := logger.NewLogWriter(pd.ID, true, 0)255 cmd, err := common.ExecuteCommand(command, pd.pluginPath, writer.Stdout, writer.Stderr)256 if err != nil {257 return nil, err258 }259 var mutex = &sync.Mutex{}260 go func() {261 pState, _ := cmd.Process.Wait()262 mutex.Lock()263 cmd.ProcessState = pState264 mutex.Unlock()265 }()266 plugin := &plugin{pluginCmd: cmd, descriptor: pd, mutex: mutex}267 return plugin, nil268}269func SetEnvForPlugin(action pluginScope, pd *PluginDescriptor, m *manifest.Manifest, pluginEnvVars map[string]string) error {270 pluginEnvVars[fmt.Sprintf("%s_action", pd.ID)] = string(action)271 pluginEnvVars["test_language"] = m.Language272 return setEnvironmentProperties(pluginEnvVars)273}274func setEnvironmentProperties(properties map[string]string) error {275 for k, v := range properties {276 if err := common.SetEnvVariable(k, v); err != nil {277 return err278 }279 }280 return nil281}282func IsPluginAdded(m *manifest.Manifest, descriptor *PluginDescriptor) bool {283 for _, pluginID := range m.Plugins {284 if pluginID == descriptor.ID {285 return true286 }287 }288 return false289}290func startPluginsForExecution(m *manifest.Manifest) (Handler, []string) {291 var warnings []string292 handler := &GaugePlugins{}293 envProperties := make(map[string]string)294 for _, pluginID := range m.Plugins {295 pd, err := GetPluginDescriptor(pluginID, "")296 if err != nil {297 warnings = append(warnings, fmt.Sprintf("Unable to start plugin %s. %s. To install, run `gauge install %s`.", pluginID, err.Error(), pluginID))298 continue299 }300 compatibilityErr := version.CheckCompatibility(version.CurrentGaugeVersion, &pd.GaugeVersionSupport)301 if compatibilityErr != nil {302 warnings = append(warnings, fmt.Sprintf("Compatible %s plugin version to current Gauge version %s not found", pd.Name, version.CurrentGaugeVersion))303 continue304 }305 if pd.hasScope(executionScope) {306 gaugeConnectionHandler, err := conn.NewGaugeConnectionHandler(0, nil)307 if err != nil {308 warnings = append(warnings, err.Error())309 continue310 }311 envProperties[pluginConnectionPortEnv] = strconv.Itoa(gaugeConnectionHandler.ConnectionPortNumber())312 prop, err := common.GetGaugeConfigurationFor(common.GaugePropertiesFile)313 if err != nil {314 warnings = append(warnings, fmt.Sprintf("Unable to read Gauge configuration. %s", err.Error()))315 continue316 }317 envProperties["plugin_kill_timeout"] = prop["plugin_kill_timeout"]318 err = SetEnvForPlugin(executionScope, pd, m, envProperties)319 if err != nil {320 warnings = append(warnings, fmt.Sprintf("Error setting environment for plugin %s %s. %s", pd.Name, pd.Version, err.Error()))321 continue322 }323 logger.Debugf(true, "Starting %s plugin", pd.Name)324 plugin, err := startPlugin(pd, executionScope)325 if err != nil {326 warnings = append(warnings, fmt.Sprintf("Error starting plugin %s %s. %s", pd.Name, pd.Version, err.Error()))327 continue328 }329 if plugin.gRPCConn != nil {330 handler.addPlugin(pluginID, plugin)331 continue332 }333 pluginConnection, err := gaugeConnectionHandler.AcceptConnection(config.PluginConnectionTimeout(), make(chan error))334 if err != nil {335 warnings = append(warnings, fmt.Sprintf("Error starting plugin %s %s. Failed to connect to plugin. %s", pd.Name, pd.Version, err.Error()))336 err := plugin.pluginCmd.Process.Kill()337 if err != nil {338 logger.Errorf(false, "unable to kill plugin %s: %s", plugin.descriptor.Name, err.Error())339 }340 continue341 }342 logger.Debugf(true, "Established connection to %s plugin", pd.Name)343 plugin.connection = pluginConnection344 handler.addPlugin(pluginID, plugin)345 }346 }347 return handler, warnings348}349func GenerateDoc(pluginName string, specDirs []string, startAPIFunc func([]string) int) {350 pd, err := GetPluginDescriptor(pluginName, "")351 if err != nil {352 logger.Fatalf(true, "Error starting plugin %s. Failed to get plugin.json. %s. To install, run `gauge install %s`.", pluginName, err.Error(), pluginName)353 }354 if err := version.CheckCompatibility(version.CurrentGaugeVersion, &pd.GaugeVersionSupport); err != nil {355 logger.Fatalf(true, "Compatible %s plugin version to current Gauge version %s not found", pd.Name, version.CurrentGaugeVersion)356 }357 if !pd.hasScope(docScope) {358 logger.Fatalf(true, "Invalid plugin name: %s, this plugin cannot generate documentation.", pd.Name)359 }360 var sources []string361 for _, src := range specDirs {362 path, _ := filepath.Abs(src)363 sources = append(sources, path)364 }365 os.Setenv("GAUGE_SPEC_DIRS", strings.Join(sources, "||"))366 os.Setenv("GAUGE_PROJECT_ROOT", config.ProjectRoot)367 if pd.hasCapability(gRPCSupportCapability) {368 p, err := startPlugin(pd, docScope)369 if err != nil {370 logger.Fatalf(true, " %s %s. %s", pd.Name, pd.Version, err.Error())371 }372 _, err = p.DocumenterClient.GenerateDocs(context.Background(), getSpecDetails(specDirs))373 grpcErr := p.killGrpcProcess()374 if grpcErr != nil {375 logger.Errorf(false, "Unable to kill plugin %s : %s", p.descriptor.Name, grpcErr.Error())376 }377 if err != nil {378 logger.Fatalf(true, "Failed to generate docs. %s", err.Error())379 }380 } else {381 port := startAPIFunc(specDirs)382 err := os.Setenv(common.APIPortEnvVariableName, strconv.Itoa(port))383 if err != nil {384 logger.Fatalf(true, "Failed to set env GAUGE_API_PORT. %s", err.Error())385 }386 p, err := startPlugin(pd, docScope)387 if err != nil {...

Full Screen

Full Screen

killGrpcProcess

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 p, err := plugin.Open("plugin.so")4 if err != nil {5 panic(err)6 }7 killGrpcProcess, err := p.Lookup("KillGrpcProcess")8 if err != nil {9 panic(err)10 }11 killGrpcProcess.(func())()12 fmt.Println("Process Killed")13}

Full Screen

Full Screen

killGrpcProcess

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 client := plugin.NewClient(&plugin.ClientConfig{4 Cmd: exec.Command("sh", "-c", "go run 2.go"),5 AllowedProtocols: []plugin.Protocol{6 plugin.ProtocolGRPC},7 })8 rpcClient, err := client.Client()9 if err != nil {10 log.Fatal(err)11 }12 raw, err := rpcClient.Dispense("greeter")13 if err != nil {14 log.Fatal(err)15 }16 greeter := raw.(shared.Greeter)17 resp, err := greeter.Greet(context.Background(), &shared.GreetRequest{Name: "World"})18 if err != nil {19 log.Fatal(err)20 }21 fmt.Println(resp.Greeting)22 client.Kill()23 if err := client.Wait(); err != nil {24 if !plugin.IsExitError(err, &exitErr) {25 log.Fatal(err)26 }27 }28 fmt.Printf("Plugin process exited with a non-zero exit code: %v", exitErr.ExitCode())29}30import (

Full Screen

Full Screen

killGrpcProcess

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 client := plugin.NewClient(&plugin.ClientConfig{4 Cmd: exec.Command("/bin/sh", "-c", "sleep 10"),5 AllowedProtocols: []plugin.Protocol{plugin.ProtocolGRPC},6 })7 defer client.Kill()8 r, err := client.Client()9 if err != nil {10 panic(err)11 }12 raw, err := r.Dispense("killGrpcProcess")13 if err != nil {14 panic(err)15 }16 killGrpcProcess := raw.(KillGrpcProcess)17 killGrpcProcess.KillGrpcProcess()18}19import (20func main() {21 client := plugin.NewClient(&plugin.ClientConfig{22 Cmd: exec.Command("/bin/sh", "-c", "sleep 10"),23 AllowedProtocols: []plugin.Protocol{plugin.ProtocolGRPC},24 })25 defer client.Kill()26 r, err := client.Client()27 if err != nil {28 panic(err)29 }30 raw, err := r.Dispense("killGrpcProcess")31 if err != nil {32 panic(err)33 }34 killGrpcProcess := raw.(KillGrpcProcess)35 killGrpcProcess.KillGrpcProcess()36}37import (38func main() {

Full Screen

Full Screen

killGrpcProcess

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 client, err := rpc.DialHTTP("tcp", "localhost:1234")4 if err != nil {5 fmt.Println("Error in dialing:", err)6 }7 err = client.Call("Plugin.KillGrpcProcess", "Hello", &reply)8 if err != nil {9 fmt.Println("Error in KillGrpcProcess:", err)10 }11 fmt.Println(reply)12}

Full Screen

Full Screen

killGrpcProcess

Using AI Code Generation

copy

Full Screen

1func main() {2 plugin := new(Plugin)3 err := plugin.Load("plugin.so")4 if err != nil {5 panic(err)6 }7 killGrpcProcess := plugin.Lookup("KillGrpcProcess")8 killGrpcProcess.(func())()9}10import (11type Plugin struct {12}13func (p *Plugin) Load(path string) error {14}15func (p *Plugin) Lookup(name string) interface{} {16 switch name {17 }18}19func (p *Plugin) KillGrpcProcess() {20 cmd := exec.Command("pkill", "grpc")21 err := cmd.Run()22 if err != nil {23 fmt.Println("Failed to kill grpc process")24 os.Exit(1)25 }26 fmt.Println("grpc proc

Full Screen

Full Screen

killGrpcProcess

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 p, err := plugin.Open("myPlugin.so")4 if err != nil {5 log.Fatal(err)6 }7 killGrpcProcess, err := p.Lookup("killGrpcProcess")8 if err != nil {9 log.Fatal(err)10 }11 killGrpcProcess.(func())()12 fmt.Println("Grpc process killed successfully")13}

Full Screen

Full Screen

killGrpcProcess

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 log.Println("main method called")4 killgrpcplugin.KillGrpcProcess()5}6import (7func main() {8 log.Println("main method called")9 killgrpcplugin.KillGrpcProcess()10}

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