def node_rollback(self, node_list):
        """Implements rollback for node creation failure

        :param list node_list: faulty nodes to be deleted
        """
        LOGGER.info('About to rollback nodes from cluster with name: %s' %
                    self.cluster_name)
        LOGGER.info('Node list to be deleted:%s' % node_list)
        vapp = VApp(self.client_tenant, href=self.cluster['vapp_href'])
        template = self.get_template()
        try:
            delete_nodes_from_cluster(self.config,
                                      vapp,
                                      template,
                                      node_list,
                                      force=True)
        except Exception:
            LOGGER.warning("Couldn't delete node %s from cluster:%s" %
                           (node_list, self.cluster_name))
        for vm_name in node_list:
            vm = VM(self.client_tenant, resource=vapp.get_vm(vm_name))
            try:
                vm.undeploy()
            except Exception:
                LOGGER.warning("Couldn't undeploy VM %s" % vm_name)
        vapp.delete_vms(node_list)
        LOGGER.info('Successfully deleted nodes: %s' % node_list)
    def node_rollback(self, node_list):
        """Rollback for node creation failure.

        :param list node_list: faulty nodes to be deleted
        """
        LOGGER.info(f"About to rollback nodes from cluster with name: "
                    "{self.cluster_name}")
        LOGGER.info(f"Node list to be deleted:{node_list}")
        vapp = VApp(self.tenant_client, href=self.cluster['vapp_href'])
        template = self._get_template()
        try:
            server_config = get_server_runtime_config()
            delete_nodes_from_cluster(server_config, vapp, template,
                                      node_list, force=True)
        except Exception:
            LOGGER.warning("Couldn't delete node {node_list} from cluster:"
                           "{self.cluster_name}")
        for vm_name in node_list:
            vm = VM(self.tenant_client, resource=vapp.get_vm(vm_name))
            try:
                vm.undeploy()
            except Exception:
                LOGGER.warning(f"Couldn't undeploy VM {vm_name}")
        vapp.delete_vms(node_list)
        LOGGER.info(f"Successfully deleted nodes: {node_list}")
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 delete_nodes_thread(self):
     LOGGER.debug(f"About to delete nodes from cluster with name: "
                  f"{self.cluster_name}")
     try:
         vapp = VApp(self.tenant_client, href=self.cluster['vapp_href'])
         template = self._get_template()
         self._update_task(
             TaskStatus.RUNNING,
             message=f"Deleting "
                     f"{len(self.req_spec.get(RequestKey.NODE_NAMES_LIST))}"
                     f" node(s) from "
                     f"{self.cluster_name}({self.cluster_id})")
         try:
             server_config = get_server_runtime_config()
             delete_nodes_from_cluster(
                 server_config,
                 vapp,
                 template,
                 self.req_spec.get(RequestKey.NODE_NAMES_LIST),
                 self.req_spec.get(RequestKey.FORCE_DELETE))
         except Exception:
             LOGGER.error(f"Couldn't delete node "
                          f"{self.req_spec.get(RequestKey.NODE_NAMES_LIST)}"
                          f" from cluster:{self.cluster_name}")
         self._update_task(
             TaskStatus.RUNNING,
             message=f"Undeploying "
                     f"{len(self.req_spec.get(RequestKey.NODE_NAMES_LIST))}"
                     f" node(s) for {self.cluster_name}({self.cluster_id})")
         for vm_name in self.req_spec.get(RequestKey.NODE_NAMES_LIST):
             vm = VM(self.tenant_client, resource=vapp.get_vm(vm_name))
             try:
                 task = vm.undeploy()
                 self.tenant_client.get_task_monitor().wait_for_status(task)
             except Exception:
                 LOGGER.warning(f"Couldn't undeploy VM {vm_name}")
         self._update_task(
             TaskStatus.RUNNING,
             message=f"Deleting "
                     f"{len(self.req_spec.get(RequestKey.NODE_NAMES_LIST))}"
                     f" VM(s) for {self.cluster_name}({self.cluster_id})")
         task = vapp.delete_vms(self.req_spec.get(RequestKey.NODE_NAMES_LIST)) # noqa: E501
         self.tenant_client.get_task_monitor().wait_for_status(task)
         self._update_task(
             TaskStatus.SUCCESS,
             message=f"Deleted "
                     f"{len(self.req_spec.get(RequestKey.NODE_NAMES_LIST))}"
                     f" node(s) to cluster "
                     f"{self.cluster_name}({self.cluster_id})")
     except Exception as e:
         LOGGER.error(traceback.format_exc())
         error_obj = error_to_json(e)
         stack_trace = \
             ''.join(error_obj[ERROR_MESSAGE_KEY][ERROR_STACKTRACE_KEY])
         self._update_task(
             TaskStatus.ERROR,
             error_message=error_obj[ERROR_MESSAGE_KEY][ERROR_DESCRIPTION_KEY],  # noqa: E501
             stack_trace=stack_trace)
     finally:
         self._disconnect_sys_admin()
Exemple #5
0
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))
Exemple #6
0
    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 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
Exemple #8
0
 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
Exemple #9
0
 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
Exemple #10
0
def delete(ctx, name, vm_names, force):
    try:
        client = ctx.obj['client']
        vdc_href = ctx.obj['profiles'].get('vdc_href')
        vdc = VDC(client, href=vdc_href)
        if len(vm_names) == 0:
            task = vdc.delete_vapp(name, force)
        else:
            vapp_resource = vdc.get_vapp(name)
            vapp = VApp(client, resource=vapp_resource)
            task = vapp.delete_vms(vm_names)
        stdout(task, ctx)
    except Exception as e:
        stderr(e, ctx)
