-
Notifications
You must be signed in to change notification settings - Fork 926
/
install_plugin_command.go
385 lines (314 loc) · 13.4 KB
/
install_plugin_command.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
package common
import (
"io/ioutil"
"os"
"runtime"
"strings"
"code.cloudfoundry.org/cli/actor/actionerror"
"code.cloudfoundry.org/cli/actor/pluginaction"
"code.cloudfoundry.org/cli/api/plugin"
"code.cloudfoundry.org/cli/api/plugin/pluginerror"
"code.cloudfoundry.org/cli/command"
"code.cloudfoundry.org/cli/command/flag"
"code.cloudfoundry.org/cli/command/plugin/shared"
"code.cloudfoundry.org/cli/command/translatableerror"
"code.cloudfoundry.org/cli/util"
"code.cloudfoundry.org/cli/util/configv3"
log "github.com/sirupsen/logrus"
)
//go:generate counterfeiter . InstallPluginActor
type InstallPluginActor interface {
CreateExecutableCopy(path string, tempPluginDir string) (string, error)
DownloadExecutableBinaryFromURL(url string, tempPluginDir string, proxyReader plugin.ProxyReader) (string, error)
FileExists(path string) bool
GetAndValidatePlugin(metadata pluginaction.PluginMetadata, commands pluginaction.CommandList, path string) (configv3.Plugin, error)
GetPlatformString(runtimeGOOS string, runtimeGOARCH string) string
GetPluginInfoFromRepositoriesForPlatform(pluginName string, pluginRepos []configv3.PluginRepository, platform string) (pluginaction.PluginInfo, []string, error)
GetPluginRepository(repositoryName string) (configv3.PluginRepository, error)
InstallPluginFromPath(path string, plugin configv3.Plugin) error
UninstallPlugin(uninstaller pluginaction.PluginUninstaller, name string) error
ValidateFileChecksum(path string, checksum string) bool
}
const installConfirmationPrompt = "Do you want to install the plugin {{.Path}}?"
type cancelInstall struct {
}
func (cancelInstall) Error() string {
return "Nobody should see this error. If you do, report it!"
}
type PluginSource int
const (
PluginFromRepository PluginSource = iota
PluginFromLocalFile
PluginFromURL
)
type InstallPluginCommand struct {
OptionalArgs flag.InstallPluginArgs `positional-args:"yes"`
SkipSSLValidation bool `short:"k" hidden:"true" description:"Skip SSL certificate validation"`
Force bool `short:"f" description:"Force install of plugin without confirmation"`
RegisteredRepository string `short:"r" description:"Restrict search for plugin to this registered repository"`
usage interface{} `usage:"CF_NAME install-plugin PLUGIN_NAME [-r REPO_NAME] [-f]\n CF_NAME install-plugin LOCAL-PATH/TO/PLUGIN | URL [-f]\n\nWARNING:\n Plugins are binaries written by potentially untrusted authors.\n Install and use plugins at your own risk.\n\nEXAMPLES:\n CF_NAME install-plugin ~/Downloads/plugin-foobar\n CF_NAME install-plugin https://example.com/plugin-foobar_linux_amd64\n CF_NAME install-plugin -r My-Repo plugin-echo"`
relatedCommands interface{} `related_commands:"add-plugin-repo, list-plugin-repos, plugins"`
UI command.UI
Config command.Config
Actor InstallPluginActor
ProgressBar plugin.ProxyReader
}
func (cmd *InstallPluginCommand) Setup(config command.Config, ui command.UI) error {
cmd.UI = ui
cmd.Config = config
cmd.Actor = pluginaction.NewActor(config, shared.NewClient(config, ui, cmd.SkipSSLValidation))
cmd.ProgressBar = shared.NewProgressBarProxyReader(cmd.UI.Writer())
return nil
}
func (cmd InstallPluginCommand) Execute([]string) error {
log.WithField("PluginHome", cmd.Config.PluginHome()).Info("making plugin dir")
tempPluginDir, err := ioutil.TempDir(cmd.Config.PluginHome(), "temp")
log.WithField("tempPluginDir", tempPluginDir).Debug("making tempPluginDir dir")
defer os.RemoveAll(tempPluginDir)
if err != nil {
return err
}
tempPluginPath, pluginSource, err := cmd.getPluginBinaryAndSource(tempPluginDir)
if _, ok := err.(cancelInstall); ok {
cmd.UI.DisplayText("Plugin installation cancelled.")
return nil
} else if err != nil {
return err
}
log.WithFields(log.Fields{"tempPluginPath": tempPluginPath, "pluginSource": pluginSource}).Debug("getPluginBinaryAndSource")
// copy twice when downloading from a URL to keep Windows specific code
// isolated to CreateExecutableCopy
executablePath, err := cmd.Actor.CreateExecutableCopy(tempPluginPath, tempPluginDir)
if err != nil {
return err
}
log.WithField("executablePath", executablePath).Debug("created executable copy")
rpcService, err := shared.NewRPCService(cmd.Config, cmd.UI)
if err != nil {
return err
}
log.Info("started RPC server")
plugin, err := cmd.Actor.GetAndValidatePlugin(rpcService, Commands, executablePath)
if err != nil {
return err
}
log.Info("validated plugin")
if installedPlugin, installed := cmd.Config.GetPluginCaseInsensitive(plugin.Name); installed {
log.WithField("version", installedPlugin.Version).Debug("uninstall plugin")
if !cmd.Force && pluginSource != PluginFromRepository {
return translatableerror.PluginAlreadyInstalledError{
BinaryName: cmd.Config.BinaryName(),
Name: plugin.Name,
Version: plugin.Version.String(),
}
}
err = cmd.uninstallPlugin(installedPlugin, rpcService)
if err != nil {
return err
}
}
log.Info("install plugin")
return cmd.installPlugin(plugin, executablePath)
}
func (cmd InstallPluginCommand) installPlugin(plugin configv3.Plugin, pluginPath string) error {
cmd.UI.DisplayTextWithFlavor("Installing plugin {{.Name}}...", map[string]interface{}{
"Name": plugin.Name,
})
installErr := cmd.Actor.InstallPluginFromPath(pluginPath, plugin)
if installErr != nil {
return installErr
}
cmd.UI.DisplayOK()
cmd.UI.DisplayText("Plugin {{.Name}} {{.Version}} successfully installed.", map[string]interface{}{
"Name": plugin.Name,
"Version": plugin.Version.String(),
})
return nil
}
func (cmd InstallPluginCommand) uninstallPlugin(plugin configv3.Plugin, rpcService *shared.RPCService) error {
cmd.UI.DisplayText("Plugin {{.Name}} {{.Version}} is already installed. Uninstalling existing plugin...", map[string]interface{}{
"Name": plugin.Name,
"Version": plugin.Version.String(),
})
uninstallErr := cmd.Actor.UninstallPlugin(rpcService, plugin.Name)
if uninstallErr != nil {
return uninstallErr
}
cmd.UI.DisplayOK()
cmd.UI.DisplayText("Plugin {{.Name}} successfully uninstalled.", map[string]interface{}{
"Name": plugin.Name,
})
return nil
}
func (cmd InstallPluginCommand) getPluginBinaryAndSource(tempPluginDir string) (string, PluginSource, error) {
pluginNameOrLocation := cmd.OptionalArgs.PluginNameOrLocation.String()
switch {
case cmd.RegisteredRepository != "":
log.WithField("RegisteredRepository", cmd.RegisteredRepository).Info("installing from specified repository")
pluginRepository, err := cmd.Actor.GetPluginRepository(cmd.RegisteredRepository)
if err != nil {
return "", 0, err
}
path, pluginSource, err := cmd.getPluginFromRepositories(pluginNameOrLocation, []configv3.PluginRepository{pluginRepository}, tempPluginDir)
if err != nil {
switch pluginErr := err.(type) {
case actionerror.PluginNotFoundInAnyRepositoryError:
return "", 0, translatableerror.PluginNotFoundInRepositoryError{
BinaryName: cmd.Config.BinaryName(),
PluginName: pluginNameOrLocation,
RepositoryName: cmd.RegisteredRepository,
}
case actionerror.FetchingPluginInfoFromRepositoryError:
// The error wrapped inside pluginErr is handled differently in the case of
// a specified repo from that of searching through all repos. pluginErr.Err
// is then processed by shared.HandleError by this function's caller.
return "", 0, pluginErr.Err
default:
return "", 0, err
}
}
return path, pluginSource, nil
case cmd.Actor.FileExists(pluginNameOrLocation):
log.WithField("pluginNameOrLocation", pluginNameOrLocation).Info("installing from specified file")
return cmd.getPluginFromLocalFile(pluginNameOrLocation)
case util.IsHTTPScheme(pluginNameOrLocation):
log.WithField("pluginNameOrLocation", pluginNameOrLocation).Info("installing from specified URL")
return cmd.getPluginFromURL(pluginNameOrLocation, tempPluginDir)
case util.IsUnsupportedURLScheme(pluginNameOrLocation):
log.WithField("pluginNameOrLocation", pluginNameOrLocation).Error("Unsupported URL")
return "", 0, translatableerror.UnsupportedURLSchemeError{UnsupportedURL: pluginNameOrLocation}
default:
log.Info("installing from first repository with plugin")
repos := cmd.Config.PluginRepositories()
if len(repos) == 0 {
return "", 0, translatableerror.PluginNotFoundOnDiskOrInAnyRepositoryError{PluginName: pluginNameOrLocation, BinaryName: cmd.Config.BinaryName()}
}
path, pluginSource, err := cmd.getPluginFromRepositories(pluginNameOrLocation, repos, tempPluginDir)
if err != nil {
switch pluginErr := err.(type) {
case actionerror.PluginNotFoundInAnyRepositoryError:
return "", 0, translatableerror.PluginNotFoundOnDiskOrInAnyRepositoryError{PluginName: pluginNameOrLocation, BinaryName: cmd.Config.BinaryName()}
case actionerror.FetchingPluginInfoFromRepositoryError:
return "", 0, cmd.handleFetchingPluginInfoFromRepositoriesError(pluginErr)
default:
return "", 0, err
}
}
return path, pluginSource, nil
}
}
// These are specific errors that we output to the user in the context of
// installing from any repository.
func (InstallPluginCommand) handleFetchingPluginInfoFromRepositoriesError(fetchErr actionerror.FetchingPluginInfoFromRepositoryError) error {
switch clientErr := fetchErr.Err.(type) {
case pluginerror.RawHTTPStatusError:
return translatableerror.FetchingPluginInfoFromRepositoriesError{
Message: clientErr.Status,
RepositoryName: fetchErr.RepositoryName,
}
case pluginerror.SSLValidationHostnameError:
return translatableerror.FetchingPluginInfoFromRepositoriesError{
Message: clientErr.Error(),
RepositoryName: fetchErr.RepositoryName,
}
case pluginerror.UnverifiedServerError:
return translatableerror.FetchingPluginInfoFromRepositoriesError{
Message: clientErr.Error(),
RepositoryName: fetchErr.RepositoryName,
}
default:
return clientErr
}
}
func (cmd InstallPluginCommand) getPluginFromLocalFile(pluginLocation string) (string, PluginSource, error) {
err := cmd.installPluginPrompt(installConfirmationPrompt, map[string]interface{}{
"Path": pluginLocation,
})
if err != nil {
return "", 0, err
}
return pluginLocation, PluginFromLocalFile, err
}
func (cmd InstallPluginCommand) getPluginFromURL(pluginLocation string, tempPluginDir string) (string, PluginSource, error) {
err := cmd.installPluginPrompt(installConfirmationPrompt, map[string]interface{}{
"Path": pluginLocation,
})
if err != nil {
return "", 0, err
}
cmd.UI.DisplayText("Starting download of plugin binary from URL...")
tempPath, err := cmd.Actor.DownloadExecutableBinaryFromURL(pluginLocation, tempPluginDir, cmd.ProgressBar)
if err != nil {
return "", 0, err
}
return tempPath, PluginFromURL, err
}
func (cmd InstallPluginCommand) getPluginFromRepositories(pluginName string, repos []configv3.PluginRepository, tempPluginDir string) (string, PluginSource, error) {
var repoNames []string
for _, repo := range repos {
repoNames = append(repoNames, repo.Name)
}
cmd.UI.DisplayTextWithFlavor("Searching {{.RepositoryName}} for plugin {{.PluginName}}...", map[string]interface{}{
"RepositoryName": strings.Join(repoNames, ", "),
"PluginName": pluginName,
})
currentPlatform := cmd.Actor.GetPlatformString(runtime.GOOS, runtime.GOARCH)
pluginInfo, repoList, err := cmd.Actor.GetPluginInfoFromRepositoriesForPlatform(pluginName, repos, currentPlatform)
if err != nil {
return "", 0, err
}
cmd.UI.DisplayText("Plugin {{.PluginName}} {{.PluginVersion}} found in: {{.RepositoryName}}", map[string]interface{}{
"PluginName": pluginName,
"PluginVersion": pluginInfo.Version,
"RepositoryName": strings.Join(repoList, ", "),
})
installedPlugin, exist := cmd.Config.GetPlugin(pluginName)
if exist {
cmd.UI.DisplayText("Plugin {{.PluginName}} {{.PluginVersion}} is already installed.", map[string]interface{}{
"PluginName": installedPlugin.Name,
"PluginVersion": installedPlugin.Version.String(),
})
err = cmd.installPluginPrompt("Do you want to uninstall the existing plugin and install {{.Path}} {{.PluginVersion}}?", map[string]interface{}{
"Path": pluginName,
"PluginVersion": pluginInfo.Version,
})
} else {
err = cmd.installPluginPrompt(installConfirmationPrompt, map[string]interface{}{
"Path": pluginName,
})
}
if err != nil {
return "", 0, err
}
cmd.UI.DisplayText("Starting download of plugin binary from repository {{.RepositoryName}}...", map[string]interface{}{
"RepositoryName": repoList[0],
})
tempPath, err := cmd.Actor.DownloadExecutableBinaryFromURL(pluginInfo.URL, tempPluginDir, cmd.ProgressBar)
if err != nil {
return "", 0, err
}
if !cmd.Actor.ValidateFileChecksum(tempPath, pluginInfo.Checksum) {
return "", 0, translatableerror.InvalidChecksumError{}
}
return tempPath, PluginFromRepository, err
}
func (cmd InstallPluginCommand) installPluginPrompt(template string, templateValues ...map[string]interface{}) error {
cmd.UI.DisplayHeader("Attention: Plugins are binaries written by potentially untrusted authors.")
cmd.UI.DisplayHeader("Install and use plugins at your own risk.")
if cmd.Force {
return nil
}
var (
really bool
promptErr error
)
really, promptErr = cmd.UI.DisplayBoolPrompt(false, template, templateValues...)
if promptErr != nil {
return promptErr
}
if !really {
log.Debug("plugin confirmation - 'no' inputed")
return cancelInstall{}
}
return nil
}