-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
plugin.go
332 lines (279 loc) · 8.37 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
package plugin
import (
"context"
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"golang.org/x/xerrors"
"gopkg.in/yaml.v3"
"github.com/aquasecurity/trivy/pkg/downloader"
"github.com/aquasecurity/trivy/pkg/log"
"github.com/aquasecurity/trivy/pkg/utils"
)
const (
configFile = "plugin.yaml"
)
var (
pluginsRelativeDir = filepath.Join(".trivy", "plugins")
officialPlugins = map[string]string{
"kubectl": "github.com/aquasecurity/trivy-plugin-kubectl",
"aqua": "github.com/aquasecurity/trivy-plugin-aqua",
}
)
// Plugin represents a plugin.
type Plugin struct {
Name string `yaml:"name"`
Repository string `yaml:"repository"`
Version string `yaml:"version"`
Usage string `yaml:"usage"`
Description string `yaml:"description"`
Platforms []Platform `yaml:"platforms"`
// runtime environment for testability
GOOS string `yaml:"_goos"`
GOARCH string `yaml:"_goarch"`
}
// Platform represents where the execution file exists per platform.
type Platform struct {
Selector *Selector
URI string
Bin string
}
// Selector represents the environment.
type Selector struct {
OS string
Arch string
}
// Run runs the plugin
func (p Plugin) Run(ctx context.Context, args []string) error {
platform, err := p.selectPlatform()
if err != nil {
return xerrors.Errorf("platform selection error: %w", err)
}
execFile := filepath.Join(dir(), p.Name, platform.Bin)
cmd := exec.CommandContext(ctx, execFile, args...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Env = os.Environ()
// If an error is found during the execution of the plugin, figure
// out if the error was from not being able to execute the plugin or
// an error set by the plugin itself.
if err = cmd.Run(); err != nil {
if _, ok := err.(*exec.ExitError); !ok {
return xerrors.Errorf("exit: %w", err)
}
return xerrors.Errorf("plugin exec: %w", err)
}
return nil
}
func (p Plugin) selectPlatform() (Platform, error) {
// These values are only filled in during unit tests.
if p.GOOS == "" {
p.GOOS = runtime.GOOS
}
if p.GOARCH == "" {
p.GOARCH = runtime.GOARCH
}
for _, platform := range p.Platforms {
if platform.Selector == nil {
return platform, nil
}
selector := platform.Selector
if (selector.OS == "" || p.GOOS == selector.OS) &&
(selector.Arch == "" || p.GOARCH == selector.Arch) {
log.Logger.Debugf("Platform found, os: %s, arch: %s", selector.OS, selector.Arch)
return platform, nil
}
}
return Platform{}, xerrors.New("platform not found")
}
func (p Plugin) install(ctx context.Context, dst, pwd string) error {
log.Logger.Debugf("Installing the plugin to %s...", dst)
platform, err := p.selectPlatform()
if err != nil {
return xerrors.Errorf("platform selection error: %w", err)
}
log.Logger.Debugf("Downloading the execution file from %s...", platform.URI)
if err = downloader.Download(ctx, platform.URI, dst, pwd); err != nil {
return xerrors.Errorf("unable to download the execution file (%s): %w", platform.URI, err)
}
return nil
}
func (p Plugin) dir() (string, error) {
if p.Name == "" {
return "", xerrors.Errorf("'name' is empty")
}
// e.g. ~/.trivy/plugins/kubectl
return filepath.Join(dir(), p.Name), nil
}
// Install installs a plugin
func Install(ctx context.Context, url string, force bool) (Plugin, error) {
// Replace short names with full qualified names
// e.g. kubectl => github.com/aquasecurity/trivy-plugin-kubectl
if v, ok := officialPlugins[url]; ok {
url = v
}
if !force {
// If the plugin is already installed, it skips installing the plugin.
if p, installed := isInstalled(url); installed {
return p, nil
}
}
log.Logger.Infof("Installing the plugin from %s...", url)
tempDir, err := downloader.DownloadToTempDir(ctx, url)
if err != nil {
return Plugin{}, xerrors.Errorf("download failed: %w", err)
}
defer os.RemoveAll(tempDir)
log.Logger.Info("Loading the plugin metadata...")
plugin, err := loadMetadata(tempDir)
if err != nil {
return Plugin{}, xerrors.Errorf("failed to load the plugin metadata: %w", err)
}
pluginDir, err := plugin.dir()
if err != nil {
return Plugin{}, xerrors.Errorf("failed to determine the plugin dir: %w", err)
}
if err = plugin.install(ctx, pluginDir, tempDir); err != nil {
return Plugin{}, xerrors.Errorf("failed to install the plugin: %w", err)
}
// Copy plugin.yaml into the plugin dir
if _, err = utils.CopyFile(filepath.Join(tempDir, configFile), filepath.Join(pluginDir, configFile)); err != nil {
return Plugin{}, xerrors.Errorf("failed to copy plugin.yaml: %w", err)
}
return plugin, nil
}
// Uninstall installs the plugin
func Uninstall(name string) error {
pluginDir := filepath.Join(dir(), name)
return os.RemoveAll(pluginDir)
}
// Information gets the information about an installed plugin
func Information(name string) (string, error) {
pluginDir := filepath.Join(dir(), name)
if _, err := os.Stat(pluginDir); err != nil {
if os.IsNotExist(err) {
return "", xerrors.Errorf("could not find a plugin called '%s', did you install it?", name)
}
return "", xerrors.Errorf("stat error: %w", err)
}
plugin, err := loadMetadata(pluginDir)
if err != nil {
return "", xerrors.Errorf("unable to load metadata: %w", err)
}
return fmt.Sprintf(`
Plugin: %s
Description: %s
Version: %s
Usage: %s
`, plugin.Name, plugin.Description, plugin.Version, plugin.Usage), nil
}
// List gets a list of all installed plugins
func List() (string, error) {
if _, err := os.Stat(dir()); err != nil {
if os.IsNotExist(err) {
return "No Installed Plugins\n", nil
}
return "", xerrors.Errorf("stat error: %w", err)
}
plugins, err := LoadAll()
if err != nil {
return "", xerrors.Errorf("unable to load plugins: %w", err)
}
pluginList := []string{"Installed Plugins:"}
for _, plugin := range plugins {
pluginList = append(pluginList, fmt.Sprintf(" Name: %s\n Version: %s\n", plugin.Name, plugin.Version))
}
return strings.Join(pluginList, "\n"), nil
}
// Update updates an existing plugin
func Update(name string) error {
pluginDir := filepath.Join(dir(), name)
if _, err := os.Stat(pluginDir); err != nil {
if os.IsNotExist(err) {
return xerrors.Errorf("could not find a plugin called '%s' to update: %w", name, err)
}
return err
}
plugin, err := loadMetadata(pluginDir)
if err != nil {
return err
}
log.Logger.Infof("Updating plugin '%s'", name)
updated, err := Install(nil, plugin.Repository, true)
if err != nil {
return xerrors.Errorf("unable to perform an update installation: %w", err)
}
if plugin.Version == updated.Version {
log.Logger.Infof("The %s plugin is the latest version. [%s]", name, plugin.Version)
} else {
log.Logger.Infof("Updated '%s' from %s to %s", name, plugin.Version, updated.Version)
}
return nil
}
// LoadAll loads all plugins
func LoadAll() ([]Plugin, error) {
pluginsDir := dir()
dirs, err := os.ReadDir(pluginsDir)
if err != nil {
return nil, xerrors.Errorf("failed to read %s: %w", pluginsDir, err)
}
var plugins []Plugin
for _, d := range dirs {
if !d.IsDir() {
continue
}
plugin, err := loadMetadata(filepath.Join(pluginsDir, d.Name()))
if err != nil {
log.Logger.Warnf("plugin load error: %s", err)
continue
}
plugins = append(plugins, plugin)
}
return plugins, nil
}
// RunWithArgs runs the plugin with arguments
func RunWithArgs(ctx context.Context, url string, args []string) error {
pl, err := Install(ctx, url, false)
if err != nil {
return xerrors.Errorf("plugin install error: %w", err)
}
if err = pl.Run(ctx, args); err != nil {
return xerrors.Errorf("unable to run %s plugin: %w", pl.Name, err)
}
return nil
}
func IsPredefined(name string) bool {
_, ok := officialPlugins[name]
return ok
}
func loadMetadata(dir string) (Plugin, error) {
filePath := filepath.Join(dir, configFile)
f, err := os.Open(filePath)
if err != nil {
return Plugin{}, xerrors.Errorf("file open error: %w", err)
}
var plugin Plugin
if err = yaml.NewDecoder(f).Decode(&plugin); err != nil {
return Plugin{}, xerrors.Errorf("yaml decode error: %w", err)
}
return plugin, nil
}
func dir() string {
return filepath.Join(utils.HomeDir(), pluginsRelativeDir)
}
func isInstalled(url string) (Plugin, bool) {
installedPlugins, err := LoadAll()
if err != nil {
return Plugin{}, false
}
for _, plugin := range installedPlugins {
if plugin.Repository == url {
return plugin, true
}
}
return Plugin{}, false
}