def info(ctx, catalog_name, item_name): try: restore_session(ctx) client = ctx.obj['client'] in_use_org_href = ctx.obj['profiles'].get('org_href') org = Org(client, in_use_org_href) if item_name is None: catalog = org.get_catalog(catalog_name) result = to_dict(catalog) # We don't have a way to know in advance if a user has access to a # catalog's ACL or not. So we try to retrieve it always. If the # call fails due to permission issues, we silently eat the # exception and exclude ACL settings from the output of the current # command. Users who have access to ACL of the catalog will remain # unaffected. Also any other errors/exceptions will bubble up as # usual. try: access_control_settings = access_settings_to_dict( org.get_catalog_access_settings(catalog_name)) result.update(access_control_settings) except AccessForbiddenException as e: pass else: catalog_item = org.get_catalog_item(catalog_name, item_name) result = to_dict(catalog_item) vapp = VApp(client, href=catalog_item.Entity.get('href')) vapp.reload() template = vapp_to_dict(vapp.resource) for k, v in template.items(): result['template-%s' % k] = v stdout(result, ctx) except Exception as e: stderr(e, ctx)
def test_0010_vm_setup(self): """Setup the vms required for the other tests in this module. Create a vApp with just one vm as per the configuration stated above. This test passes if the vApp and vm hrefs are not None. """ logger = Environment.get_default_logger() TestPVDC._org_client = Environment.get_client_in_default_org( TestPVDC._test_runner_role) vdc = Environment.get_test_vdc(TestPVDC._org_client) logger.debug('Creating vApp ' + TestPVDC._test_vapp_name + '.') TestPVDC._test_vapp_href = create_customized_vapp_from_template( client=TestPVDC._org_client, vdc=vdc, name=TestPVDC._test_vapp_name, catalog_name=Environment.get_default_catalog_name(), template_name=Environment.get_default_template_name(), memory_size=TestPVDC._test_vapp_first_vm_memory_size, num_cpu=TestPVDC._test_vapp_first_vm_num_cpu, disk_size=TestPVDC._test_vapp_first_vm_first_disk_size, vm_name=TestPVDC._test_vapp_first_vm_name, nw_adapter_type=TestPVDC._test_vapp_first_vm_network_adapter_type) self.assertIsNotNone(TestPVDC._test_vapp_href) vapp = VApp(TestPVDC._org_client, href=TestPVDC._test_vapp_href) vm_resource = vapp.get_vm(TestPVDC._test_vapp_first_vm_name) TestPVDC._test_vapp_first_vm_href = vm_resource.get('href') self.assertIsNotNone(TestPVDC._test_vapp_first_vm_href)
def test_060_attach_disk_to_vm_in_vapp(self): logged_in_org = self.client.get_org() org = Org(self.client, resource=logged_in_org) vdc_resource = org.get_vdc(self.config['vcd']['vdc']) vdc = VDC(self.client, resource=vdc_resource) assert self.config['vcd']['vdc'] == vdc.get_resource().get('name') vapp_resource = vdc.get_vapp(self.config['vcd']['vapp']) assert self.config['vcd']['vapp'] == vapp_resource.get('name') vapp = VApp(self.client, resource=vapp_resource) disk = vdc.get_disk(self.config['vcd']['idisk_name']) result = vapp.attach_disk_to_vm(disk_href=disk.get('href'), vm_name=self.config['vcd']['vm']) task = self.client.get_task_monitor().wait_for_status( task=result, timeout=60, poll_frequency=2, fail_on_statuses=None, expected_target_statuses=[ TaskStatus.SUCCESS, TaskStatus.ABORTED, TaskStatus.ERROR, TaskStatus.CANCELED], callback=None) assert task.get('status') == TaskStatus.SUCCESS.value
def get_test_vapp_with_network(cls, client): """Gets the vapp for testing in current vDC. :param pyvcloud.vcd.client.Client client: client which will be used to create the VDC object. :return: the vdc that is backing the organization in which all tests will run. :rtype: pyvcloud.vcd.vdc.VDC """ if not cls._vapp_href: vdc = Environment.get_test_vdc(client) try: vapp = vdc.get_vapp(VAppConstants.name) cls._vapp_href = vapp.get('href') except EntityNotFoundException: cls._vapp_href = create_vapp_from_template( client, vdc, VAppConstants.name, cls._config['vcd']['default_catalog_name'], cls._config['vcd']['default_template_file_name'], power_on=False, deploy=False) vapp = VApp(client, href=cls._vapp_href) task = vapp.create_vapp_network( VAppConstants.network1_name, VAppConstants.network1_cidr, ip_ranges=VAppConstants.network1_ip_ranges) client.get_task_monitor().wait_for_success(task=task) return VApp(client, href=cls._vapp_href)
def test_1006_snapshot_create(self): logged_in_org = self.client.get_org() org = Org(self.client, resource=logged_in_org) vdc_resource = org.get_vdc(self.config['vcd']['vdc']) vdc = VDC(self.client, resource=vdc_resource) assert self.config['vcd']['vdc'] == vdc.get_resource().get('name') vapp_resource = vdc.get_vapp(self.config['vcd']['vapp']) assert vapp_resource.get('name') == self.config['vcd']['vapp'] vapp = VApp(self.client, resource=vapp_resource) vm_resource = vapp.get_vm(self.config['vcd']['vm']) assert vm_resource.get('name') == self.config['vcd']['vm'] vm = VM(self.client, resource=vm_resource) task = vm.snapshot_create(memory=False, quiesce=False) task = self.client.get_task_monitor().wait_for_status( task=task, timeout=120, poll_frequency=2, fail_on_statuses=None, expected_target_statuses=[ TaskStatus.SUCCESS, TaskStatus.ABORTED, TaskStatus.ERROR, TaskStatus.CANCELED], callback=None) assert task.get('status') == TaskStatus.SUCCESS.value
def test_0002_modify_memory(self): logged_in_org = self.client.get_org() org = Org(self.client, resource=logged_in_org) vdc_resource = org.get_vdc(self.config['vcd']['vdc']) vdc = VDC(self.client, resource=vdc_resource) assert self.config['vcd']['vdc'] == vdc.get_resource().get('name') vapp_resource = vdc.get_vapp(self.config['vcd']['vapp']) vapp = VApp(self.client, resource=vapp_resource) vm_resource = vapp.get_vm(self.config['vcd']['vm']) vm = VM(self.client, resource=vm_resource) task = vm.modify_memory(self.config['vcd']['memory']) task = self.client.get_task_monitor().wait_for_status( task=task, timeout=60, poll_frequency=2, fail_on_statuses=None, expected_target_statuses=[ TaskStatus.SUCCESS, TaskStatus.ABORTED, TaskStatus.ERROR, TaskStatus.CANCELED], callback=None) assert task.get('status') == TaskStatus.SUCCESS.value vm.reload() assert vm.get_memory() == self.config['vcd']['memory']
def test_0002_add_vm(self): logged_in_org = self.client.get_org() org = Org(self.client, resource=logged_in_org) vdc_resource = org.get_vdc(self.config['vcd']['vdc']) vdc = VDC(self.client, href=vdc_resource.get('href')) assert self.config['vcd']['vdc'] == vdc.get_resource().get('name') vapp_resource = vdc.get_vapp(self.config['vcd']['vapp']) assert vapp_resource.get('name') == self.config['vcd']['vapp'] vapp = VApp(self.client, resource=vapp_resource) catalog_item = org.get_catalog_item(self.config['vcd']['catalog'], self.config['vcd']['template']) source_vapp_resource = self.client.get_resource( catalog_item.Entity.get('href')) spec = {'source_vm_name': self.config['vcd']['vm'], 'vapp': source_vapp_resource} spec['target_vm_name'] = self.config['vcd']['hostname'] spec['hostname'] = self.config['vcd']['hostname'] spec['network'] = self.config['vcd']['network'] spec['ip_allocation_mode'] = self.config['vcd']['ip_allocation_mode'] spec['storage_profile'] = vdc.get_storage_profile( self.config['vcd']['storage_profile']) vms = [spec] result = vapp.add_vms(vms) task = self.client.get_task_monitor().wait_for_status( task=result, timeout=60, poll_frequency=2, fail_on_statuses=None, expected_target_statuses=[ TaskStatus.SUCCESS, TaskStatus.ABORTED, TaskStatus.ERROR, TaskStatus.CANCELED], callback=None) assert task.get('status') == TaskStatus.SUCCESS.value
def read(self, request): logging.info("__INIT__read[VappVm]") res = vapp_vm_pb2.ReadVappVmResult() res.present = False org_resource = self.client.get_org() org = Org(self.client, resource=org_resource) try: vdc_resource = org.get_vdc(request.target_vdc) vdc = VDC( self.client, name=request.target_vdc, resource=vdc_resource) vapp_resource = vdc.get_vapp(request.target_vapp) vapp = VApp( self.client, name=request.target_vapp, resource=vapp_resource) read_vapp_vm_resp = vapp.get_vm(request.target_vm_name) vm = VM(client=self.client, href=None, resource=read_vapp_vm_resp) res.present = True except Exception as e: errmsg = '__ERROR_read[VappVm] failed for VappVm {0}. __ErrorMessage__ {1}' logging.warn(errmsg.format(request.target_vm_name, str(e))) return res logging.info("__DONE__read[VappVm]") return res
def create_from_vapp(self, request): logging.info("__INIT__create[VappVm] source_catalog_name[%s]", request.source_vapp) res = vapp_vm_pb2.CreateVappVmResult() res.created = False source_vapp_resource = self.get_vapp_resource( request.target_vdc, vapp_name=request.source_vapp) target_vapp_resource = self.get_vapp_resource( request.target_vdc, vapp_name=request.target_vapp) specs = [{ 'vapp': source_vapp_resource, 'source_vm_name': request.source_vm_name, 'target_vm_name': request.target_vm_name, 'hostname': request.hostname, 'password': request.password, 'password_auto': request.password_auto, 'password_reset': request.password_reset, 'cust_script': request.cust_script, 'network': request.network, # 'storage_profile': request.storage_profile }] try: vapp = VApp(self.client, resource=target_vapp_resource) create_vapp_vm_resp = vapp.add_vms( specs, power_on=request.power_on, all_eulas_accepted=request.all_eulas_accepted) task_monitor = self.client.get_task_monitor() task = task_monitor.wait_for_status( task=create_vapp_vm_resp, timeout=60, poll_frequency=2, fail_on_statuses=None, expected_target_statuses=[ TaskStatus.SUCCESS, TaskStatus.ABORTED, TaskStatus.ERROR, TaskStatus.CANCELED ], callback=None) st = task.get('status') if st != TaskStatus.SUCCESS.value: raise errors.VappVmCreateError( etree.tostring(task, pretty_print=True)) message = 'status : {0} '.format(st) logging.info(message) res.created = True except Exception as e: errmsg = '''__ERROR_create[VappVm] failed for vm {0}. __ErrorMessage__ {1}''' logging.warn(errmsg.format(request.target_vm_name, str(e))) self.context.set_code(grpc.StatusCode.INVALID_ARGUMENT) self.context.set_details(errmsg) return res logging.info("__DONE__create[VappVm]") return res
def delete_vm(client): print("================= Vdc delete request ===================") vdc_name = "pcp_vdc_02" target_vm_name = "pcp_vm" org_resource = client.get_org() org = Org(client, resource=org_resource) print("Org name: ", org.get_name()) print("Vdc name: ", vdc_name) vdc_resource = org.get_vdc(vdc_name) vdc = VDC(client, name=vdc_name, resource=vdc_resource) vapp_resource = vdc.get_vapp(vapp_name) vapp = VApp(client, name=vapp_name, resource=vapp_resource) delete_vapp_vm_resp = vapp.delete_vms(target_vm_name) task = client.get_task_monitor().wait_for_status( task=delete_vapp_vm_resp, timeout=60, poll_frequency=2, fail_on_statuses=None, expected_target_statuses=[ TaskStatus.SUCCESS, TaskStatus.ABORTED, TaskStatus.ERROR, TaskStatus.CANCELED ], callback=None) st = task.get('status') if st == TaskStatus.SUCCESS.value: message = 'delete vdc status : {0} '.format(st) logging.info(message) else: raise errors.VCDVdcDeleteError(etree.tostring(task, pretty_print=True))
def test_1002_deploy_vm(self): logged_in_org = self.client.get_org() org = Org(self.client, resource=logged_in_org) v = org.get_vdc(self.config['vcd']['vdc']) vdc = VDC(self.client, href=v.get('href')) assert self.config['vcd']['vdc'] == vdc.get_resource().get('name') vapp_resource = vdc.get_vapp(self.config['vcd']['vapp']) assert vapp_resource.get('name') == self.config['vcd']['vapp'] vapp = VApp(self.client, resource=vapp_resource) vm_resource = vapp.get_vm(self.config['vcd']['vm']) vm = VM(self.client, resource=vm_resource) result = vm.deploy() # result = vm.shutdown() task = self.client.get_task_monitor().wait_for_status( task=result, timeout=60, poll_frequency=2, fail_on_statuses=None, expected_target_statuses=[ TaskStatus.SUCCESS, TaskStatus.ABORTED, TaskStatus.ERROR, TaskStatus.CANCELED], callback=None) assert task.get('status') == TaskStatus.SUCCESS.value
def test_1003_get_vapp_access(self): logged_in_org = self.client.get_org() org = Org(self.client, resource=logged_in_org) vdc_resource = org.get_vdc(self.config['vcd']['vdc']) vdc = VDC(self.client, resource=vdc_resource) vapp_resource = vdc.get_vapp(self.config['vcd']['vapp']) vapp = VApp(self.client, resource=vapp_resource) control_access = vapp.get_access_settings() assert len(control_access.AccessSettings.AccessSetting) == 2
def test_1001_remove_all_vapp_access(self): logged_in_org = self.client.get_org() org = Org(self.client, resource=logged_in_org) vdc_resource = org.get_vdc(self.config['vcd']['vdc']) vdc = VDC(self.client, resource=vdc_resource) vapp_resource = vdc.get_vapp(self.config['vcd']['vapp']) vapp = VApp(self.client, resource=vapp_resource) control_access = vapp.remove_access_settings(remove_all=True) self.assertFalse(hasattr(control_access, 'AccessSettings'))
def test_1006_unshare_vapp_access(self): logged_in_org = self.client.get_org() org = Org(self.client, resource=logged_in_org) vdc_resource = org.get_vdc(self.config['vcd']['vdc']) vdc = VDC(self.client, resource=vdc_resource) vapp_resource = vdc.get_vapp(self.config['vcd']['vapp']) vapp = VApp(self.client, resource=vapp_resource) control_access = vapp.unshare_from_org_members() assert control_access.IsSharedToEveryone.text == 'false'
def list_networks(self): vapp_name = self.params.get('vapp_name') vapp_resource = self.vdc.get_vapp(vapp_name) vapp = VApp(self.client, name=vapp_name, resource=vapp_resource) response = dict() response['msg'] = [] for network in vapp.get_all_networks(): response['msg'].append(network.get('{'+NSMAP['ovf']+'}name')) return response
def delete(self, request): logging.info("__INIT__delete[VappVm]") res = vapp_vm_pb2.DeleteVappVmResult() res.deleted = False org_resource = self.client.get_org() org = Org(self.client, resource=org_resource) try: vdc_resource = org.get_vdc(request.target_vdc) vdc = VDC( self.client, name=request.target_vdc, resource=vdc_resource) vapp_resource = vdc.get_vapp(request.target_vapp) vapp = VApp( self.client, name=request.target_vapp, resource=vapp_resource) # Before deleting power_off vm # self.power_off(request.target_vdc, request.target_vapp) # Before deleting undeploy vm self.undeploy(request) vms = [request.target_vm_name] delete_vapp_vm_resp = vapp.delete_vms(vms) task = self.client.get_task_monitor().wait_for_status( task=delete_vapp_vm_resp, timeout=60, poll_frequency=2, fail_on_statuses=None, expected_target_statuses=[ TaskStatus.SUCCESS, TaskStatus.ABORTED, TaskStatus.ERROR, TaskStatus.CANCELED ], callback=None) st = task.get('status') if st != TaskStatus.SUCCESS.value: raise errors.VappVmDeleteError( etree.tostring(task, pretty_print=True)) message = 'delete vapp_vm status : {0} '.format(st) logging.info(message) res.deleted = True except Exception as e: res.deleted = False errmsg = '__ERROR_delete[VappVm] failed for VappVm {0}. __ErrorMessage__ {1}' logging.warn(errmsg.format(request.target_vm_name, str(e))) self.context.set_code(grpc.StatusCode.INVALID_ARGUMENT) self.context.set_details(errmsg) return res logging.info("__DONE__delete[VappVm]") return res
def test_1005_share_vapp_access(self): logged_in_org = self.client.get_org() org = Org(self.client, resource=logged_in_org) vdc_resource = org.get_vdc(self.config['vcd']['vdc']) vdc = VDC(self.client, resource=vdc_resource) vapp_resource = vdc.get_vapp(self.config['vcd']['vapp']) vapp = VApp(self.client, resource=vapp_resource) control_access = vapp.share_with_org_members( everyone_access_level='ReadOnly') assert control_access.IsSharedToEveryone.text == 'true' assert control_access.EveryoneAccessLevel.text == 'ReadOnly'
def test_0007_delete(self): logged_in_org = self.client.get_org() org = Org(self.client, resource=logged_in_org) vdc_resource = org.get_vdc(self.config['vcd']['vdc']) vdc = VDC(self.client, resource=vdc_resource) assert self.config['vcd']['vdc'] == vdc.get_resource().get('name') vapp_resource = vdc.get_vapp(self.config['vcd']['vapp']) vapp = VApp(self.client, resource=vapp_resource) task = vapp.delete_vms([self.config['vcd']['vm']]) task = self.client.get_task_monitor().wait_for_status(task) assert task.get('status') == TaskStatus.SUCCESS.value
def disconnect(ctx, name, network): try: restore_session(ctx, vdc_required=True) client = ctx.obj['client'] vdc_href = ctx.obj['profiles'].get('vdc_href') vdc = VDC(client, href=vdc_href) vapp_resource = vdc.get_vapp(name) vapp = VApp(client, resource=vapp_resource) task = vapp.disconnect_org_vdc_network(network) stdout(task, ctx) except Exception as e: stderr(e, ctx)
def test_1004_remove_vapp_access(self): logged_in_org = self.client.get_org() org = Org(self.client, resource=logged_in_org) vdc_resource = org.get_vdc(self.config['vcd']['vdc']) vdc = VDC(self.client, resource=vdc_resource) vapp_resource = vdc.get_vapp(self.config['vcd']['vapp']) vapp = VApp(self.client, resource=vapp_resource) control_access = vapp.remove_access_settings( access_settings_list=[ {'name': self.config['vcd']['access_user'], 'type': 'user'} ]) assert len(control_access.AccessSettings.AccessSetting) == 1
def add_disk(ctx, name, vm_name, size, storage_profile): try: restore_session(ctx, vdc_required=True) client = ctx.obj['client'] vdc_href = ctx.obj['profiles'].get('vdc_href') vdc = VDC(client, href=vdc_href) vapp_resource = vdc.get_vapp(name) vapp = VApp(client, resource=vapp_resource) task = vapp.add_disk_to_vm(vm_name, size) stdout(task, ctx) except Exception as e: stderr(e, ctx)
def modify_cpu(self, request): logging.info("__INIT__modify_cpu[VappVm]") res = vapp_vm_pb2.ModifyVappVmCPUResult() res.modified = False org_resource = self.client.get_org() org = Org(self.client, resource=org_resource) try: vdc_resource = org.get_vdc(request.target_vdc) vdc = VDC( self.client, name=request.target_vdc, resource=vdc_resource) vapp_resource = vdc.get_vapp(request.target_vapp) vapp = VApp( self.client, name=request.target_vapp, resource=vapp_resource) vapp_vm_resource = vapp.get_vm(request.target_vm_name) vm = VM(self.client, resource=vapp_vm_resource) self.undeploy(request) modify_cpu_response = vm.modify_cpu(request.virtual_cpus, request.cores_per_socket) task = self.client.get_task_monitor().wait_for_status( task=modify_cpu_response, timeout=60, poll_frequency=2, fail_on_statuses=None, expected_target_statuses=[ TaskStatus.SUCCESS, TaskStatus.ABORTED, TaskStatus.ERROR, TaskStatus.CANCELED ], callback=None) st = task.get('status') if st != TaskStatus.SUCCESS.value: raise errors.VappVmModifyCPUError( etree.tostring(task, pretty_print=True)) message = 'status : {0} '.format(st) logging.info(message) self.power_on(request) res.modified = True except Exception as e: errmsg = '__ERROR_modify_cpu[VappVm] failed for VappVm {0}. __ErrorMessage__ {1}' logging.warn(errmsg.format(request.target_vm_name, str(e))) self.context.set_code(grpc.StatusCode.INVALID_ARGUMENT) self.context.set_details(errmsg) logging.info("__DONE__modify_cpu[VappVm]") return res
def add(ctx, vapp_name, access_list): try: restore_session(ctx, vdc_required=True) client = ctx.obj['client'] vdc_href = ctx.obj['profiles'].get('vdc_href') vdc = VDC(client, href=vdc_href) vapp = VApp(client, resource=vdc.get_vapp(vapp_name)) vapp.add_access_settings( access_settings_list=acl_str_to_list_of_dict(access_list)) stdout('Access settings added to vapp \'%s\'.' % vapp_name, ctx) except Exception as e: stderr(e, ctx)
def test_0020_get_vm(self): """Test the method VApp.get_vm(). This test passes if the retrieved vm's name and href matches with the expected values. """ vapp = VApp(TestVM._client, href=TestVM._test_vapp_href) vm_resource = vapp.get_vm(TestVM._test_vapp_first_vm_name) self.assertEqual(TestVM._test_vapp_first_vm_name, vm_resource.get('name')) self.assertEqual(TestVM._test_vapp_first_vm_href, vm_resource.get('href'))
def test_0030_get_non_existent_vm(self): """Test the method VApp.get_vm(). This test passes if the non-existent vm can't be successfully retrieved by name. """ vapp = VApp(TestVM._client, href=TestVM._test_vapp_href) try: vapp.get_vm(TestVM._non_existent_vm_name) self.fail('Should not be able to fetch vm ' + TestVM._non_existent_vm_name) except EntityNotFoundException: return
def test_11_change_owner(self): logged_in_org = self.client.get_org() org = Org(self.client, resource=logged_in_org) vdc_resource = org.get_vdc(self.config['vcd']['vdc']) user_resource = org.get_user(self.config['vcd']['new_vapp_user']) vdc = VDC(self.client, href=vdc_resource.get('href')) vapp_resource = vdc.get_vapp(self.config['vcd']['vapp']) vapp = VApp(self.client, resource=vapp_resource) vapp.change_owner(user_resource.get('href')) vapp_resource = vdc.get_vapp(self.config['vcd']['vapp']) assert self.config['vcd']['new_vapp_user'] == \ vapp_resource.Owner.User.get('name')
def update(client, context, vappInfo): logging.info("__INIT__update[Vapp]") cresult = vapp_pb2.UpdateVAppResult() cresult.updated = False print("Vapp[ {0} ], Vdc[ {1} ]".format(vappInfo.name, vappInfo.vdc)) org_resource = client.get_org() org = Org(client, resource=org_resource) try: vdc_resource = org.get_vdc(vappInfo.vdc) vdc = VDC(client, name=vappInfo.vdc, resource=vdc_resource) vapp_resource = vdc.get_vapp(vappInfo.name) vapp = VApp(client, name=vappInfo.name, resource=vapp_resource) resp = None if (vappInfo.power_on == True): logging.info("Powering on [Vapp %v]".format(vappInfo.name)) resp = vapp.power_on() else: logging.info("Powering off [Vapp %v]".format(vappInfo.name)) resp = vapp.undeploy() task = client.get_task_monitor().wait_for_status( task=resp, timeout=60, poll_frequency=2, fail_on_statuses=None, expected_target_statuses=[ TaskStatus.SUCCESS, TaskStatus.ABORTED, TaskStatus.ERROR, TaskStatus.CANCELED ], callback=None) st = task.get('status') if st == TaskStatus.SUCCESS.value: message = 'status : {0} '.format(st) logging.info(message) cresult.updated = True else: raise errors.VappUpdateError( etree.tostring(task, pretty_print=True)) except Exception as e: error_message = '__ERROR_updating [Vapp] power_on={0} for Vapp {1} . __ErrorMessage__ {2}'.format( vappInfo.power_on, vappInfo.name, str(e)) logging.warn(error_message) cresult.updated = False context.set_code(grpc.StatusCode.INVALID_ARGUMENT) context.set_details(error_message) logging.info("__DONE__update[Vapp]") return cresult
def unshare(ctx, vapp_name): try: restore_session(ctx, vdc_required=True) client = ctx.obj['client'] vdc_href = ctx.obj['profiles'].get('vdc_href') vdc = VDC(client, href=vdc_href) vapp = VApp(client, resource=vdc.get_vapp(vapp_name)) vapp.unshare_from_org_members() stdout( 'Vapp \'%s\' unshared from all members of the org \'%s\'.' % (vapp_name, ctx.obj['profiles'].get('org_in_use')), ctx) except Exception as e: stderr(e, ctx)
def list_acl(ctx, vapp_name): try: restore_session(ctx, vdc_required=True) client = ctx.obj['client'] vdc_href = ctx.obj['profiles'].get('vdc_href') vdc = VDC(client, href=vdc_href) vapp = VApp(client, resource=vdc.get_vapp(vapp_name)) acl = vapp.get_access_settings() stdout( access_settings_to_list( acl, ctx.obj['profiles'].get('org_in_use')), ctx) except Exception as e: stderr(e, ctx)
def update_lease(ctx, name, runtime_seconds, storage_seconds): try: restore_session(ctx, vdc_required=True) client = ctx.obj['client'] vdc_href = ctx.obj['profiles'].get('vdc_href') vdc = VDC(client, href=vdc_href) vapp_resource = vdc.get_vapp(name) vapp = VApp(client, resource=vapp_resource) if storage_seconds is None: storage_seconds = runtime_seconds task = vapp.set_lease(runtime_seconds, storage_seconds) stdout(task, ctx) except Exception as e: stderr(e, ctx)
def update(ctx, vapp_name, vm_name, cpu, cores, memory): try: restore_session(ctx, vdc_required=True) client = ctx.obj['client'] vdc_href = ctx.obj['profiles'].get('vdc_href') vdc = VDC(client, href=vdc_href) vapp_resource = vdc.get_vapp(vapp_name) vapp = VApp(client, resource=vapp_resource) vm_resource = vapp.get_vm(vm_name) vm = VM(client, resource=vm_resource) if cpu is not None: task_cpu_update = vm.modify_cpu(cpu, cores) stdout("Updating cpu (and core(s) if specified) for the VM") stdout(task_cpu_update, ctx) if memory is not None: task_memory_update = vm.modify_memory(memory) stdout("Updating memory for the VM") stdout(task_memory_update, ctx) except Exception as e: stderr(e, ctx)
def capture_as_template(ctx, config, vapp_resource, org, catalog, template): vapp_name = vapp_resource.get('name') click.secho('Found vApp \'%s\', capturing as template on catalog \'%s\'' % (vapp_name, catalog.get('name')), fg='green') client = ctx.obj['client'] vapp = VApp(client, href=vapp_resource.get('href')) vapp.reload() if vapp.resource.get('status') == '4': task = vapp.shutdown() stdout(task, ctx) time.sleep(4) task = org.capture_vapp(catalog, vapp_resource.get('href'), template['catalog_item'], 'CSE Kubernetes template', customize_on_instantiate=True, overwrite=True) stdout(task, ctx) return True
def shutdown(self): vapp_name = self.params.get('vapp_name') response = dict() response['changed'] = False vapp = self.get_vapp() try: if not vapp.is_powered_off(): vapp_resource = self.vdc.get_vapp(vapp_name) vapp = VApp(self.client, name=vapp_name, resource=vapp_resource) shutdown_vapp_task = vapp.shutdown() self.execute_task(shutdown_vapp_task) response['msg'] = 'Vapp {} has been shutted down.'.format(vapp_name) response['changed'] = True else: response['warnings'] = 'Vapp {} is already powered off.'.format(vapp_name) except OperationNotSupportedException: response['warnings'] = 'Operation is not supported. You may have no VM(s) in {}'.format(vapp_name) return response
def undeploy(self): vapp_name = self.params.get('vapp_name') response = dict() response['changed'] = False vapp = self.get_vapp() if not vapp.is_deployed(): msg = 'Vapp {} is already undeployed' response['warnings'] = msg.format(vapp_name) return response vapp_resource = self.vdc.get_vapp(vapp_name) vapp = VApp(self.client, name=vapp_name, resource=vapp_resource) undeploy_vapp_task = vapp.undeploy(action="powerOff") self.execute_task(undeploy_vapp_task) response['msg'] = 'Vapp {} has been undeployed.'.format(vapp_name) response['changed'] = True return response
def get_default_vapp(cls, client): """Gets the default vApp that will be used for testing. :param pyvcloud.vcd.client.Client client: client which will be used to create the VApp object. :return: the vApp that will be used in tests. :rtype: pyvcloud.vcd.vapp.VApp """ return VApp(client, href=cls._vapp_href)
def get_cluster_config(self, cluster_name): self._connect_tenant() clusters = load_from_metadata(self.tenant_client, name=cluster_name) if len(clusters) != 1: raise CseServerError(f"Cluster '{cluster_name}' not found") vapp = VApp(self.tenant_client, href=clusters[0]['vapp_href']) template = self.get_template(name=clusters[0]['template']) server_config = get_server_runtime_config() result = get_cluster_config(server_config, vapp, template['admin_password']) return result
def info(ctx, catalog_name, item_name): try: client = ctx.obj['client'] org_name = ctx.obj['profiles'].get('org') in_use_org_href = ctx.obj['profiles'].get('org_href') org = Org(client, in_use_org_href, org_name == 'System') if item_name is None: catalog = org.get_catalog(catalog_name) result = to_dict(catalog) else: catalog_item = org.get_catalog_item(catalog_name, item_name) result = to_dict(catalog_item) vapp = VApp(client, href=catalog_item.Entity.get('href')) vapp.reload() template = vapp_to_dict(vapp.resource) for k, v in template.items(): result['template-%s' % k] = v stdout(result, ctx) except Exception as e: stderr(e, ctx)
def get_cluster_info(self, cluster_name): """Get the info of the cluster. :param cluster_name: (str): Name of the cluster :return: (dict): Info of the cluster. """ self._connect_tenant() clusters = load_from_metadata( self.tenant_client, name=cluster_name, org_name=self.req_spec.get(RequestKey.ORG_NAME), vdc_name=self.req_spec.get(RequestKey.OVDC_NAME)) if len(clusters) > 1: raise CseDuplicateClusterError(f"Multiple clusters of name" f" '{cluster_name}' detected.") if len(clusters) == 0: raise ClusterNotFoundError(f"Cluster '{cluster_name}' not found.") cluster = clusters[0] cluster[K8S_PROVIDER_KEY] = K8sProviders.NATIVE vapp = VApp(self.tenant_client, href=clusters[0]['vapp_href']) vms = vapp.get_all_vms() for vm in vms: node_info = { 'name': vm.get('name'), 'ipAddress': '' } try: node_info['ipAddress'] = vapp.get_primary_ip( vm.get('name')) except Exception: LOGGER.debug(f"Unable to get ip address of node " f"{vm.get('name')}") if vm.get('name').startswith(NodeType.MASTER): cluster.get('master_nodes').append(node_info) elif vm.get('name').startswith(NodeType.WORKER): cluster.get('nodes').append(node_info) elif vm.get('name').startswith(NodeType.NFS): cluster.get('nfs_nodes').append(node_info) return cluster
def delete_nodes_thread(self): LOGGER.debug('about to delete nodes from cluster with name: %s', self.cluster_name) try: vapp = VApp(self.client_tenant, href=self.cluster['vapp_href']) template = self.get_template() self.update_task( TaskStatus.RUNNING, message='Deleting %s node(s) from %s(%s)' % (len(self.body['nodes']), self.cluster_name, self.cluster_id)) try: delete_nodes_from_cluster(self.config, vapp, template, self.body['nodes'], self.body['force']) except Exception: LOGGER.error("Couldn't delete node %s from cluster:%s" % (self.body['nodes'], self.cluster_name)) self.update_task( TaskStatus.RUNNING, message='Undeploying %s node(s) for %s(%s)' % (len(self.body['nodes']), self.cluster_name, self.cluster_id)) for vm_name in self.body['nodes']: vm = VM(self.client_tenant, resource=vapp.get_vm(vm_name)) try: task = vm.undeploy() self.client_tenant.get_task_monitor().wait_for_status(task) except Exception as e: LOGGER.warning('couldn\'t undeploy VM %s' % vm_name) self.update_task( TaskStatus.RUNNING, message='Deleting %s VM(s) for %s(%s)' % (len(self.body['nodes']), self.cluster_name, self.cluster_id)) task = vapp.delete_vms(self.body['nodes']) self.client_tenant.get_task_monitor().wait_for_status(task) self.update_task( TaskStatus.SUCCESS, message='Deleted %s node(s) to cluster %s(%s)' % (len(self.body['nodes']), self.cluster_name, self.cluster_id)) except Exception as e: LOGGER.error(traceback.format_exc()) self.update_task(TaskStatus.ERROR, error_message=str(e))
def get_cluster_config(self, cluster_name, headers): result = {} self._connect_tenant(headers) clusters = load_from_metadata(self.client_tenant, name=cluster_name) if len(clusters) != 1: raise CseServerError('Cluster \'%s\' not found' % cluster_name) vapp = VApp(self.client_tenant, href=clusters[0]['vapp_href']) template = self.get_template(name=clusters[0]['template']) result['body'] = get_cluster_config(self.config, vapp, template['admin_password']) result['status_code'] = OK return result
def test_102_disconnect_orgvdc_network(self): org_in_use = self.config['vcd']['org_in_use'] org = Org(self.client, href=self.client.get_org_by_name(org_in_use).get('href')) v = org.get_vdc(self.config['vcd']['vdc']) vdc = VDC(self.client, href=v.get('href')) vapp_resource = vdc.get_vapp(self.config['vcd']['vapp']) vapp = VApp(self.client, resource=vapp_resource) result = vapp.disconnect_org_vdc_network( self.config['vcd']['orgvdc_network']) task = self.client.get_task_monitor().wait_for_status( task=result, timeout=60, poll_frequency=2, fail_on_statuses=None, expected_target_statuses=[ TaskStatus.SUCCESS, TaskStatus.ABORTED, TaskStatus.ERROR, TaskStatus.CANCELED ], callback=None) assert task.get('status') == TaskStatus.SUCCESS.value
def test_1005_reboot_vapp(self): logged_in_org = self.client.get_org() org = Org(self.client, resource=logged_in_org) v = org.get_vdc(self.config['vcd']['vdc']) vdc = VDC(self.client, href=v.get('href')) assert self.config['vcd']['vdc'] == vdc.get_resource().get('name') vapp_resource = vdc.get_vapp(self.config['vcd']['vapp']) assert vapp_resource.get('name') == self.config['vcd']['vapp'] vapp = VApp(self.client, resource=vapp_resource) result = vapp.reboot() task = self.client.get_task_monitor().wait_for_status( task=result, timeout=60, poll_frequency=2, fail_on_statuses=None, expected_target_statuses=[ TaskStatus.SUCCESS, TaskStatus.ABORTED, TaskStatus.ERROR, TaskStatus.CANCELED ], callback=None) assert task.get('status') == TaskStatus.SUCCESS.value
def deploy(self): vapp_name = self.params.get('vapp_name') response = dict() response['changed'] = False vapp = self.get_vapp() if vapp.is_deployed(): msg = 'Vapp {} is already deployed' response['warnings'] = msg.format(vapp_name) return response vapp_resource = self.vdc.get_vapp(vapp_name) vapp = VApp(self.client, name=vapp_name, resource=vapp_resource) deploy_vapp_task = vapp.deploy() self.execute_task(deploy_vapp_task) msg = 'Vapp {} has been deployed' response['msg'] = msg.format(vapp_name) response['changed'] = True return response
def power_off(client, target_vdc, target_vapp, target_vm_name): logging.info("__INIT__delete[VappVm]") powered_off = False org_resource = client.get_org() org = Org(client, resource=org_resource) try: vdc_resource = org.get_vdc(target_vdc) vdc = VDC(slef.client, name=target_vdc, resource=vdc_resource) vapp_resource = vdc.get_vapp(target_vapp) vapp = VApp(client, name=target_vapp, resource=vapp_resource) vapp_vm_resource = vapp.get_vm(target_vm_name) vm = VM(client, resource=vapp_vm_resource) vm.power_off() powered_off = True except Exception as e: error_message = '__ERROR_power_off[VappVm] failed for VappVm {0}. __ErrorMessage__ {1}'.format( target_vm_name, str(e)) logging.warn(error_message) return powered_off
def create_nodes_thread(self): LOGGER.debug('about to add nodes to cluster with name: %s', self.cluster_name) try: org_resource = self.client_tenant.get_org() org = Org(self.client_tenant, resource=org_resource) vdc = VDC(self.client_tenant, href=self.cluster['vdc_href']) vapp = VApp(self.client_tenant, href=self.cluster['vapp_href']) template = self.get_template() self.update_task( TaskStatus.RUNNING, message='Creating %s node(s) for %s(%s)' % (self.body['node_count'], self.cluster_name, self.cluster_id)) new_nodes = add_nodes(self.body['node_count'], template, TYPE_NODE, self.config, self.client_tenant, org, vdc, vapp, self.body, wait=True) self.update_task( TaskStatus.RUNNING, message='Adding %s node(s) to %s(%s)' % (self.body['node_count'], self.cluster_name, self.cluster_id)) target_nodes = [] for spec in new_nodes['specs']: target_nodes.append(spec['target_vm_name']) vapp.reload() join_cluster(self.config, vapp, template, target_nodes) self.update_task( TaskStatus.SUCCESS, message='Added %s node(s) to cluster %s(%s)' % (self.body['node_count'], self.cluster_name, self.cluster_id)) except Exception as e: LOGGER.error(traceback.format_exc()) self.update_task(TaskStatus.ERROR, error_message=str(e))
def get_vsphere(config, vapp, vm_name): global cache vm_resource = vapp.get_vm(vm_name) vm_id = vm_resource.get('id') if vm_id not in cache: client_sysadmin = Client(uri=config['vcd']['host'], api_version=config['vcd']['api_version'], verify_ssl_certs=config['vcd']['verify'], log_headers=True, log_bodies=True) client_sysadmin.set_credentials( BasicLoginCredentials(config['vcd']['username'], 'System', config['vcd']['password'])) vapp_sys = VApp(client_sysadmin, href=vapp.href) vm_resource = vapp_sys.get_vm(vm_name) vm_sys = VM(client_sysadmin, resource=vm_resource) vcenter_name = vm_sys.get_vc() platform = Platform(client_sysadmin) vcenter = platform.get_vcenter(vcenter_name) vcenter_url = urlparse(vcenter.Url.text) cache_item = { 'hostname': vcenter_url.hostname, 'username': vcenter.Username.text, 'port': vcenter_url.port } for vc in config['vcs']: if vc['name'] == vcenter_name: cache_item['password'] = vc['password'] break cache[vm_id] = cache_item else: LOGGER.debug('vCenter retrieved from cache: %s / %s' % (vm_id, cache[vm_id]['hostname'])) v = VSphere(cache[vm_id]['hostname'], cache[vm_id]['username'], cache[vm_id]['password'], cache[vm_id]['port']) return v
def test_0050_attach_disk_to_vm_in_vapp(self): """Test the method vapp.attach_disk_to_vm(). Invoke the method for the second independent disk, and attach it to the first vm in the vApp created during setup. The vApp must be in deployed state before we try to attach the disk to it. This test passes if the disk attachment task succeeds. """ vdc = Environment.get_test_vdc(TestDisk._client) vapp = VApp(TestDisk._client, href=TestDisk._test_vapp_href) vm_name = TestDisk._test_vapp_first_vm_name disk = vdc.get_disk(disk_id=TestDisk._idisk2_id) # vApp needs to be deployed for attach to succeed. if vapp.is_suspended(): task = vapp.deploy() TestDisk._client.get_task_monitor().wait_for_success(task=task) task = vapp.attach_disk_to_vm(disk_href=disk.get('href'), vm_name=vm_name) TestDisk._client.get_task_monitor().wait_for_success(task=task)
def info(ctx, catalog_name, item_name): try: client = ctx.obj['client'] in_use_org_href = ctx.obj['profiles'].get('org_href') org = Org(client, in_use_org_href) if item_name is None: catalog = org.get_catalog(catalog_name) result = to_dict(catalog) access_control_settings = access_settings_to_dict( org.get_catalog_access_settings(catalog_name)) result.update(access_control_settings) else: catalog_item = org.get_catalog_item(catalog_name, item_name) result = to_dict(catalog_item) vapp = VApp(client, href=catalog_item.Entity.get('href')) vapp.reload() template = vapp_to_dict(vapp.resource) for k, v in template.items(): result['template-%s' % k] = v stdout(result, ctx) except Exception as e: stderr(e, ctx)
def get_cluster_info(self, name, headers, body): """Get the info of the cluster. :param cluster_name: (str): Name of the cluster :param headers: (str): Request headers :return: (dict): Info of the cluster. """ result = {} try: result['body'] = [] result['status_code'] = OK self._connect_tenant(headers) clusters = load_from_metadata(self.client_tenant, name=name) if len(clusters) == 0: raise Exception('Cluster \'%s\' not found.' % name) vapp = VApp(self.client_tenant, href=clusters[0]['vapp_href']) vms = vapp.get_all_vms() for vm in vms: node_info = {'name': vm.get('name'), 'ipAddress': ''} try: node_info['ipAddress'] = vapp.get_primary_ip( vm.get('name')) except Exception: LOGGER.debug('cannot get ip address for node %s' % vm.get('name')) if vm.get('name').startswith(TYPE_MASTER): clusters[0].get('master_nodes').append(node_info) elif vm.get('name').startswith(TYPE_NODE): clusters[0].get('nodes').append(node_info) elif vm.get('name').startswith(TYPE_NFS): clusters[0].get('nfs_nodes').append(node_info) result['body'] = clusters[0] except Exception as e: LOGGER.error(traceback.format_exc()) result['body'] = [] result['status_code'] = INTERNAL_SERVER_ERROR result['message'] = str(e) return result
def list_vms(self): params = self.params catalog_name = params.get('catalog_name') item_name = params.get('item_name') response = dict() result = list() response['changed'] = False catalog_item = self.org.get_catalog_item(catalog_name, item_name) vapp_template_resource = self.client.get_resource( catalog_item.Entity.get('href')) vapp_template = VApp(self.client, name=item_name, resource=vapp_template_resource) for vm in vapp_template.get_all_vms(): result.append(vm.get('name')) response['msg'] = result response['changed'] = False return response
def test_0003_power_on(self): logged_in_org = self.client.get_org() org = Org(self.client, resource=logged_in_org) vdc_resource = org.get_vdc(self.config['vcd']['vdc']) vdc = VDC(self.client, resource=vdc_resource) assert self.config['vcd']['vdc'] == vdc.get_resource().get('name') vapp_resource = vdc.get_vapp(self.config['vcd']['vapp']) vapp = VApp(self.client, resource=vapp_resource) vm_resource = vapp.get_vm(self.config['vcd']['vm']) vm = VM(self.client, resource=vm_resource) task = vm.power_on() task = self.client.get_task_monitor().wait_for_status( task=task, timeout=60, poll_frequency=2, fail_on_statuses=None, expected_target_statuses=[ TaskStatus.SUCCESS, TaskStatus.ABORTED, TaskStatus.ERROR, TaskStatus.CANCELED ], callback=None) assert task.get('status') == TaskStatus.SUCCESS.value
def get_cluster_info(self, data): """Get cluster metadata as well as node data. Common broker function that validates data for the 'cluster info' operation and returns cluster/node metadata as dictionary. Required data: cluster_name Optional data and default values: org_name=None, ovdc_name=None """ required = [RequestKey.CLUSTER_NAME] req_utils.validate_payload(data, required) defaults = {RequestKey.ORG_NAME: None, RequestKey.OVDC_NAME: None} validated_data = {**defaults, **data} cluster_name = validated_data[RequestKey.CLUSTER_NAME] cluster = get_cluster(self.tenant_client, cluster_name, org_name=validated_data[RequestKey.ORG_NAME], ovdc_name=validated_data[RequestKey.OVDC_NAME]) cluster[K8S_PROVIDER_KEY] = K8sProvider.NATIVE vapp = VApp(self.tenant_client, href=cluster['vapp_href']) vms = vapp.get_all_vms() for vm in vms: node_info = {'name': vm.get('name'), 'ipAddress': ''} try: node_info['ipAddress'] = vapp.get_primary_ip(vm.get('name')) except Exception: LOGGER.debug(f"Unable to get ip address of node " f"{vm.get('name')}") if vm.get('name').startswith(NodeType.MASTER): cluster.get('master_nodes').append(node_info) elif vm.get('name').startswith(NodeType.WORKER): cluster.get('nodes').append(node_info) elif vm.get('name').startswith(NodeType.NFS): cluster.get('nfs_nodes').append(node_info) return cluster
def deploy(ctx, name, vm_names, power_on, force_customization): try: client = ctx.obj['client'] vdc_href = ctx.obj['profiles'].get('vdc_href') vdc = VDC(client, href=vdc_href) vapp_resource = vdc.get_vapp(name) vapp = VApp(client, resource=vapp_resource) if power_on is not None: power_on = False if force_customization is not None: force_customization = True if len(vm_names) == 0: task = vapp.deploy(power_on=power_on) stdout(task, ctx) else: for vm_name in vm_names: vm = VM(client, href=vapp.get_vm(vm_name).get('href')) vm.reload() task = vm.deploy(power_on=power_on, force_customization=force_customization) stdout(task, ctx) except Exception as e: stderr(e, ctx)
def get_vapp_in_test_vdc(cls, client, vapp_name): """Gets the vapp identified by it's name in the current VDC. :param client: (pyvcloud.vcd.client.Client): The client which will be used to create the VApp object. :param vapp_name: (str): Name of the vApp which needs to be retrieved. :return: A :class: pyvcloud.vcd.vapp.VApp object representing the requested vApp. """ vdc = cls.get_test_vdc(client) vapp_resource = vdc.get_vapp(vapp_name) return VApp(client, resource=vapp_resource)
def download(ctx, vapp_name, vm_name, vc_host, vc_user, vc_password, guest_user, guest_password, source, output): try: client = ctx.obj['client'] vdc_href = ctx.obj['profiles'].get('vdc_href') vdc = VDC(client, vdc_href=vdc_href) vapp_resource = vdc.get_vapp(vapp_name) va = VApp(client, resource=vapp_resource) vs = VSphere(vc_host, vc_user, vc_password) moid = va.get_vm_moid(vm_name) vs.connect() vm = vs.get_vm_by_moid(moid) result = vs.download_file_from_guest(vm, guest_user, guest_password, source) if result.status_code == 200: if output is None: click.secho(result.content) else: output.write(result.content) else: raise Exception(result.content) except Exception as e: stderr(e, ctx)
def add_vm(ctx, name, source_vapp, source_vm, catalog, target_vm, hostname, network, ip_allocation_mode, storage_profile, password_auto, accept_all_eulas): try: restore_session(ctx, vdc_required=True) client = ctx.obj['client'] in_use_org_href = ctx.obj['profiles'].get('org_href') org = Org(client, in_use_org_href) vdc_href = ctx.obj['profiles'].get('vdc_href') vdc = VDC(client, href=vdc_href) source_vapp_resource = None if catalog is None: source_vapp_resource = vdc.get_vapp(source_vapp) else: catalog_item = org.get_catalog_item(catalog, source_vapp) source_vapp_resource = client.get_resource( catalog_item.Entity.get('href')) assert source_vapp_resource is not None vapp_resource = vdc.get_vapp(name) vapp = VApp(client, resource=vapp_resource) spec = {'source_vm_name': source_vm, 'vapp': source_vapp_resource} if target_vm is not None: spec['target_vm_name'] = target_vm if hostname is not None: spec['hostname'] = hostname if network is not None: spec['network'] = network spec['ip_allocation_mode'] = ip_allocation_mode if storage_profile is not None: spec['storage_profile'] = vdc.get_storage_profile(storage_profile) if password_auto is not None: spec['password_auto'] = password_auto task = vapp.add_vms([spec], all_eulas_accepted=accept_all_eulas) stdout(task, ctx) except Exception as e: stderr(e, ctx)
def get_vapp_in_test_vdc(cls, client, vapp_name): """Gets the vApp identified by it's name in the current org vdc. :param pyvcloud.vcd.client.Client client: client which will be used to create the VApp object. :param str vapp_name: name of the vApp which needs to be retrieved. :return: the requested vApp. :rtype: pyvcloud.vcd.vapp.VApp """ vdc = cls.get_test_vdc(client) vapp_resource = vdc.get_vapp(vapp_name) return VApp(client, resource=vapp_resource)
def test_0002_add_vm(self): logged_in_org = self.client.get_org() org = Org(self.client, resource=logged_in_org) vdc_resource = org.get_vdc(self.config['vcd']['vdc']) vdc = VDC(self.client, href=vdc_resource.get('href')) assert self.config['vcd']['vdc'] == vdc.get_resource().get('name') vapp_resource = vdc.get_vapp(self.config['vcd']['vapp']) assert vapp_resource.get('name') == self.config['vcd']['vapp'] vapp = VApp(self.client, resource=vapp_resource) catalog_item = org.get_catalog_item(self.config['vcd']['catalog'], self.config['vcd']['template']) source_vapp_resource = self.client.get_resource( catalog_item.Entity.get('href')) spec = { 'source_vm_name': self.config['vcd']['vm'], 'vapp': source_vapp_resource } spec['target_vm_name'] = self.config['vcd']['hostname'] spec['hostname'] = self.config['vcd']['hostname'] spec['network'] = self.config['vcd']['network'] spec['ip_allocation_mode'] = self.config['vcd']['ip_allocation_mode'] spec['storage_profile'] = vdc.get_storage_profile( self.config['vcd']['storage_profile']) vms = [spec] result = vapp.add_vms(vms) task = self.client.get_task_monitor().wait_for_status( task=result, timeout=60, poll_frequency=2, fail_on_statuses=None, expected_target_statuses=[ TaskStatus.SUCCESS, TaskStatus.ABORTED, TaskStatus.ERROR, TaskStatus.CANCELED ], callback=None) assert task.get('status') == TaskStatus.SUCCESS.value
def _clone(self, source_vapp_name, target_vapp_name, target_vm_name, source_delete): """Clone VM from one vApp to another. :param: str source vApp name :param: str target vApp name :param: str target VM name :param: bool source delete option :return: an object containing EntityType.TASK XML data which represents the asynchronous task that is copying VM :rtype: lxml.objectify.ObjectifiedElement """ from pyvcloud.vcd.vapp import VApp vm_resource = self.get_resource() resource_type = ResourceType.VAPP.value if self.is_powered_off(vm_resource) or source_delete: records1 = self.___validate_vapp_records( vapp_name=source_vapp_name, resource_type=resource_type) source_vapp_href = records1[0].get('href') records2 = self.___validate_vapp_records( vapp_name=target_vapp_name, resource_type=resource_type) target_vapp_href = records2[0].get('href') source_vapp = VApp(self.client, href=source_vapp_href) target_vapp = VApp(self.client, href=target_vapp_href) target_vapp.reload() spec = { 'vapp': source_vapp.get_resource(), 'source_vm_name': self.get_resource().get('name'), 'target_vm_name': target_vm_name } return target_vapp.add_vms([spec], deploy=False, power_on=False, all_eulas_accepted=True, source_delete=source_delete ) else: raise InvalidStateException("VM Must be powered off.")
def get_cluster_config(self, cluster_name, headers): result = {} try: self._connect_tenant(headers) clusters = load_from_metadata(self.client_tenant, name=cluster_name) if len(clusters) != 1: raise Exception('Cluster \'%s\' not found' % cluster_name) vapp = VApp(self.client_tenant, href=clusters[0]['vapp_href']) template = self.get_template(name=clusters[0]['template']) result['body'] = get_cluster_config(self.config, vapp, template['admin_password']) result['status_code'] = OK except Exception as e: result['body'] = str(e) result['status_code'] = INTERNAL_SERVER_ERROR return result