Exemple #11
0
 def delete_nodes_thread(self):
     LOGGER.debug(f"About to delete nodes from cluster with name: "
                  f"{self.cluster_name}")
     try:
         vapp = VApp(self.tenant_client, href=self.cluster['vapp_href'])
         template = self.get_template()
         self.update_task(
             TaskStatus.RUNNING,
             message=f"Deleting {len(self.req_spec['nodes'])} node(s) from "
             f"{self.cluster_name}({self.cluster_id})")
         try:
             server_config = get_server_runtime_config()
             delete_nodes_from_cluster(server_config, vapp, template,
                                       self.req_spec['nodes'],
                                       self.req_spec['force'])
         except Exception:
             LOGGER.error(f"Couldn't delete node {self.req_spec['nodes']} "
                          f"from cluster:{self.cluster_name}")
         self.update_task(
             TaskStatus.RUNNING,
             message=f"Undeploying {len(self.req_spec['nodes'])} node(s) "
             f"for {self.cluster_name}({self.cluster_id})")
         for vm_name in self.req_spec['nodes']:
             vm = VM(self.tenant_client, resource=vapp.get_vm(vm_name))
             try:
                 task = vm.undeploy()
                 self.tenant_client.get_task_monitor().wait_for_status(task)
             except Exception:
                 LOGGER.warning(f"Couldn't undeploy VM {vm_name}")
         self.update_task(
             TaskStatus.RUNNING,
             message=f"Deleting {len(self.req_spec['nodes'])} VM(s) for "
             f"{self.cluster_name}({self.cluster_id})")
         task = vapp.delete_vms(self.req_spec['nodes'])
         self.tenant_client.get_task_monitor().wait_for_status(task)
         self.update_task(
             TaskStatus.SUCCESS,
             message=f"Deleted {len(self.req_spec['nodes'])} node(s) to "
             f"cluster {self.cluster_name}({self.cluster_id})")
     except Exception as e:
         LOGGER.error(traceback.format_exc())
         error_obj = error_to_json(e)
         stack_trace = ''.join(error_obj[ERROR_MESSAGE][ERROR_STACKTRACE])
         self.update_task(
             TaskStatus.ERROR,
             error_message=error_obj[ERROR_MESSAGE][ERROR_DESCRIPTION],
             stack_trace=stack_trace)
     finally:
         self._disconnect_sys_admin()
Exemple #12
0
def delete(ctx, name, vm_names, force):
    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)
        if len(vm_names) == 0:
            task = vdc.delete_vapp(name, force)
        else:
            vapp_resource = vdc.get_vapp(name)
            vapp = VApp(client, resource=vapp_resource)
            task = vapp.delete_vms(vm_names)
        stdout(task, ctx)
    except Exception as e:
        stderr(e, ctx)
 def _delete_nodes(self, *args,
                   cluster_name, cluster_vapp_href, node_names_list):
     LOGGER.debug(f"About to delete nodes {node_names_list} "
                  f"from cluster {cluster_name}")
     vapp = VApp(self.tenant_client, href=cluster_vapp_href)
     try:
         delete_nodes_from_cluster(vapp, node_names_list)
     except Exception:
         LOGGER.error(f"Couldn't delete node {node_names_list} "
                      f"from cluster:{cluster_name}")
     for vm_name in node_names_list:
         vm = VM(self.tenant_client, resource=vapp.get_vm(vm_name))
         try:
             task = vm.undeploy()
             self.tenant_client.get_task_monitor().wait_for_status(task)
         except Exception:
             LOGGER.warning(f"Couldn't undeploy VM {vm_name}")
     task = vapp.delete_vms(node_names_list)
     self.tenant_client.get_task_monitor().wait_for_status(task)
 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))
