forked from vmware/govmomi
/
client.go
409 lines (328 loc) · 8.32 KB
/
client.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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
/*
Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package flags
import (
"crypto/sha1"
"crypto/tls"
"encoding/json"
"errors"
"flag"
"fmt"
"net/url"
"os"
"path/filepath"
"strings"
"github.com/vmware/govmomi/session"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/soap"
"golang.org/x/net/context"
)
const (
envURL = "GOVC_URL"
envUsername = "GOVC_USERNAME"
envPassword = "GOVC_PASSWORD"
envCertificate = "GOVC_CERTIFICATE"
envPrivateKey = "GOVC_PRIVATE_KEY"
envInsecure = "GOVC_INSECURE"
envPersist = "GOVC_PERSIST_SESSION"
envMinAPIVersion = "GOVC_MIN_API_VERSION"
)
const cDescr = "ESX or vCenter URL"
type ClientFlag struct {
common
*DebugFlag
url *url.URL
username string
password string
cert string
key string
insecure bool
persist bool
minAPIVersion string
client *vim25.Client
}
var clientFlagKey = flagKey("client")
func NewClientFlag(ctx context.Context) (*ClientFlag, context.Context) {
if v := ctx.Value(clientFlagKey); v != nil {
return v.(*ClientFlag), ctx
}
v := &ClientFlag{}
v.DebugFlag, ctx = NewDebugFlag(ctx)
ctx = context.WithValue(ctx, clientFlagKey, v)
return v, ctx
}
func (flag *ClientFlag) URLWithoutPassword() *url.URL {
if flag.url == nil {
return nil
}
withoutCredentials := *flag.url
withoutCredentials.User = url.User(flag.url.User.Username())
return &withoutCredentials
}
func (flag *ClientFlag) String() string {
url := flag.URLWithoutPassword()
if url == nil {
return ""
}
return url.String()
}
func (flag *ClientFlag) Set(s string) error {
var err error
flag.url, err = soap.ParseURL(s)
return err
}
func (flag *ClientFlag) Register(ctx context.Context, f *flag.FlagSet) {
flag.RegisterOnce(func() {
flag.DebugFlag.Register(ctx, f)
{
flag.Set(os.Getenv(envURL))
usage := fmt.Sprintf("%s [%s]", cDescr, envURL)
f.Var(flag, "u", usage)
}
{
flag.username = os.Getenv(envUsername)
flag.password = os.Getenv(envPassword)
}
{
value := os.Getenv(envCertificate)
usage := fmt.Sprintf("Certificate [%s]", envCertificate)
f.StringVar(&flag.cert, "cert", value, usage)
}
{
value := os.Getenv(envPrivateKey)
usage := fmt.Sprintf("Private key [%s]", envPrivateKey)
f.StringVar(&flag.key, "key", value, usage)
}
{
insecure := false
switch env := strings.ToLower(os.Getenv(envInsecure)); env {
case "1", "true":
insecure = true
}
usage := fmt.Sprintf("Skip verification of server certificate [%s]", envInsecure)
f.BoolVar(&flag.insecure, "k", insecure, usage)
}
{
persist := true
switch env := strings.ToLower(os.Getenv(envPersist)); env {
case "0", "false":
persist = false
}
usage := fmt.Sprintf("Persist session to disk [%s]", envPersist)
f.BoolVar(&flag.persist, "persist-session", persist, usage)
}
{
env := os.Getenv(envMinAPIVersion)
if env == "" {
env = "5.5"
}
flag.minAPIVersion = env
}
})
}
func (flag *ClientFlag) Process(ctx context.Context) error {
return flag.ProcessOnce(func() error {
if err := flag.DebugFlag.Process(ctx); err != nil {
return err
}
if flag.url == nil {
return errors.New("specify an " + cDescr)
}
// Override username if set
if flag.username != "" {
var password string
var ok bool
if flag.url.User != nil {
password, ok = flag.url.User.Password()
}
if ok {
flag.url.User = url.UserPassword(flag.username, password)
} else {
flag.url.User = url.User(flag.username)
}
}
// Override password if set
if flag.password != "" {
var username string
if flag.url.User != nil {
username = flag.url.User.Username()
}
flag.url.User = url.UserPassword(username, flag.password)
}
return nil
})
}
// Retry twice when a temporary I/O error occurs.
// This means a maximum of 3 attempts.
func attachRetries(rt soap.RoundTripper) soap.RoundTripper {
return vim25.Retry(rt, vim25.TemporaryNetworkError(3))
}
func (flag *ClientFlag) sessionFile() string {
url := flag.URLWithoutPassword()
// Key session file off of full URI and insecure setting.
// Hash key to get a predictable, canonical format.
key := fmt.Sprintf("%s#insecure=%t", url.String(), flag.insecure)
name := fmt.Sprintf("%040x", sha1.Sum([]byte(key)))
return filepath.Join(os.Getenv("HOME"), ".govmomi", "sessions", name)
}
func (flag *ClientFlag) saveClient(c *vim25.Client) error {
if !flag.persist {
return nil
}
p := flag.sessionFile()
err := os.MkdirAll(filepath.Dir(p), 0700)
if err != nil {
return err
}
f, err := os.OpenFile(p, os.O_CREATE|os.O_WRONLY, 0600)
if err != nil {
return err
}
defer f.Close()
err = json.NewEncoder(f).Encode(c)
if err != nil {
return err
}
return nil
}
func (flag *ClientFlag) restoreClient(c *vim25.Client) (bool, error) {
if !flag.persist {
return false, nil
}
f, err := os.Open(flag.sessionFile())
if err != nil {
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
defer f.Close()
dec := json.NewDecoder(f)
err = dec.Decode(c)
if err != nil {
return false, err
}
return true, nil
}
func (flag *ClientFlag) loadClient() (*vim25.Client, error) {
c := new(vim25.Client)
ok, err := flag.restoreClient(c)
if err != nil {
return nil, err
}
if !ok || !c.Valid() {
return nil, nil
}
// Add retry functionality before making any calls
c.RoundTripper = attachRetries(c.RoundTripper)
m := session.NewManager(c)
u, err := m.UserSession(context.TODO())
if err != nil {
return nil, err
}
// If the session is nil, the client is not authenticated
if u == nil {
return nil, nil
}
return c, nil
}
func (flag *ClientFlag) newClient() (*vim25.Client, error) {
sc := soap.NewClient(flag.url, flag.insecure)
isTunnel := false
if flag.cert != "" {
isTunnel = true
cert, err := tls.LoadX509KeyPair(flag.cert, flag.key)
if err != nil {
return nil, err
}
sc.SetCertificate(cert)
}
// Add retry functionality before making any calls
rt := attachRetries(sc)
c, err := vim25.NewClient(context.TODO(), rt)
if err != nil {
return nil, err
}
// Set client, since we didn't pass it in the constructor
c.Client = sc
m := session.NewManager(c)
u := flag.url.User
if isTunnel {
err = m.LoginExtensionByCertificate(context.TODO(), u.Username(), "")
if err != nil {
return nil, err
}
} else {
err = m.Login(context.TODO(), u)
if err != nil {
return nil, err
}
}
err = flag.saveClient(c)
if err != nil {
return nil, err
}
return c, nil
}
// apiVersionValid returns whether or not the API version supported by the
// server the client is connected to is not recent enough.
func apiVersionValid(c *vim25.Client, minVersionString string) error {
if minVersionString == "-" {
// Disable version check
return nil
}
apiVersion := c.ServiceContent.About.ApiVersion
if strings.HasSuffix(apiVersion, ".x") {
// Skip version check for development builds
return nil
}
realVersion, err := ParseVersion(apiVersion)
if err != nil {
return err
}
minVersion, err := ParseVersion(minVersionString)
if err != nil {
return err
}
if !minVersion.Lte(realVersion) {
err = fmt.Errorf("Require API version %s, connected to API version %s (set %s to override)",
minVersionString,
c.ServiceContent.About.ApiVersion,
envMinAPIVersion)
return err
}
return nil
}
func (flag *ClientFlag) Client() (*vim25.Client, error) {
if flag.client != nil {
return flag.client, nil
}
c, err := flag.loadClient()
if err != nil {
return nil, err
}
// loadClient returns nil if it was unable to load a session from disk
if c == nil {
c, err = flag.newClient()
if err != nil {
return nil, err
}
}
// Check that the endpoint has the right API version
err = apiVersionValid(c, flag.minAPIVersion)
if err != nil {
return nil, err
}
flag.client = c
return flag.client, nil
}