-
Notifications
You must be signed in to change notification settings - Fork 27
/
occm_gcp.go
622 lines (537 loc) · 18.9 KB
/
occm_gcp.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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
package cloudmanager
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"log"
"strings"
"time"
"github.com/fatih/structs"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"golang.org/x/oauth2/jwt"
"gopkg.in/yaml.v2"
)
// OCCMMGCPResult the response name of a occm
type OCCMMGCPResult struct {
Name string `json:"name"`
}
// GCP template
type tcontent struct {
Resources []tresource `yaml:"resources"`
}
type tresource struct {
Name string `yaml:"name"`
Properties properties `yaml:"properties"`
Type string `yaml:"type"`
Metadata metaData `yaml:"metadata,omitempty"`
Labels map[string]string `yaml:"labels,omitempty"`
}
type properties struct {
Name string `yaml:"name,omitempty"`
SizeGb int `yaml:"sizeGb,omitempty"`
SourceImage string `yaml:"sourceImage,omitempty"`
Type string `yaml:"type,omitempty"`
Tags tags `yaml:"tags,omitempty"`
Disks []pdisk `yaml:"disks,omitempty"`
MachineType string `yaml:"machineType,omitempty"`
Zone string `yaml:"zone"`
Metadata pmetadata `yaml:"metadata,omitempty"`
NetworkInterfaces []networkInterface `yaml:"networkInterfaces,omitempty"`
ServiceAccounts []serviceAccount `yaml:"serviceAccounts,omitempty"`
Labels map[string]string `yaml:"labels,omitempty"`
}
type label struct {
Key string `yaml:"key,omitempty"`
Value string `yaml:"value,omitempty"`
}
type metaData struct {
DependsOn []string `yaml:"dependsOn"`
}
type tags struct {
Items []string `yaml:"items"`
}
type pdisk struct {
AutoDelete bool `yaml:"autoDelete"`
Boot bool `yaml:"boot"`
DeviceName string `yaml:"deviceName"`
Name string `yaml:"name"`
Source string `yaml:"source"`
Type string `yaml:"type"`
}
type pmetadata struct {
Items []item `yaml:"items"`
}
type item struct {
Key, Value interface{}
}
type networkInterface struct {
AccessConfigs []accessConfig `yaml:"accessConfigs"`
Kind string `yaml:"kind"`
Subnetwork string `yaml:"subnetwork"`
}
type accessConfig struct {
Kind string `yaml:"kind"`
Name string `yaml:"name"`
Type string `yaml:"type"`
NetworkTier string `yaml:"networkTier"`
}
type serviceAccount struct {
Email string `yaml:"email"`
Scopes []string `yaml:"scopes"`
}
func (c *Client) getCustomDataForGCP(registerAgentTOService registerAgentTOServiceRequest, proxyCertificates []string, clientID string) (string, string, error) {
accesTokenResult, err := c.getAccessToken()
if err != nil {
return "", "", err
}
log.Print("getAccessToken ", accesTokenResult.Token)
c.Token = accesTokenResult.Token
if c.AccountID == "" {
accountID, err := c.getAccount(clientID)
if err != nil {
return "", "", err
}
log.Print("getAccount ", accountID)
registerAgentTOService.AccountID = accountID
} else {
registerAgentTOService.AccountID = c.AccountID
}
userDataRespone, err := c.registerAgentTOServiceForGCP(registerAgentTOService, clientID)
if err != nil {
return "", "", err
}
newClientID := userDataRespone.ClientID
c.AccountID = userDataRespone.AccountID
userDataRespone.ProxySettings.ProxyCertificates = proxyCertificates
rawUserData, _ := json.Marshal(userDataRespone)
userData := string(rawUserData)
log.Print("userData ", userData)
return userData, newClientID, nil
}
func (c *Client) registerAgentTOServiceForGCP(registerAgentTOServiceRequest registerAgentTOServiceRequest, clientID string) (createUserData, error) {
baseURL := "/agents-mgmt/connector-setup"
hostType := "CloudManagerHost"
registerAgentTOServiceRequest.Placement.Provider = "GCP"
log.Print(c.Token)
params := structs.Map(registerAgentTOServiceRequest)
statusCode, response, _, err := c.CallAPIMethod("POST", baseURL, params, c.Token, hostType, clientID)
if err != nil {
log.Print("registerAgentTOService request failed ", statusCode)
return createUserData{}, err
}
responseError := apiResponseChecker(statusCode, response, "registerAgentTOService")
if responseError != nil {
return createUserData{}, responseError
}
var result createUserData
if err := json.Unmarshal(response, &result); err != nil {
log.Print("Failed to unmarshall response from registerAgentTOService ", err)
return createUserData{}, err
}
result.IgnoreUpgrade = true
return result, nil
}
func (c *Client) deployGCPVM(occmDetails createOCCMDetails, proxyCertificates []string, clientID string) (OCCMMResult, error) {
var registerAgentTOService registerAgentTOServiceRequest
registerAgentTOService.Name = occmDetails.Name
registerAgentTOService.Placement.Region = occmDetails.Region
registerAgentTOService.Company = occmDetails.Company
if occmDetails.ProxyURL != "" {
registerAgentTOService.Extra.Proxy.ProxyURL = occmDetails.ProxyURL
}
if occmDetails.ProxyUserName != "" {
registerAgentTOService.Extra.Proxy.ProxyUserName = occmDetails.ProxyUserName
}
if occmDetails.ProxyPassword != "" {
registerAgentTOService.Extra.Proxy.ProxyPassword = occmDetails.ProxyPassword
}
registerAgentTOService.Placement.Subnet = occmDetails.SubnetID
userData, newClientID, err := c.getCustomDataForGCP(registerAgentTOService, proxyCertificates, clientID)
if err != nil {
return OCCMMResult{}, err
}
c.UserData = userData
var result OCCMMResult
log.Printf("Set result clientid=%s", newClientID)
result.ClientID = newClientID
result.AccountID = c.AccountID
gcpCustomData := base64.StdEncoding.EncodeToString([]byte(userData))
gcpSaScopes := []string{"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/compute",
"https://www.googleapis.com/auth/compute.readonly",
"https://www.googleapis.com/auth/ndev.cloudman",
"https://www.googleapis.com/auth/ndev.cloudman.readonly"}
content := tcontent{}
// first resource
t := tresource{}
t.Name = fmt.Sprintf("%s-vm", occmDetails.Name)
if occmDetails.FirewallTags {
t.Properties.Tags.Items = []string{"firewall-tag-bvsu", "http-server", "https-server"}
}
if len(occmDetails.Tags) > 0 {
t.Properties.Tags.Items = append(t.Properties.Tags.Items, occmDetails.Tags...)
}
deviceName := fmt.Sprintf("%s-vm-disk-boot", occmDetails.Name)
t.Properties.Disks = []pdisk{
{AutoDelete: true,
Boot: true,
DeviceName: deviceName,
Name: deviceName,
Source: fmt.Sprintf("\\\"$(ref.%s.selfLink)\\\"", deviceName),
Type: "PERSISTENT",
},
}
t.Properties.MachineType = fmt.Sprintf("zones/%s/machineTypes/%s", occmDetails.Zone, occmDetails.MachineType)
t.Properties.Metadata.Items = []item{
{Key: "serial-port-enable", Value: 1},
{Key: "customData", Value: gcpCustomData}}
var accessConfigs []accessConfig
if occmDetails.AssociatePublicIP {
accessConfigs = []accessConfig{{Kind: "compute#accessConfig", Name: "External NAT", Type: "ONE_TO_ONE_NAT", NetworkTier: "PREMIUM"}}
}
var projectID string
if occmDetails.NetworkProjectID != "" {
projectID = occmDetails.NetworkProjectID
} else {
projectID = occmDetails.GCPProject
}
subnetID, err := convertSubnetID(projectID, occmDetails, occmDetails.SubnetID)
if err != nil {
return OCCMMResult{}, err
}
t.Properties.NetworkInterfaces = []networkInterface{
{AccessConfigs: accessConfigs,
Kind: "compute#networkInterface",
Subnetwork: subnetID,
},
}
t.Properties.ServiceAccounts = []serviceAccount{{Email: occmDetails.ServiceAccountEmail, Scopes: gcpSaScopes}}
t.Properties.Zone = occmDetails.Zone
t.Type = "compute.v1.instance"
t.Metadata.DependsOn = []string{deviceName}
// the resource which the first resource depends on
td := tresource{}
td.Name = deviceName
td.Properties.Name = deviceName
td.Properties.SizeGb = 100
td.Properties.SourceImage = fmt.Sprintf("projects/%s/global/images/family/%s", c.GCPImageProject, c.GCPImageFamily)
td.Properties.Type = fmt.Sprintf("zones/%s/diskTypes/pd-ssd", occmDetails.Zone)
td.Properties.Zone = occmDetails.Zone
td.Type = "compute.v1.disks"
if occmDetails.Labels != nil {
label := map[string]string{}
for key, value := range occmDetails.Labels {
key = fmt.Sprintf("\\\"%s\\\"", key)
value = fmt.Sprintf("\\\"%s\\\"", value)
label[key] = value
t.Properties.Labels = label
td.Properties.Labels = label
}
}
content.Resources = []tresource{t, td}
data, err := yaml.Marshal(&content)
if err != nil {
return OCCMMResult{}, fmt.Errorf("error: %v", err)
}
mydata := string(data)
c.GCPDeploymentTemplate = fmt.Sprintf(`{
"name": "%s%s",
"target": {
"config": {
"content": "%s"
}
}
}`, occmDetails.Name, occmDetails.GCPCommonSuffixName, mydata)
token, err := c.getGCPToken(c.GCPServiceAccountKey)
if err != nil {
return OCCMMResult{}, err
}
baseURL := fmt.Sprintf("/deploymentmanager/v2/projects/%s/global/deployments", occmDetails.GCPProject)
hostType := "GCPDeploymentManager"
log.Print("POST")
log.Printf("deployGCPVM: call depolyments api base client=%s", newClientID)
statusCode, response, _, err := c.CallAPIMethod("POST", baseURL, nil, token, hostType, newClientID)
if err != nil {
log.Print("deployGCPVM request failed")
return OCCMMResult{}, err
}
responseError := apiResponseChecker(statusCode, response, "deployGCPVM")
if responseError != nil {
return OCCMMResult{}, responseError
}
log.Print("Sleep for 2 minutes")
time.Sleep(time.Duration(120) * time.Second)
retries := 26
for {
occmResp, err := c.checkOCCMStatus(newClientID)
if err != nil {
return OCCMMResult{}, err
}
if occmResp.Status == "active" {
break
} else {
if retries == 0 {
log.Print("Taking too long for status to be active")
return OCCMMResult{}, fmt.Errorf("Taking too long for OCCM agent to be active or not properly setup")
}
time.Sleep(time.Duration(30) * time.Second)
retries--
}
}
return result, nil
}
func (c *Client) getdeployGCPVM(occmDetails createOCCMDetails, id string, clientID string) (string, error) {
log.Print("getdeployGCPVM")
token, err := c.getGCPToken(c.GCPServiceAccountKey)
if err != nil {
return "", err
}
baseURL := fmt.Sprintf("/deploymentmanager/v2/projects/%s/global/deployments/%s%s", occmDetails.GCPProject, occmDetails.Name, occmDetails.GCPCommonSuffixName)
hostType := "GCPDeploymentManager"
log.Print("GET")
statusCode, response, _, err := c.CallAPIMethod("GET", baseURL, nil, token, hostType, clientID)
if err != nil {
log.Print("getdeployGCPVM request failed")
return "", err
}
responseError := apiResponseChecker(statusCode, response, "getdeployGCPVM")
if responseError != nil {
return "", responseError
}
var result OCCMMGCPResult
if err := json.Unmarshal(response, &result); err != nil {
log.Print("Failed to unmarshall response from getVolumeByID")
return "", err
}
if result.Name == id {
return result.Name, nil
}
return "", nil
}
func (c *Client) getDisk(occmDetails createOCCMDetails, clientID string) (map[string]interface{}, error) {
hostType := "GCPCompute"
token, err := c.getGCPToken(c.GCPServiceAccountKey)
if err != nil {
return nil, err
}
baseURL := fmt.Sprintf("/compute/v1/projects/%s/zones/%s/disks/%s-vm-disk-boot", occmDetails.GCPProject, occmDetails.Zone, occmDetails.Name)
statusCode, response, _, err := c.CallAPIMethod("GET", baseURL, nil, token, hostType, clientID)
if err != nil {
log.Printf("getDisk request failed: %s", err.Error())
return nil, err
}
responseError := apiResponseChecker(statusCode, response, "getDisk")
if responseError != nil {
return nil, responseError
}
var result map[string]interface{}
if err := json.Unmarshal(response, &result); err != nil {
log.Print("Failed to unmarshall response from getDisk")
return nil, err
}
return result, nil
}
func (c *Client) getVMInstance(occmDetails createOCCMDetails, clientID string) (map[string]interface{}, error) {
log.Print("getVMInstance")
token, err := c.getGCPToken(c.GCPServiceAccountKey)
if err != nil {
return nil, err
}
baseURL := fmt.Sprintf("/compute/v1/projects/%s/zones/%s/instances/%s-vm", occmDetails.GCPProject, occmDetails.Zone, occmDetails.Name)
hostType := "GCPCompute"
log.Print("GET")
statusCode, response, _, err := c.CallAPIMethod("GET", baseURL, nil, token, hostType, clientID)
if err != nil {
log.Printf("getVMInstance request failed: %s", err.Error())
return nil, err
}
responseError := apiResponseChecker(statusCode, response, "getVMInstance")
if responseError != nil {
return nil, responseError
}
var result map[string]interface{}
if err := json.Unmarshal(response, &result); err != nil {
log.Print("Failed to unmarshall response from getVMInstance")
return nil, err
}
return result, nil
}
// This function is not used because can't get the update instance API from GCP working. Receive the following error: Boot disk must be the first disk attached to the instance.
// Although there is only one disk exists all the time, I can't figure it out to make it work.
func (c *Client) updateVMInstance(occmDetails createOCCMDetails, clientID string, updatePropertities map[string]interface{}) error {
token, err := c.getGCPToken(c.GCPServiceAccountKey)
if err != nil {
return err
}
baseURL := fmt.Sprintf("/compute/v1/projects/%s/zones/%s/instances/%s-vm", occmDetails.GCPProject, occmDetails.Zone, occmDetails.Name)
hostType := "GCPCompute"
statusCode, response, _, err := c.CallAPIMethod("PUT", baseURL, updatePropertities, token, hostType, clientID)
if err != nil {
log.Print("updateVMInstance request failed")
return err
}
responseError := apiResponseChecker(statusCode, response, "getVMInstance")
if responseError != nil {
return responseError
}
return nil
}
func (c *Client) setVMLabels(occmDetails createOCCMDetails, labels map[string]interface{}, clientID string) error {
log.Print("setVMLabels")
token, err := c.getGCPToken(c.GCPServiceAccountKey)
if err != nil {
return err
}
baseURL := fmt.Sprintf("/compute/v1/projects/%s/zones/%s/instances/%s-vm/setLabels", occmDetails.GCPProject, occmDetails.Zone, occmDetails.Name)
hostType := "GCPCompute"
statusCode, response, _, err := c.CallAPIMethod("POST", baseURL, labels, token, hostType, clientID)
if err != nil {
log.Printf("setVMLabels request failed: %s", err.Error())
return err
}
responseError := apiResponseChecker(statusCode, response, "setVMLabels")
if responseError != nil {
return responseError
}
return nil
}
func (c *Client) setDiskLabels(occmDetails createOCCMDetails, labels map[string]interface{}, clientID string) error {
log.Print("setDiskLabels")
token, err := c.getGCPToken(c.GCPServiceAccountKey)
if err != nil {
return err
}
baseURL := fmt.Sprintf("/compute/v1/projects/%s/zones/%s/disks/%s-vm-disk-boot/setLabels", occmDetails.GCPProject, occmDetails.Zone, occmDetails.Name)
hostType := "GCPCompute"
statusCode, response, _, err := c.CallAPIMethod("POST", baseURL, labels, token, hostType, clientID)
if err != nil {
log.Printf("setDiskLabels request failed: %s", err.Error())
return err
}
responseError := apiResponseChecker(statusCode, response, "setDiskLabels")
if responseError != nil {
return responseError
}
return nil
}
func (c *Client) setVMInstaceTags(occmDetails createOCCMDetails, fingerprint string, clientID string) error {
log.Print("setVMInstaceTags")
token, err := c.getGCPToken(c.GCPServiceAccountKey)
if err != nil {
return err
}
baseURL := fmt.Sprintf("/compute/v1/projects/%s/zones/%s/instances/%s-vm/setTags", occmDetails.GCPProject, occmDetails.Zone, occmDetails.Name)
hostType := "GCPDeploymentManager"
body := make(map[string]interface{})
body["items"] = occmDetails.Tags
body["fingerprint"] = fingerprint
statusCode, response, _, err := c.CallAPIMethod("POST", baseURL, body, token, hostType, clientID)
if err != nil {
log.Print("setVMInstaceTags request failed")
return err
}
responseError := apiResponseChecker(statusCode, response, "setVMInstaceTags")
if responseError != nil {
return responseError
}
return nil
}
func (c *Client) deleteOCCMGCP(request deleteOCCMDetails, clientID string) error {
log.Printf("deleteOCCMGCP %s client %s", request.Name, clientID)
token, err := c.getGCPToken(c.GCPServiceAccountKey)
if err != nil {
return err
}
baseURL := fmt.Sprintf("/deploymentmanager/v2/projects/%s/global/deployments/%s%s", request.Project, request.Name, request.GCPCommonSuffixName)
hostType := "GCPDeploymentManager"
log.Print("DELETE")
statusCode, response, _, err := c.CallAPIMethod("DELETE", baseURL, nil, token, hostType, clientID)
if err != nil {
log.Print("deleteOCCMGCP request failed")
return err
}
responseError := apiResponseChecker(statusCode, response, "deleteOCCMGCP")
if responseError != nil {
return responseError
}
log.Print("Sleep for 30 seconds")
time.Sleep(time.Duration(30) * time.Second)
accesTokenResult, err := c.getAccessToken()
c.Token = accesTokenResult.Token
if err != nil {
return err
}
retries := 30
for {
occmResp, err := c.checkOCCMStatus(clientID)
if err != nil {
return err
}
if occmResp.Status != "active" {
break
} else {
if retries == 0 {
log.Print("Taking too long for instance to finish terminating")
return fmt.Errorf("Taking too long for instance to finish terminating")
}
time.Sleep(time.Duration(10) * time.Second)
retries--
}
}
if err := c.callOCCMDelete(clientID); err != nil {
return err
}
return nil
}
func convertSubnetID(projectID string, occmDetails createOCCMDetails, input string) (string, error) {
if !strings.Contains(input, "/") {
return fmt.Sprintf("projects/%s/regions/%s/subnetworks/%s", projectID, occmDetails.Region, occmDetails.SubnetID), nil
}
return input, nil
}
func (c *Client) getGCPToken(gcpServiceAccountKey string) (string, error) {
var token string
log.Printf("getGCPToken...")
scopes := []string{
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/compute",
"https://www.googleapis.com/auth/compute.readonly",
"https://www.googleapis.com/auth/ndev.cloudman",
"https://www.googleapis.com/auth/ndev.cloudman.readonly",
"https://www.googleapis.com/auth/devstorage.full_control",
"https://www.googleapis.com/auth/devstorage.read_write",
}
if gcpServiceAccountKey != "" {
var c = struct {
Email string `json:"client_email"`
PrivateKey string `json:"private_key"`
}{}
json.Unmarshal([]byte(gcpServiceAccountKey), &c)
config := &jwt.Config{
Email: c.Email,
PrivateKey: []byte(c.PrivateKey),
Scopes: scopes,
TokenURL: google.JWTTokenURL,
}
gcpToken, err := config.TokenSource(oauth2.NoContext).Token()
if err != nil {
return "", err
}
token = gcpToken.AccessToken
} else {
// find default application credential
ctx := context.Background()
credential, err := google.FindDefaultCredentials(ctx, scopes...)
if err != nil {
return "", fmt.Errorf("cannot get credentials: %v", err)
}
t, err := credential.TokenSource.Token()
if err != nil {
return "", fmt.Errorf("getGCPToken failed on get token from credential: %v", err)
}
token = t.AccessToken
}
return token, nil
}