class VappVM(VcdAnsibleModule):
    def __init__(self, **kwargs):
        super(VappVM, self).__init__(**kwargs)
        vapp_resource = self.get_target_resource()
        self.vapp = VApp(self.client, resource=vapp_resource)

    def manage_states(self):
        state = self.params.get('state')
        if state == "present":
            return self.add_vm()

        if state == "absent":
            return self.delete_vm()

        if state == "update":
            return self.update_vm()

    def manage_operations(self):
        operation = self.params.get('operation')
        if operation == "poweron":
            return self.power_on_vm()

        if operation == "poweroff":
            return self.power_off_vm()

        if operation == "reloadvm":
            return self.reload_vm()

        if operation == "deploy":
            return self.deploy_vm()

        if operation == "undeploy":
            return self.undeploy_vm()

        if operation == "list_disks":
            return self.list_disks()

        if operation == "list_nics":
            return self.list_nics()

    def get_source_resource(self):
        source_catalog_name = self.params.get('source_catalog_name')
        source_template_name = self.params.get('source_template_name')
        source_vdc = self.params.get('source_vdc')
        source_vapp = self.params.get('source_vapp')
        org_resource = Org(self.client, resource=self.client.get_org())
        source_vapp_resource = None

        if source_vapp:
            source_vdc_resource = VDC(
                self.client, resource=org_resource.get_vdc(source_vdc))
            source_vapp_resource_href = source_vdc_resource.get_resource_href(
                name=source_vapp, entity_type=EntityType.VAPP)
            source_vapp_resource = self.client.get_resource(
                source_vapp_resource_href)

        if source_catalog_name:
            catalog_item = org_resource.get_catalog_item(
                source_catalog_name, source_template_name)
            source_vapp_resource = self.client.get_resource(
                catalog_item.Entity.get('href'))

        return source_vapp_resource

    def get_target_resource(self):
        target_vapp = self.params.get('target_vapp')
        target_vdc = self.params.get('target_vdc')
        org_resource = Org(self.client, resource=self.client.get_org())
        target_vapp_resource = None

        target_vdc_resource = VDC(
            self.client, resource=org_resource.get_vdc(target_vdc))
        target_vapp_resource = target_vdc_resource.get_vapp(target_vapp)

        return target_vapp_resource

    def get_storage_profile(self, profile_name):
        target_vdc = self.params.get('target_vdc')
        org_resource = Org(self.client, resource=self.client.get_org())
        vdc_resource = VDC(
            self.client, resource=org_resource.get_vdc(target_vdc))

        return vdc_resource.get_storage_profile(profile_name)

    def get_vm(self):
        vapp_vm_resource = self.vapp.get_vm(self.params.get('target_vm_name'))

        return VM(self.client, resource=vapp_vm_resource)

    def add_vm(self):
        params = self.params
        source_vapp_resource = self.get_source_resource()
        target_vm_name = params.get('target_vm_name')
        source_vm_name = params.get('source_vm_name')
        hostname = params.get('hostname')
        vmpassword = params.get('vmpassword')
        vmpassword_auto = params.get('vmpassword_auto')
        vmpassword_reset = params.get('vmpassword_reset')
        network = params.get('network')
        all_eulas_accepted = params.get('all_eulas_accepted')
        power_on = params.get('power_on')
        deploy = params.get('deploy')
        ip_allocation_mode = params.get('ip_allocation_mode')
        cust_script = params.get('cust_script')
        storage_profile = params.get('storage_profile')
        response = dict()
        response['changed'] = False

        try:
            self.get_vm()
        except EntityNotFoundException:
            spec = {
                'source_vm_name': source_vm_name,
                'vapp': source_vapp_resource,
                'target_vm_name': target_vm_name,
                'hostname': hostname,
                'password': vmpassword,
                'password_auto': vmpassword_auto,
                'password_reset': vmpassword_reset,
                'ip_allocation_mode': ip_allocation_mode,
                'network': network,
                'cust_script': cust_script
            }

            spec = {k: v for k, v in spec.items() if v}
            if storage_profile:
                spec['storage_profile'] = self.get_storage_profile(storage_profile)
            specs = [spec]
            args = {
                "specs": specs,
                "deploy": deploy,
                "power_on": power_on,
                "all_eulas_accepted": all_eulas_accepted
            }
            add_vms_task = self.vapp.add_vms(**args)
            self.execute_task(add_vms_task)
            response['msg'] = 'VM {} has been created.'.format(target_vm_name)
            response['changed'] = True
        else:
            msg = 'VM {} is already present.'
            response['warnings'] = msg.format(target_vm_name)

        return response

    def delete_vm(self):
        vm_name = self.params.get('target_vm_name')
        response = dict()
        response['changed'] = False

        try:
            vm = self.get_vm()
        except EntityNotFoundException:
            response['warnings'] = 'VM {} is not present.'.format(vm_name)
        else:
            if not vm.is_powered_off():
                self.undeploy_vm()
            delete_vms_task = self.vapp.delete_vms([vm_name])
            self.execute_task(delete_vms_task)
            response['msg'] = 'VM {} has been deleted.'.format(vm_name)
            response['changed'] = True

        return response

    def update_vm(self):
        vm_name = self.params.get('target_vm_name')
        response = dict()
        response['changed'] = False

        if self.params.get("virtual_cpus"):
            self.update_vm_cpu()
            response['changed'] = True

        if self.params.get("memory"):
            self.update_vm_memory()
            response['changed'] = True

        response['msg'] = 'VM {} has been updated.'.format(vm_name)

        return response

    def update_vm_cpu(self):
        virtual_cpus = self.params.get('virtual_cpus')
        cores_per_socket = self.params.get('cores_per_socket')

        vm = self.get_vm()
        update_cpu_task = vm.modify_cpu(virtual_cpus, cores_per_socket)

        return self.execute_task(update_cpu_task)

    def update_vm_memory(self):
        memory = self.params.get('memory')

        vm = self.get_vm()
        update_memory_task = vm.modify_memory(memory)

        return self.execute_task(update_memory_task)

    def power_on_vm(self):
        vm_name = self.params.get('target_vm_name')
        response = dict()
        response['changed'] = False

        vm = self.get_vm()
        if not vm.is_powered_on():
            self.deploy_vm()
            response['msg'] = 'VM {} has been powered on.'.format(vm_name)
            response['changed'] = True
        else:
            response['warnings'] = 'VM {} is powered on.'.format(vm_name)

        return response

    def power_off_vm(self,):
        vm_name = self.params.get('target_vm_name')
        response = dict()
        response['changed'] = False

        vm = self.get_vm()
        if not vm.is_powered_off():
            self.undeploy_vm()
            response['msg'] = 'VM {} has been powered off.'.format(vm_name)
            response['changed'] = True
        else:
            response['warnings'] = 'VM {} is powered off.'.format(vm_name)

        return response

    def reload_vm(self):
        vm_name = self.params.get('target_vm_name')
        response = dict()
        response['changed'] = False

        vm = self.get_vm()
        vm.reload()
        response['msg'] = 'VM {} has been reloaded.'.format(vm_name)
        response['changed'] = True

        return response

    def deploy_vm(self):
        vm_name = self.params.get('target_vm_name')
        force_customization = self.params.get('force_customization')
        response = dict()
        response['changed'] = False

        vm = self.get_vm()
        if not vm.is_deployed():
            deploy_vm_task = vm.deploy(force_customization=force_customization)
            self.execute_task(deploy_vm_task)
            msg = 'VM {} has been deployed'
            response['msg'] = msg.format(vm_name)
            response['changed'] = True
        else:
            msg = 'VM {} is already deployed'
            response['warnings'] = msg.format(vm_name)

        return response

    def undeploy_vm(self):
        vm_name = self.params.get('target_vm_name')
        response = dict()
        response['changed'] = False

        vm = self.get_vm()
        if not vm.is_deployed():
            undeploy_vm_task = vm.undeploy(action="powerOff")
            self.execute_task(undeploy_vm_task)
            msg = 'VM {} has been undeployed'
            response['msg'] = msg.format(vm_name)
            response['changed'] = True
        else:
            msg = 'VM {} is already undeployed'
            response['warnings'] = msg.format(vm_name)

        return response

    def list_disks(self):
        response = dict()
        response['changed'] = False
        response['msg'] = list()

        vm = self.get_vm()
        response['msg'] = vm.list_virtual_hardware_section(
            is_cpu=False, is_memory=False, is_disk=True)

        return response

    def list_nics(self):
        response = dict()
        response['changed'] = False
        response['msg'] = list()

        vm = self.get_vm()
        response['msg'] = vm.list_nics()

        return response
