forked from getgauge/gauge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
plugin.go
322 lines (284 loc) · 8.26 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
package main
import (
"code.google.com/p/goprotobuf/proto"
"encoding/json"
"errors"
"fmt"
"github.com/getgauge/common"
"net"
"os/exec"
"path"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
"time"
)
const (
executionScope = "execution"
pluginConnectionTimeout = time.Second * 10
setupScope = "setup"
pluginConnectionPortEnv = "plugin_connection_port"
)
type pluginDescriptor struct {
Id string
Version string
Name string
Description string
Command struct {
Windows []string
Linux []string
Darwin []string
}
Scope []string
pluginPath string
}
type pluginHandler struct {
pluginsMap map[string]*plugin
}
type plugin struct {
connection net.Conn
pluginCmd *exec.Cmd
descriptor *pluginDescriptor
}
func (plugin *plugin) kill(wg *sync.WaitGroup) error {
defer wg.Done()
if plugin.isStillRunning() {
exited := make(chan bool, 1)
go func() {
for {
if plugin.isStillRunning() {
time.Sleep(100 * time.Millisecond)
} else {
exited <- true
return
}
}
}()
select {
case done := <-exited:
if done {
fmt.Println(fmt.Sprintf("Plugin [%s] with pid [%d] has exited", plugin.descriptor.Name, plugin.pluginCmd.Process.Pid))
}
case <-time.After(pluginConnectionTimeout):
fmt.Println(fmt.Sprintf("Plugin [%s] with pid [%d] did not exit after %.2f seconds. Forcefully killing it.", plugin.descriptor.Name, plugin.pluginCmd.Process.Pid, pluginConnectionTimeout.Seconds()))
return plugin.pluginCmd.Process.Kill()
}
}
return nil
}
func (plugin *plugin) isStillRunning() bool {
return plugin.pluginCmd.ProcessState == nil || !plugin.pluginCmd.ProcessState.Exited()
}
func isPluginInstalled(pluginName, pluginVersion string) bool {
pluginsInstallDir, err := common.GetPluginsInstallDir(pluginName)
if err != nil {
return false
}
thisPluginDir := path.Join(pluginsInstallDir, pluginName)
if !common.DirExists(thisPluginDir) {
return false
}
if pluginVersion != "" {
pluginJson := path.Join(thisPluginDir, pluginVersion, common.PluginJsonFile)
if common.FileExists(pluginJson) {
return true
} else {
return false
}
} else {
return true
}
}
func getPluginJsonPath(pluginName, version string) (string, error) {
if !isPluginInstalled(pluginName, version) {
return "", errors.New(fmt.Sprintf("%s %s is not installed", pluginName, version))
}
pluginInstallDir, err := common.GetPluginInstallDir(pluginName, "")
if err != nil {
return "", err
}
return filepath.Join(pluginInstallDir, common.PluginJsonFile), nil
}
func getPluginDescriptor(pluginId, pluginVersion string) (*pluginDescriptor, error) {
pluginJson, err := getPluginJsonPath(pluginId, pluginVersion)
if err != nil {
return nil, err
}
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, errors.New(fmt.Sprintf("%s: %s", pluginJson, err.Error()))
}
pd.pluginPath = filepath.Dir(pluginJson)
return &pd, nil
}
func startPlugin(pd *pluginDescriptor, action string, wait bool) (*exec.Cmd, error) {
command := []string{}
switch runtime.GOOS {
case "windows":
command = pd.Command.Windows
break
case "darwin":
command = pd.Command.Darwin
break
default:
command = pd.Command.Linux
break
}
if len(command) == 0 {
return nil, errors.New(fmt.Sprintf("Platform specific command not specified: %s.", runtime.GOOS))
}
pluginConsoleWriter := &pluginConsoleWriter{pluginName: pd.Name}
cmd, err := common.ExecuteCommand(command, pd.pluginPath, pluginConsoleWriter, pluginConsoleWriter)
if err != nil {
return nil, err
}
if wait {
return cmd, cmd.Wait()
} else {
go func() {
cmd.Wait()
}()
}
return cmd, nil
}
func setEnvForPlugin(action string, pd *pluginDescriptor, manifest *manifest, pluginEnvVars map[string]string) error {
pluginEnvVars[fmt.Sprintf("%s_action", pd.Id)] = action
pluginEnvVars["test_language"] = manifest.Language
if err := setEnvironmentProperties(pluginEnvVars); err != nil {
return err
}
if err := setCurrentProjectEnvVariable(); err != nil {
return err
}
return nil
}
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 addPluginToTheProject(pluginName string, pluginArgs map[string]string, manifest *manifest) error {
pd, err := getPluginDescriptor(pluginName, pluginArgs["version"])
if err != nil {
return err
}
if isPluginAdded(manifest, pd) {
return errors.New("Plugin " + pd.Name + " is already added")
}
action := setupScope
if err := setEnvForPlugin(action, pd, manifest, pluginArgs); err != nil {
return err
}
if _, err := startPlugin(pd, action, true); err != nil {
return err
}
manifest.Plugins = append(manifest.Plugins, pd.Id)
return manifest.save()
}
func isPluginAdded(manifest *manifest, descriptor *pluginDescriptor) bool {
for _, pluginId := range manifest.Plugins {
if pluginId == descriptor.Id {
return true
}
}
return false
}
func startPluginsForExecution(manifest *manifest) (*pluginHandler, []string) {
warnings := make([]string, 0)
handler := &pluginHandler{}
envProperties := make(map[string]string)
for _, pluginId := range manifest.Plugins {
pd, err := getPluginDescriptor(pluginId, "")
if err != nil {
warnings = append(warnings, fmt.Sprintf("Error starting plugin %s. Failed to get plugin.json. %s", pluginId, err.Error()))
continue
}
if isExecutionScopePlugin(pd) {
gaugeConnectionHandler, err := newGaugeConnectionHandler(0, nil)
if err != nil {
warnings = append(warnings, err.Error())
continue
}
envProperties[pluginConnectionPortEnv] = strconv.Itoa(gaugeConnectionHandler.connectionPortNumber())
setEnvForPlugin(executionScope, pd, manifest, envProperties)
pluginCmd, err := startPlugin(pd, executionScope, false)
if err != nil {
warnings = append(warnings, fmt.Sprintf("Error starting plugin %s %s. %s", pd.Name, pd.Version, err.Error()))
continue
}
pluginConnection, err := gaugeConnectionHandler.acceptConnection(pluginConnectionTimeout)
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()))
pluginCmd.Process.Kill()
continue
}
handler.addPlugin(pluginId, &plugin{connection: pluginConnection, pluginCmd: pluginCmd, descriptor: pd})
}
}
return handler, warnings
}
func isExecutionScopePlugin(pd *pluginDescriptor) bool {
for _, scope := range pd.Scope {
if strings.ToLower(scope) == executionScope {
return true
}
}
return false
}
func (handler *pluginHandler) addPlugin(pluginId string, pluginToAdd *plugin) {
if handler.pluginsMap == nil {
handler.pluginsMap = make(map[string]*plugin)
}
handler.pluginsMap[pluginId] = pluginToAdd
}
func (handler *pluginHandler) removePlugin(pluginId string) {
delete(handler.pluginsMap, pluginId)
}
func (handler *pluginHandler) notifyPlugins(message *Message) {
for id, plugin := range handler.pluginsMap {
err := plugin.sendMessage(message)
if err != nil {
fmt.Printf("[Warinig] Unable to connect to plugin %s %s. %s\n", plugin.descriptor.Name, plugin.descriptor.Version, err.Error())
handler.killPlugin(id)
}
}
}
func (handler *pluginHandler) killPlugin(pluginId string) {
plugin := handler.pluginsMap[pluginId]
fmt.Printf("Killing Plugin %s %s\n", plugin.descriptor.Name, plugin.descriptor.Version)
err := plugin.pluginCmd.Process.Kill()
if err != nil {
fmt.Printf("[Error] Failed to kill plugin %s %s. %s\n", plugin.descriptor.Name, plugin.descriptor.Version, err.Error())
}
handler.removePlugin(pluginId)
}
func (handler *pluginHandler) gracefullyKillPlugins() {
var wg sync.WaitGroup
for _, plugin := range handler.pluginsMap {
wg.Add(1)
go plugin.kill(&wg)
}
wg.Wait()
}
func (plugin *plugin) sendMessage(message *Message) error {
messageId := common.GetUniqueId()
message.MessageId = &messageId
messageBytes, err := proto.Marshal(message)
if err != nil {
return err
}
err = write(plugin.connection, messageBytes)
if err != nil {
return errors.New(fmt.Sprintf("[Warning] Failed to send message to plugin: %d %s", plugin.descriptor.Id, err.Error()))
}
return nil
}