-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathmanager.go
244 lines (217 loc) · 6.74 KB
/
manager.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
package manager
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io/fs"
"os"
"os/exec"
"path"
"path/filepath"
"runtime"
"github.com/notaryproject/notation-go/plugin"
)
// Plugin represents a potential plugin with all it's metadata.
type Plugin struct {
plugin.Metadata
Path string `json:",omitempty"`
// Err is non-nil if the plugin failed one of the candidate tests.
Err error `json:",omitempty"`
}
// ErrNotFound is returned by Manager.Get and Manager.Run when the plugin is not found.
var ErrNotFound = errors.New("plugin not found")
// ErrNotCompliant is returned by Manager.Run when the plugin is found but not compliant.
var ErrNotCompliant = errors.New("plugin not compliant")
// commander is defined for mocking purposes.
type commander interface {
// Output runs the command, passing req to the its stdin.
// It only returns an error if the binary can't be executed.
// Returns stdout if success is true, stderr if success is false.
Output(ctx context.Context, path string, command string, req []byte) (out []byte, success bool, err error)
}
// execCommander implements the commander interface using exec.Command().
type execCommander struct{}
func (c execCommander) Output(ctx context.Context, name string, command string, req []byte) ([]byte, bool, error) {
var stdout, stderr bytes.Buffer
cmd := exec.CommandContext(ctx, name, command)
cmd.Stdin = bytes.NewReader(req)
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()
if _, ok := err.(*exec.ExitError); err != nil && !ok {
return nil, false, err
}
if !cmd.ProcessState.Success() {
return stderr.Bytes(), false, nil
}
return stdout.Bytes(), true, nil
}
// rootedFS is io.FS implementation used in New.
// root is the root of the file system tree passed to os.DirFS.
type rootedFS struct {
fs.FS
root string
}
// Manager manages plugins installed on the system.
type Manager struct {
fsys fs.FS
cmder commander
}
// New returns a new manager rooted at root.
//
// root is the path of the directory where plugins are stored
// following the {root}/{plugin-name}/notation-{plugin-name}[.exe] pattern.
func New(root string) *Manager {
return &Manager{rootedFS{os.DirFS(root), root}, execCommander{}}
}
// Get returns a plugin on the system by its name.
//
// If the plugin is not found, the error is of type ErrNotFound.
// The plugin might be incomplete if p.Err is not nil.
func (mgr *Manager) Get(ctx context.Context, name string) (*Plugin, error) {
return mgr.newPlugin(ctx, name)
}
// List produces a list of the plugins available on the system.
//
// Some plugins might be incomplete if their Err is not nil.
func (mgr *Manager) List(ctx context.Context) ([]*Plugin, error) {
var plugins []*Plugin
fs.WalkDir(mgr.fsys, ".", func(dir string, d fs.DirEntry, _ error) error {
if dir == "." {
// Ignore root dir.
return nil
}
typ := d.Type()
if !typ.IsDir() || typ&fs.ModeSymlink != 0 {
// Ignore non-directories and symlinked directories.
return nil
}
p, err := mgr.newPlugin(ctx, d.Name())
if err == nil {
plugins = append(plugins, p)
}
return fs.SkipDir
})
return plugins, nil
}
// Runner returns a plugin.Runner.
//
// If the plugin is not found or is not a valid candidate, the error is of type ErrNotFound.
func (mgr *Manager) Runner(name string) (plugin.Runner, error) {
ok := isCandidate(mgr.fsys, name)
if !ok {
return nil, ErrNotFound
}
return pluginRunner{name: name, path: binPath(mgr.fsys, name), cmder: mgr.cmder}, nil
}
// newPlugin determines if the given candidate is valid and returns a Plugin.
func (mgr *Manager) newPlugin(ctx context.Context, name string) (*Plugin, error) {
ok := isCandidate(mgr.fsys, name)
if !ok {
return nil, ErrNotFound
}
p := &Plugin{Path: binPath(mgr.fsys, name)}
out, err := run(ctx, mgr.cmder, p.Path, plugin.CommandGetMetadata, nil)
if err != nil {
p.Err = fmt.Errorf("failed to fetch metadata: %w", err)
return p, nil
}
p.Metadata = *out.(*plugin.Metadata)
if p.Name != name {
p.Err = fmt.Errorf("executable name must be %q instead of %q", addExeSuffix(plugin.Prefix+p.Name), filepath.Base(p.Path))
} else if err := p.Metadata.Validate(); err != nil {
p.Err = fmt.Errorf("invalid metadata: %w", err)
}
return p, nil
}
type pluginRunner struct {
name string
path string
cmder commander
}
func (p pluginRunner) Run(ctx context.Context, req plugin.Request) (interface{}, error) {
var data []byte
if req != nil {
var err error
data, err = json.Marshal(req)
if err != nil {
return nil, pluginErr(p.name, fmt.Errorf("failed to marshal request object: %w", err))
}
}
resp, err := run(ctx, p.cmder, p.path, req.Command(), data)
if err != nil {
return nil, pluginErr(p.name, err)
}
return resp, nil
}
// run executes the command and decodes the response.
func run(ctx context.Context, cmder commander, pluginPath string, cmd plugin.Command, req []byte) (interface{}, error) {
out, ok, err := cmder.Output(ctx, pluginPath, string(cmd), req)
if err != nil {
return nil, fmt.Errorf("failed running the plugin: %w", err)
}
if !ok {
var re plugin.RequestError
err = json.Unmarshal(out, &re)
if err != nil {
return nil, plugin.RequestError{Code: plugin.ErrorCodeGeneric, Err: fmt.Errorf("failed to decode json response: %w", ErrNotCompliant)}
}
return nil, re
}
var resp interface{}
switch cmd {
case plugin.CommandGetMetadata:
resp = new(plugin.Metadata)
case plugin.CommandGenerateSignature:
resp = new(plugin.GenerateSignatureResponse)
case plugin.CommandGenerateEnvelope:
resp = new(plugin.GenerateEnvelopeResponse)
case plugin.CommandDescribeKey:
resp = new(plugin.DescribeKeyResponse)
default:
return nil, fmt.Errorf("unsupported command: %s", cmd)
}
err = json.Unmarshal(out, resp)
if err != nil {
return nil, fmt.Errorf("failed to decode json response: %w", ErrNotCompliant)
}
return resp, nil
}
func pluginErr(name string, err error) error {
return fmt.Errorf("%s: %w", name, err)
}
// isCandidate checks if the named plugin is a valid candidate.
func isCandidate(fsys fs.FS, name string) bool {
base := binName(name)
fi, err := fs.Stat(fsys, path.Join(name, base))
if err != nil {
// Ignore any file which we cannot Stat
// (e.g. due to permissions or anything else).
return false
}
if !fi.Mode().IsRegular() {
// Ignore non-regular files.
return false
}
return true
}
func binName(name string) string {
return addExeSuffix(plugin.Prefix + name)
}
func binPath(fsys fs.FS, name string) string {
base := binName(name)
// New() always instantiate a rootedFS.
// Other fs.FS implementations are only supported for testing purposes.
if fsys, ok := fsys.(rootedFS); ok {
return filepath.Join(fsys.root, name, base)
}
return filepath.Join(name, base)
}
func addExeSuffix(s string) string {
if runtime.GOOS == "windows" {
s += ".exe"
}
return s
}