class VappVM(object):
    def __init__(self, module, vapp_resource):
        self.module = module
        self.vapp = VApp(module.client, resource=vapp_resource)

    def execute_task(self, task):
        client = self.module.client
        task_monitor = client.get_task_monitor()
        task_state = 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)

        task_status = task_state.get('status')
        if task_status != TaskStatus.SUCCESS.value:
            raise Exception(etree.tostring(task_state, pretty_print=True))

        return 1

    def get_vm(self, vm_name):
        vapp_vm_resource = self.vapp.get_vm(vm_name)

        return VM(self.module.client, resource=vapp_vm_resource)

    def add_vms(self, target_vm_name, source_vapp_resource):
        params = self.module.params
        source_vm_name = params.get('source_vm_name')
        hostname = params.get('hostname')
        vmpassword = params.get('vmpassword')
        vmpassword_auto = params.get('vmpassword_auto')
        vmpassword_reset = params.get('vmpassword_reset')
        network = params.get('network')
        all_eulas_accepted = params.get('all_eulas_accepted', True)
        power_on = params.get('power_on', True)
        ip_allocation_mode = params.get('ip_allocation_mode')
        # cust_script = module.params.get('cust_script')
        # storage_profile = module.params.get('storage_profile')
        response = dict()

        specs = [{
            'source_vm_name': source_vm_name,
            'vapp': source_vapp_resource,
            'target_vm_name': target_vm_name,
            'hostname': hostname,
            'password': vmpassword,
            'password_auto': vmpassword_auto,
            'password_reset': vmpassword_reset,
            'ip_allocation_mode': ip_allocation_mode,
            'network': network,
            # 'cust_script': cust_script,
            # 'storage_profile': storage_profile
        }]
        add_vms_task = self.vapp.add_vms(specs,
                                         power_on=power_on,
                                         all_eulas_accepted=all_eulas_accepted)
        self.execute_task(add_vms_task)
        response['msg'] = 'Vapp VM {} has been created.'.format(target_vm_name)
        response['changed'] = True

        return response

    def delete_vms(self, vm_name):
        response = dict()

        self.undeploy_vm(vm_name)
        delete_vms_task = self.vapp.delete_vms([vm_name])
        self.execute_task(delete_vms_task)
        response['msg'] = 'Vapp VM {} has been deleted.'.format(vm_name)
        response['changed'] = True

        return response

    def power_on_vm(self, vm_name):
        vm = self.get_vm(vm_name)
        response = dict()

        power_on_task = vm.power_on()
        self.execute_task(power_on_task)
        response['msg'] = 'Vapp VM {} has been powered on.'.format(vm_name)
        response['changed'] = True

        return response

    def power_off_vm(self, vm_name):
        vm = self.get_vm(vm_name)
        response = dict()

        power_off_task = vm.power_off()
        self.execute_task(power_off_task)
        response['msg'] = 'Vapp VM {} has been powered off.'.format(vm_name)
        response['changed'] = True

        return response

    def reload_vm(self, vm_name):
        vm = self.get_vm(vm_name)
        response = dict()

        vm.reload()
        response['msg'] = 'Vapp VM {} has been reloaded.'.format(vm_name)
        response['changed'] = True

        return response

    def update_cpu_of_vm(self, vm_name):
        params = self.module.params
        vm = self.get_vm(vm_name)
        virtual_cpus = params.get('virtual_cpus')
        cores_per_socket = params.get('cores_per_socket')
        response = dict()

        self.power_off_vm(vm_name)
        update_cpu_task = vm.modify_cpu(virtual_cpus, cores_per_socket)
        self.execute_task(update_cpu_task)
        response['msg'] = 'Vapp VM {} has been updated.'.format(vm_name)
        response['changed'] = True

        return response

    def update_memory_of_vm(self, vm_name):
        params = self.module.params
        vm = self.get_vm(vm_name)
        memory = params.get('memory')
        response = dict()

        self.power_off_vm(vm_name)
        update_memory_task = vm.modify_memory(memory)
        self.execute_task(update_memory_task)
        response['msg'] = 'Vapp VM {} has been updated.'.format(vm_name)
        response['changed'] = True

        return response

    def deploy_vm(self, vm_name):
        vm = self.get_vm(vm_name)
        response = dict()

        deploy_vm_task = vm.deploy()
        self.execute_task(deploy_vm_task)
        response['msg'] = 'Vapp VM {} has been deployed.'.format(vm_name)
        response['changed'] = True

        return response

    def undeploy_vm(self, vm_name):
        vm = self.get_vm(vm_name)
        response = dict()

        undeploy_vm_task = vm.undeploy()
        self.execute_task(undeploy_vm_task)
        response['msg'] = 'Vapp VM {} has been undeployed.'.format(vm_name)
        response['changed'] = True

        return response
