Best Syzkaller code snippet using vm.Info
VMHandler.go
Source:VMHandler.go
...30 VM = "VM"31 DefaultSGName = "SSH"32)33type ClouditVMHandler struct {34 CredentialInfo idrv.CredentialInfo35 Client *client.RestClient36}37func (vmHandler *ClouditVMHandler) StartVM(vmReqInfo irs.VMReqInfo) (startVM irs.VMInfo, createError error) {38 // log HisCall39 hiscallInfo := GetCallLogScheme(ClouditRegion, call.VM, VM, "StartVM()")40 err := notSupportRootDiskCustom(vmReqInfo)41 if err != nil {42 createErr := errors.New(fmt.Sprintf("Failed to Create VM. err = %s", err.Error()))43 cblogger.Error(createErr.Error())44 LoggingError(hiscallInfo, createErr)45 return irs.VMInfo{}, createErr46 }47 // ê°ììë² ì´ë¦ ì¤ë³µ ì²´í¬48 exist, err := vmHandler.getExistVmName(vmReqInfo.IId.NameId)49 if exist {50 createErr := errors.New(fmt.Sprintf("Failed to Create VM. err = %s already exist", vmReqInfo.IId.NameId))51 if err != nil {52 createErr := errors.New(fmt.Sprintf("Failed to Create VM. err = %s", err.Error()))53 cblogger.Error(createErr.Error())54 LoggingError(hiscallInfo, createErr)55 return irs.VMInfo{}, createErr56 }57 cblogger.Error(createErr.Error())58 LoggingError(hiscallInfo, createErr)59 return irs.VMInfo{}, createErr60 }61 // ì´ë¯¸ì§ ì ë³´ ì¡°í (Name)62 imageHandler := ClouditImageHandler{63 Client: vmHandler.Client,64 CredentialInfo: vmHandler.CredentialInfo,65 }66 image, err := imageHandler.GetImage(vmReqInfo.ImageIID)67 if err != nil {68 createErr := errors.New(fmt.Sprintf("Failed to Create VM. err = Failed to get image, %s", err.Error()))69 cblogger.Error(createErr.Error())70 LoggingError(hiscallInfo, createErr)71 return irs.VMInfo{}, createErr72 }73 // ë¤í¸ìí¬ ì ë³´ ì¡°í (Name)74 vpcHandler := ClouditVPCHandler{75 Client: vmHandler.Client,76 CredentialInfo: vmHandler.CredentialInfo,77 }78 vpcInfo, err := vpcHandler.GetVPC(vmReqInfo.VpcIID)79 if err != nil {80 createErr := errors.New(fmt.Sprintf("Failed to Create VM. err = Failed to get VPC, %s", err.Error()))81 cblogger.Error(createErr.Error())82 LoggingError(hiscallInfo, createErr)83 return irs.VMInfo{}, createErr84 }85 subnet, err := vpcHandler.GetSubnet(vmReqInfo.SubnetIID)86 if err != nil {87 createErr := errors.New(fmt.Sprintf("Failed to Create VM. err = Failed to get subnet, %s", err.Error()))88 cblogger.Error(createErr.Error())89 LoggingError(hiscallInfo, createErr)90 return irs.VMInfo{}, createErr91 }92 subnetCheck := false93 for _, sub := range vpcInfo.SubnetInfoList {94 if subnet.ID == sub.IId.SystemId {95 subnetCheck = true96 break97 }98 }99 if !subnetCheck {100 createErr := errors.New(fmt.Sprintf("Failed to Create VM. err = subnet: '%s' cannot be found in VPC: '%s'", vmReqInfo.SubnetIID.NameId, vpcInfo.IId.NameId))101 cblogger.Error(createErr.Error())102 LoggingError(hiscallInfo, createErr)103 return irs.VMInfo{}, createErr104 }105 // ë³´ì그룹 ì ë³´ ì¡°í (Name)106 sgHandler := ClouditSecurityHandler{107 Client: vmHandler.Client,108 CredentialInfo: vmHandler.CredentialInfo,109 }110 securityInfo, err := sgHandler.getRawSecurityGroup(irs.IID{NameId: DefaultSGName})111 if err != nil {112 createErr := errors.New(fmt.Sprintf("Failed to Create VM. err = %s", err.Error()))113 cblogger.Error(createErr.Error())114 LoggingError(hiscallInfo, createErr)115 return irs.VMInfo{}, createErr116 }117 addUserSSHSG := []server.SecGroupInfo{{securityInfo.ID}}118 // Spec ì ë³´ ì¡°í (Name)119 vmSpecId, err := GetVMSpecByName(vmHandler.Client.AuthenticatedHeaders(), vmHandler.Client, vmReqInfo.VMSpecName)120 if err != nil {121 createErr := errors.New(fmt.Sprintf("Failed to Create VM. err = %s", err.Error()))122 cblogger.Error(createErr.Error())123 LoggingError(hiscallInfo, createErr)124 return irs.VMInfo{}, createErr125 }126 vmHandler.Client.TokenID = vmHandler.CredentialInfo.AuthToken127 authHeader := vmHandler.Client.AuthenticatedHeaders()128 KeyPairDes := fmt.Sprintf("keypair:%s", vmReqInfo.KeyPairIID.NameId)129 reqInfo := server.VMReqInfo{130 TemplateId: image.IId.SystemId,131 SpecId: *vmSpecId,132 Name: vmReqInfo.IId.NameId,133 HostName: vmReqInfo.IId.NameId,134 RootPassword: VMDefaultPassword,135 SubnetAddr: subnet.Addr,136 Secgroups: addUserSSHSG,137 Description: KeyPairDes,138 }139 requestOpts := client.RequestOpts{140 MoreHeaders: authHeader,141 JSONBody: reqInfo,142 }143 // Check PublicIP144 _, err = vmHandler.creatablePublicIP()145 if err != nil {146 createErr := errors.New(fmt.Sprintf("Failed to Create VM. err = %s", err.Error()))147 cblogger.Error(createErr.Error())148 LoggingError(hiscallInfo, createErr)149 return irs.VMInfo{}, createErr150 }151 // VM ìì±152 start := call.Start()153 creatingVm, err := server.Start(vmHandler.Client, &requestOpts)154 if err != nil {155 createErr := errors.New(fmt.Sprintf("Failed to Create VM. err = %s", err.Error()))156 cblogger.Error(createErr.Error())157 LoggingError(hiscallInfo, createErr)158 return irs.VMInfo{}, createErr159 }160 LoggingInfo(hiscallInfo, start)161 cleanVMIID := irs.IID{162 NameId: creatingVm.Name, SystemId: creatingVm.ID,163 }164 var createErr error165 defer func() {166 if createError != nil {167 cleanerErr := vmHandler.vmCleaner(cleanVMIID)168 if cleanerErr != nil {169 createError = errors.New(fmt.Sprintf("%s and Failed to rollback err = %s", createError.Error(), cleanerErr.Error()))170 }171 }172 }()173 // VM ìì± ìë£ê¹ì§ wait174 curRetryCnt := 0175 maxRetryCnt := 120176 for {177 // Check VM Deploy Status178 vmInfo, err := server.Get(vmHandler.Client, creatingVm.ID, &requestOpts)179 if err != nil {180 createErr = errors.New(fmt.Sprintf("Failed to Create VM. err = %s", err.Error()))181 cblogger.Error(createErr.Error())182 LoggingError(hiscallInfo, createErr)183 return irs.VMInfo{}, createErr184 }185 if vmInfo.PrivateIp != "" && getVmStatus(vmInfo.State) == irs.Running {186 ok, err := vmHandler.AssociatePublicIP(creatingVm.Name, vmInfo.PrivateIp)187 if !ok {188 createErr = errors.New(fmt.Sprintf("Failed to Create VM. err = Failed AssociatePublicIP"))189 if err != nil {190 createErr = errors.New(fmt.Sprintf("Failed to Create VM. err = Failed AssociatePublicIP err= %s", err.Error()))191 }192 cblogger.Error(createErr.Error())193 LoggingError(hiscallInfo, createErr)194 return irs.VMInfo{}, createErr195 }196 break197 }198 time.Sleep(1 * time.Second)199 curRetryCnt++200 if curRetryCnt > maxRetryCnt {201 createErr = errors.New(fmt.Sprintf("Failed to Create VM. err = exceeded maximum retry count %d", maxRetryCnt))202 cblogger.Error(createErr.Error())203 LoggingError(hiscallInfo, createErr)204 return irs.VMInfo{}, createErr205 }206 }207 vm, err := server.Get(vmHandler.Client, creatingVm.ID, &requestOpts)208 if err != nil {209 createErr = errors.New(fmt.Sprintf("Failed to Create VM. err = %s", err.Error()))210 cblogger.Error(createErr.Error())211 LoggingError(hiscallInfo, createErr)212 return irs.VMInfo{}, createErr213 }214 // SSH ì ì ì¬ì©ì ë° ê³µê°í¤ ë±ë¡215 loginUserId := SSHDefaultUser216 createUserErr := errors.New(fmt.Sprintf("Failed adding cb-User to new VM"))217 // SSH ì ìê¹ì§ ìë218 curConnectionCnt := 0219 maxConnectionRetryCnt := 120220 for {221 cblogger.Info("Trying to connect via root user ...")222 _, err := RunCommand(vm.AdaptiveIp, SSHDefaultPort, VMDefaultUser, VMDefaultPassword, "echo test")223 if err == nil {224 break225 }226 time.Sleep(1 * time.Second)227 curConnectionCnt++228 if curConnectionCnt > maxConnectionRetryCnt {229 createErr = errors.New(fmt.Sprintf("Failed to Create VM. err = %s, not Connected", createUserErr.Error()))230 cblogger.Error(createErr.Error())231 LoggingError(hiscallInfo, createErr)232 return irs.VMInfo{}, createErr233 }234 }235 // ì¬ì©ì ë±ë¡ ë° sudoer ê¶í ì¶ê°236 _, err = RunCommand(vm.AdaptiveIp, SSHDefaultPort, VMDefaultUser, VMDefaultPassword, fmt.Sprintf("useradd -s /bin/bash %s -rm", loginUserId))237 if err != nil {238 createErr = errors.New(fmt.Sprintf("Failed to Create VM. err = %s = %s", createUserErr.Error(), err.Error()))239 cblogger.Error(createErr.Error())240 LoggingError(hiscallInfo, createErr)241 return irs.VMInfo{}, createErr242 }243 _, err = RunCommand(vm.AdaptiveIp, SSHDefaultPort, VMDefaultUser, VMDefaultPassword, fmt.Sprintf("echo \"%s ALL=(root) NOPASSWD:ALL\" >> /etc/sudoers", loginUserId))244 if err != nil {245 createErr = errors.New(fmt.Sprintf("Failed to Create VM. err = %s = %s", createUserErr.Error(), err.Error()))246 cblogger.Error(createErr.Error())247 LoggingError(hiscallInfo, createErr)248 return irs.VMInfo{}, createErr249 }250 // ê³µê°í¤ ë±ë¡251 _, err = RunCommand(vm.AdaptiveIp, SSHDefaultPort, VMDefaultUser, VMDefaultPassword, fmt.Sprintf("mkdir -p /home/%s/.ssh", loginUserId))252 publicKey, err := GetPublicKey(vmHandler.CredentialInfo, vmReqInfo.KeyPairIID.NameId)253 if err != nil {254 createErr = errors.New(fmt.Sprintf("Failed to Create VM. err = %s = %s", createUserErr.Error(), err.Error()))255 cblogger.Error(createErr.Error())256 LoggingError(hiscallInfo, createErr)257 return irs.VMInfo{}, createErr258 }259 _, err = RunCommand(vm.AdaptiveIp, SSHDefaultPort, VMDefaultUser, VMDefaultPassword, fmt.Sprintf("echo \"%s\" > /home/%s/.ssh/authorized_keys", publicKey, loginUserId))260 if err != nil {261 createErr = errors.New(fmt.Sprintf("Failed to Create VM. err = %s = %s", createUserErr.Error(), err.Error()))262 cblogger.Error(createErr.Error())263 LoggingError(hiscallInfo, createErr)264 return irs.VMInfo{}, createErr265 }266 // ssh ì ì ë°©ë² ë³ê²½ (sshd_config íì¼ ë³ê²½)267 _, err = RunCommand(vm.AdaptiveIp, SSHDefaultPort, VMDefaultUser, VMDefaultPassword, "sed -i 's/PasswordAuthentication yes/PasswordAuthentication no/g' /etc/ssh/sshd_config")268 if err != nil {269 createErr = errors.New(fmt.Sprintf("Failed to Create VM. err = %s = %s", createUserErr.Error(), err.Error()))270 cblogger.Error(createErr.Error())271 LoggingError(hiscallInfo, createErr)272 return irs.VMInfo{}, createErr273 }274 _, err = RunCommand(vm.AdaptiveIp, SSHDefaultPort, VMDefaultUser, VMDefaultPassword, "sed -i 's/#PubkeyAuthentication yes/PubkeyAuthentication yes/g' /etc/ssh/sshd_config")275 if err != nil {276 createErr = errors.New(fmt.Sprintf("Failed to Create VM. err = %s = %s", createUserErr.Error(), err.Error()))277 cblogger.Error(createErr.Error())278 LoggingError(hiscallInfo, createErr)279 return irs.VMInfo{}, createErr280 }281 _, err = RunCommand(vm.AdaptiveIp, SSHDefaultPort, VMDefaultUser, VMDefaultPassword, "systemctl restart sshd")282 if err != nil {283 createErr = errors.New(fmt.Sprintf("Failed to Create VM. err = %s = %s", createUserErr.Error(), err.Error()))284 cblogger.Error(createErr.Error())285 LoggingError(hiscallInfo, createErr)286 return irs.VMInfo{}, createErr287 }288 vmHandler.Client.TokenID = vmHandler.CredentialInfo.AuthToken289 secGroups := make([]string, len(vmReqInfo.SecurityGroupIIDs))290 if len(vmReqInfo.SecurityGroupIIDs) > 0 {291 for i, s := range vmReqInfo.SecurityGroupIIDs {292 secGroups[i] = s.SystemId293 }294 } else {295 secGroups = append(secGroups, "")296 }297 vnicList, err := ListVNic(authHeader, vmHandler.Client, vm.ID)298 if err != nil {299 createErr = errors.New(fmt.Sprintf("Failed to Create VM. Not found default VNic err = %s", err.Error()))300 cblogger.Error(createErr.Error())301 LoggingError(hiscallInfo, createErr)302 return irs.VMInfo{}, createErr303 }304 changesgrequestOpts := client.RequestOpts{305 MoreHeaders: authHeader,306 }307 if vnicList != nil {308 defaultVnic := (*vnicList)[0]309 err := nic.ChangeSecurityGroup(vmHandler.Client, vm.ID, &changesgrequestOpts, defaultVnic.Mac, secGroups)310 if err != nil {311 createErr = errors.New(fmt.Sprintf("Failed to Create VM. err = change Security Groups err = %s", err.Error()))312 cblogger.Error(createErr.Error())313 LoggingError(hiscallInfo, createErr)314 return irs.VMInfo{}, createErr315 }316 } else {317 createErr = errors.New(fmt.Sprintf("Failed to Create VM. err = Not found default VNic"))318 cblogger.Error(createErr.Error())319 LoggingError(hiscallInfo, createErr)320 return irs.VMInfo{}, createErr321 }322 vm, err = server.Get(vmHandler.Client, creatingVm.ID, &requestOpts)323 if err != nil {324 createErr = errors.New(fmt.Sprintf("Failed to Create VM. err = %s", err.Error()))325 cblogger.Error(createErr.Error())326 LoggingError(hiscallInfo, createErr)327 return irs.VMInfo{}, createErr328 }329 vmInfo, err := vmHandler.mappingServerInfo(*vm)330 if err != nil {331 createErr = errors.New(fmt.Sprintf("Failed to Create VM. err = %s", err.Error()))332 cblogger.Error(createErr.Error())333 LoggingError(hiscallInfo, createErr)334 return irs.VMInfo{}, createErr335 }336 return vmInfo, nil337}338func (vmHandler *ClouditVMHandler) SuspendVM(vmIID irs.IID) (irs.VMStatus, error) {339 // log HisCall340 hiscallInfo := GetCallLogScheme(ClouditRegion, call.VM, vmIID.NameId, "SuspendVM()")341 vmHandler.Client.TokenID = vmHandler.CredentialInfo.AuthToken342 authHeader := vmHandler.Client.AuthenticatedHeaders()343 requestOpts := client.RequestOpts{344 MoreHeaders: authHeader,345 }346 rawVm, err := vmHandler.getRawVm(vmIID)347 if err != nil {348 getErr := errors.New(fmt.Sprintf("Failed to Get VMStatus. err = %s", err.Error()))349 cblogger.Error(getErr.Error())350 LoggingError(hiscallInfo, getErr)351 return "", getErr352 }353 // Set VM Status Info354 vmStatus := getVmStatus(rawVm.State)355 if vmStatus != irs.Running {356 getErr := errors.New(fmt.Sprintf("Failed to SuspendVM. err = not Running"))357 cblogger.Error(getErr.Error())358 LoggingError(hiscallInfo, getErr)359 return irs.Failed, getErr360 }361 start := call.Start()362 err = server.Suspend(vmHandler.Client, rawVm.ID, &requestOpts)363 if err != nil {364 getErr := errors.New(fmt.Sprintf("Failed to SuspendVM. err = %s", err.Error()))365 cblogger.Error(getErr.Error())366 LoggingError(hiscallInfo, getErr)367 return irs.Failed, getErr368 }369 curRetryCnt := 0370 maxRetryCnt := 120371 for {372 // Check VM Deploy Status373 vmStatus, _ := vmHandler.GetVMStatus(vmIID)374 if vmStatus == irs.Suspended {375 LoggingInfo(hiscallInfo, start)376 return vmStatus, nil377 }378 time.Sleep(1 * time.Second)379 curRetryCnt++380 if curRetryCnt > maxRetryCnt {381 createErr := errors.New(fmt.Sprintf("Failed to SuspendVM. err = exceeded maximum retry count %d", maxRetryCnt))382 cblogger.Error(createErr.Error())383 LoggingError(hiscallInfo, createErr)384 return irs.Failed, createErr385 }386 }387}388func (vmHandler *ClouditVMHandler) ResumeVM(vmIID irs.IID) (irs.VMStatus, error) {389 // log HisCall390 hiscallInfo := GetCallLogScheme(ClouditRegion, call.VM, vmIID.NameId, "ResumeVM()")391 vmHandler.Client.TokenID = vmHandler.CredentialInfo.AuthToken392 authHeader := vmHandler.Client.AuthenticatedHeaders()393 requestOpts := client.RequestOpts{394 MoreHeaders: authHeader,395 }396 rawVm, err := vmHandler.getRawVm(vmIID)397 if err != nil {398 getErr := errors.New(fmt.Sprintf("Failed to Get VMStatus. err = %s", err.Error()))399 cblogger.Error(getErr.Error())400 LoggingError(hiscallInfo, getErr)401 return "", getErr402 }403 vmStatus := getVmStatus(rawVm.State)404 if vmStatus != irs.Suspended {405 getErr := errors.New(fmt.Sprintf("Failed to ResumeVM. err = not Suspended"))406 cblogger.Error(getErr.Error())407 LoggingError(hiscallInfo, getErr)408 return irs.Failed, getErr409 }410 start := call.Start()411 err = server.Resume(vmHandler.Client, rawVm.ID, &requestOpts)412 if err != nil {413 getErr := errors.New(fmt.Sprintf("Failed to ResumeVM. err = %s", err.Error()))414 cblogger.Error(getErr.Error())415 LoggingError(hiscallInfo, getErr)416 return irs.Failed, getErr417 }418 curRetryCnt := 0419 maxRetryCnt := 120420 for {421 // Check VM Deploy Status422 vmStatus, _ := vmHandler.GetVMStatus(vmIID)423 if vmStatus == irs.Running {424 LoggingInfo(hiscallInfo, start)425 return vmStatus, nil426 }427 time.Sleep(1 * time.Second)428 curRetryCnt++429 if curRetryCnt > maxRetryCnt {430 createErr := errors.New(fmt.Sprintf("Failed to ResumeVM. err = exceeded maximum retry count %d", maxRetryCnt))431 cblogger.Error(createErr.Error())432 LoggingError(hiscallInfo, createErr)433 return irs.Failed, createErr434 }435 }436}437func (vmHandler *ClouditVMHandler) RebootVM(vmIID irs.IID) (irs.VMStatus, error) {438 // log HisCall439 hiscallInfo := GetCallLogScheme(ClouditRegion, call.VM, vmIID.NameId, "RebootVM()")440 vmHandler.Client.TokenID = vmHandler.CredentialInfo.AuthToken441 authHeader := vmHandler.Client.AuthenticatedHeaders()442 requestOpts := client.RequestOpts{443 MoreHeaders: authHeader,444 }445 rawVm, err := vmHandler.getRawVm(vmIID)446 if err != nil {447 getErr := errors.New(fmt.Sprintf("Failed to Get VMStatus. err = %s", err.Error()))448 cblogger.Error(getErr.Error())449 LoggingError(hiscallInfo, getErr)450 return "", getErr451 }452 vmStatus := getVmStatus(rawVm.State)453 if vmStatus != irs.Running {454 getErr := errors.New(fmt.Sprintf("Failed to RebootVM. err = not Running"))455 cblogger.Error(getErr.Error())456 LoggingError(hiscallInfo, getErr)457 return irs.Failed, getErr458 }459 start := call.Start()460 err = server.Reboot(vmHandler.Client, rawVm.ID, &requestOpts)461 if err != nil {462 getErr := errors.New(fmt.Sprintf("Failed to RebootVM. err = %s", err.Error()))463 cblogger.Error(getErr.Error())464 LoggingError(hiscallInfo, getErr)465 return irs.Failed, getErr466 }467 LoggingInfo(hiscallInfo, start)468 // VM ìí ì ë³´ ë°í469 vmStatus, err = vmHandler.GetVMStatus(vmIID)470 if err != nil {471 getErr := errors.New(fmt.Sprintf("Failed to RebootVM. err = %s", err.Error()))472 cblogger.Error(getErr.Error())473 LoggingError(hiscallInfo, getErr)474 return irs.Failed, getErr475 }476 return vmStatus, nil477}478func (vmHandler *ClouditVMHandler) TerminateVM(vmIID irs.IID) (irs.VMStatus, error) {479 // log HisCall480 hiscallInfo := GetCallLogScheme(ClouditRegion, call.VM, vmIID.NameId, "TerminateVM()")481 start := call.Start()482 err := vmHandler.vmCleaner(vmIID)483 if err != nil {484 TerminateErr := errors.New(fmt.Sprintf("Failed to Terminate VM err = %s", err.Error()))485 cblogger.Error(TerminateErr.Error())486 LoggingError(hiscallInfo, TerminateErr)487 return irs.Failed, TerminateErr488 }489 LoggingInfo(hiscallInfo, start)490 // VM ìí ì ë³´ ë°í491 return irs.Terminated, nil492}493func (vmHandler *ClouditVMHandler) ListVMStatus() ([]*irs.VMStatusInfo, error) {494 // log HisCall495 hiscallInfo := GetCallLogScheme(ClouditRegion, call.VM, VM, "ListVMStatus()")496 vmHandler.Client.TokenID = vmHandler.CredentialInfo.AuthToken497 authHeader := vmHandler.Client.AuthenticatedHeaders()498 requestOpts := client.RequestOpts{499 MoreHeaders: authHeader,500 }501 start := call.Start()502 vmList, err := server.List(vmHandler.Client, &requestOpts)503 if err != nil {504 getErr := errors.New(fmt.Sprintf("Failed to Get ListVMStatus. err = %s", err.Error()))505 cblogger.Error(getErr.Error())506 LoggingError(hiscallInfo, getErr)507 return nil, getErr508 }509 LoggingInfo(hiscallInfo, start)510 vmStatusList := make([]*irs.VMStatusInfo, len(*vmList))511 for i, vm := range *vmList {512 vmStatusInfo := irs.VMStatusInfo{513 IId: irs.IID{514 NameId: vm.Name,515 SystemId: vm.ID,516 },517 VmStatus: irs.VMStatus(vm.State),518 }519 vmStatusList[i] = &vmStatusInfo520 }521 return vmStatusList, nil522}523func (vmHandler *ClouditVMHandler) GetVMStatus(vmIID irs.IID) (irs.VMStatus, error) {524 // log HisCall525 hiscallInfo := GetCallLogScheme(ClouditRegion, call.VM, vmIID.NameId, "GetVMStatus()")526 start := call.Start()527 rawVm, err := vmHandler.getRawVm(vmIID)528 if err != nil {529 getErr := errors.New(fmt.Sprintf("Failed to Get VMStatus. err = %s", err.Error()))530 cblogger.Error(getErr.Error())531 LoggingError(hiscallInfo, getErr)532 return "", getErr533 }534 LoggingInfo(hiscallInfo, start)535 // Set VM Status Info536 status := getVmStatus(rawVm.State)537 return status, nil538}539func (vmHandler *ClouditVMHandler) ListVM() ([]*irs.VMInfo, error) {540 // log HisCall541 hiscallInfo := GetCallLogScheme(ClouditRegion, call.VM, VM, "ListVM()")542 vmHandler.Client.TokenID = vmHandler.CredentialInfo.AuthToken543 authHeader := vmHandler.Client.AuthenticatedHeaders()544 requestOpts := client.RequestOpts{545 MoreHeaders: authHeader,546 }547 start := call.Start()548 vmList, err := server.List(vmHandler.Client, &requestOpts)549 if err != nil {550 getErr := errors.New(fmt.Sprintf("Failed to Get VMList. err = %s", err.Error()))551 cblogger.Error(getErr.Error())552 LoggingError(hiscallInfo, getErr)553 return nil, getErr554 }555 LoggingInfo(hiscallInfo, start)556 vmInfoList := make([]*irs.VMInfo, len(*vmList))557 for i, vm := range *vmList {558 vmInfo, err := vmHandler.mappingServerInfo(vm)559 if err != nil {560 getErr := errors.New(fmt.Sprintf("Failed to Get VMList. err = %s", err.Error()))561 cblogger.Error(getErr.Error())562 LoggingError(hiscallInfo, getErr)563 return nil, getErr564 }565 vmInfoList[i] = &vmInfo566 }567 return vmInfoList, nil568}569func (vmHandler *ClouditVMHandler) GetVM(vmIID irs.IID) (irs.VMInfo, error) {570 // log HisCall571 hiscallInfo := GetCallLogScheme(ClouditRegion, call.VM, vmIID.NameId, "GetVM()")572 start := call.Start()573 vm, err := vmHandler.getRawVm(vmIID)574 if err != nil {575 getErr := errors.New(fmt.Sprintf("Failed to Get VM. err = %s", err.Error()))576 cblogger.Error(getErr.Error())577 LoggingError(hiscallInfo, getErr)578 return irs.VMInfo{}, getErr579 }580 LoggingInfo(hiscallInfo, start)581 vmInfo, err := vmHandler.mappingServerInfo(*vm)582 if err != nil {583 getErr := errors.New(fmt.Sprintf("Failed to Get VM. err = %s", err.Error()))584 cblogger.Error(getErr.Error())585 LoggingError(hiscallInfo, getErr)586 return irs.VMInfo{}, getErr587 }588 return vmInfo, nil589}590func (vmHandler *ClouditVMHandler) vmCleaner(vmIID irs.IID) error {591 vmHandler.Client.TokenID = vmHandler.CredentialInfo.AuthToken592 authHeader := vmHandler.Client.AuthenticatedHeaders()593 requestOpts := client.RequestOpts{594 MoreHeaders: authHeader,595 }596 rawVm, err := vmHandler.getRawVm(vmIID)597 if err != nil {598 cleanErr := errors.New(fmt.Sprintf("Failed to Get. err = %s", err.Error()))599 return cleanErr600 }601 // DisassociatePublicIP602 if rawVm.AdaptiveIp != "" {603 if ok, err := vmHandler.DisassociatePublicIP(rawVm.AdaptiveIp); !ok {604 TerminateErr := errors.New(fmt.Sprintf("Failed DisassociatePublicIP"))605 if err != nil {606 TerminateErr = errors.New(fmt.Sprintf("Failed DisassociatePublicIP err= %s", err.Error()))607 }608 return TerminateErr609 }610 time.Sleep(5 * time.Second)611 }612 // Terminate613 if err := server.Terminate(vmHandler.Client, rawVm.ID, &requestOpts); err != nil {614 if err.Error() != "EOF" {615 cleanErr := errors.New(fmt.Sprintf("Failed to Terminate VM err = %s", err.Error()))616 return cleanErr617 }618 }619 curRetryCnt := 0620 maxRetryCnt := 120621 // Terminate Check622 for {623 checkVMList, err := server.List(vmHandler.Client, &requestOpts)624 if err == nil {625 terminateChk := true626 for _, checkVm := range *checkVMList {627 if checkVm.ID == rawVm.ID {628 terminateChk = false629 }630 }631 if terminateChk {632 return nil633 }634 }635 time.Sleep(1 * time.Second)636 curRetryCnt++637 if curRetryCnt > maxRetryCnt {638 cleanErr := errors.New(fmt.Sprintf("Success to Terminate. but Failed to confirm Terminate VM err = exceeded maximum retry count %d", maxRetryCnt))639 return cleanErr640 }641 }642}643func (vmHandler *ClouditVMHandler) creatablePublicIP() (adaptiveip.IPInfo, error) {644 vmHandler.Client.TokenID = vmHandler.CredentialInfo.AuthToken645 authHeader := vmHandler.Client.AuthenticatedHeaders()646 requestOpts := client.RequestOpts{647 MoreHeaders: authHeader,648 }649 if availableIPList, err := adaptiveip.ListAvailableIP(vmHandler.Client, &requestOpts); err != nil {650 return adaptiveip.IPInfo{}, err651 } else {652 if len(*availableIPList) == 0 {653 return adaptiveip.IPInfo{}, errors.New(fmt.Sprintf("There is no PublicIPs to allocate"))654 } else {655 return (*availableIPList)[0], nil656 }657 }658}659// VMì PublicIP ì°ê²°660func (vmHandler *ClouditVMHandler) AssociatePublicIP(vmName string, vmIp string) (bool, error) {661 // 1. ì¬ì© ê°ë¥í PublicIP ê°ì ¸ì¤ê¸°662 availableIP, err := vmHandler.creatablePublicIP()663 if err != nil {664 allocateErr := errors.New(fmt.Sprintf("There is no PublicIPs to allocate"))665 return false, allocateErr666 }667 // 2. PublicIP ìì± ë° í ë¹668 reqInfo := adaptiveip.PublicIPReqInfo{669 IP: availableIP.IP,670 Name: vmName,671 PrivateIP: vmIp,672 }673 vmHandler.Client.TokenID = vmHandler.CredentialInfo.AuthToken674 authHeader := vmHandler.Client.AuthenticatedHeaders()675 createOpts := client.RequestOpts{676 JSONBody: reqInfo,677 MoreHeaders: authHeader,678 }679 _, err = adaptiveip.Create(vmHandler.Client, &createOpts)680 if err != nil {681 return false, err682 }683 return true, nil684}685// VMì PublicIP í´ì 686func (vmHandler *ClouditVMHandler) DisassociatePublicIP(publicIP string) (bool, error) {687 vmHandler.Client.TokenID = vmHandler.CredentialInfo.AuthToken688 authHeader := vmHandler.Client.AuthenticatedHeaders()689 requestOpts := client.RequestOpts{690 MoreHeaders: authHeader,691 }692 if err := adaptiveip.Delete(vmHandler.Client, publicIP, &requestOpts); err != nil {693 cblogger.Error(err)694 return false, err695 } else {696 return true, nil697 }698}699func (vmHandler *ClouditVMHandler) mappingServerInfo(server server.ServerInfo) (irs.VMInfo, error) {700 // Get Default VM Info701 vmInfo := irs.VMInfo{702 IId: irs.IID{703 NameId: server.Name,704 SystemId: server.ID,705 },706 Region: irs.RegionInfo{707 Region: server.TenantID,708 Zone: server.TenantID,709 },710 ImageIId: irs.IID{711 NameId: server.Template,712 SystemId: server.TemplateID,713 },714 VMSpecName: server.Spec,715 KeyPairIId: irs.IID{716 NameId: strings.Replace(server.Description, "keypair:", "", 1),717 SystemId: strings.Replace(server.Description, "keypair:", "", 1),718 },719 VMUserId: SSHDefaultUser,720 PublicIP: server.AdaptiveIp,721 PrivateIP: server.PrivateIp,722 SSHAccessPoint: fmt.Sprintf("%s:%d", server.AdaptiveIp, SSHDefaultPort),723 RootDiskSize: strconv.Itoa(server.VolumeSize),724 RootDeviceName: "Not visible in Cloudit",725 VMBlockDisk: "Not visible in Cloudit",726 }727 if server.CreatedAt != "" {728 timeArr := strings.Split(server.CreatedAt, " ")729 timeFormatStr := fmt.Sprintf("%sT%sZ", timeArr[0], timeArr[1])730 if createTime, err := time.Parse(time.RFC3339, timeFormatStr); err == nil {731 vmInfo.StartTime = createTime732 }733 }734 // Get Subnet Info735 VPCHandler := ClouditVPCHandler{736 Client: vmHandler.Client,737 CredentialInfo: vmHandler.CredentialInfo,738 }739 defaultVPC, err := VPCHandler.GetDefaultVPC()740 if err == nil {741 vmInfo.VpcIID = defaultVPC.IId742 }743 subnet, err := VPCHandler.GetSubnet(irs.IID{NameId: server.SubnetAddr})744 if err != nil {745 return irs.VMInfo{}, errors.New(fmt.Sprintf("Failed Get Subnet err= %s", err.Error()))746 }747 vmInfo.SubnetIID = irs.IID{748 NameId: subnet.Name,749 SystemId: subnet.ID,750 }751 // Get SecurityGroup Info752 vmHandler.Client.TokenID = vmHandler.CredentialInfo.AuthToken753 authHeader := vmHandler.Client.AuthenticatedHeaders()754 vnicList, err := ListVNic(authHeader, vmHandler.Client, server.ID)755 if err != nil {756 return irs.VMInfo{}, errors.New(fmt.Sprintf("Failed Get VNic err= %s", err.Error()))757 }758 if vnicList != nil {759 defaultVnic := (*vnicList)[0]760 segGroupList := make([]irs.IID, len(defaultVnic.SecGroups))761 for i, s := range defaultVnic.SecGroups {762 segGroupList[i] = irs.IID{763 NameId: s.Name,764 SystemId: s.Id,765 }766 }767 vmInfo.SecurityGroupIIds = segGroupList768 }769 return vmInfo, nil770}771func (vmHandler *ClouditVMHandler) getExistVmName(name string) (bool, error) {772 if name == "" {773 return true, errors.New("invalid vmName")774 }775 vmHandler.Client.TokenID = vmHandler.CredentialInfo.AuthToken776 authHeader := vmHandler.Client.AuthenticatedHeaders()777 requestOpts := client.RequestOpts{778 MoreHeaders: authHeader,779 }780 vmList, err := server.List(vmHandler.Client, &requestOpts)781 if err != nil {782 return true, err783 }784 for _, rawvm := range *vmList {785 if strings.EqualFold(name, rawvm.Name) {786 return true, nil787 }788 }789 return false, nil790}791func (vmHandler *ClouditVMHandler) getRawVm(vmIID irs.IID) (*server.ServerInfo, error) {792 if vmIID.SystemId == "" && vmIID.NameId == "" {793 return nil, errors.New("invalid IID")794 }795 vmHandler.Client.TokenID = vmHandler.CredentialInfo.AuthToken796 authHeader := vmHandler.Client.AuthenticatedHeaders()797 requestOpts := client.RequestOpts{798 MoreHeaders: authHeader,799 }800 if vmIID.SystemId == "" {801 vmList, err := server.List(vmHandler.Client, &requestOpts)802 if err != nil {803 return nil, err804 }805 for _, rawvm := range *vmList {806 if strings.EqualFold(vmIID.NameId, rawvm.Name) {807 return &rawvm, nil808 }809 }810 } else {811 return server.Get(vmHandler.Client, vmIID.SystemId, &requestOpts)812 }813 return nil, errors.New("not found vm")814}815func getVmStatus(vmStatus string) irs.VMStatus {816 var resultStatus string817 switch strings.ToLower(vmStatus) {818 case "creating":819 resultStatus = "Creating"820 case "running":821 resultStatus = "Running"822 case "stopping":823 resultStatus = "Suspending"824 case "stopped":825 resultStatus = "Suspended"826 case "starting":827 resultStatus = "Resuming"828 case "rebooting":829 resultStatus = "Rebooting"830 case "terminating":831 resultStatus = "Terminating"832 case "terminated":833 resultStatus = "Terminated"834 case "failed":835 default:836 resultStatus = "Failed"837 }838 return irs.VMStatus(resultStatus)839}840func (vmHandler *ClouditVMHandler) attachSgToVnic(authHeader map[string]string, vmID string, reqClient *client.RestClient, vnicMac string, sgGroup []server.SecGroupInfo) {841 reqInfo := server.VMReqInfo{842 Secgroups: sgGroup,843 }844 requestOpts := client.RequestOpts{845 MoreHeaders: authHeader,846 JSONBody: reqInfo,847 }848 nic.Put(reqClient, vmID, &requestOpts, vnicMac)849}850func notSupportRootDiskCustom(vmReqInfo irs.VMReqInfo) error {851 if vmReqInfo.RootDiskType != "" && strings.ToLower(vmReqInfo.RootDiskType) != "default" {852 return errors.New("CLOUDIT_CANNOT_CHANGE_ROOTDISKTYPE")853 }854 if vmReqInfo.RootDiskSize != "" && strings.ToLower(vmReqInfo.RootDiskSize) != "default" {855 return errors.New("CLOUDIT_CANNOT_CHANGE_ROOTDISKSIZE")856 }857 return nil858}...
Info
Using AI Code Generation
1import (2func main() {3 ctx, cancel := context.WithCancel(context.Background())4 defer cancel()5 u, err := url.Parse(os.Args[1])6 if err != nil {7 log.Fatal(err)8 }9 u.User = url.UserPassword(os.Args[2], os.Args[3])10 c, err := govmomi.NewClient(ctx, u, true)11 if err != nil {12 log.Fatal(err)13 }14 f := find.NewFinder(c.Client, true)15 vms, err := f.VirtualMachineList(ctx, "*")16 if err != nil {17 log.Fatal(err)18 }19 m := view.NewManager(c.Client)20 v, err := m.CreateContainerView(ctx, c.ServiceContent.RootFolder, []string{"VirtualMachine"}, true)21 if err != nil {22 log.Fatal(err)23 }24 defer v.Destroy(ctx)25 err = v.Retrieve(ctx, []string{"VirtualMachine"}, []string{"summary"}, &vmt)26 if err != nil {27 log.Fatal(err)28 }29 for _, vm := range vmt {30 fmt.Printf("%s: %s\n", vm.Summary.Config.Name, vm.Summary.Guest.IpAddress)31 }
Info
Using AI Code Generation
1import (2func main() {3 u.User = url.UserPassword("user", "password")4 c, _ := govmomi.NewClient(context.Background(), u, true)5 m := view.NewManager(c.Client)6 v, _ := m.CreateContainerView(context.Background(), c.ServiceContent.RootFolder, []string{"VirtualMachine"}, true)7 v.Retrieve(context.Background(), []string{"VirtualMachine"}, []string{"summary"}, &vms)8 for _, vm := range vms {9 fmt.Println(vm.Summary.Config.Name)10 }11}
Info
Using AI Code Generation
1import (2func main() {3 fmt.Println("Hello World!")4}5import (6func main() {7 fmt.Println("Hello World!")8 vm.Info()9}10import (11func main() {12 fmt.Println("Hello World!")13 vm.Info()14}15import (16func main() {17 fmt.Println("Hello World!")18 vm.Info()19}20import (21func main() {22 fmt.Println("Hello World!")23 vm.Info()24}25import (26func main() {27 fmt.Println("Hello World!")28 vm.Info()29}30import (31func main() {32 fmt.Println("Hello World!")33 vm.Info()34}35import (36func main() {37 fmt.Println("Hello World!")38 vm.Info()39}40import (41func main() {42 fmt.Println("Hello World!")43 vm.Info()44}45import (46func main() {47 fmt.Println("Hello World!")48 vm.Info()49}50import (51func main() {52 fmt.Println("Hello World!")53 vm.Info()54}55import (56func main() {57 fmt.Println("Hello
Info
Using AI Code Generation
1import "fmt"2func main() {3 fmt.Println("Hello, playground")4 vm := new(VM)5 vm.Info()6}7import "fmt"8func main() {9 fmt.Println("Hello, playground")10 vm := new(VM)11 vm.Info()12}13import "fmt"14func main() {15 fmt.Println("Hello, playground")16 vm := new(VM)17 vm.Info()18}19import "fmt"20func main() {21 fmt.Println("Hello, playground")22 vm := new(VM)23 vm.Info()24}25import "fmt"26func main() {27 fmt.Println("Hello, playground")28 vm := new(VM)29 vm.Info()30}31import "fmt"32func main() {33 fmt.Println("Hello, playground")34 vm := new(VM)35 vm.Info()36}37import "fmt"38func main() {39 fmt.Println("Hello, playground")40 vm := new(VM)41 vm.Info()42}43import "fmt"44func main() {45 fmt.Println("Hello, playground")46 vm := new(VM)47 vm.Info()48}49import "fmt"50func main() {51 fmt.Println("Hello, playground")52 vm := new(VM)53 vm.Info()54}55import "fmt"56func main() {57 fmt.Println("Hello, playground")58 vm := new(VM)59 vm.Info()60}61import "fmt"62func main() {63 fmt.Println("Hello, playground
Info
Using AI Code Generation
1import (2func main() {3 v := vm.New("test")4 fmt.Println(v.Info())5}6import (7func main() {8 v := vm.New("test")9 fmt.Println(v.Info())10}11import (12func main() {13 v := vm.New("test")14 fmt.Println(v.Info())15}16import (17func main() {18 v := vm.New("test")19 fmt.Println(v.Info())20}21import (22func main() {23 v := vm.New("test")24 fmt.Println(v.Info())25}26import (27func main() {28 v := vm.New("test")29 fmt.Println(v.Info())30}31import (32func main() {33 v := vm.New("test")34 fmt.Println(v.Info())35}36import (37func main() {38 v := vm.New("test")39 fmt.Println(v.Info())40}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!