forked from yunionio/cloudpods
-
Notifications
You must be signed in to change notification settings - Fork 1
/
climc.go
272 lines (245 loc) · 7.82 KB
/
climc.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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"time"
"github.com/c-bata/go-prompt"
"yunion.io/x/log"
"yunion.io/x/pkg/util/version"
"yunion.io/x/structarg"
"yunion.io/x/onecloud/cmd/climc/promputils"
"yunion.io/x/onecloud/cmd/climc/shell"
"yunion.io/x/onecloud/pkg/mcclient"
_ "yunion.io/x/onecloud/cmd/climc/shell/k8s"
)
type BaseOptions struct {
Help bool `help:"Show help" short-token:"h"`
Debug bool `help:"Show debug information"`
Version bool `help:"Show version"`
Timeout int `default:"600" help:"Number of seconds to wait for a response"`
Insecure bool `default:"false" help:"Allow skip server cert verification if URL is https" short-token:"k"`
CertFile string `default:"$YUNION_CERT_FILE" help:"certificate file"`
KeyFile string `default:"$YUNION_KEY_FILE" help:"private key file"`
UseCachedToken bool `default:"$YUNION_USE_CACHED_TOKEN|false" help:"Use cached token"`
OsUsername string `default:"$OS_USERNAME" help:"Username, defaults to env[OS_USERNAME]"`
OsPassword string `default:"$OS_PASSWORD" help:"Password, defaults to env[OS_PASSWORD]"`
// OsProjectId string `default:"$OS_PROJECT_ID" help:"Proejct ID, defaults to env[OS_PROJECT_ID]"`
OsProjectName string `default:"$OS_PROJECT_NAME" help:"Project name, defaults to env[OS_PROJECT_NAME]"`
OsDomainName string `default:"$OS_DOMAIN_NAME" help:"Domain name, defaults to env[OS_DOMAIN_NAME]"`
OsAuthURL string `default:"$OS_AUTH_URL" help:"Defaults to env[OS_AUTH_URL]"`
OsRegionName string `default:"$OS_REGION_NAME" help:"Defaults to env[OS_REGION_NAME]"`
OsZoneName string `default:"$OS_ZONE_NAME" help:"Defaults to env[OS_ZONE_NAME]"`
OsEndpointType string `default:"$OS_ENDPOINT_TYPE|internalURL" help:"Defaults to env[OS_ENDPOINT_TYPE] or internalURL" choices:"publicURL|internalURL|adminURL"`
ApiVersion string `default:"$API_VERSION|v1" help:"apiVersion, default to v1"`
SUBCOMMAND string `help:"climc subcommand" subcommand:"true"`
}
func getSubcommandsParser() (*structarg.ArgumentParser, error) {
parse, e := structarg.NewArgumentParser(&BaseOptions{},
"climc",
`Command-line interface to the API server.`,
`See "climc help COMMAND" for help on a specific command.`)
if e != nil {
return nil, e
}
subcmd := parse.GetSubcommand()
if subcmd == nil {
return nil, fmt.Errorf("No subcommand argument")
}
type HelpOptions struct {
SUBCOMMAND string `help:"Sub-command name"`
}
shell.R(&HelpOptions{}, "help", "Show help information of any subcommand", func(suboptions *HelpOptions) error {
helpstr, e := subcmd.SubHelpString(suboptions.SUBCOMMAND)
if e != nil {
return e
} else {
fmt.Print(helpstr)
return nil
}
})
for _, v := range shell.CommandTable {
_par, e := subcmd.AddSubParser(v.Options, v.Command, v.Desc, v.Callback)
if e != nil {
return nil, e
}
promputils.AppendCommand(v.Command, v.Desc)
cmd := v.Command
for _, v := range _par.GetOptArgs() {
text := v.String()
text = strings.TrimLeft(text, "[<")
text = strings.TrimRight(text, "]>")
promputils.AppendOpt(cmd, text, v.HelpString(""))
}
for _, v := range _par.GetPosArgs() {
text := v.String()
text = strings.TrimLeft(text, "[<")
text = strings.TrimRight(text, "]>")
promputils.AppendPos(cmd, text, v.HelpString(""))
}
}
return parse, nil
}
func showErrorAndExit(e error) {
fmt.Printf("Error: %s\n", e)
os.Exit(1)
}
func newClientSession(options *BaseOptions) (*mcclient.ClientSession, error) {
if len(options.OsAuthURL) == 0 {
return nil, fmt.Errorf("Missing OS_AUTH_URL")
}
if len(options.OsUsername) == 0 {
return nil, fmt.Errorf("Missing OS_USERNAME")
}
if len(options.OsPassword) == 0 {
return nil, fmt.Errorf("Missing OS_PASSWORD")
}
if len(options.OsRegionName) == 0 {
return nil, fmt.Errorf("Missing OS_REGION_NAME")
}
// if len(options.OsProjectId) == 0 && len(options.OsProjectName) == 0 {
// showErrorAndExit(fmt.Errorf("Missing OS_PROEJCT_ID or OS_PROJECT_NAME"))
if len(options.OsProjectName) == 0 {
return nil, fmt.Errorf("Missing OS_PROJECT_NAME")
}
logLevel := "info"
if options.Debug {
logLevel = "debug"
}
log.SetLogLevelByString(log.Logger(), logLevel)
client := mcclient.NewClient(options.OsAuthURL,
options.Timeout,
options.Debug,
options.Insecure,
options.CertFile,
options.KeyFile)
var cacheToken mcclient.TokenCredential
authUrlAlter := strings.Replace(options.OsAuthURL, "/", "", -1)
authUrlAlter = strings.Replace(authUrlAlter, ":", "", -1)
tokenCachePath := filepath.Join(os.TempDir(), fmt.Sprintf("OS_AUTH_CACHE_TOKEN-%s-%s-%s-%s", authUrlAlter, options.OsUsername, options.OsDomainName, options.OsProjectName))
if options.UseCachedToken {
cacheFile, err := os.Open(tokenCachePath)
if err == nil && cacheFile != nil {
fileInfo, _ := cacheFile.Stat()
dur, err := time.ParseDuration("-24h")
if fileInfo != nil && err == nil && fileInfo.ModTime().After(time.Now().Add(dur)) {
bytesToken, err := ioutil.ReadAll(cacheFile)
if err == nil {
token := client.NewAuthTokenCredential()
err := json.Unmarshal(bytesToken, token)
if err != nil {
fmt.Printf("Unmarshal token error:%s", err)
} else if token.IsValid() {
cacheToken = token
}
}
cacheFile.Close()
}
}
}
if cacheToken == nil {
token, err := client.Authenticate(options.OsUsername,
options.OsPassword,
options.OsDomainName,
options.OsProjectName)
if err != nil {
return nil, err
}
cacheToken = token
bytesCacheToken, err := json.Marshal(cacheToken)
if err != nil {
fmt.Printf("Marshal token error:%s", err)
} else {
fo, err := os.Create(tokenCachePath)
if err != nil {
fmt.Printf("Save token cache fail: %s", err)
} else {
fo.Write(bytesCacheToken)
fo.Close()
}
}
} else {
// fmt.Printf("******** Use Token Cache At %s ********\n", tokenCachePath)
}
session := client.NewSession(options.OsRegionName,
options.OsZoneName,
options.OsEndpointType,
cacheToken,
options.ApiVersion)
return session, nil
}
func enterInteractiveMode(
parser *structarg.ArgumentParser,
sessionFactory func() *mcclient.ClientSession,
) {
promputils.InitEnv(parser, sessionFactory())
defer fmt.Println("Bye!")
p := prompt.New(
promputils.Executor,
promputils.Completer,
prompt.OptionPrefix("climc> "),
prompt.OptionTitle("Climc, a Command Line Interface to Manage Clouds"),
prompt.OptionMaxSuggestion(16),
)
p.Run()
}
func executeSubcommand(
subcmd *structarg.SubcommandArgument,
subparser *structarg.ArgumentParser,
options *BaseOptions,
sessionFactory func() *mcclient.ClientSession,
) {
var e error
suboptions := subparser.Options()
if options.SUBCOMMAND == "help" {
e = subcmd.Invoke(suboptions)
} else {
e = subcmd.Invoke(sessionFactory(), suboptions)
}
if e != nil {
showErrorAndExit(e)
}
}
func main() {
parser, e := getSubcommandsParser()
if e != nil {
showErrorAndExit(e)
}
e = parser.ParseArgs(os.Args[1:], false)
options := parser.Options().(*BaseOptions)
if options.Help {
fmt.Print(parser.HelpString())
return
}
if options.Version {
fmt.Printf("Yunion API client version:\n %s\n", version.GetJsonString())
return
}
ensureSessionFactory := func() *mcclient.ClientSession {
session, err := newClientSession(options)
if err != nil {
showErrorAndExit(err)
}
return session
}
// enter interactive mode when not enough argument and SUBCOMMAND is empty
if _, ok := e.(*structarg.NotEnoughArgumentsError); ok && options.SUBCOMMAND == "" {
enterInteractiveMode(parser, ensureSessionFactory)
return
}
subcmd := parser.GetSubcommand()
subparser := subcmd.GetSubParser()
if e != nil {
if subparser != nil {
fmt.Print(subparser.Usage())
} else {
fmt.Print(parser.Usage())
}
showErrorAndExit(e)
}
// execute subcommand in non-interactive mode
executeSubcommand(subcmd, subparser, options, ensureSessionFactory)
}