-
Notifications
You must be signed in to change notification settings - Fork 343
/
Copy pathplugin.go
575 lines (530 loc) · 18.1 KB
/
plugin.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
/*----------------------------------------------------------------
* Copyright (c) ThoughtWorks, Inc.
* Licensed under the Apache License, Version 2.0
* See LICENSE in the project root for license information.
*----------------------------------------------------------------*/
package plugin
import (
"context"
"encoding/json"
"fmt"
"net"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
"time"
"github.com/getgauge/common"
"github.com/getgauge/gauge-proto/go/gauge_messages"
"github.com/getgauge/gauge/api/infoGatherer"
"github.com/getgauge/gauge/config"
"github.com/getgauge/gauge/conn"
"github.com/getgauge/gauge/gauge"
"github.com/getgauge/gauge/logger"
"github.com/getgauge/gauge/manifest"
"github.com/getgauge/gauge/plugin/pluginInfo"
"github.com/getgauge/gauge/version"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
)
type pluginScope string
const (
executionScope pluginScope = "execution"
docScope pluginScope = "documentation"
pluginConnectionPortEnv = "plugin_connection_port"
)
type plugin struct {
mutex *sync.Mutex
connection net.Conn
gRPCConn *grpc.ClientConn
ReporterClient gauge_messages.ReporterClient
DocumenterClient gauge_messages.DocumenterClient
pluginCmd *exec.Cmd
descriptor *PluginDescriptor
killTimer *time.Timer
}
func isProcessRunning(p *plugin) bool {
p.mutex.Lock()
ps := p.pluginCmd.ProcessState
p.mutex.Unlock()
return ps == nil || !ps.Exited()
}
func (p *plugin) killGrpcProcess() error {
var m *gauge_messages.Empty
var err error
if p.ReporterClient != nil {
m, err = p.ReporterClient.Kill(context.Background(), &gauge_messages.KillProcessRequest{})
} else if p.DocumenterClient != nil {
m, err = p.DocumenterClient.Kill(context.Background(), &gauge_messages.KillProcessRequest{})
}
if m == nil || err != nil {
errStatus, _ := status.FromError(err)
if errStatus.Code() == codes.Unavailable {
// Ref https://www.grpc.io/docs/guides/error/#general-errors
// GRPC_STATUS_UNAVAILABLE is thrown when Server is shutting down. Ignore it here.
return nil
}
return err
}
if p.gRPCConn == nil && p.pluginCmd == nil {
return nil
}
defer p.gRPCConn.Close()
if isProcessRunning(p) {
exited := make(chan bool, 1)
go func() {
for {
if isProcessRunning(p) {
time.Sleep(100 * time.Millisecond)
} else {
exited <- true
return
}
}
}()
select {
case done := <-exited:
if done {
logger.Debugf(true, "Runner with PID:%d has exited", p.pluginCmd.Process.Pid)
return nil
}
case <-time.After(config.PluginKillTimeout()):
logger.Warningf(true, "Killing runner with PID:%d forcefully", p.pluginCmd.Process.Pid)
return p.pluginCmd.Process.Kill()
}
}
return nil
}
func (p *plugin) kill(wg *sync.WaitGroup) error {
defer wg.Done()
if p.gRPCConn != nil && p.ReporterClient != nil {
return p.killGrpcProcess()
}
if isProcessRunning(p) {
defer p.connection.Close()
p.killTimer = time.NewTimer(config.PluginKillTimeout())
err := conn.SendProcessKillMessage(p.connection)
if err != nil {
logger.Warningf(true, "Error while killing plugin %s : %s ", p.descriptor.Name, err.Error())
}
exited := make(chan bool, 1)
go func() {
for {
if isProcessRunning(p) {
time.Sleep(100 * time.Millisecond)
} else {
exited <- true
return
}
}
}()
select {
case <-exited:
if !p.killTimer.Stop() {
<-p.killTimer.C
}
logger.Debugf(true, "Plugin [%s] with pid [%d] has exited", p.descriptor.Name, p.pluginCmd.Process.Pid)
case <-p.killTimer.C:
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())
err := p.pluginCmd.Process.Kill()
if err != nil {
logger.Warningf(true, "Error while killing plugin %s : %s ", p.descriptor.Name, err.Error())
}
return err
}
}
return nil
}
// IsPluginInstalled checks if given plugin with specific version is installed or not.
func IsPluginInstalled(pluginName, pluginVersion string) bool {
pluginsInstallDir, err := common.GetPluginsInstallDir(pluginName)
if err != nil {
return false
}
thisPluginDir := filepath.Join(pluginsInstallDir, pluginName)
if !common.DirExists(thisPluginDir) {
return false
}
if pluginVersion != "" {
return common.FileExists(filepath.Join(thisPluginDir, pluginVersion, common.PluginJSONFile))
}
return true
}
func getPluginJSONPath(pluginName, pluginVersion string) (string, error) {
if !IsPluginInstalled(pluginName, pluginVersion) {
plugin := strings.TrimSpace(fmt.Sprintf("%s %s", pluginName, pluginVersion))
return "", fmt.Errorf("Plugin %s is not installed", plugin)
}
pluginInstallDir, err := GetInstallDir(pluginName, "")
if err != nil {
return "", err
}
return filepath.Join(pluginInstallDir, common.PluginJSONFile), nil
}
// GetPluginDescriptor return the information about the plugin including name, id, commands to start etc.
func GetPluginDescriptor(pluginID, pluginVersion string) (*PluginDescriptor, error) {
pluginJSON, err := getPluginJSONPath(pluginID, pluginVersion)
if err != nil {
return nil, err
}
return GetPluginDescriptorFromJSON(pluginJSON)
}
func GetPluginDescriptorFromJSON(pluginJSON string) (*PluginDescriptor, error) {
pluginJSONContents, err := common.ReadFileContents(pluginJSON)
if err != nil {
return nil, err
}
var pd PluginDescriptor
if err = json.Unmarshal([]byte(pluginJSONContents), &pd); err != nil {
return nil, fmt.Errorf("%s: %s", pluginJSON, err.Error())
}
pd.pluginPath = filepath.Dir(pluginJSON)
return &pd, nil
}
func startPlugin(pd *PluginDescriptor, action pluginScope) (*plugin, error) {
var command []string
switch runtime.GOOS {
case "windows":
command = pd.Command.Windows
case "darwin":
command = pd.Command.Darwin
default:
command = pd.Command.Linux
}
if len(command) == 0 {
return nil, fmt.Errorf("Platform specific command not specified: %s.", runtime.GOOS)
}
if pd.hasCapability(gRPCSupportCapability) {
return startGRPCPlugin(pd, command)
}
return startLegacyPlugin(pd, command)
}
func startGRPCPlugin(pd *PluginDescriptor, command []string) (*plugin, error) {
portChan := make(chan string)
writer := &logger.LogWriter{
Stderr: logger.NewCustomWriter(portChan, os.Stderr, pd.ID, true),
Stdout: logger.NewCustomWriter(portChan, os.Stdout, pd.ID, false),
}
cmd, err := common.ExecuteCommand(command, pd.pluginPath, writer.Stdout, writer.Stderr)
go func() {
err = cmd.Wait()
if err != nil {
logger.Errorf(true, "Error occurred while waiting for plugin process to finish.\nError : %s", err.Error())
}
}()
if err != nil {
return nil, err
}
var port string
select {
case port = <-portChan:
close(portChan)
case <-time.After(config.PluginConnectionTimeout()):
return nil, fmt.Errorf("timed out connecting to %s", pd.ID)
}
logger.Debugf(true, "Attempting to connect to grpc server at port: %s", port)
gRPCConn, err := grpc.NewClient(fmt.Sprintf("%s:%s", "127.0.0.1", port),
grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithDefaultCallOptions(grpc.MaxCallSendMsgSize(1024*1024*1024), grpc.MaxCallRecvMsgSize(1024*1024*1024)))
if err != nil {
return nil, err
}
plugin := &plugin{
pluginCmd: cmd,
descriptor: pd,
gRPCConn: gRPCConn,
mutex: &sync.Mutex{},
}
if pd.hasScope(docScope) {
plugin.DocumenterClient = gauge_messages.NewDocumenterClient(gRPCConn)
} else {
plugin.ReporterClient = gauge_messages.NewReporterClient(gRPCConn)
}
logger.Debugf(true, "Successfully made the connection with plugin with port: %s", port)
return plugin, nil
}
func startLegacyPlugin(pd *PluginDescriptor, command []string) (*plugin, error) {
writer := logger.NewLogWriter(pd.ID, true, 0)
cmd, err := common.ExecuteCommand(command, pd.pluginPath, writer.Stdout, writer.Stderr)
if err != nil {
return nil, err
}
var mutex = &sync.Mutex{}
go func() {
pState, _ := cmd.Process.Wait()
mutex.Lock()
cmd.ProcessState = pState
mutex.Unlock()
}()
plugin := &plugin{pluginCmd: cmd, descriptor: pd, mutex: mutex}
return plugin, nil
}
func SetEnvForPlugin(action pluginScope, pd *PluginDescriptor, m *manifest.Manifest, pluginEnvVars map[string]string) error {
pluginEnvVars[fmt.Sprintf("%s_action", pd.ID)] = string(action)
pluginEnvVars["test_language"] = m.Language
return setEnvironmentProperties(pluginEnvVars)
}
func setEnvironmentProperties(properties map[string]string) error {
for k, v := range properties {
if err := common.SetEnvVariable(k, v); err != nil {
return err
}
}
return nil
}
func IsPluginAdded(m *manifest.Manifest, descriptor *PluginDescriptor) bool {
for _, pluginID := range m.Plugins {
if pluginID == descriptor.ID {
return true
}
}
return false
}
func startPluginsForExecution(m *manifest.Manifest) (Handler, []string) {
var warnings []string
handler := &GaugePlugins{}
envProperties := make(map[string]string)
for _, pluginID := range m.Plugins {
pd, err := GetPluginDescriptor(pluginID, "")
if err != nil {
warnings = append(warnings, fmt.Sprintf("Unable to start plugin %s. %s. To install, run `gauge install %s`.", pluginID, err.Error(), pluginID))
continue
}
compatibilityErr := version.CheckCompatibility(version.CurrentGaugeVersion, &pd.GaugeVersionSupport)
if compatibilityErr != nil {
warnings = append(warnings, fmt.Sprintf("Compatible %s plugin version to current Gauge version %s not found", pd.Name, version.CurrentGaugeVersion))
continue
}
if pd.hasScope(executionScope) {
gaugeConnectionHandler, err := conn.NewGaugeConnectionHandler(0, nil)
if err != nil {
warnings = append(warnings, err.Error())
continue
}
envProperties[pluginConnectionPortEnv] = strconv.Itoa(gaugeConnectionHandler.ConnectionPortNumber())
prop, err := common.GetGaugeConfigurationFor(common.GaugePropertiesFile)
if err != nil {
warnings = append(warnings, fmt.Sprintf("Unable to read Gauge configuration. %s", err.Error()))
continue
}
envProperties["plugin_kill_timeout"] = prop["plugin_kill_timeout"]
err = SetEnvForPlugin(executionScope, pd, m, envProperties)
if err != nil {
warnings = append(warnings, fmt.Sprintf("Error setting environment for plugin %s %s. %s", pd.Name, pd.Version, err.Error()))
continue
}
logger.Debugf(true, "Starting %s plugin", pd.Name)
plugin, err := startPlugin(pd, executionScope)
if err != nil {
warnings = append(warnings, fmt.Sprintf("Error starting plugin %s %s. %s", pd.Name, pd.Version, err.Error()))
continue
}
if plugin.gRPCConn != nil {
handler.addPlugin(pluginID, plugin)
continue
}
pluginConnection, err := gaugeConnectionHandler.AcceptConnection(config.PluginConnectionTimeout(), make(chan error))
if err != nil {
warnings = append(warnings, fmt.Sprintf("Error starting plugin %s %s. Failed to connect to plugin. %s", pd.Name, pd.Version, err.Error()))
err := plugin.pluginCmd.Process.Kill()
if err != nil {
logger.Errorf(false, "unable to kill plugin %s: %s", plugin.descriptor.Name, err.Error())
}
continue
}
logger.Debugf(true, "Established connection to %s plugin", pd.Name)
plugin.connection = pluginConnection
handler.addPlugin(pluginID, plugin)
}
}
return handler, warnings
}
func GenerateDoc(pluginName string, specDirs []string, startAPIFunc func([]string) int) {
pd, err := GetPluginDescriptor(pluginName, "")
if err != nil {
logger.Fatalf(true, "Error starting plugin %s. Failed to get plugin.json. %s. To install, run `gauge install %s`.", pluginName, err.Error(), pluginName)
}
if err := version.CheckCompatibility(version.CurrentGaugeVersion, &pd.GaugeVersionSupport); err != nil {
logger.Fatalf(true, "Compatible %s plugin version to current Gauge version %s not found", pd.Name, version.CurrentGaugeVersion)
}
if !pd.hasScope(docScope) {
logger.Fatalf(true, "Invalid plugin name: %s, this plugin cannot generate documentation.", pd.Name)
}
var sources []string
for _, src := range specDirs {
path, _ := filepath.Abs(src)
sources = append(sources, path)
}
os.Setenv("GAUGE_SPEC_DIRS", strings.Join(sources, "||"))
os.Setenv("GAUGE_PROJECT_ROOT", config.ProjectRoot)
if pd.hasCapability(gRPCSupportCapability) {
p, err := startPlugin(pd, docScope)
if err != nil {
logger.Fatalf(true, " %s %s. %s", pd.Name, pd.Version, err.Error())
}
_, err = p.DocumenterClient.GenerateDocs(context.Background(), getSpecDetails(specDirs))
grpcErr := p.killGrpcProcess()
if grpcErr != nil {
logger.Errorf(false, "Unable to kill plugin %s : %s", p.descriptor.Name, grpcErr.Error())
}
if err != nil {
logger.Fatalf(true, "Failed to generate docs. %s", err.Error())
}
} else {
port := startAPIFunc(specDirs)
err := os.Setenv(common.APIPortEnvVariableName, strconv.Itoa(port))
if err != nil {
logger.Fatalf(true, "Failed to set env GAUGE_API_PORT. %s", err.Error())
}
p, err := startPlugin(pd, docScope)
if err != nil {
logger.Fatalf(true, " %s %s. %s", pd.Name, pd.Version, err.Error())
}
for isProcessRunning(p) {
}
}
}
func (p *plugin) invokeService(m *gauge_messages.Message) error {
ctx := context.Background()
var err error
switch m.GetMessageType() {
case gauge_messages.Message_SuiteExecutionResult:
_, err = p.ReporterClient.NotifySuiteResult(ctx, m.GetSuiteExecutionResult())
case gauge_messages.Message_ExecutionStarting:
_, err = p.ReporterClient.NotifyExecutionStarting(ctx, m.GetExecutionStartingRequest())
case gauge_messages.Message_ExecutionEnding:
_, err = p.ReporterClient.NotifyExecutionEnding(ctx, m.GetExecutionEndingRequest())
case gauge_messages.Message_SpecExecutionEnding:
_, err = p.ReporterClient.NotifySpecExecutionEnding(ctx, m.GetSpecExecutionEndingRequest())
case gauge_messages.Message_SpecExecutionStarting:
_, err = p.ReporterClient.NotifySpecExecutionStarting(ctx, m.GetSpecExecutionStartingRequest())
case gauge_messages.Message_ScenarioExecutionEnding:
_, err = p.ReporterClient.NotifyScenarioExecutionEnding(ctx, m.GetScenarioExecutionEndingRequest())
case gauge_messages.Message_ScenarioExecutionStarting:
_, err = p.ReporterClient.NotifyScenarioExecutionStarting(ctx, m.GetScenarioExecutionStartingRequest())
case gauge_messages.Message_StepExecutionEnding:
_, err = p.ReporterClient.NotifyStepExecutionEnding(ctx, m.GetStepExecutionEndingRequest())
case gauge_messages.Message_StepExecutionStarting:
_, err = p.ReporterClient.NotifyStepExecutionStarting(ctx, m.GetStepExecutionStartingRequest())
case gauge_messages.Message_ConceptExecutionEnding:
_, err = p.ReporterClient.NotifyConceptExecutionEnding(ctx, m.GetConceptExecutionEndingRequest())
case gauge_messages.Message_ConceptExecutionStarting:
_, err = p.ReporterClient.NotifyConceptExecutionStarting(ctx, m.GetConceptExecutionStartingRequest())
}
return err
}
func (p *plugin) sendMessage(message *gauge_messages.Message) error {
if p.gRPCConn != nil {
return p.invokeService(message)
}
messageID := common.GetUniqueID()
message.MessageId = messageID
messageBytes, err := proto.Marshal(message)
if err != nil {
return err
}
err = conn.Write(p.connection, messageBytes)
if err != nil {
return fmt.Errorf("[Warning] Failed to send message to plugin: %s %s", p.descriptor.ID, err.Error())
}
return nil
}
func StartPlugins(m *manifest.Manifest) Handler {
pluginHandler, warnings := startPluginsForExecution(m)
logger.HandleWarningMessages(true, warnings)
return pluginHandler
}
func PluginsWithoutScope() (infos []pluginInfo.PluginInfo) {
if plugins, err := pluginInfo.GetAllInstalledPluginsWithVersion(); err == nil {
for _, p := range plugins {
pd, err := GetPluginDescriptor(p.Name, p.Version.String())
if err == nil && !pd.hasAnyScope() {
infos = append(infos, p)
}
}
}
return
}
// GetInstallDir returns the install directory of given plugin and a given version.
func GetInstallDir(pluginName, v string) (string, error) {
allPluginsInstallDir, err := common.GetPluginsInstallDir(pluginName)
if err != nil {
return "", err
}
pluginDir := filepath.Join(allPluginsInstallDir, pluginName)
if v != "" {
pluginDir = filepath.Join(pluginDir, v)
} else {
latestPlugin, err := pluginInfo.GetLatestInstalledPlugin(pluginDir)
if err != nil {
return "", err
}
pluginDir = latestPlugin.Path
}
return pluginDir, nil
}
func GetLanguageJSONFilePath(language string) (string, error) {
languageInstallDir, err := GetInstallDir(language, "")
if err != nil {
return "", err
}
languageJSON := filepath.Join(languageInstallDir, fmt.Sprintf("%s.json", language))
if !common.FileExists(languageJSON) {
return "", fmt.Errorf("Failed to find the implementation for: %s. %s does not exist.", language, languageJSON)
}
return languageJSON, nil
}
func IsLanguagePlugin(plugin string) bool {
if _, err := GetLanguageJSONFilePath(plugin); err != nil {
return false
}
return true
}
func QueryParams() string {
return fmt.Sprintf("?l=%s&p=%s&o=%s&a=%s", language(), plugins(), runtime.GOOS, runtime.GOARCH)
}
func language() string {
if config.ProjectRoot == "" {
return ""
}
m, err := manifest.ProjectManifest()
if err != nil {
return ""
}
return m.Language
}
func plugins() string {
pluginInfos, err := pluginInfo.GetAllInstalledPluginsWithVersion()
if err != nil {
return ""
}
var plugins []string
for _, p := range pluginInfos {
plugins = append(plugins, p.Name)
}
return strings.Join(plugins, ",")
}
func getSpecDetails(specDirs []string) *gauge_messages.SpecDetails {
sig := &infoGatherer.SpecInfoGatherer{SpecDirs: specDirs}
sig.Init()
specDetails := make([]*gauge_messages.SpecDetails_SpecDetail, 0)
for _, d := range sig.GetAvailableSpecDetails(specDirs) {
detail := &gauge_messages.SpecDetails_SpecDetail{}
if d.HasSpec() {
detail.Spec = gauge.ConvertToProtoSpec(d.Spec)
}
for _, e := range d.Errs {
detail.ParseErrors = append(detail.ParseErrors, &gauge_messages.Error{Type: gauge_messages.Error_PARSE_ERROR, Filename: e.FileName, Message: e.Message, LineNumber: int32(e.LineNo)})
}
specDetails = append(specDetails, detail)
}
return &gauge_messages.SpecDetails{
Details: specDetails,
}
}