class VappVM(VcdAnsibleModule):
    def __init__(self, **kwargs):
        super(VappVM, self).__init__(**kwargs)
        vapp_resource = self.get_target_resource()
        self.vapp = VApp(self.client, resource=vapp_resource)

    def manage_states(self):
        state = self.params.get('state')
        if state == "present":
            return self.add_vm()

        if state == "absent":
            return self.delete_vm()

        if state == "update":
            return self.update_vm()

    def manage_operations(self):
        operation = self.params.get('operation')
        if operation == "poweron":
            return self.power_on_vm()

        if operation == "poweroff":
            return self.power_off_vm()

        if operation == "reloadvm":
            return self.reload_vm()

        if operation == "deploy":
            return self.deploy_vm()

        if operation == "undeploy":
            return self.undeploy_vm()

        if operation == "list_disks":
            return self.list_disks()

        if operation == "list_nics":
            return self.list_nics()

    def get_source_resource(self):
        source_catalog_name = self.params.get('source_catalog_name')
        source_template_name = self.params.get('source_template_name')
        source_vdc = self.params.get('source_vdc')
        source_vapp = self.params.get('source_vapp')
        org_resource = Org(self.client, resource=self.client.get_org())
        source_vapp_resource = None

        if source_vapp:
            source_vdc_resource = VDC(
                self.client, resource=org_resource.get_vdc(source_vdc))
            source_vapp_resource_href = source_vdc_resource.get_resource_href(
                name=source_vapp, entity_type=EntityType.VAPP)
            source_vapp_resource = self.client.get_resource(
                source_vapp_resource_href)

        if source_catalog_name:
            catalog_item = org_resource.get_catalog_item(
                source_catalog_name, source_template_name)
            source_vapp_resource = self.client.get_resource(
                catalog_item.Entity.get('href'))

        return source_vapp_resource

    def get_target_resource(self):
        target_vapp = self.params.get('target_vapp')
        target_vdc = self.params.get('target_vdc')
        org_resource = Org(self.client, resource=self.client.get_org())
        target_vapp_resource = None

        target_vdc_resource = VDC(
            self.client, resource=org_resource.get_vdc(target_vdc))
        target_vapp_resource = target_vdc_resource.get_vapp(target_vapp)

        return target_vapp_resource

    def get_storage_profile(self, profile_name):
        target_vdc = self.params.get('target_vdc')
        org_resource = Org(self.client, resource=self.client.get_org())
        vdc_resource = VDC(self.client, resource=org_resource.get_vdc(target_vdc))

        return vdc_resource.get_storage_profile(profile_name)

    def get_vm(self):
        vapp_vm_resource = self.vapp.get_vm(self.params.get('target_vm_name'))

        return VM(self.client, resource=vapp_vm_resource)

    def add_vm(self):
        params = self.params
        source_vapp_resource = self.get_source_resource()
        target_vm_name = params.get('target_vm_name')
        source_vm_name = params.get('source_vm_name')
        hostname = params.get('hostname')
        vmpassword = params.get('vmpassword')
        vmpassword_auto = params.get('vmpassword_auto')
        vmpassword_reset = params.get('vmpassword_reset')
        network = params.get('network')
        all_eulas_accepted = params.get('all_eulas_accepted')
        power_on = params.get('power_on')
        ip_allocation_mode = params.get('ip_allocation_mode')
        cust_script = params.get('cust_script')
        storage_profile = params.get('storage_profile')
        properties = params.get('properties')
        response = dict()
        response['changed'] = False

        try:
            self.get_vm()
        except EntityNotFoundException:
            spec = {
                'source_vm_name': source_vm_name,
                'vapp': source_vapp_resource,
                'target_vm_name': target_vm_name,
                'hostname': hostname,
                'password': vmpassword,
                'password_auto': vmpassword_auto,
                'password_reset': vmpassword_reset,
                'ip_allocation_mode': ip_allocation_mode,
                'network': network,
                'cust_script': cust_script
            }
            if storage_profile!='':
                spec['storage_profile'] = self.get_storage_profile(storage_profile)
            spec = {k: v for k, v in spec.items() if v}
            source_vm = self.vapp.to_sourced_item(spec)

            # Check the source vm if we need to inject OVF properties.
            source_vapp = VApp(self.client, resource=source_vapp_resource)
            vm = source_vapp.get_vm(source_vm_name)
            productsection = vm.find('ovf:ProductSection', NSMAP)
            if productsection is not None:
                for prop in productsection.iterfind('ovf:Property', NSMAP):
                    if properties and prop.get('{'+NSMAP['ovf']+'}key') in properties:
                        val = prop.find('ovf:Value', NSMAP)
                        if val:
                            prop.remove(val)
                        val = E_OVF.Value()
                        val.set('{'+NSMAP['ovf']+'}value', properties[prop.get('{'+NSMAP['ovf']+'}key')])
                        prop.append(val)
                source_vm.InstantiationParams.append(productsection)
                source_vm.VmGeneralParams.NeedsCustomization = E.NeedsCustomization('true')

            params = E.RecomposeVAppParams(deploy='true', powerOn='true' if power_on else 'false')
            params.append(source_vm)
            if all_eulas_accepted is not None:
                params.append(E.AllEULAsAccepted(all_eulas_accepted))

            add_vms_task = self.client.post_linked_resource(
                self.get_target_resource(), RelationType.RECOMPOSE,
                EntityType.RECOMPOSE_VAPP_PARAMS.value, params)
            self.execute_task(add_vms_task)
            response['msg'] = 'Vapp VM {} has been created.'.format(
                target_vm_name)
            response['changed'] = True
        else:
            response['warnings'] = 'Vapp VM {} is already present.'.format(
                target_vm_name)

        return response

    def delete_vm(self):
        vm_name = self.params.get('target_vm_name')
        response = dict()
        response['changed'] = False

        try:
            self.get_vm()
        except EntityNotFoundException:
            response['warnings'] = 'Vapp VM {} is not present.'.format(vm_name)
        else:
            self.undeploy_vm()
            delete_vms_task = self.vapp.delete_vms([vm_name])
            self.execute_task(delete_vms_task)
            response['msg'] = 'Vapp VM {} has been deleted.'.format(vm_name)
            response['changed'] = True

        return response

    def update_vm(self):
        vm_name = self.params.get('target_vm_name')
        response = dict()
        response['changed'] = False

        if self.params.get("virtual_cpus"):
            self.update_vm_cpu()
            response['changed'] = True

        if self.params.get("memory"):
            self.update_vm_memory()
            response['changed'] = True

        response['msg'] = 'Vapp VM {} has been updated.'.format(vm_name)

        return response

    def update_vm_cpu(self):
        virtual_cpus = self.params.get('virtual_cpus')
        cores_per_socket = self.params.get('cores_per_socket')

        vm = self.get_vm()
        update_cpu_task = vm.modify_cpu(virtual_cpus, cores_per_socket)

        return self.execute_task(update_cpu_task)

    def update_vm_memory(self):
        memory = self.params.get('memory')

        vm = self.get_vm()
        update_memory_task = vm.modify_memory(memory)

        return self.execute_task(update_memory_task)

    def power_on_vm(self):
        vm_name = self.params.get('target_vm_name')
        response = dict()
        response['changed'] = False

        try:
            vm = self.get_vm()
            power_on_task = vm.power_on()
            self.execute_task(power_on_task)
            response['msg'] = 'Vapp VM {} has been powered on.'.format(vm_name)
            response['changed'] = True
        except OperationNotSupportedException:
            response['warnings'] = 'Vapp VM {} is already powered on.'.format(
                vm_name)

        return response

    def power_off_vm(self,):
        vm_name = self.params.get('target_vm_name')
        response = dict()
        response['changed'] = False

        try:
            vm = self.get_vm()
            power_off_task = vm.power_off()
            self.execute_task(power_off_task)
            response['msg'] = 'Vapp VM {} has been powered off.'.format(
                vm_name)
            response['changed'] = True
        except OperationNotSupportedException:
            response['warnings'] = 'Vapp VM {} is already powered off.'.format(
                vm_name)

        return response

    def reload_vm(self):
        vm_name = self.params.get('target_vm_name')
        response = dict()
        response['changed'] = False

        vm = self.get_vm()
        vm.reload()
        response['msg'] = 'Vapp VM {} has been reloaded.'.format(vm_name)
        response['changed'] = True

        return response

    def deploy_vm(self):
        vm_name = self.params.get('target_vm_name')
        response = dict()
        response['changed'] = False

        try:
            vm = self.get_vm()
            deploy_vm_task = vm.deploy()
            self.execute_task(deploy_vm_task)
            response['msg'] = 'Vapp VM {} has been deployed.'.format(vm_name)
            response['changed'] = True
        except OperationNotSupportedException:
            response['warnings'] = 'Vapp VM {} is already deployed.'.format(
                vm_name)

        return response

    def undeploy_vm(self):
        vm_name = self.params.get('target_vm_name')
        response = dict()
        response['changed'] = False

        try:
            vm = self.get_vm()
            undeploy_vm_task = vm.undeploy()
            self.execute_task(undeploy_vm_task)
            response['msg'] = 'Vapp VM {} has been undeployed.'.format(vm_name)
            response['changed'] = True
        except OperationNotSupportedException:
            response['warnings'] = 'Vapp VM {} is already undeployed.'.format(
                vm_name)

        return response

    def list_disks(self):
        response = dict()
        response['changed'] = False
        response['msg'] = []

        vm = self.get_vm()
        disks = self.client.get_resource(vm.resource.get('href') + '/virtualHardwareSection/disks')
        for disk in disks.Item:
            if disk['{'+NSMAP['rasd']+'}ResourceType'] == 17:
                response['msg'].append({
                    'id': disk['{'+NSMAP['rasd']+'}InstanceID'].text,
                    'name': disk['{'+NSMAP['rasd']+'}ElementName'].text,
                    'description': disk['{'+NSMAP['rasd']+'}Description'].text,
                    'size': disk['{'+NSMAP['rasd']+'}HostResource'].get('{'+NSMAP['vcloud']+'}capacity')
                })

        return response

    def list_nics(self):
        response = dict()
        response['changed'] = False
        response['msg'] = []

        vm = self.get_vm()
        nics = self.client.get_resource(vm.resource.get('href') + '/networkConnectionSection')
        for nic in nics.NetworkConnection:
            response['msg'].append({
                'index': nic.NetworkConnectionIndex.text,
                'network': nic.get('network')
            })

        return response
