-
Notifications
You must be signed in to change notification settings - Fork 310
/
Copy pathmain.go
374 lines (315 loc) · 10.6 KB
/
main.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
//
// (C) Copyright 2018-2023 Intel Corporation.
//
// SPDX-License-Identifier: BSD-2-Clause-Patent
//
package main
import (
"encoding/json"
"fmt"
"io"
"os"
"path"
flags "github.com/jessevdk/go-flags"
"github.com/pkg/errors"
"github.com/daos-stack/daos/src/control/build"
"github.com/daos-stack/daos/src/control/common"
"github.com/daos-stack/daos/src/control/common/cmdutil"
"github.com/daos-stack/daos/src/control/fault"
"github.com/daos-stack/daos/src/control/lib/atm"
"github.com/daos-stack/daos/src/control/lib/control"
"github.com/daos-stack/daos/src/control/lib/daos"
"github.com/daos-stack/daos/src/control/lib/hostlist"
"github.com/daos-stack/daos/src/control/lib/ui"
"github.com/daos-stack/daos/src/control/logging"
)
type (
hostListGetter interface {
getHostList() []string
}
hostListSetter interface {
setHostList(*hostlist.HostSet)
}
hostListCmd struct {
HostList ui.HostSetFlag `short:"l" long:"host-list" description:"A comma separated list of addresses <ipv4addr/hostname> to connect to"`
hostlist []string
}
singleHostCmd struct {
HostList singleHostFlag `short:"l" long:"host-list" default:"localhost" description:"Single host address <ipv4addr/hostname> to connect to"`
host string
}
ctlInvoker interface {
setInvoker(control.Invoker)
}
ctlInvokerCmd struct {
ctlInvoker control.Invoker
}
jsonOutputter interface {
enableJsonOutput(bool, io.Writer, *atm.Bool)
jsonOutputEnabled() bool
outputJSON(interface{}, error) error
errorJSON(error) error
}
jsonOutputCmd struct {
wroteJSON *atm.Bool
writer io.Writer
shouldEmitJSON bool
}
)
func (cmd *ctlInvokerCmd) setInvoker(c control.Invoker) {
cmd.ctlInvoker = c
}
func (cmd *hostListCmd) getHostList() []string {
if cmd.hostlist == nil && !cmd.HostList.Empty() {
cmd.hostlist = cmd.HostList.Slice()
}
return cmd.hostlist
}
func (cmd *hostListCmd) setHostList(newList *hostlist.HostSet) {
cmd.HostList.Replace(newList)
}
func (cmd *singleHostCmd) getHostList() []string {
if cmd.host == "" {
if cmd.HostList.Count() == 0 {
cmd.host = "localhost"
} else {
cmd.host = cmd.HostList.Slice()[0]
}
}
return []string{cmd.host}
}
func (cmd *singleHostCmd) setHostList(newList *hostlist.HostSet) {
cmd.HostList.Replace(newList)
}
func (cmd *jsonOutputCmd) enableJsonOutput(emitJson bool, w io.Writer, wj *atm.Bool) {
cmd.shouldEmitJSON = emitJson
cmd.writer = w
cmd.wroteJSON = wj
}
func (cmd *jsonOutputCmd) jsonOutputEnabled() bool {
return cmd.shouldEmitJSON
}
func outputJSON(out io.Writer, in interface{}, cmdErr error) error {
status := 0
var errStr *string
if cmdErr != nil {
errStr = new(string)
*errStr = cmdErr.Error()
if s, ok := errors.Cause(cmdErr).(daos.Status); ok {
status = int(s)
} else {
status = int(daos.MiscError)
}
}
data, err := json.MarshalIndent(struct {
Response interface{} `json:"response"`
Error *string `json:"error"`
Status int `json:"status"`
}{in, errStr, status}, "", " ")
if err != nil {
fmt.Fprintf(out, "unable to marshal json: %s\n", err.Error())
return err
}
if _, err = out.Write(append(data, []byte("\n")...)); err != nil {
fmt.Fprintf(out, "unable to write json: %s\n", err.Error())
return err
}
return cmdErr
}
func (cmd *jsonOutputCmd) outputJSON(in interface{}, cmdErr error) error {
if cmd.wroteJSON.IsTrue() {
return cmdErr
}
cmd.wroteJSON.SetTrue()
return outputJSON(cmd.writer, in, cmdErr)
}
func errorJSON(err error) error {
return outputJSON(os.Stdout, nil, err)
}
func (cmd *jsonOutputCmd) errorJSON(err error) error {
return cmd.outputJSON(nil, err)
}
var _ jsonOutputter = (*jsonOutputCmd)(nil)
type cmdLogger interface {
setLog(*logging.LeveledLogger)
}
type baseCmd struct {
cmdutil.NoArgsCmd
cmdutil.LogCmd
}
// cmdConfigSetter is an interface for setting the control config on a command
type cmdConfigSetter interface {
setConfig(*control.Config)
}
// cfgCmd is a structure that can be used by commands that need the control
// config.
type cfgCmd struct {
config *control.Config
}
func (c *cfgCmd) setConfig(cfg *control.Config) {
c.config = cfg
}
type cliOptions struct {
AllowProxy bool `long:"allow-proxy" description:"Allow proxy configuration via environment"`
HostList ui.HostSetFlag `short:"l" long:"host-list" hidden:"true" description:"DEPRECATED: A comma separated list of addresses <ipv4addr/hostname> to connect to"`
Insecure bool `short:"i" long:"insecure" description:"Have dmg attempt to connect without certificates"`
Debug bool `short:"d" long:"debug" description:"Enable debug output"`
LogFile string `long:"log-file" description:"Log command output to the specified file"`
JSON bool `short:"j" long:"json" description:"Enable JSON output"`
JSONLogs bool `short:"J" long:"json-logging" description:"Enable JSON-formatted log output"`
ConfigPath string `short:"o" long:"config-path" description:"Client config file path"`
Server serverCmd `command:"server" alias:"srv" description:"Perform tasks related to remote servers"`
Storage storageCmd `command:"storage" alias:"sto" description:"Perform tasks related to storage attached to remote servers"`
Config configCmd `command:"config" alias:"cfg" description:"Perform tasks related to configuration of hardware on remote servers"`
System SystemCmd `command:"system" alias:"sys" description:"Perform distributed tasks related to DAOS system"`
Network NetCmd `command:"network" alias:"net" description:"Perform tasks related to network devices attached to remote servers"`
Support supportCmd `command:"support" alias:"supp" description:"Perform debug tasks to help support team"`
Pool PoolCmd `command:"pool" description:"Perform tasks related to DAOS pools"`
Cont ContCmd `command:"container" alias:"cont" description:"Perform tasks related to DAOS containers"`
Version versionCmd `command:"version" description:"Print dmg version"`
Telemetry telemCmd `command:"telemetry" alias:"telem" description:"Perform telemetry operations"`
firmwareOption // build with tag "firmware" to enable
ManPage cmdutil.ManCmd `command:"manpage" hidden:"true"`
}
type versionCmd struct{}
func (cmd *versionCmd) Execute(_ []string) error {
fmt.Printf("dmg version %s\n", build.DaosVersion)
os.Exit(0)
return nil
}
func exitWithError(log logging.Logger, err error) {
cmdName := path.Base(os.Args[0])
log.Errorf("%s: %v", cmdName, err)
if fault.HasResolution(err) {
log.Errorf("%s: %s", cmdName, fault.ShowResolutionFor(err))
}
os.Exit(1)
}
func parseOpts(args []string, opts *cliOptions, invoker control.Invoker, log *logging.LeveledLogger) error {
var wroteJSON atm.Bool
p := flags.NewParser(opts, flags.Default)
p.Name = "dmg"
p.ShortDescription = "Administrative tool for managing DAOS clusters"
p.LongDescription = `dmg (DAOS Management) is a tool for connecting to DAOS servers
for the purpose of issuing administrative commands to the cluster. dmg is
provided as a means for allowing administrators to securely discover and
administer DAOS components such as storage allocations, network configuration,
and access control settings, along with system wide operations.`
p.Options ^= flags.PrintErrors // Don't allow the library to print errors
p.CommandHandler = func(cmd flags.Commander, args []string) error {
if cmd == nil {
return nil
}
if manCmd, ok := cmd.(cmdutil.ManPageWriter); ok {
manCmd.SetWriteFunc(p.WriteManPage)
// Just execute now without any more setup.
return cmd.Execute(args)
}
if !opts.AllowProxy {
common.ScrubProxyVariables()
}
if opts.LogFile != "" {
f, err := common.AppendFile(opts.LogFile)
if err != nil {
return errors.WithMessage(err, "create log file")
}
defer f.Close()
log.Debugf("%s logging to file %s",
os.Args[0], opts.LogFile)
// Create an additional set of loggers which append everything
// to the specified file.
log = log.
WithErrorLogger(logging.NewErrorLogger("dmg", f)).
WithNoticeLogger(logging.NewNoticeLogger("dmg", f)).
WithInfoLogger(logging.NewInfoLogger("dmg", f)).
WithDebugLogger(logging.NewDebugLogger(f)).
WithTraceLogger(logging.NewTraceLogger(f))
}
if opts.Debug {
log.SetLevel(logging.LogLevelTrace)
log.Debug("debug output enabled")
}
if opts.JSONLogs {
log.WithJSONOutput()
}
if jsonCmd, ok := cmd.(jsonOutputter); ok {
jsonCmd.enableJsonOutput(opts.JSON, os.Stdout, &wroteJSON)
if opts.JSON {
// disable output on stdout other than JSON
log.ClearLevel(logging.LogLevelInfo)
}
}
if logCmd, ok := cmd.(cmdutil.LogSetter); ok {
logCmd.SetLog(log)
}
ctlCfg, err := control.LoadConfig(opts.ConfigPath)
if err != nil {
if errors.Cause(err) != control.ErrNoConfigFile {
return errors.Wrap(err, "failed to load control configuration")
}
// Use the default config if no config file was found.
ctlCfg = control.DefaultConfig()
}
if ctlCfg.Path != "" {
log.Debugf("control config loaded from %s", ctlCfg.Path)
}
if opts.Insecure {
ctlCfg.TransportConfig.AllowInsecure = true
}
if err := ctlCfg.TransportConfig.PreLoadCertData(); err != nil {
return errors.Wrap(err, "Unable to load Certificate Data")
}
invoker.SetConfig(ctlCfg)
if ctlCmd, ok := cmd.(ctlInvoker); ok {
ctlCmd.setInvoker(invoker)
}
// Handle the deprecated global hostlist flag
if !opts.HostList.Empty() {
if hlCmd, ok := cmd.(hostListSetter); ok {
hlCmd.setHostList(&opts.HostList.HostSet)
} else {
return &flags.Error{
Type: flags.ErrUnknownFlag,
Message: "unknown flag `l'/`host-list'",
}
}
}
if hlCmd, ok := cmd.(hostListGetter); ok {
hl := hlCmd.getHostList()
if len(hl) > 0 {
ctlCfg.HostList = hl
}
}
if cfgCmd, ok := cmd.(cmdConfigSetter); ok {
cfgCmd.setConfig(ctlCfg)
}
if argsCmd, ok := cmd.(cmdutil.ArgsHandler); ok {
if err := argsCmd.CheckArgs(args); err != nil {
return err
}
}
if err := cmd.Execute(args); err != nil {
return err
}
return nil
}
_, err := p.ParseArgs(args)
if opts.JSON && wroteJSON.IsFalse() {
return errorJSON(err)
}
return err
}
func main() {
var opts cliOptions
log := logging.NewCommandLineLogger()
ctlInvoker := control.NewClient(
control.WithClientLogger(log),
)
if err := parseOpts(os.Args[1:], &opts, ctlInvoker, log); err != nil {
if fe, ok := errors.Cause(err).(*flags.Error); ok && fe.Type == flags.ErrHelp {
log.Info(fe.Error())
os.Exit(0)
}
exitWithError(log, err)
}
}