How to use isProcessRunning method of plugin Package

Best Gauge code snippet using plugin.isProcessRunning

plugin.go

Source:plugin.go Github

copy

Full Screen

...48 pluginCmd *exec.Cmd49 descriptor *PluginDescriptor50 killTimer *time.Timer51}52func isProcessRunning(p *plugin) bool {53 p.mutex.Lock()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 {388 logger.Fatalf(true, " %s %s. %s", pd.Name, pd.Version, err.Error())389 }390 for isProcessRunning(p) {391 }392 }393}394func (p *plugin) invokeService(m *gauge_messages.Message) error {395 ctx := context.Background()396 var err error397 switch m.GetMessageType() {398 case gauge_messages.Message_SuiteExecutionResult:399 _, err = p.ReporterClient.NotifySuiteResult(ctx, m.GetSuiteExecutionResult())400 case gauge_messages.Message_ExecutionStarting:401 _, err = p.ReporterClient.NotifyExecutionStarting(ctx, m.GetExecutionStartingRequest())402 case gauge_messages.Message_ExecutionEnding:403 _, err = p.ReporterClient.NotifyExecutionEnding(ctx, m.GetExecutionEndingRequest())404 case gauge_messages.Message_SpecExecutionEnding:...

Full Screen

Full Screen

runner.go

Source:runner.go Github

copy

Full Screen

1// Copyright 2015 ThoughtWorks, Inc.2// This file is part of Gauge.3// Gauge is free software: you can redistribute it and/or modify4// it under the terms of the GNU General Public License as published by5// the Free Software Foundation, either version 3 of the License, or6// (at your option) any later version.7// Gauge is distributed in the hope that it will be useful,8// but WITHOUT ANY WARRANTY; without even the implied warranty of9// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the10// GNU General Public License for more details.11// You should have received a copy of the GNU General Public License12// along with Gauge. If not, see <http://www.gnu.org/licenses/>.13package runner14import (15 "encoding/json"16 "fmt"17 "net"18 "os"19 "os/exec"20 "path/filepath"21 "runtime"22 "strconv"23 "strings"24 "time"25 "sync"26 "github.com/getgauge/common"27 "github.com/getgauge/gauge/config"28 "github.com/getgauge/gauge/conn"29 "github.com/getgauge/gauge/gauge_messages"30 "github.com/getgauge/gauge/logger"31 "github.com/getgauge/gauge/manifest"32 "github.com/getgauge/gauge/plugin"33 "github.com/getgauge/gauge/reporter"34 "github.com/getgauge/gauge/version"35)36type Runner interface {37 ExecuteAndGetStatus(m *gauge_messages.Message) *gauge_messages.ProtoExecutionResult38 IsProcessRunning() bool39 Kill() error40 Connection() net.Conn41 IsMultithreaded() bool42 Pid() int43}44type LanguageRunner struct {45 mutex *sync.Mutex46 Cmd *exec.Cmd47 connection net.Conn48 errorChannel chan error49 multiThreaded bool50}51type MultithreadedRunner struct {52 r *LanguageRunner53}54func (r *MultithreadedRunner) IsProcessRunning() bool {55 if r.r.mutex != nil && r.r.Cmd != nil {56 return r.r.IsProcessRunning()57 }58 return false59}60func (r *MultithreadedRunner) IsMultithreaded() bool {61 return false62}63func (r *MultithreadedRunner) SetConnection(c net.Conn) {64 r.r = &LanguageRunner{connection: c}65}66func (r *MultithreadedRunner) Kill() error {67 defer r.r.connection.Close()68 conn.SendProcessKillMessage(r.r.connection)69 exited := make(chan bool, 1)70 go func() {71 for {72 if r.IsProcessRunning() {73 time.Sleep(100 * time.Millisecond)74 } else {75 exited <- true76 return77 }78 }79 }()80 select {81 case done := <-exited:82 if done {83 return nil84 }85 case <-time.After(config.PluginKillTimeout()):86 return r.killRunner()87 }88 return nil89}90func (r *MultithreadedRunner) Connection() net.Conn {91 return r.r.connection92}93func (r *MultithreadedRunner) killRunner() error {94 if r.r.Cmd != nil && r.r.Cmd.Process != nil {95 logger.Warning("Killing runner with PID:%d forcefully", r.r.Cmd.Process.Pid)96 return r.r.Cmd.Process.Kill()97 }98 return nil99}100func (r *MultithreadedRunner) Pid() int {101 return -1102}103func (r *MultithreadedRunner) ExecuteAndGetStatus(message *gauge_messages.Message) *gauge_messages.ProtoExecutionResult {104 return r.r.ExecuteAndGetStatus(message)105}106type RunnerInfo struct {107 Id string108 Name string109 Version string110 Description string111 Run struct {112 Windows []string113 Linux []string114 Darwin []string115 }116 Init struct {117 Windows []string118 Linux []string119 Darwin []string120 }121 Lib string122 Multithreaded bool123 GaugeVersionSupport version.VersionSupport124}125func ExecuteInitHookForRunner(language string) error {126 if err := config.SetProjectRoot([]string{}); err != nil {127 return err128 }129 runnerInfo, err := GetRunnerInfo(language)130 if err != nil {131 return err132 }133 command := []string{}134 switch runtime.GOOS {135 case "windows":136 command = runnerInfo.Init.Windows137 break138 case "darwin":139 command = runnerInfo.Init.Darwin140 break141 default:142 command = runnerInfo.Init.Linux143 break144 }145 languageJSONFilePath, err := plugin.GetLanguageJSONFilePath(language)146 runnerDir := filepath.Dir(languageJSONFilePath)147 cmd, err := common.ExecuteCommand(command, runnerDir, os.Stdout, os.Stderr)148 if err != nil {149 return err150 }151 return cmd.Wait()152}153func GetRunnerInfo(language string) (*RunnerInfo, error) {154 runnerInfo := new(RunnerInfo)155 languageJSONFilePath, err := plugin.GetLanguageJSONFilePath(language)156 if err != nil {157 return nil, err158 }159 contents, err := common.ReadFileContents(languageJSONFilePath)160 if err != nil {161 return nil, err162 }163 err = json.Unmarshal([]byte(contents), &runnerInfo)164 if err != nil {165 return nil, err166 }167 return runnerInfo, nil168}169func (r *LanguageRunner) IsProcessRunning() bool {170 r.mutex.Lock()171 ps := r.Cmd.ProcessState172 r.mutex.Unlock()173 return ps == nil || !ps.Exited()174}175func (r *LanguageRunner) IsMultithreaded() bool {176 return r.multiThreaded177}178func (r *LanguageRunner) Kill() error {179 if r.IsProcessRunning() {180 defer r.connection.Close()181 conn.SendProcessKillMessage(r.connection)182 exited := make(chan bool, 1)183 go func() {184 for {185 if r.IsProcessRunning() {186 time.Sleep(100 * time.Millisecond)187 } else {188 exited <- true189 return190 }191 }192 }()193 select {194 case done := <-exited:195 if done {196 return nil197 }198 case <-time.After(config.PluginKillTimeout()):199 logger.Warning("Killing runner with PID:%d forcefully", r.Cmd.Process.Pid)200 return r.killRunner()201 }202 }203 return nil204}205func (r *LanguageRunner) Connection() net.Conn {206 return r.connection207}208func (r *LanguageRunner) killRunner() error {209 return r.Cmd.Process.Kill()210}211func (r *LanguageRunner) Pid() int {212 return r.Cmd.Process.Pid213}214func (r *LanguageRunner) ExecuteAndGetStatus(message *gauge_messages.Message) *gauge_messages.ProtoExecutionResult {215 response, err := conn.GetResponseForGaugeMessage(message, r.connection)216 if err != nil {217 return &gauge_messages.ProtoExecutionResult{Failed: true, ErrorMessage: err.Error()}218 }219 if response.GetMessageType() == gauge_messages.Message_ExecutionStatusResponse {220 executionResult := response.GetExecutionStatusResponse().GetExecutionResult()221 if executionResult == nil {222 errMsg := "ProtoExecutionResult obtained is nil"223 logger.Errorf(errMsg)224 return errorResult(errMsg)225 }226 return executionResult227 }228 errMsg := fmt.Sprintf("Expected ExecutionStatusResponse. Obtained: %s", response.GetMessageType())229 logger.Errorf(errMsg)230 return errorResult(errMsg)231}232func errorResult(message string) *gauge_messages.ProtoExecutionResult {233 return &gauge_messages.ProtoExecutionResult{Failed: true, ErrorMessage: message, RecoverableError: false}234}235// Looks for a runner configuration inside the runner directory236// finds the runner configuration matching to the manifest and executes the commands for the current OS237func StartRunner(manifest *manifest.Manifest, port string, reporter reporter.Reporter, killChannel chan bool, debug bool) (*LanguageRunner, error) {238 var r RunnerInfo239 runnerDir, err := getLanguageJSONFilePath(manifest, &r)240 if err != nil {241 return nil, err242 }243 compatibilityErr := version.CheckCompatibility(version.CurrentGaugeVersion, &r.GaugeVersionSupport)244 if compatibilityErr != nil {245 return nil, fmt.Errorf("Compatibility error. %s", compatibilityErr.Error())246 }247 command := getOsSpecificCommand(r)248 env := getCleanEnv(port, os.Environ(), debug)249 cmd, err := common.ExecuteCommandWithEnv(command, runnerDir, reporter, reporter, env)250 if err != nil {251 return nil, err252 }253 go func() {254 select {255 case <-killChannel:256 cmd.Process.Kill()257 }258 }()259 // Wait for the process to exit so we will get a detailed error message260 errChannel := make(chan error)261 testRunner := &LanguageRunner{Cmd: cmd, errorChannel: errChannel, mutex: &sync.Mutex{}, multiThreaded: r.Multithreaded}262 testRunner.waitAndGetErrorMessage()263 return testRunner, nil264}265func getLanguageJSONFilePath(manifest *manifest.Manifest, r *RunnerInfo) (string, error) {266 languageJSONFilePath, err := plugin.GetLanguageJSONFilePath(manifest.Language)267 if err != nil {268 return "", err269 }270 contents, err := common.ReadFileContents(languageJSONFilePath)271 if err != nil {272 return "", err273 }274 err = json.Unmarshal([]byte(contents), r)275 if err != nil {276 return "", err277 }278 return filepath.Dir(languageJSONFilePath), nil279}280func (r *LanguageRunner) waitAndGetErrorMessage() {281 go func() {282 pState, err := r.Cmd.Process.Wait()283 r.mutex.Lock()284 r.Cmd.ProcessState = pState285 r.mutex.Unlock()286 if err != nil {287 logger.Debug("Runner exited with error: %s", err)288 r.errorChannel <- fmt.Errorf("Runner exited with error: %s\n", err.Error())289 }290 if !pState.Success() {291 r.errorChannel <- fmt.Errorf("Runner with pid %d quit unexpectedly(%s).", pState.Pid(), pState.String())292 }293 }()294}295func getCleanEnv(port string, env []string, debug bool) []string {296 //clear environment variable common.GaugeInternalPortEnvName297 isPresent := false298 for i, k := range env {299 if strings.TrimSpace(strings.Split(k, "=")[0]) == common.GaugeInternalPortEnvName {300 isPresent = true301 env[i] = common.GaugeInternalPortEnvName + "=" + port302 }303 }304 if !isPresent {305 env = append(env, common.GaugeInternalPortEnvName+"="+port)306 }307 if debug {308 env = append(env, "debugging=true")309 }310 return env311}312func getOsSpecificCommand(r RunnerInfo) []string {313 command := []string{}314 switch runtime.GOOS {315 case "windows":316 command = r.Run.Windows317 break318 case "darwin":319 command = r.Run.Darwin320 break321 default:322 command = r.Run.Linux323 break324 }325 return command326}327type StartChannels struct {328 // this will hold the runner329 RunnerChan chan Runner330 // this will hold the error while creating runner331 ErrorChan chan error332 // this holds a flag based on which the runner is terminated333 KillChan chan bool334}335func Start(manifest *manifest.Manifest, reporter reporter.Reporter, killChannel chan bool, debug bool) (Runner, error) {336 port, err := conn.GetPortFromEnvironmentVariable(common.GaugePortEnvName)337 if err != nil {338 port = 0339 }340 handler, err := conn.NewGaugeConnectionHandler(port, nil)341 if err != nil {342 return nil, err343 }344 runner, err := StartRunner(manifest, strconv.Itoa(handler.ConnectionPortNumber()), reporter, killChannel, debug)345 if err != nil {346 return nil, err347 }348 return connect(handler, runner)349}350func connect(h *conn.GaugeConnectionHandler, runner *LanguageRunner) (Runner, error) {351 connection, connErr := h.AcceptConnection(config.RunnerConnectionTimeout(), runner.errorChannel)352 if connErr != nil {353 logger.Debug("Runner connection error: %s", connErr)354 if err := runner.killRunner(); err != nil {355 logger.Debug("Error while killing runner: %s", err)356 }357 return nil, connErr358 }359 runner.connection = connection360 return runner, nil361}...

Full Screen

Full Screen

isProcessRunning

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 symIsProcessRunning, err := p.Lookup("IsProcessRunning")8 if err != nil {9 panic(err)10 }11 isProcessRunning, ok := symIsProcessRunning.(func(string) bool)12 if !ok {13 panic("unexpected type from module symbol")14 }15 fmt.Println(isProcessRunning("firefox"))16}17import (18func main() {19 p, err := plugin.Open("plugin.so")20 if err != nil {21 panic(err)22 }23 symIsProcessRunning, err := p.Lookup("IsProcessRunning")24 if err != nil {25 panic(err)26 }27 isProcessRunning, ok := symIsProcessRunning.(func(string) bool)28 if !ok {29 panic("unexpected type from module symbol")30 }31 fmt.Println(isProcessRunning("firefox"))32}33import (34func IsProcessRunning(processName string) bool {35 cmd := exec.Command("ps", "-A")36 out, err := cmd.CombinedOutput()37 if err != nil {38 log.Fatal(err)39 }40 if strings.Contains(string(out), processName) {41 }42}43func main() {44 fmt.Println("This is a plugin")45}46import (47func IsProcessRunning(processName string) bool {48 cmd := exec.Command("ps", "-A")49 out, err := cmd.CombinedOutput()50 if err != nil {51 log.Fatal(err)52 }53 if strings.Contains(string(out), processName) {54 }55}56func main() {57 fmt.Println("This is a plugin")58}59import (60func IsProcessRunning(processName string) bool {61 cmd := exec.Command("ps", "-A")

Full Screen

Full Screen

isProcessRunning

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 p, err := plugin.Open("plugin.so")4 if err != nil {5 fmt.Println(err)6 }7 sym, err := p.Lookup("IsProcessRunning")8 if err != nil {9 fmt.Println(err)10 }11 f := sym.(func(string) bool)12 fmt.Println(f("firefox"))13}

Full Screen

Full Screen

isProcessRunning

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 p, _ := process.NewProcess(1)4 fmt.Println(p.Name())5 fmt.Println(p.Username())6 fmt.Println(p.Cmdline())7 fmt.Println(p.CreateTime())8 fmt.Println(p.Cwd())9 fmt.Println(p.Exe())10 fmt.Println(p.Gids())11 fmt.Println(p.MemoryInfo())12 fmt.Println(p.MemoryInfoEx())13 fmt.Println(p.MemoryMaps())14 fmt.Println(p.MemoryPercent())15 fmt.Println(p.MemoryPercent())16 fmt.Println(p.MemoryPercent())17 fmt.Println(p.Nice())18 fmt.Println(p.NumCtxSwitches())19 fmt.Println(p.NumFDs())20 fmt.Println(p.NumThreads())21 fmt.Println(p.OpenFiles())22 fmt.Println(p.Parent())23 fmt.Println(p.Ppid())24 fmt.Println(p.Status())25 fmt.Println(p.Tgid())26 fmt.Println(p.Times())27 fmt.Println(p.Uids())28 fmt.Println(p.Username())29}30import (31func main() {32 p, _ := process.NewProcess(1)33 fmt.Println(p.Name())34 fmt.Println(p.Username())35 fmt.Println(p.Cmdline())36 fmt.Println(p.CreateTime())37 fmt.Println(p.Cwd())38 fmt.Println(p.Exe())39 fmt.Println(p.Gids())40 fmt.Println(p.MemoryInfo())41 fmt.Println(p.MemoryInfoEx())42 fmt.Println(p.MemoryMaps())43 fmt.Println(p.MemoryPercent())44 fmt.Println(p.MemoryPercent())45 fmt.Println(p.MemoryPercent())46 fmt.Println(p.Nice())47 fmt.Println(p.NumCtxSwitches())48 fmt.Println(p.NumFDs())49 fmt.Println(p.NumThreads())50 fmt.Println(p.OpenFiles())51 fmt.Println(p.Parent())52 fmt.Println(p.Ppid())53 fmt.Println(p.Status())54 fmt.Println(p.Tgid())55 fmt.Println(p.Times())56 fmt.Println(p.Uids())57 fmt.Println(p.Username())58}59import (60func main() {61 p, _ := process.NewProcess(1)62 fmt.Println(p.Name())63 fmt.Println(p.Username())

Full Screen

Full Screen

isProcessRunning

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 p, err := process.NewProcess(1)4 if err != nil {5 panic(err)6 }7 fmt.Println(p.Name())8}9Thanks for your reply. I am new to GoLang. I am trying to use the gopsutil library in my GoLang project. I am trying to use the isProcessRunning method of Process class. I have added the library in my project and also added the import statement. But I am getting the following error:10no required module provides package github.com/shirou/gopsutil/process: go.mod file not found in current directory or any parent directory; see ‘go help modules’

Full Screen

Full Screen

isProcessRunning

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 p = plugin.Plugin{}4 fmt.Println(p.IsProcessRunning("java"))5}6import (7func main() {8 p = plugin.Plugin{}9 fmt.Println(p.IsProcessRunning("java"))10}11import (12func main() {13 p = plugin.Plugin{}14 fmt.Println(p.IsProcessRunning("java"))15}16import (17func main() {18 p = plugin.Plugin{}19 fmt.Println(p.IsProcessRunning("java"))20}21import (22func main() {23 p = plugin.Plugin{}24 fmt.Println(p.IsProcessRunning("java"))25}26import (27func main() {28 p = plugin.Plugin{}29 fmt.Println(p.IsProcessRunning("java"))30}31import (32func main() {33 p = plugin.Plugin{}34 fmt.Println(p.IsProcessRunning("java"))35}36import (

Full Screen

Full Screen

isProcessRunning

Using AI Code Generation

copy

Full Screen

1var plugin = new Plugin();2var processName = "chrome.exe";3var processRunning = plugin.isProcessRunning(processName);4if(processRunning == true)5{6 alert("Process is running");7}8{9 alert("Process is not running");10}11var plugin = new Plugin();12var processName = "chrome.exe";13var processRunning = plugin.isProcessRunning(processName);14if(processRunning == true)15{16 alert("Process is running");17}18{19 alert("Process is not running");20}21var plugin = new Plugin();22var processName = "chrome.exe";23var processRunning = plugin.isProcessRunning(processName);24if(processRunning == true)25{26 alert("Process is running");27}28{29 alert("Process is not running");30}31var plugin = new Plugin();32var processName = "chrome.exe";33var processRunning = plugin.isProcessRunning(processName);34if(processRunning == true)35{36 alert("Process is running");37}38{39 alert("Process is not running");40}41var plugin = new Plugin();42var processName = "chrome.exe";43var processRunning = plugin.isProcessRunning(processName);44if(processRunning == true)45{46 alert("Process is running");47}48{49 alert("Process is not running");50}

Full Screen

Full Screen

isProcessRunning

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 p, err := plugin.Open("plugin.so")4 if err != nil {5 fmt.Println("Error opening plugin:", err)6 os.Exit(1)7 }8 symbol, err := p.Lookup("Plugin")9 if err != nil {10 fmt.Println("Error looking up symbol:", err)11 os.Exit(1)12 }13 plugin, ok := symbol.(Plugin)14 if !ok {15 fmt.Println("Error asserting type")16 os.Exit(1)17 }18 plugin.isProcessRunning("firefox")19}20import "fmt"21type Plugin struct{}22func (p Plugin) isProcessRunning(processName string) {23 fmt.Println("Checking if process is running:", processName)24}25import "fmt"26type Plugin struct{}27func (p Plugin) isProcessRunning(processName string) {28 fmt.Println("Checking if process is running:", processName)29}30import (31func main() {32 p, err := plugin.Open("plugin.so")33 if err != nil {34 fmt.Println("Error opening plugin:", err)35 os.Exit(1)36 }37 symbol, err := p.Lookup("Plugin")38 if err != nil {39 fmt.Println("Error looking up symbol:", err)40 os.Exit(1)41 }42 plugin, ok := symbol.(Plugin)43 if !ok {44 fmt.Println("Error asserting type")45 os.Exit(1)46 }47 plugin.isProcessRunning("firefox")48}49import "

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