class VappVM(VcdAnsibleModule):
    def __init__(self, **kwargs):
        super(VappVM, self).__init__(**kwargs)
        vapp_resource = self.get_target_resource()
        self.vapp = VApp(self.client, resource=vapp_resource)

    def manage_states(self):
        state = self.params.get('state')
        if state == "present":
            return self.add_vm()

        if state == "absent":
            return self.delete_vm()

        if state == "update":
            return self.update_vm()

    def manage_operations(self):
        operation = self.params.get('operation')
        if operation == "poweron":
            return self.power_on_vm()

        if operation == "poweroff":
            return self.power_off_vm()

        if operation == "reloadvm":
            return self.reload_vm()

        if operation == "deploy":
            return self.deploy_vm()

        if operation == "undeploy":
            return self.undeploy_vm()

        if operation == "list_disks":
            return self.list_disks()

        if operation == "list_nics":
            return self.list_nics()

        if operation == "snapshot":
            return self.take_snapshot()

        if operation == "revert":
            return self.revert_to_snapshot()

    def get_source_resource(self):
        source_catalog_name = self.params.get('source_catalog_name')
        source_template_name = self.params.get('source_template_name')
        source_vdc = self.params.get('source_vdc')
        source_vapp = self.params.get('source_vapp')
        org_resource = Org(self.client, resource=self.client.get_org())
        source_vapp_resource = None

        if source_vapp:
            source_vdc_resource = VDC(
                self.client, resource=org_resource.get_vdc(source_vdc))
            source_vapp_resource_href = source_vdc_resource.get_resource_href(
                name=source_vapp, entity_type=EntityType.VAPP)
            source_vapp_resource = self.client.get_resource(
                source_vapp_resource_href)

        if source_catalog_name:
            catalog_item = org_resource.get_catalog_item(
                source_catalog_name, source_template_name)
            source_vapp_resource = self.client.get_resource(
                catalog_item.Entity.get('href'))

        return source_vapp_resource

    def get_target_resource(self):
        target_vapp = self.params.get('target_vapp')
        target_vdc = self.params.get('target_vdc')
        org_resource = Org(self.client, resource=self.client.get_org())
        target_vapp_resource = None

        target_vdc_resource = VDC(
            self.client, resource=org_resource.get_vdc(target_vdc))
        target_vapp_resource = target_vdc_resource.get_vapp(target_vapp)

        return target_vapp_resource

    def get_storage_profile(self, profile_name):
        target_vdc = self.params.get('target_vdc')
        org_resource = Org(self.client, resource=self.client.get_org())
        vdc_resource = VDC(self.client, resource=org_resource.get_vdc(target_vdc))

        return vdc_resource.get_storage_profile(profile_name)

    def get_vm(self):
        vapp_vm_resource = self.vapp.get_vm(self.params.get('target_vm_name'))

        return VM(self.client, resource=vapp_vm_resource)

    def add_vm(self):
        params = self.params
        source_vapp_resource = self.get_source_resource()
        target_vm_name = params.get('target_vm_name')
        source_vm_name = params.get('source_vm_name')
        hostname = params.get('hostname')
        vmpassword = params.get('vmpassword')
        vmpassword_auto = params.get('vmpassword_auto')
        vmpassword_reset = params.get('vmpassword_reset')
        network = params.get('network')
        all_eulas_accepted = params.get('all_eulas_accepted')
        power_on = params.get('power_on')
        ip_allocation_mode = params.get('ip_allocation_mode')
        cust_script = params.get('cust_script')
        storage_profile = params.get('storage_profile')
        properties = params.get('properties')
        response = dict()
        response['changed'] = False

        try:
            self.get_vm()
        except EntityNotFoundException:
            spec = {
                'source_vm_name': source_vm_name,
                'vapp': source_vapp_resource,
                'target_vm_name': target_vm_name,
                'hostname': hostname,
                'password': vmpassword,
                'password_auto': vmpassword_auto,
                'password_reset': vmpassword_reset,
                'ip_allocation_mode': ip_allocation_mode,
                'network': network,
                'cust_script': cust_script
            }
            if storage_profile!='':
                spec['storage_profile'] = self.get_storage_profile(storage_profile)
            spec = {k: v for k, v in spec.items() if v}
            source_vm = self.vapp.to_sourced_item(spec)

            # Check the source vm if we need to inject OVF properties.
            source_vapp = VApp(self.client, resource=source_vapp_resource)
            vm = source_vapp.get_vm(source_vm_name)
            productsection = vm.find('ovf:ProductSection', NSMAP)
            if productsection is not None:
                for prop in productsection.iterfind('ovf:Property', NSMAP):
                    if properties and prop.get('{'+NSMAP['ovf']+'}key') in properties:
                        val = prop.find('ovf:Value', NSMAP)
                        if val:
                            prop.remove(val)
                        val = E_OVF.Value()
                        val.set('{'+NSMAP['ovf']+'}value', properties[prop.get('{'+NSMAP['ovf']+'}key')])
                        prop.append(val)
                source_vm.InstantiationParams.append(productsection)
                source_vm.VmGeneralParams.NeedsCustomization = E.NeedsCustomization('true')

            params = E.RecomposeVAppParams(deploy='true', powerOn='true' if power_on else 'false')
            params.append(source_vm)
            if all_eulas_accepted is not None:
                params.append(E.AllEULAsAccepted(all_eulas_accepted))

            add_vms_task = self.client.post_linked_resource(
                self.get_target_resource(), RelationType.RECOMPOSE,
                EntityType.RECOMPOSE_VAPP_PARAMS.value, params)
            self.execute_task(add_vms_task)
            response['msg'] = 'Vapp VM {} has been created.'.format(
                target_vm_name)
            response['changed'] = True
        else:
            response['warnings'] = 'Vapp VM {} is already present.'.format(
                target_vm_name)

        return response

    def delete_vm(self):
        vm_name = self.params.get('target_vm_name')
        response = dict()
        response['changed'] = False

        try:
            self.get_vm()
        except EntityNotFoundException:
            response['warnings'] = 'Vapp VM {} is not present.'.format(vm_name)
        else:
            self.undeploy_vm()
            delete_vms_task = self.vapp.delete_vms([vm_name])
            self.execute_task(delete_vms_task)
            response['msg'] = 'Vapp VM {} has been deleted.'.format(vm_name)
            response['changed'] = True

        return response

    def update_vm(self):
        vm_name = self.params.get('target_vm_name')
        response = dict()
        response['changed'] = False

        if self.params.get("virtual_cpus"):
            self.update_vm_cpu()
            response['changed'] = True

        if self.params.get("memory"):
            self.update_vm_memory()
            response['changed'] = True

        response['msg'] = 'Vapp VM {} has been updated.'.format(vm_name)

        return response

    def update_vm_cpu(self):
        virtual_cpus = self.params.get('virtual_cpus')
        cores_per_socket = self.params.get('cores_per_socket')

        vm = self.get_vm()
        update_cpu_task = vm.modify_cpu(virtual_cpus, cores_per_socket)

        return self.execute_task(update_cpu_task)

    def update_vm_memory(self):
        memory = self.params.get('memory')

        vm = self.get_vm()
        update_memory_task = vm.modify_memory(memory)

        return self.execute_task(update_memory_task)

    def power_on_vm(self):
        vm_name = self.params.get('target_vm_name')
        response = dict()
        response['changed'] = False

        try:
            vm = self.get_vm()
            power_on_task = vm.power_on()
            self.execute_task(power_on_task)
            response['msg'] = 'Vapp VM {} has been powered on.'.format(vm_name)
            response['changed'] = True
        except OperationNotSupportedException:
            response['warnings'] = 'Vapp VM {} is already powered on.'.format(
                vm_name)

        return response

    def power_off_vm(self,):
        vm_name = self.params.get('target_vm_name')
        response = dict()
        response['changed'] = False

        try:
            vm = self.get_vm()
            power_off_task = vm.power_off()
            self.execute_task(power_off_task)
            response['msg'] = 'Vapp VM {} has been powered off.'.format(
                vm_name)
            response['changed'] = True
        except OperationNotSupportedException:
            response['warnings'] = 'Vapp VM {} is already powered off.'.format(
                vm_name)

        return response

    def reload_vm(self):
        vm_name = self.params.get('target_vm_name')
        response = dict()
        response['changed'] = False

        vm = self.get_vm()
        vm.reload()
        response['msg'] = 'Vapp VM {} has been reloaded.'.format(vm_name)
        response['changed'] = True

        return response

    def deploy_vm(self):
        vm_name = self.params.get('target_vm_name')
        response = dict()
        response['changed'] = False

        try:
            vm = self.get_vm()
            deploy_vm_task = vm.deploy()
            self.execute_task(deploy_vm_task)
            response['msg'] = 'Vapp VM {} has been deployed.'.format(vm_name)
            response['changed'] = True
        except OperationNotSupportedException:
            response['warnings'] = 'Vapp VM {} is already deployed.'.format(
                vm_name)

        return response

    def undeploy_vm(self):
        vm_name = self.params.get('target_vm_name')
        response = dict()
        response['changed'] = False

        try:
            vm = self.get_vm()
            undeploy_vm_task = vm.undeploy()
            self.execute_task(undeploy_vm_task)
            response['msg'] = 'Vapp VM {} has been undeployed.'.format(vm_name)
            response['changed'] = True
        except OperationNotSupportedException:
            response['warnings'] = 'Vapp VM {} is already undeployed.'.format(
                vm_name)

        return response

    def list_disks(self):
        response = dict()
        response['changed'] = False
        response['msg'] = []

        vm = self.get_vm()
        disks = self.client.get_resource(vm.resource.get('href') + '/virtualHardwareSection/disks')
        for disk in disks.Item:
            if disk['{'+NSMAP['rasd']+'}ResourceType'] == 17:
                response['msg'].append({
                    'id': disk['{'+NSMAP['rasd']+'}InstanceID'].text,
                    'name': disk['{'+NSMAP['rasd']+'}ElementName'].text,
                    'description': disk['{'+NSMAP['rasd']+'}Description'].text,
                    'size': disk['{'+NSMAP['rasd']+'}HostResource'].get('{'+NSMAP['vcloud']+'}capacity')
                })

        return response

    def list_nics(self):
        response = dict()
        response['changed'] = False
        response['msg'] = []

        vm = self.get_vm()
        nics = self.client.get_resource(vm.resource.get('href') + '/networkConnectionSection')
        for nic in nics.NetworkConnection:
            response['msg'].append({
                'index': nic.NetworkConnectionIndex.text,
                'network': nic.get('network')
            })

        return response

    def take_snapshot(self):
        response = dict(changed=False, msg=[])

        vm = self.get_vm()
        snapshot_create_taks = vm.snapshot_create(memory=True, quiesce=True)
        self.execute_task(snapshot_create_taks)
        response["changed"] = True

        return response

    def revert_to_snapshot(self):
        response = dict(changed=False, msg=[])

        vm = self.get_vm()
        revert_to_current_task = vm.snapshot_revert_to_current()
        self.execute_task(revert_to_current_task)
        response["changed"] = True

        return response
