|
| 1 | +package command |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "os/exec" |
| 6 | + "path/filepath" |
| 7 | + "runtime" |
| 8 | + "strings" |
| 9 | + |
| 10 | + hcplugin "github.com/hashicorp/go-plugin" |
| 11 | + "github.com/spf13/viper" |
| 12 | +) |
| 13 | + |
| 14 | +// PluginError retains an error object and the name of the pack that generated it |
| 15 | +type PluginError struct { |
| 16 | + Plugin string |
| 17 | + Err error |
| 18 | +} |
| 19 | + |
| 20 | +// PluginErrors holds a list of errors and an Error() method |
| 21 | +// so it adheres to the standard Error interface |
| 22 | +type PluginErrors struct { |
| 23 | + Errors []PluginError |
| 24 | +} |
| 25 | + |
| 26 | +func (e *PluginErrors) Error() string { |
| 27 | + return fmt.Sprintf("Service Pack Errors: %v", e.Errors) |
| 28 | +} |
| 29 | + |
| 30 | +type PluginPkg struct { |
| 31 | + Name string |
| 32 | + Path string |
| 33 | + ServiceTarget string |
| 34 | + Command *exec.Cmd |
| 35 | + Result string |
| 36 | + |
| 37 | + Available bool |
| 38 | + Requested bool |
| 39 | + Successful bool |
| 40 | + Error error |
| 41 | +} |
| 42 | + |
| 43 | +func (p *PluginPkg) getBinary() (binaryName string, err error) { |
| 44 | + p.Name = filepath.Base(strings.ToLower(p.Name)) // in some cases a filepath may arrive here instead of the base name; overwrite if so |
| 45 | + if runtime.GOOS == "windows" && !strings.HasSuffix(p.Name, ".exe") { |
| 46 | + p.Name = fmt.Sprintf("%s.exe", p.Name) |
| 47 | + } |
| 48 | + plugins, _ := hcplugin.Discover(p.Name, viper.GetString("binaries-path")) |
| 49 | + if len(plugins) != 1 { |
| 50 | + err = fmt.Errorf("failed to locate requested plugin '%s' at path '%s'", p.Name, viper.GetString("binaries-path")) |
| 51 | + return |
| 52 | + } |
| 53 | + binaryName = plugins[0] |
| 54 | + |
| 55 | + return |
| 56 | +} |
| 57 | + |
| 58 | +func (p *PluginPkg) queueCmd() { |
| 59 | + cmd := exec.Command(p.Path) |
| 60 | + flags := []string{ |
| 61 | + fmt.Sprintf("--config=%s", viper.GetString("config")), |
| 62 | + fmt.Sprintf("--loglevel=%s", viper.GetString("loglevel")), |
| 63 | + fmt.Sprintf("--service=%s", p.ServiceTarget), |
| 64 | + } |
| 65 | + for _, flag := range flags { |
| 66 | + cmd.Args = append(cmd.Args, flag) |
| 67 | + p.Command = cmd |
| 68 | + } |
| 69 | +} |
| 70 | + |
| 71 | +func NewPluginPkg(pluginName string, serviceName string) *PluginPkg { |
| 72 | + plugin := &PluginPkg{ |
| 73 | + Name: pluginName, |
| 74 | + } |
| 75 | + path, err := plugin.getBinary() |
| 76 | + if err != nil { |
| 77 | + plugin.Error = err |
| 78 | + } |
| 79 | + plugin.Path = path |
| 80 | + plugin.ServiceTarget = serviceName |
| 81 | + plugin.queueCmd() |
| 82 | + return plugin |
| 83 | +} |
0 commit comments