-
Notifications
You must be signed in to change notification settings - Fork 2
/
seed.go
289 lines (268 loc) · 7.74 KB
/
seed.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
package appliance
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"github.com/AlecAivazis/survey/v2"
"github.com/appgate/sdp-api-client-go/api/v20/openapi"
"github.com/appgate/sdpctl/pkg/api"
appliancepkg "github.com/appgate/sdpctl/pkg/appliance"
"github.com/appgate/sdpctl/pkg/configuration"
"github.com/appgate/sdpctl/pkg/docs"
"github.com/appgate/sdpctl/pkg/factory"
"github.com/appgate/sdpctl/pkg/prompt"
"github.com/appgate/sdpctl/pkg/util"
"github.com/spf13/cobra"
)
type seedOpts struct {
Config *configuration.Config
Out io.Writer
In io.ReadCloser
Appliance func(c *configuration.Config) (*appliancepkg.Appliance, error)
debug bool
CanPrompt bool
json bool
// Seed config options
applianceID string
password string
sshKey string
provideCloudSSHKey bool
allowCustomization bool
validityDays int
iso bool
format seedformat
}
type authmethod int
const (
cloud authmethod = iota
publicKey
passphrase
)
type seedformat int
const (
jsonFormat seedformat = iota
isoFormat
)
// NewSeedCmd return a new appliance seed command
func NewSeedCmd(f *factory.Factory) *cobra.Command {
opts := seedOpts{
Config: f.Config,
Appliance: f.Appliance,
debug: f.Config.Debug,
Out: f.IOOutWriter,
In: f.Stdin,
CanPrompt: f.CanPrompt(),
}
var cmd = &cobra.Command{
Use: "export-seed",
Short: docs.ApplianceSeedDocs.Short,
Long: docs.ApplianceSeedDocs.Long,
Example: docs.ApplianceSeedDocs.ExampleString(),
PreRunE: func(cmd *cobra.Command, args []string) error {
noInteractive, err := cmd.Flags().GetBool("no-interactive")
if err != nil {
return err
}
a, err := opts.Appliance(opts.Config)
if err != nil {
return err
}
ctx := context.Background()
filter := map[string]map[string]string{
"include": {
"activated": "false",
},
}
orderBy, err := cmd.Flags().GetStringSlice("order-by")
if err != nil {
return err
}
descending, err := cmd.Flags().GetBool("descending")
if err != nil {
return err
}
switch len(args) {
// no arguments will provider a interactive experience for the user, if TTY support it
case 0:
if noInteractive || !opts.CanPrompt {
return errors.New("can't prompt, You need to provide all arguments")
}
applianceID, err := appliancepkg.PromptSelectAll(ctx, a, filter, orderBy, descending)
if err != nil {
// no inactive appliance found
return nil
}
opts.applianceID = applianceID
format := []string{
jsonFormat: "JSON format",
isoFormat: "ISO format",
}
qs := &survey.Select{
PageSize: len(format),
Message: "Seed type:",
Options: format,
}
selectedFormat := 0
if err := prompt.SurveyAskOne(qs, &selectedFormat, survey.WithValidator(survey.Required)); err != nil {
return err
}
opts.format = seedformat(selectedFormat)
if opts.format == isoFormat {
opts.iso = true
}
methods := []string{
cloud: "Use SSH key provided by the cloud instance",
publicKey: "Use SSH public key",
passphrase: "Use Password",
}
qs = &survey.Select{
PageSize: len(methods),
Message: "SSH Authentication Method:",
Options: methods,
}
selectedIndex := 0
if err := prompt.SurveyAskOne(qs, &selectedIndex, survey.WithValidator(survey.Required)); err != nil {
return err
}
switch selectedIndex {
case int(cloud):
opts.provideCloudSSHKey = true
case int(publicKey):
qs := &survey.Input{
Message: "path to public ssh key:",
}
if err := prompt.SurveyAskOne(qs, &opts.sshKey); err != nil {
return err
}
case int(passphrase):
hasStdin := false
stat, err := os.Stdin.Stat()
if err == nil && (stat.Mode()&os.ModeCharDevice) == 0 {
hasStdin = true
}
password, err := prompt.GetPassphrase(opts.In, opts.CanPrompt, hasStdin, "Appliance's CZ user password:")
if err != nil {
return err
}
opts.password = password
}
case 1:
if !util.IsUUID(args[0]) {
return errors.New("expected appliance UUID")
}
opts.applianceID = args[0]
}
return nil
},
RunE: func(c *cobra.Command, args []string) error {
return seedRun(c, args, &opts)
},
}
cmd.Flags().BoolVar(&opts.provideCloudSSHKey, "provide-cloud-ssh-key", false, "Tells appliance to use the key generated by AWS or Azure")
cmd.Flags().BoolVar(&opts.allowCustomization, "allow-customization", false, "Whether the Appliance should allow customizations or not")
cmd.Flags().BoolVar(&opts.iso, "iso-format", false, "Export as ISO format")
cmd.Flags().BoolVar(&opts.json, "json", false, "output as json to stdout, only applicable in json seed type")
cmd.Flags().StringVarP(&opts.sshKey, "ssh-key", "", "", "filepath to public ssh key to be allowed")
cmd.Flags().IntVarP(&opts.validityDays, "validity-days", "", 1, "How many days the seed should be valid for")
return cmd
}
func seedRun(cmd *cobra.Command, args []string, opts *seedOpts) error {
if len(opts.applianceID) == 0 {
fmt.Fprintln(opts.Out, "no inactive appliance found")
return nil
}
cfg := opts.Config
a, err := opts.Appliance(cfg)
if err != nil {
return err
}
token, err := opts.Config.GetBearTokenHeaderValue()
if err != nil {
return err
}
ctx := context.Background()
appliance, err := a.Get(ctx, opts.applianceID)
if err != nil {
return err
}
if appliance.GetActivated() {
return fmt.Errorf("appliance %s is already activated", appliance.GetName())
}
sshConfig := openapi.NewSSHConfig()
if cfg.Version < 15 {
sshConfig.AllowCustomization = nil
sshConfig.ValidityDays = nil
}
sshConfig.AllowCustomization = openapi.PtrBool(opts.allowCustomization)
sshConfig.ValidityDays = openapi.PtrFloat32(float32(opts.validityDays))
if len(opts.sshKey) > 0 {
pub, err := readFile(opts.sshKey)
if err != nil {
return err
}
sshConfig.SetSshKey(pub)
} else if opts.provideCloudSSHKey {
sshConfig.SetProvideCloudSSHKey(true)
} else if len(opts.password) < 1 {
hasStdin := false
stat, err := os.Stdin.Stat()
if err == nil && (stat.Mode()&os.ModeCharDevice) == 0 {
hasStdin = true
}
password, err := prompt.GetPassphrase(opts.In, false, hasStdin, "")
if err != nil {
return errors.New("You need to provide passphrase through stdin or select --ssh-key=/path/to/key.pub or --provide-cloud-ssh-key")
}
sshConfig.SetPassword(password)
} else {
sshConfig.SetPassword(opts.password)
}
var (
data []byte
ext string
)
if opts.iso {
seed, response, err := a.APIClient.AppliancesApi.AppliancesIdExportIsoPost(ctx, appliance.GetId()).SSHConfig(*sshConfig).Authorization(token).Execute()
if err != nil {
return api.HTTPErrorResponse(response, err)
}
data = []byte(seed.GetIso())
ext = "iso"
} else {
seed, response, err := a.APIClient.AppliancesApi.AppliancesIdExportPost(ctx, appliance.GetId()).SSHConfig(*sshConfig).Authorization(token).Execute()
if err != nil {
return api.HTTPErrorResponse(response, err)
}
encodedSeed, err := json.MarshalIndent(seed, "", " ")
if err != nil {
return fmt.Errorf("Could not parse json seed file: %w", err)
}
if opts.json {
fmt.Fprintln(opts.Out, string(encodedSeed))
return nil
}
data = encodedSeed
ext = "json"
}
path, err := os.Getwd()
if err != nil {
return err
}
outputfile := filepath.Join(path, fmt.Sprintf("%s_seed.%s", appliance.GetId(), ext))
if err := os.WriteFile(outputfile, data, 0644); err != nil {
return err
}
fmt.Fprintf(opts.Out, "Saved appliance %s seed file to %s\n", appliance.GetName(), outputfile)
return nil
}
func readFile(p string) (string, error) {
dat, err := os.ReadFile(p)
if err != nil {
return "", err
}
return string(dat), nil
}