This repository has been archived by the owner on Sep 2, 2021. It is now read-only.
/
startup.go
383 lines (368 loc) · 11.3 KB
/
startup.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
package cli
import (
"fmt"
"io/ioutil"
"log"
"os"
"path"
"runtime"
"strconv"
"strings"
v4 "github.com/digitalrebar/provision/v4"
"github.com/digitalrebar/provision/v4/api"
"github.com/digitalrebar/provision/v4/models"
"github.com/spf13/cobra"
)
type registerSection func(*cobra.Command)
var (
version = v4.RSVersion
debug = false
catalog = "https://repo.rackn.io"
defaultCatalog = "https://repo.rackn.io"
endpoint = "https://127.0.0.1:8092"
defaultEndpoint = "https://127.0.0.1:8092"
defaultEndpoints = []string{"https://127.0.0.1:8092"}
token = ""
defaultToken = ""
username = "rocketskates"
defaultUsername = "rocketskates"
password = "r0cketsk8ts"
defaultPassword = "r0cketsk8ts"
downloadProxy = ""
defaultDownloadProxy = ""
format = ""
defaultFormat = "json"
printFields = ""
defaultPrintFields = ""
defaultTruncateLength = 40
truncateLength = 40
noHeader = false
defaultNoHeader = false
// Session is the global client access session
Session *api.Client
noToken = false
force = false
noPretty = false
ref = ""
defaultRef = ""
trace = ""
traceToken = ""
defaultUrlProxy = ""
urlProxy = ""
registrations = []registerSection{}
)
func addRegistrar(rs registerSection) {
registrations = append(registrations, rs)
}
var ppr = func(c *cobra.Command, a []string) error {
c.SilenceUsage = true
if Session == nil {
epInList := false
for i := range defaultEndpoints {
if defaultEndpoints[i] == endpoint {
epInList = true
break
}
}
if !epInList {
l := len(defaultEndpoints)
defaultEndpoints = append(defaultEndpoints, endpoint)
defaultEndpoints[0], defaultEndpoints[l] = defaultEndpoints[l], defaultEndpoints[0]
}
var sessErr error
for _, endpoint = range defaultEndpoints {
if token != "" {
Session, sessErr = api.TokenSession(endpoint, token)
} else {
home := os.ExpandEnv("${HOME}")
tPath := os.ExpandEnv("${RS_TOKEN_CACHE}")
if tPath == "" && home != "" {
tPath = path.Join(home, ".cache", "drpcli", "tokens")
}
tokenFile := path.Join(tPath, "."+username+".token")
if !noToken && tPath != "" {
if err := os.MkdirAll(tPath, 0700); err == nil {
if tokenStr, err := ioutil.ReadFile(tokenFile); err == nil {
Session, sessErr = api.TokenSession(endpoint, string(tokenStr))
if sessErr == nil {
if _, err := Session.Info(); err == nil {
Session.Trace(trace)
Session.TraceToken(traceToken)
break
}
}
}
}
}
Session, sessErr = api.UserSessionToken(endpoint, username, password, !noToken)
if !noToken && tPath != "" && sessErr == nil {
if err := os.MkdirAll(tPath, 700); err == nil {
tok := &models.UserToken{}
if err := Session.
Req().UrlFor("users", username, "token").
Params("ttl", "7200").Do(&tok); err == nil {
ioutil.WriteFile(tokenFile, []byte(tok.Token), 0600)
}
}
}
}
if sessErr == nil {
break
}
}
if sessErr != nil {
return fmt.Errorf("Error creating Session: %v", sessErr)
}
}
// We have a session.
Session.UrlProxy(urlProxy)
Session.Trace(trace)
Session.TraceToken(traceToken)
return nil
}
// NewApp is the app start function
func NewApp() *cobra.Command {
app := &cobra.Command{
Use: "drpcli",
Short: "A CLI application for interacting with the DigitalRebar Provision API",
}
if dep := os.Getenv("RS_ENDPOINTS"); dep != "" {
defaultEndpoints = strings.Split(dep, " ")
}
if ep := os.Getenv("RS_ENDPOINT"); ep != "" {
defaultEndpoints = []string{ep}
}
if ep := os.Getenv("RS_URL_PROXY"); ep != "" {
defaultUrlProxy = ep
}
if tk := os.Getenv("RS_TOKEN"); tk != "" {
defaultToken = tk
}
if tk := os.Getenv("RS_CATALOG"); tk != "" {
defaultCatalog = tk
}
if tk := os.Getenv("RS_FORMAT"); tk != "" {
defaultFormat = tk
}
if tk := os.Getenv("RS_PRINT_FIELDS"); tk != "" {
defaultPrintFields = tk
}
if tk := os.Getenv("RS_NO_HEADER"); tk != "" {
var e error
defaultNoHeader, e = strconv.ParseBool(tk)
if e != nil {
log.Fatal("RS_NO_HEADER should be a boolean value")
}
}
if tk := os.Getenv("RS_TRUNCATE_LENGTH"); tk != "" {
var e error
defaultTruncateLength, e = strconv.Atoi(tk)
if e != nil {
log.Fatal("RS_TRUNCATE_LENGTH should be an integer value")
}
}
if kv := os.Getenv("RS_KEY"); kv != "" {
key := strings.SplitN(kv, ":", 2)
if len(key) < 2 {
log.Fatal("RS_KEY does not contain a username:password pair!")
}
if key[0] == "" || key[1] == "" {
log.Fatal("RS_KEY contains an invalid username:password pair!")
}
defaultUsername = key[0]
defaultPassword = key[1]
}
home := os.ExpandEnv("${HOME}")
if data, err := ioutil.ReadFile(fmt.Sprintf("%s/.drpclirc", home)); err == nil {
lines := strings.Split(string(data), "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
parts := strings.SplitN(line, "=", 2)
switch parts[0] {
case "RS_NO_HEADER":
var e error
defaultNoHeader, e = strconv.ParseBool(parts[1])
if e != nil {
log.Fatal("RS_NO_HEADER should be a boolean value in drpclirc")
}
case "RS_ENDPOINT":
defaultEndpoints = []string{parts[1]}
case "RS_TOKEN":
defaultToken = parts[1]
case "RS_USERNAME":
defaultUsername = parts[1]
case "RS_PASSWORD":
defaultPassword = parts[1]
case "RS_URL_PROXY":
defaultUrlProxy = parts[1]
case "RS_DOWNLOAD_PROXY":
defaultDownloadProxy = parts[1]
case "RS_FORMAT":
defaultFormat = parts[1]
case "RS_PRINT_FIELDS":
defaultPrintFields = parts[1]
case "RS_TRUNCATE_LENGTH":
var e error
defaultTruncateLength, e = strconv.Atoi(parts[1])
if e != nil {
log.Fatal("RS_TRUNCATE_LENGTH should be an integer value in drpclirc")
}
case "RS_KEY":
key := strings.SplitN(parts[1], ":", 2)
if len(key) < 2 {
continue
}
if key[0] == "" || key[1] == "" {
continue
}
defaultUsername = key[0]
defaultPassword = key[1]
}
}
}
app.PersistentFlags().StringVarP(&endpoint,
"endpoint", "E", defaultEndpoints[0],
"The Digital Rebar Provision API endpoint to talk to")
app.PersistentFlags().StringVarP(&username,
"username", "U", defaultUsername,
"Name of the Digital Rebar Provision user to talk to")
app.PersistentFlags().StringVarP(&password,
"password", "P", defaultPassword,
"password of the Digital Rebar Provision user")
app.PersistentFlags().StringVarP(&token,
"token", "T", defaultToken,
"token of the Digital Rebar Provision access")
app.PersistentFlags().BoolVarP(&debug,
"debug", "d", false,
"Whether the CLI should run in debug mode")
app.PersistentFlags().StringVarP(&format,
"format", "F", defaultFormat,
`The serialization we expect for output. Can be "json" or "yaml" or "text" or "table"`)
app.PersistentFlags().StringVarP(&printFields,
"print-fields", "J", defaultPrintFields,
`The fields of the object to display in "text" or "table" mode. Comma separated`)
app.PersistentFlags().BoolVarP(&noHeader,
"no-header", "H", defaultNoHeader,
`Should header be shown in "text" or "table" mode`)
app.PersistentFlags().IntVarP(&truncateLength,
"truncate-length", "j", defaultTruncateLength,
`Truncate columns at this length`)
app.PersistentFlags().BoolVarP(&force,
"force", "f", false,
"When needed, attempt to force the operation - used on some update/patch calls")
app.PersistentFlags().StringVarP(&ref,
"ref", "r", defaultRef,
"A reference object for update commands that can be a file name, yaml, or json blob")
app.PersistentFlags().StringVarP(&trace,
"trace", "t", "",
"The log level API requests should be logged at on the server side")
app.PersistentFlags().StringVarP(&traceToken,
"traceToken", "Z", "",
"A token that individual traced requests should report in the server logs")
app.PersistentFlags().StringVarP(&catalog,
"catalog", "c", defaultCatalog,
"The catalog file to use to get product information")
app.PersistentFlags().StringVarP(&downloadProxy,
"download-proxy", "D", defaultDownloadProxy,
"HTTP Proxy to use for downloading catalog and content")
app.PersistentFlags().BoolVarP(&noToken,
"noToken", "x", noToken,
"Do not use token auth or token cache")
app.PersistentFlags().StringVarP(&urlProxy,
"url-proxy", "u", defaultUrlProxy,
"URL Proxy for passing actions through another DRP")
if runtime.GOOS != "windows" {
app.AddCommand(&cobra.Command{
Use: "proxy [socket]",
Short: "Run a local UNIX socket proxy for further drpcli commands. Requires RS_LOCAL_PROXY to be set in the env.",
RunE: func(c *cobra.Command, args []string) error {
if len(args) != 1 {
return fmt.Errorf("No location for the local proxy socket")
}
if pl := os.Getenv("RS_LOCAL_PROXY"); pl != "" {
return fmt.Errorf("Local proxy already running at %s", pl)
}
return Session.RunProxy(args[0])
},
})
}
for _, rs := range registrations {
rs(app)
}
for _, c := range app.Commands() {
// contents needs some help.
switch c.Use {
case "catalog":
for _, sc := range c.Commands() {
if strings.HasPrefix(sc.Use, "updateLocal") {
sc.PersistentPreRunE = ppr
}
}
case "contents":
for _, sc := range c.Commands() {
if !strings.HasPrefix(sc.Use, "bundle") &&
!strings.HasPrefix(sc.Use, "unbundle") &&
!strings.HasPrefix(sc.Use, "document") {
sc.PersistentPreRunE = ppr
}
}
case "users":
for _, sc := range c.Commands() {
if !strings.HasPrefix(sc.Use, "passwordhash") {
sc.PersistentPreRunE = ppr
}
}
case "support":
for _, sc := range c.Commands() {
if !strings.HasPrefix(sc.Use, "bundle") {
sc.PersistentPreRunE = ppr
}
}
default:
c.PersistentPreRunE = ppr
}
}
// top-level commands that do not need PersistentPreRun go here.
app.AddCommand(&cobra.Command{
Use: "version",
Short: "Digital Rebar Provision CLI Command Version",
RunE: func(cmd *cobra.Command, args []string) error {
fmt.Printf("Version: %v\n", version)
return nil
},
})
app.AddCommand(&cobra.Command{
Use: "autocomplete [filename]",
Short: "Generate CLI Command Bash AutoCompletion File (may require 'bash-completion' pkg be installed)",
Long: "Generate a bash autocomplete file as *filename*.\nPlace the generated file in /etc/bash_completion.d or /usr/local/etc/bash_completion.d.\nMay require the 'bash-completion' package is installed to work correctly.",
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) != 1 {
return fmt.Errorf("%v requires 1 argument", cmd.UseLine())
}
app.GenBashCompletionFile(args[0])
return nil
},
})
app.AddCommand(&cobra.Command{
Use: "gohai",
Short: "Get basic system information as a JSON blob",
Args: cobra.NoArgs,
RunE: func(c *cobra.Command, args []string) error {
return gohai()
},
})
app.AddCommand(&cobra.Command{
Use: "fingerprint",
Short: "Get the machine fingerprint used to determine what machine we are running on",
Args: cobra.NoArgs,
RunE: func(c *cobra.Command, args []string) error {
w := &models.Whoami{}
if err := w.Fill(); err != nil {
return err
}
return prettyPrint(w)
},
})
app.AddCommand(agentHandler)
return app
}