-
Notifications
You must be signed in to change notification settings - Fork 47
/
VMHandler.go
822 lines (729 loc) · 24.7 KB
/
VMHandler.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
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
// Proof of Concepts of CB-Spider.
// The CB-Spider is a sub-Framework of the Cloud-Barista Multi-Cloud Project.
// The CB-Spider Mission is to connect all the clouds with a single interface.
//
// * Cloud-Barista: https://github.com/cloud-barista
//
// This is a Cloud Driver Example for PoC Test.
//
// program by ysjeon@mz.co.kr, 2019.07.
// modify by devunet@mz.co.kr, 2019.11.
package resources
import (
"context"
"errors"
_ "errors"
"fmt"
"strings"
"time"
compute "google.golang.org/api/compute/v1"
call "github.com/cloud-barista/cb-spider/cloud-control-manager/cloud-driver/call-log"
idrv "github.com/cloud-barista/cb-spider/cloud-control-manager/cloud-driver/interfaces"
irs "github.com/cloud-barista/cb-spider/cloud-control-manager/cloud-driver/interfaces/resources"
"github.com/davecgh/go-spew/spew"
)
type GCPVMHandler struct {
Region idrv.RegionInfo
Ctx context.Context
Client *compute.Service
Credential idrv.CredentialInfo
}
func (vmHandler *GCPVMHandler) StartVM(vmReqInfo irs.VMReqInfo) (irs.VMInfo, error) {
// Set VM Create Information
// GCP 는 reqinfo에 ProjectID를 받아야 함.
cblogger.Info(vmReqInfo)
//ctx := vmHandler.Ctx
vmName := vmReqInfo.IId.NameId
projectID := vmHandler.Credential.ProjectID
prefix := "https://www.googleapis.com/compute/v1/projects/" + projectID
//imageURL := "projects/ubuntu-os-cloud/global/images/ubuntu-minimal-1804-bionic-v20191024"
imageURL := vmReqInfo.ImageIID.SystemId
region := vmHandler.Region.Region
zone := vmHandler.Region.Zone
// email을 어디다가 넣지? 이것또한 문제넹
clientEmail := vmHandler.Credential.ClientEmail
/* // 2020-05-15 Name 기반 로직을 임의로 막아 놓음 - 다음 버전에 적용 예정. 현재는 URL 방식
//이미지 URL처리
cblogger.Infof("[%s] Image Name에 해당하는 Image Url 정보를 조회합니다.", vmReqInfo.ImageIID.SystemId)
imageHandler := GCPImageHandler{Credential: vmHandler.Credential, Region: vmHandler.Region, Client: vmHandler.Client}
imageInfo, errImage := imageHandler.FindImageInfo(vmReqInfo.ImageIID.SystemId)
if errImage != nil {
return irs.VMInfo{}, nil
}
cblogger.Infof("ImageName: [%s] ---> ImageUrl : [%s]", vmReqInfo.ImageIID.SystemId, imageInfo.ImageUrl)
imageURL = imageInfo.ImageUrl
*/
//PublicIP처리
// var publicIPAddress string
// cblogger.Info("PublicIp 처리 시작")
// publicIpHandler := GCPPublicIPHandler{
// vmHandler.Region, vmHandler.Ctx, vmHandler.Client, vmHandler.Credential}
//PublicIp를 전달 받았으면 전달 받은 Ip를 할당
// if vmReqInfo.PublicIPId != "" {
// cblogger.Info("PublicIp 정보 조회 시작")
// publicIPInfo, err := publicIpHandler.GetPublicIP(vmReqInfo.PublicIPId)
// if err != nil {
// cblogger.Error(err)
// return irs.VMInfo{}, err
// }
// cblogger.Info("PublicIp 조회됨")
// cblogger.Info(publicIPInfo)
// publicIPAddress = publicIPInfo.PublicIP
// } else { //PublicIp가 없으면 직접 생성
// cblogger.Info("PublicIp 생성 시작")
// // PublicIPHandler 불러서 처리 해야 함.
// publicIpName := vmReqInfo.VMName
// publicIpReqInfo := irs.PublicIPReqInfo{Name: publicIpName}
// publicIPInfo, err := publicIpHandler.CreatePublicIP(publicIpReqInfo)
// if err != nil {
// cblogger.Error(err)
// return irs.VMInfo{}, err
// }
// cblogger.Info("PublicIp 생성됨")
// cblogger.Info(publicIPInfo)
// publicIPAddress = publicIPInfo.PublicIP
// }
//KEYPAIR HANDLER
keypairHandler := GCPKeyPairHandler{
vmHandler.Credential, vmHandler.Region}
keypairInfo, errKeypair := keypairHandler.GetKey(vmReqInfo.KeyPairIID)
pubKey := "cb-user:" + keypairInfo.PublicKey
if errKeypair != nil {
cblogger.Error(errKeypair)
return irs.VMInfo{}, errKeypair
}
cblogger.Info("keypairInfo 정보")
spew.Dump(keypairInfo)
/*
type GCPImageHandler struct {
Region idrv.RegionInfo
Ctx context.Context
Client *compute.Service
Credential idrv.CredentialInfo
}
*/
// Security Group Tags
var securityTags []string
for _, item := range vmReqInfo.SecurityGroupIIDs {
//securityTags = append(securityTags, item.NameId)
securityTags = append(securityTags, item.SystemId)
}
cblogger.Info("Security Tags 정보 : ", securityTags)
//networkURL := prefix + "/global/networks/" + vmReqInfo.VpcIID.NameId
networkURL := prefix + "/global/networks/" + vmReqInfo.VpcIID.SystemId
//subnetWorkURL := prefix + "/regions/" + region + "/subnetworks/" + vmReqInfo.SubnetIID.NameId
subnetWorkURL := prefix + "/regions/" + region + "/subnetworks/" + vmReqInfo.SubnetIID.SystemId
cblogger.Info("networkURL 정보 : ", networkURL)
cblogger.Info("subnetWorkURL 정보 : ", subnetWorkURL)
instance := &compute.Instance{
Name: vmName,
Metadata: &compute.Metadata{
Items: []*compute.MetadataItems{
{Key: "ssh-keys",
Value: &pubKey},
},
},
Labels: map[string]string{
//"keypair": strings.ToLower(vmReqInfo.KeyPairIID.NameId),
"keypair": strings.ToLower(vmReqInfo.KeyPairIID.SystemId),
},
Description: "compute sample instance",
MachineType: prefix + "/zones/" + zone + "/machineTypes/" + vmReqInfo.VMSpecName,
Disks: []*compute.AttachedDisk{
{
AutoDelete: true,
Boot: true,
Type: "PERSISTENT",
InitializeParams: &compute.AttachedDiskInitializeParams{
DiskName: vmName + "-" + zone, //disk name 도 매번 바뀌어야 하는 값
SourceImage: imageURL,
},
},
},
NetworkInterfaces: []*compute.NetworkInterface{
{
AccessConfigs: []*compute.AccessConfig{
{
Type: "ONE_TO_ONE_NAT",
Name: "External NAT", // default
},
},
Network: networkURL,
Subnetwork: subnetWorkURL,
},
},
ServiceAccounts: []*compute.ServiceAccount{
{
Email: clientEmail,
Scopes: []string{
compute.DevstorageFullControlScope,
compute.ComputeScope,
},
},
},
Tags: &compute.Tags{
Items: securityTags,
},
}
cblogger.Info("VM 생성 시작")
cblogger.Info(instance)
spew.Dump(instance)
// logger for HisCall
callogger := call.GetLogger("HISCALL")
callLogInfo := call.CLOUDLOGSCHEMA{
CloudOS: call.GCP,
RegionZone: vmHandler.Region.Zone,
ResourceType: call.VM,
ResourceName: vmName,
CloudOSAPI: "Insert()",
ElapsedTime: "",
ErrorMSG: "",
}
callLogStart := call.Start()
op, err1 := vmHandler.Client.Instances.Insert(projectID, zone, instance).Do()
callLogInfo.ElapsedTime = call.Elapsed(callLogStart)
cblogger.Info("VM 생성 요청 호출 완료")
cblogger.Info(op)
spew.Dump(op)
if err1 != nil {
callLogInfo.ErrorMSG = err1.Error()
callogger.Error(call.String(callLogInfo))
cblogger.Error("VM 생성 실패")
cblogger.Error(err1)
return irs.VMInfo{}, err1
}
callogger.Info(call.String(callLogInfo))
/*
js, err := op.MarshalJSON()
if err != nil {
cblogger.Info("VM 생성 실패")
cblogger.Error(err)
return irs.VMInfo{}, err
}
cblogger.Info("Insert vm to marshal Json : ", string(js))
cblogger.Infof("Got compute.Operation, err: %#v, %v", op, err)
*/
// 이게 시작하는 api Start 내부 매개변수로 projectID, zone, InstanceID
//vm, err := vmHandler.Client.Instances.Start(project string, zone string, instance string)
//time.Sleep(time.Second * 10)
//2021-05-11 WaitForRun을 호출하지 않아도 GetVM() 호출 시 에러가 발생하지 않는 것은 확인했음. (우선은 정책이 최종 확정이 아니라서 WaitForRun을 사용하도록 원복함.)
vmStatus, _ := vmHandler.WaitForRun(irs.IID{NameId: vmName, SystemId: vmName})
cblogger.Info("VM 상태 : ", vmStatus)
cblogger.Info("VM 정보 조회 호출 - GetVM()")
//만약 30초 이내에 VM이 Running 상태가 되지 않더라도 GetVM으로 VM의 정보 조회를 요청해 봄.
vmInfo, errVmInfo := vmHandler.GetVM(irs.IID{NameId: vmName, SystemId: vmName})
if errVmInfo != nil {
cblogger.Errorf("[%s] VM을 생성했지만 정보 조회는 실패 함.", vmName)
cblogger.Error(errVmInfo)
return irs.VMInfo{}, errVmInfo
}
//ImageIId의 NameId는 사용자가 요청한 값으로 리턴
vmInfo.ImageIId.NameId = vmReqInfo.ImageIID.NameId
return vmInfo, nil
/* 2020-05-13 Start & Get 요청 시의 리턴 정보 통일을 위해 기존 로직 임시 제거
vm, err2 := vmHandler.Client.Instances.Get(projectID, zone, vmName).Context(ctx).Do()
if err2 != nil {
cblogger.Error(err2)
return irs.VMInfo{}, err2
}
//vmInfo := vmHandler.mappingServerInfo(vm)
var securityTag []irs.IID
for _, item := range vm.Tags.Items {
iId := irs.IID{
NameId: item,
SystemId: item,
}
securityTag = append(securityTag, iId)
}
//var vpcHandler *GCPVPCHandler
vmInfo := irs.VMInfo{
IId: irs.IID{
NameId: vm.Name,
//SystemId: strconv.FormatUint(vm.Id, 10),
SystemId: vm.Name,
},
Region: irs.RegionInfo{
Region: vmHandler.Region.Region,
Zone: vmHandler.Region.Zone,
},
VMUserId: "cb-user",
NetworkInterface: vm.NetworkInterfaces[0].Name,
SecurityGroupIIds: securityTag,
VMSpecName: vm.MachineType,
KeyPairIId: irs.IID{
NameId: vm.Labels["keypair"],
SystemId: vm.Labels["keypair"],
},
ImageIId: vmHandler.getImageInfo(vm.Disks[0].Source),
PublicIP: vm.NetworkInterfaces[0].AccessConfigs[0].NatIP,
PrivateIP: vm.NetworkInterfaces[0].NetworkIP,
VpcIID: vmReqInfo.VpcIID,
SubnetIID: vmReqInfo.SubnetIID,
KeyValueList: []irs.KeyValue{
{"SubNetwork", vm.NetworkInterfaces[0].Subnetwork},
{"AccessConfigName", vm.NetworkInterfaces[0].AccessConfigs[0].Name},
{"NetworkTier", vm.NetworkInterfaces[0].AccessConfigs[0].NetworkTier},
{"DiskDeviceName", vm.Disks[0].DeviceName},
{"DiskName", vm.Disks[0].Source},
},
}
return vmInfo, nil
*/
}
// VM 정보를 조회할 수 있을 때까지 최대 30초간 대기
func (vmHandler *GCPVMHandler) WaitForRun(vmIID irs.IID) (irs.VMStatus, error) {
cblogger.Info("======> 생성된 VM의 최종 정보 확인을 위해 Running 될 때까지 대기함.")
waitStatus := "Running"
//===================================
// Suspending 되도록 3초 정도 대기 함.
//===================================
curRetryCnt := 0
maxRetryCnt := 120
for {
curStatus, errStatus := vmHandler.GetVMStatus(vmIID)
if errStatus != nil {
cblogger.Error(errStatus.Error())
}
cblogger.Info("===>VM Status : ", curStatus)
if curStatus == irs.VMStatus(waitStatus) { //|| curStatus == irs.VMStatus("Running") {
cblogger.Infof("===>VM 상태가 [%s]라서 대기를 중단합니다.", curStatus)
break
}
//if curStatus != irs.VMStatus(waitStatus) {
curRetryCnt++
cblogger.Errorf("VM 상태가 [%s]이 아니라서 1초 대기후 조회합니다.", waitStatus)
time.Sleep(time.Second * 1)
if curRetryCnt > maxRetryCnt {
cblogger.Errorf("장시간(%d 초) 대기해도 VM의 Status 값이 [%s]으로 변경되지 않아서 강제로 중단합니다.", maxRetryCnt, waitStatus)
return irs.VMStatus("Failed"), errors.New("장시간 기다렸으나 생성된 VM의 상태가 [" + waitStatus + "]으로 바뀌지 않아서 중단 합니다.")
}
}
return irs.VMStatus(waitStatus), nil
}
// stop이라고 보면 될듯
func (vmHandler *GCPVMHandler) SuspendVM(vmID irs.IID) (irs.VMStatus, error) {
projectID := vmHandler.Credential.ProjectID
zone := vmHandler.Region.Zone
ctx := vmHandler.Ctx
// logger for HisCall
callogger := call.GetLogger("HISCALL")
callLogInfo := call.CLOUDLOGSCHEMA{
CloudOS: call.GCP,
RegionZone: vmHandler.Region.Zone,
ResourceType: call.VM,
ResourceName: vmID.SystemId,
CloudOSAPI: "Stop()",
ElapsedTime: "",
ErrorMSG: "",
}
callLogStart := call.Start()
inst, err := vmHandler.Client.Instances.Stop(projectID, zone, vmID.SystemId).Context(ctx).Do()
callLogInfo.ElapsedTime = call.Elapsed(callLogStart)
spew.Dump(inst)
if err != nil {
callLogInfo.ErrorMSG = err.Error()
callogger.Info(call.String(callLogInfo))
cblogger.Error(err)
return irs.VMStatus("Failed"), err
}
callogger.Info(call.String(callLogInfo))
fmt.Println("instance stop status :", inst.Status)
return irs.VMStatus("Suspending"), nil
}
func (vmHandler *GCPVMHandler) ResumeVM(vmID irs.IID) (irs.VMStatus, error) {
projectID := vmHandler.Credential.ProjectID
zone := vmHandler.Region.Zone
ctx := vmHandler.Ctx
// logger for HisCall
callogger := call.GetLogger("HISCALL")
callLogInfo := call.CLOUDLOGSCHEMA{
CloudOS: call.GCP,
RegionZone: vmHandler.Region.Zone,
ResourceType: call.VM,
ResourceName: vmID.SystemId,
CloudOSAPI: "Start()",
ElapsedTime: "",
ErrorMSG: "",
}
callLogStart := call.Start()
inst, err := vmHandler.Client.Instances.Start(projectID, zone, vmID.SystemId).Context(ctx).Do()
callLogInfo.ElapsedTime = call.Elapsed(callLogStart)
spew.Dump(inst)
if err != nil {
callLogInfo.ErrorMSG = err.Error()
callogger.Info(call.String(callLogInfo))
cblogger.Error(err)
return irs.VMStatus("Failed"), err
}
callogger.Info(call.String(callLogInfo))
fmt.Println("instance resume status :", inst.Status)
return irs.VMStatus("Resuming"), nil
}
func (vmHandler *GCPVMHandler) RebootVM(vmID irs.IID) (irs.VMStatus, error) {
// logger for HisCall
callogger := call.GetLogger("HISCALL")
callLogInfo := call.CLOUDLOGSCHEMA{
CloudOS: call.GCP,
RegionZone: vmHandler.Region.Zone,
ResourceType: call.VM,
ResourceName: vmID.SystemId,
CloudOSAPI: "SuspendVM()",
ElapsedTime: "",
ErrorMSG: "",
}
callLogStart := call.Start()
_, err := vmHandler.SuspendVM(vmID)
callLogInfo.ElapsedTime = call.Elapsed(callLogStart)
if err != nil {
callLogInfo.ErrorMSG = err.Error()
callogger.Info(call.String(callLogInfo))
return irs.VMStatus("Failed"), err
}
callogger.Info(call.String(callLogInfo))
_, err2 := vmHandler.ResumeVM(vmID)
if err2 != nil {
return irs.VMStatus("Failed"), err2
}
return irs.VMStatus("Rebooting"), nil
}
func (vmHandler *GCPVMHandler) TerminateVM(vmID irs.IID) (irs.VMStatus, error) {
projectID := vmHandler.Credential.ProjectID
zone := vmHandler.Region.Zone
ctx := vmHandler.Ctx
// logger for HisCall
callogger := call.GetLogger("HISCALL")
callLogInfo := call.CLOUDLOGSCHEMA{
CloudOS: call.GCP,
RegionZone: vmHandler.Region.Zone,
ResourceType: call.VM,
ResourceName: vmID.SystemId,
CloudOSAPI: "Delete()",
ElapsedTime: "",
ErrorMSG: "",
}
callLogStart := call.Start()
inst, err := vmHandler.Client.Instances.Delete(projectID, zone, vmID.SystemId).Context(ctx).Do()
callLogInfo.ElapsedTime = call.Elapsed(callLogStart)
spew.Dump(inst)
if err != nil {
callLogInfo.ErrorMSG = err.Error()
callogger.Info(call.String(callLogInfo))
cblogger.Error(err)
return irs.VMStatus("Failed"), err
}
callogger.Info(call.String(callLogInfo))
fmt.Println("instance status :", inst.Status)
return irs.VMStatus("Terminating"), nil
}
func (vmHandler *GCPVMHandler) ListVMStatus() ([]*irs.VMStatusInfo, error) {
//serverList, err := vmHandler.Client.ListAll(vmHandler.Ctx)
projectID := vmHandler.Credential.ProjectID
zone := vmHandler.Region.Zone
// logger for HisCall
callogger := call.GetLogger("HISCALL")
callLogInfo := call.CLOUDLOGSCHEMA{
CloudOS: call.GCP,
RegionZone: vmHandler.Region.Zone,
ResourceType: call.VM,
ResourceName: "",
CloudOSAPI: "List()",
ElapsedTime: "",
ErrorMSG: "",
}
callLogStart := call.Start()
serverList, err := vmHandler.Client.Instances.List(projectID, zone).Do()
callLogInfo.ElapsedTime = call.Elapsed(callLogStart)
if err != nil {
callLogInfo.ErrorMSG = err.Error()
callogger.Info(call.String(callLogInfo))
cblogger.Error(err)
return nil, err
}
callogger.Info(call.String(callLogInfo))
var vmStatusList []*irs.VMStatusInfo
for _, s := range serverList.Items {
if s.Name != "" {
vmId := s.Name
status, _ := vmHandler.GetVMStatus(irs.IID{NameId: vmId, SystemId: vmId})
vmStatusInfo := irs.VMStatusInfo{
IId: irs.IID{
NameId: vmId,
//SystemId: strconv.FormatUint(s.Id, 10),
SystemId: vmId,
},
VmStatus: status,
}
vmStatusList = append(vmStatusList, &vmStatusInfo)
}
}
return vmStatusList, nil
}
func ConvertVMStatusString(vmStatus string) (irs.VMStatus, error) {
var resultStatus string
cblogger.Infof("vmStatus : [%s]", vmStatus)
if strings.EqualFold(vmStatus, "PROVISIONING") {
resultStatus = "Creating"
//resultStatus = "Resuming" // Resume 요청을 받아서 재기동되는 단계에도 Pending이 있기 때문에 Pending은 Resuming으로 맵핑함.
} else if strings.EqualFold(vmStatus, "RUNNING") {
resultStatus = "Running"
} else if strings.EqualFold(vmStatus, "STOPPING") {
resultStatus = "Suspending"
} else if strings.EqualFold(vmStatus, "Terminated") {
resultStatus = "Suspended"
} else if strings.EqualFold(vmStatus, "STAGING") {
resultStatus = "Resuming"
} else {
//resultStatus = "Failed"
cblogger.Errorf("vmStatus [%s]와 일치하는 맵핑 정보를 찾지 못 함.", vmStatus)
return irs.VMStatus("Failed"), errors.New(vmStatus + "와 일치하는 CB VM 상태정보를 찾을 수 없습니다.")
}
cblogger.Infof("VM 상태 치환 : [%s] ==> [%s]", vmStatus, resultStatus)
return irs.VMStatus(resultStatus), nil
}
func (vmHandler *GCPVMHandler) GetVMStatus(vmID irs.IID) (irs.VMStatus, error) { // GCP의 ID는 uint64 이므로 GCP에서는 Name을 ID값으로 사용한다.
projectID := vmHandler.Credential.ProjectID
zone := vmHandler.Region.Zone
// logger for HisCall
callogger := call.GetLogger("HISCALL")
callLogInfo := call.CLOUDLOGSCHEMA{
CloudOS: call.GCP,
RegionZone: vmHandler.Region.Zone,
ResourceType: call.VM,
ResourceName: vmID.SystemId,
CloudOSAPI: "Get()",
ElapsedTime: "",
ErrorMSG: "",
}
callLogStart := call.Start()
instanceView, err := vmHandler.Client.Instances.Get(projectID, zone, vmID.SystemId).Do()
callLogInfo.ElapsedTime = call.Elapsed(callLogStart)
if err != nil {
callLogInfo.ErrorMSG = err.Error()
callogger.Info(call.String(callLogInfo))
cblogger.Error(err)
return irs.VMStatus("Failed"), err
}
callogger.Info(call.String(callLogInfo))
// Get powerState, provisioningState
//vmStatus := instanceView.Status
vmStatus, errStatus := ConvertVMStatusString(instanceView.Status)
//return irs.VMStatus(vmStatus), err
return vmStatus, errStatus
}
func (vmHandler *GCPVMHandler) ListVM() ([]*irs.VMInfo, error) {
projectID := vmHandler.Credential.ProjectID
zone := vmHandler.Region.Zone
cblogger.Info("VMLIST zone info :", zone)
// logger for HisCall
callogger := call.GetLogger("HISCALL")
callLogInfo := call.CLOUDLOGSCHEMA{
CloudOS: call.GCP,
RegionZone: vmHandler.Region.Zone,
ResourceType: call.VM,
ResourceName: "",
CloudOSAPI: "List()",
ElapsedTime: "",
ErrorMSG: "",
}
callLogStart := call.Start()
serverList, err := vmHandler.Client.Instances.List(projectID, zone).Do()
callLogInfo.ElapsedTime = call.Elapsed(callLogStart)
if err != nil {
callLogInfo.ErrorMSG = err.Error()
callogger.Info(call.String(callLogInfo))
cblogger.Error(err)
cblogger.Infof("해당존에 만들어진 Vm List 가 없음")
return nil, err
}
callogger.Info(call.String(callLogInfo))
var vmList []*irs.VMInfo
for _, server := range serverList.Items {
vmInfo := vmHandler.mappingServerInfo(server)
vmList = append(vmList, &vmInfo)
}
return vmList, nil
}
func (vmHandler *GCPVMHandler) GetVM(vmID irs.IID) (irs.VMInfo, error) {
projectID := vmHandler.Credential.ProjectID
zone := vmHandler.Region.Zone
// logger for HisCall
callogger := call.GetLogger("HISCALL")
callLogInfo := call.CLOUDLOGSCHEMA{
CloudOS: call.GCP,
RegionZone: vmHandler.Region.Zone,
ResourceType: call.VM,
ResourceName: vmID.SystemId,
CloudOSAPI: "CreateVpc()",
ElapsedTime: "",
ErrorMSG: "",
}
callLogStart := call.Start()
vm, err := vmHandler.Client.Instances.Get(projectID, zone, vmID.SystemId).Do()
callLogInfo.ElapsedTime = call.Elapsed(callLogStart)
if err != nil {
callLogInfo.ErrorMSG = err.Error()
callogger.Info(call.String(callLogInfo))
cblogger.Error(err)
return irs.VMInfo{}, err
}
callogger.Info(call.String(callLogInfo))
spew.Dump(vm)
vmInfo := vmHandler.mappingServerInfo(vm)
return vmInfo, nil
}
// func getVmStatus(vl *compute.Service) string {
// var powerState, provisioningState string
// for _, stat := range vl {
// statArr := strings.Split(*stat.Code, "/")
// if statArr[0] == "PowerState" {
// powerState = statArr[1]
// } else if statArr[0] == "ProvisioningState" {
// provisioningState = statArr[1]
// }
// }
// // Set VM Status Info
// var vmState string
// if powerState != "" && provisioningState != "" {
// vmState = powerState + "(" + provisioningState + ")"
// } else if powerState != "" && provisioningState == "" {
// vmState = powerState
// } else if powerState == "" && provisioningState != "" {
// vmState = provisioningState
// } else {
// vmState = "-"
// }
// return vmState
// }
func (vmHandler *GCPVMHandler) mappingServerInfo(server *compute.Instance) irs.VMInfo {
cblogger.Info("================맵핑=====================================")
spew.Dump(server)
//var gcpHanler *GCPVMHandler
vpcArr := strings.Split(server.NetworkInterfaces[0].Network, "/")
subnetArr := strings.Split(server.NetworkInterfaces[0].Subnetwork, "/")
vpcName := vpcArr[len(vpcArr)-1]
subnetName := subnetArr[len(subnetArr)-1]
type IIDBox struct {
Items []irs.IID
}
var iIdBox IIDBox
for _, item := range server.Tags.Items {
iId := irs.IID{
NameId: item,
SystemId: item,
}
iIdBox.Items = append(iIdBox.Items, iId)
}
vmInfo := irs.VMInfo{
IId: irs.IID{
NameId: server.Name,
//SystemId: strconv.FormatUint(server.Id, 10),
SystemId: server.Name,
},
//VMSpecName: server.MachineType,
Region: irs.RegionInfo{
Region: vmHandler.Region.Region,
Zone: vmHandler.Region.Zone,
},
VMUserId: "cb-user",
NetworkInterface: server.NetworkInterfaces[0].Name,
SecurityGroupIIds: iIdBox.Items,
KeyPairIId: irs.IID{
NameId: server.Labels["keypair"],
SystemId: server.Labels["keypair"],
},
ImageIId: vmHandler.getImageInfo(server.Disks[0].Source),
PublicIP: server.NetworkInterfaces[0].AccessConfigs[0].NatIP,
PrivateIP: server.NetworkInterfaces[0].NetworkIP,
VpcIID: irs.IID{
NameId: vpcName,
SystemId: vpcName,
},
SubnetIID: irs.IID{
NameId: subnetName,
SystemId: subnetName,
},
KeyValueList: []irs.KeyValue{
{"SubNetwork", server.NetworkInterfaces[0].Subnetwork},
{"AccessConfigName", server.NetworkInterfaces[0].AccessConfigs[0].Name},
{"NetworkTier", server.NetworkInterfaces[0].AccessConfigs[0].NetworkTier},
{"DiskDeviceName", server.Disks[0].DeviceName},
{"DiskName", server.Disks[0].Source},
},
}
arrVmSpec := strings.Split(server.MachineType, "/")
cblogger.Info(arrVmSpec)
if len(arrVmSpec) > 1 {
cblogger.Info(arrVmSpec[len(arrVmSpec)-1])
vmInfo.VMSpecName = arrVmSpec[len(arrVmSpec)-1]
}
//2020-05-13T00:15:37.183-07:00
if len(server.CreationTimestamp) > 5 {
cblogger.Infof("서버 구동 시간 처리 : [%s]", server.CreationTimestamp)
t, err := time.Parse(time.RFC3339, server.CreationTimestamp)
if err != nil {
cblogger.Error(err)
} else {
cblogger.Infof("======> [%v]", t)
vmInfo.StartTime = t
}
}
return vmInfo
}
//이미지 URL 방식 대신 이름을 사용하도록 변경 중
//@TODO : 2020-05-15 카푸치노 버전에서는 이름 대신 URL을 사용하기로 했음.
func (vmHandler *GCPVMHandler) getImageInfo(diskname string) irs.IID {
projectID := vmHandler.Credential.ProjectID
zone := vmHandler.Region.Zone
dArr := strings.Split(diskname, "/")
var result string
if dArr != nil {
result = dArr[len(dArr)-1]
}
cblogger.Infof("result : [%s]", result)
info, err := vmHandler.Client.Disks.Get(projectID, zone, result).Do()
cblogger.Infof("********************************** Disk 정보 ****************")
spew.Dump(info)
if err != nil {
cblogger.Error(err)
return irs.IID{}
}
/* 2020-05-14 카푸치노 다음 버전에서 사용 예정
arrImageUrl := strings.Split(info.SourceImage, "/")
imageName := ""
if len(arrImageUrl) > 0 {
imageName = arrImageUrl[len(arrImageUrl)-1]
}
iId := irs.IID{
NameId: imageName,
SystemId: imageName,
}
*/
iId := irs.IID{
NameId: info.SourceImage, //2020-05-14 NameId는 사용자가 사용한 이름도 있기 때문에 리턴하지 않도록 수정
SystemId: info.SourceImage,
}
/*
iId := irs.IID{
NameId: info.Name,
//SystemId: strconv.FormatUint(info.Id, 10),
SystemId: info.Name,
}
*/
return iId
}
// func (vmHandler *GCPVMHandler) getKeyPairInfo(diskname string) irs.IID {
// projectID := vmHandler.Credential.ProjectID
// zone := vmHandler.Region.Zone
// var gcpKeyPairHandler *GCPKeyPairHandler
// iId := irs.IID{
// NameId: "cb-user",
// SystemId: "cb-user",
// }
// result, err := gcpKeyPairHandler.GetKey(iId)
// spew.Dump(result)
// if err != nil {
// cblogger.Error(err)
// return result
// }
// return result
// }