Exemple #19
0
class VappVM(VcdAnsibleModule):
    def __init__(self, **kwargs):
        super(VappVM, self).__init__(**kwargs)
        vapp_resource = self.get_target_resource()
        self.vapp = VApp(self.client, resource=vapp_resource)

    def manage_states(self):
        state = self.params.get('state')
        if state == "present":
            return self.add_vm()

        if state == "absent":
            return self.delete_vm()

        if state == "update":
            return self.update_vm()

    def manage_operations(self):
        operation = self.params.get('operation')
        if operation == "poweron":
            return self.power_on_vm()

        if operation == "poweroff":
            return self.power_off_vm()

        if operation == "reloadvm":
            return self.reload_vm()

        if operation == "deploy":
            return self.deploy_vm()

        if operation == "undeploy":
            return self.undeploy_vm()

    def get_source_resource(self):
        source_catalog_name = self.params.get('source_catalog_name')
        source_template_name = self.params.get('source_template_name')
        source_vdc = self.params.get('source_vdc')
        source_vapp = self.params.get('source_vapp')
        org_resource = Org(self.client, resource=self.client.get_org())
        source_vapp_resource = None

        if source_vapp:
            source_vdc_resource = VDC(
                self.client, resource=org_resource.get_vdc(source_vdc))
            source_vapp_resource_href = source_vdc_resource.get_resource_href(
                name=source_vapp, entity_type=EntityType.VAPP)
            source_vapp_resource = self.client.get_resource(
                source_vapp_resource_href)

        if source_catalog_name:
            catalog_item = org_resource.get_catalog_item(
                source_catalog_name, source_template_name)
            source_vapp_resource = self.client.get_resource(
                catalog_item.Entity.get('href'))

        return source_vapp_resource

    def get_target_resource(self):
        target_vapp = self.params.get('target_vapp')
        target_vdc = self.params.get('target_vdc')
        org_resource = Org(self.client, resource=self.client.get_org())
        target_vapp_resource = None

        target_vdc_resource = VDC(self.client,
                                  resource=org_resource.get_vdc(target_vdc))
        target_vapp_resource = target_vdc_resource.get_vapp(target_vapp)

        return target_vapp_resource

    def get_vm(self):
        vapp_vm_resource = self.vapp.get_vm(self.params.get('target_vm_name'))

        return VM(self.client, resource=vapp_vm_resource)

    def add_vm(self):
        params = self.params
        source_vapp_resource = self.get_source_resource()
        target_vm_name = params.get('target_vm_name')
        source_vm_name = params.get('source_vm_name')
        hostname = params.get('hostname')
        vmpassword = params.get('vmpassword')
        vmpassword_auto = params.get('vmpassword_auto')
        vmpassword_reset = params.get('vmpassword_reset')
        network = params.get('network')
        all_eulas_accepted = params.get('all_eulas_accepted', True)
        power_on = params.get('power_on', True)
        ip_allocation_mode = params.get('ip_allocation_mode')
        # cust_script = params.get('cust_script')
        # storage_profile = params.get('storage_profile')
        response = dict()
        response['changed'] = False

        try:
            self.get_vm()
        except EntityNotFoundException:
            specs = [{
                'source_vm_name': source_vm_name,
                'vapp': source_vapp_resource,
                'target_vm_name': target_vm_name,
                'hostname': hostname,
                'password': vmpassword,
                'password_auto': vmpassword_auto,
                'password_reset': vmpassword_reset,
                'ip_allocation_mode': ip_allocation_mode,
                'network': network,
                # 'cust_script': cust_script,
                # 'storage_profile': json.loads(storage_profile)
            }]
            add_vms_task = self.vapp.add_vms(
                specs,
                power_on=power_on,
                all_eulas_accepted=all_eulas_accepted)
            self.execute_task(add_vms_task)
            response['msg'] = 'Vapp VM {} has been created.'.format(
                target_vm_name)
            response['changed'] = True
        else:
            response['msg'] = 'Vapp VM {} is already present.'.format(
                target_vm_name)

        return response

    def delete_vm(self):
        vm_name = self.params.get('target_vm_name')
        response = dict()
        response['changed'] = False

        try:
            self.get_vm()
        except EntityNotFoundException:
            response['msg'] = 'Vapp VM {} is not present.'.format(vm_name)
        else:
            self.undeploy_vm()
            delete_vms_task = self.vapp.delete_vms([vm_name])
            self.execute_task(delete_vms_task)
            response['msg'] = 'Vapp VM {} has been deleted.'.format(vm_name)
            response['changed'] = True

        return response

    def update_vm(self):
        vm_name = self.params.get('target_vm_name')
        response = dict()
        response['changed'] = False

        if self.params.get("virtual_cpus"):
            self.update_vm_cpu()
            response['changed'] = True

        if self.params.get("memory"):
            self.update_vm_memory()
            response['changed'] = True

        response['msg'] = 'Vapp VM {} has been updated.'.format(vm_name)

        return response

    def update_vm_cpu(self):
        virtual_cpus = self.params.get('virtual_cpus')
        cores_per_socket = self.params.get('cores_per_socket')

        vm = self.get_vm()
        update_cpu_task = vm.modify_cpu(virtual_cpus, cores_per_socket)

        return self.execute_task(update_cpu_task)

    def update_vm_memory(self):
        memory = self.params.get('memory')

        vm = self.get_vm()
        update_memory_task = vm.modify_memory(memory)

        return self.execute_task(update_memory_task)

    def power_on_vm(self):
        vm_name = self.params.get('target_vm_name')
        response = dict()
        response['changed'] = False

        try:
            vm = self.get_vm()
            power_on_task = vm.power_on()
            self.execute_task(power_on_task)
            response['msg'] = 'Vapp VM {} has been powered on.'.format(vm_name)
            response['changed'] = True
        except OperationNotSupportedException:
            response['msg'] = 'Vapp VM {} is already powered on.'.format(
                vm_name)

        return response

    def power_off_vm(self, ):
        vm_name = self.params.get('target_vm_name')
        response = dict()
        response['changed'] = False

        try:
            vm = self.get_vm()
            power_off_task = vm.power_off()
            self.execute_task(power_off_task)
            response['msg'] = 'Vapp VM {} has been powered off.'.format(
                vm_name)
            response['changed'] = True
        except OperationNotSupportedException:
            response['msg'] = 'Vapp VM {} is already powered off.'.format(
                vm_name)

        return response

    def reload_vm(self):
        vm_name = self.params.get('target_vm_name')
        response = dict()
        response['changed'] = False

        vm = self.get_vm()
        vm.reload()
        response['msg'] = 'Vapp VM {} has been reloaded.'.format(vm_name)
        response['changed'] = True

        return response

    def deploy_vm(self):
        vm_name = self.params.get('target_vm_name')
        response = dict()
        response['changed'] = False

        try:
            vm = self.get_vm()
            deploy_vm_task = vm.deploy()
            self.execute_task(deploy_vm_task)
            response['msg'] = 'Vapp VM {} has been deployed.'.format(vm_name)
            response['changed'] = True
        except OperationNotSupportedException:
            response['msg'] = 'Vapp VM {} is already deployed.'.format(vm_name)

        return response

    def undeploy_vm(self):
        vm_name = self.params.get('target_vm_name')
        response = dict()
        response['changed'] = False

        try:
            vm = self.get_vm()
            undeploy_vm_task = vm.undeploy()
            self.execute_task(undeploy_vm_task)
            response['msg'] = 'Vapp VM {} has been undeployed.'.format(vm_name)
            response['changed'] = True
        except OperationNotSupportedException:
            response['msg'] = 'Vapp VM {} is already undeployed.'.format(
                vm_name)

        return response