def deploy_from_image(self, context, deploy_data):
        """
        Deploy From Image Command, will deploy vm from ovf image

        :param models.QualiDriverModels.ResourceCommandContext context: the context of the command
        :param str deploy_data: represent a json of the parameters, example: {
                "image_url": "c:\image.ovf" or
                             "\\nas\shared\image.ovf" or
                             "http://192.168.65.88/ovf/Debian%2064%20-%20Yoav.ovf",
                "cluster_name": "QualiSB Cluster",
                "resource_pool": "LiverPool",
                "datastore_name": "eric ds cluster",
                "datacenter_name": "QualiSB"
                "power_on": False
                "app_name": "appName"
                "user_arguments": ["--compress=9", " --schemaValidate", "--etc"]
            }
        :return str deploy results
        """
        # get command parameters from the environment
        data = jsonpickle.decode(deploy_data)
        data_holder = DeployDataHolder(data)

        # execute command
        result = self.command_wrapper.execute_command_with_connection(
            context, self.deploy_command.execute_deploy_from_image,
            data_holder, context.resource)

        return set_command_result(result=result, unpicklable=False)
    def _set_connect_to_networks_by_request(self, request):
        a = DeployDataHolder(request['driverRequest'])
        res = []
        for action in a.actions:
            vm_uuid = self.ConnectionCommandOrchestrator._get_vm_uuid(action)
            vnic_name = self.ConnectionCommandOrchestrator._validate_vnic_name(
                self.ConnectionCommandOrchestrator._get_vnic_name(action))
            if vnic_name:
                vnic_name = vnic_name.strip().split(',')
            else:
                vnic_name = [None]

            for vnic in vnic_name:
                vlan_id = action.connectionParams.vlanId
                mode = action.connectionParams.mode

                interface = self._get_interface_name(action)
                name = 'Network adapter {0}'.format(
                    vnic) if vnic and vnic.isdigit() else vnic
                r = ConnectionResult(
                    mac_address=interface,
                    vnic_name=name,
                    requested_vnic=name,
                    vm_uuid=vm_uuid,
                    network_name=self.portgroup_name.generate_port_group_name(
                        'dvSwitch', vlan_id, mode),
                    network_key='aa')
                res.append(r)
        self.connector.connect_to_networks = Mock(return_value=res)
    def deploy_from_linked_clone(self, context, deploy_data):
        """
        Deploy Cloned VM From VM Command, will deploy vm from template

        :param models.QualiDriverModels.ResourceCommandContext context: the context of the command
        :param str deploy_data: represent a json of the parameters, example: {"template_resource_model": {"vm_location": "", "vcenter_name": "VMware vCenter", "refresh_ip_timeout": "600", "auto_delete": "True", "vm_storage": "", "auto_power_on": "True", "autoload": "True", "ip_regex": "", "auto_power_off": "True", "vcenter_template": "Alex\\test", "vm_cluster": "", "vm_resource_pool": "", "wait_for_ip": "True"}, "app_name": "Temp"}
        :return str deploy results
        """

        # get command parameters from the environment
        data = jsonpickle.decode(deploy_data)
        data_holder = DeployDataHolder(data)

        if not data_holder.template_resource_model.vcenter_vm:
            raise ValueError('Please insert vm to deploy from')

        data_holder.template_resource_model.vcenter_vm = \
            back_slash_to_front_converter(data_holder.template_resource_model.vcenter_vm)

        if not data_holder.template_resource_model.vcenter_vm_snapshot:
            raise ValueError('Please insert snapshot to deploy from')

        data_holder.template_resource_model.vcenter_vm_snapshot = \
            back_slash_to_front_converter(data_holder.template_resource_model.vcenter_vm_snapshot)

        # execute command
        result = self.command_wrapper.execute_command_with_connection(
            context, self.deploy_command.execute_deploy_from_linked_clone,
            data_holder)

        return set_command_result(result=result, unpicklable=False)
Esempio n. 4
0
    def test_vm_deployer_image_no_vm(self):
        self.pv_service.find_vm_by_name = Mock(return_value=None)
        params = DeployDataHolder({
            "image_url":
            "c:\image.ovf",
            "cluster_name":
            "QualiSB Cluster",
            "resource_pool":
            "LiverPool",
            "datastore_name":
            "eric ds cluster",
            "datacenter_name":
            "QualiSB",
            "power_on":
            False,
            "app_name":
            "appName",
            "user_arguments": ["--compress=9", "--schemaValidate", "--etc"]
        })

        connectivity = Mock()
        connectivity.address = 'vcenter ip or name'
        connectivity.user = '******'
        connectivity.password = '******'

        self.assertRaises(Exception, self.deployer.deploy_from_image, self.si,
                          params, connectivity)
    def test_deploy_image(self):
        # arrange

        cred = TestCredentials()
        pv_service = pyVmomiService(SmartConnect, Disconnect)
        si = pv_service.connect(cred.host, cred.username, cred.password)
        service = OvfImageDeployerService(
            'C:\\Program Files\\VMware\\VMware OVF Tool\\ovftool.exe', Mock())
        deployer = VirtualMachineDeployer(pv_service, generate_unique_name,
                                          service)

        # vm = pv_service.find_vm_by_name(si, 'QualiSB/Raz', '2')

        params = DeployDataHolder({
            "image_url": "http://192.168.65.88/ovf/Debian%2064%20-%20Yoav.ovf",
            "cluster_name": "QualiSB Cluster",
            "resource_pool": "LiverPool",
            "datastore_name": "datastore1",
            "datacenter_name": "QualiSB",
            "power_on": True,
            "app_name": "appName 1",
            "vm_folder": "Raz 2"
        })

        deploy_command = DeployCommand(deployer)
        # act
        result = deploy_command.execute_deploy_from_image(si, params, cred)

        # assert
        self.assertIsNotNone(result)
    def test_deploy_template(self):
        # arrange

        cred = TestCredentials()
        pv_service = pyVmomiService(SmartConnect, Disconnect)
        si = pv_service.connect(cred.host, cred.username, cred.password)
        deployer = VirtualMachineDeployer(pv_service, generate_unique_name)

        # vm = pv_service.find_vm_by_name(si, 'QualiSB/Raz', '2')

        deploy_params = DeployDataHolder({
            "template_model": {
                "vCenter_resource_name": "QualiSB",
                "vm_folder": "QualiSB/Raz",
                "template_name": "2"
            },
            "vm_cluster_model": {
                "cluster_name": "QualiSB Cluster",
                "resource_pool": "IT"
            },
            "datastore_name": "eric ds cluster",
            "power_on": False
        })

        deploy_command = DeployCommand(deployer)

        # act
        result = deploy_command.execute_deploy_from_template(si, deploy_params)

        # assert
        self.assertIsNotNone(result)
Esempio n. 7
0
    def _get_deployment_info(self, image_model, name):
        """
        :type image_model: vCenterVMFromImageResourceModel
        """

        return DeployDataHolder({
            'app_name': name,
            'image_params': image_model
        })
    def connect_bulk(self, si, logger, vcenter_data_model, request):
        """
        :param si:
        :param logger:
        :param VMwarevCenterResourceModel vcenter_data_model:
        :param request:
        :return:
        """
        self.logger = logger

        self.logger.info('Apply connectivity changes has started')
        self.logger.debug(
            'Apply connectivity changes has started with the requet: {0}'.
            format(request))

        holder = DeployDataHolder(jsonpickle.decode(request))

        self.vcenter_data_model = vcenter_data_model
        if vcenter_data_model.reserved_networks:
            self.reserved_networks = [
                name.strip()
                for name in vcenter_data_model.reserved_networks.split(',')
            ]

        if not vcenter_data_model.default_dvswitch:
            return self._handle_no_dvswitch_error(holder)

        dvswitch_location = VMLocation.create_from_full_path(
            vcenter_data_model.default_dvswitch)

        self.dv_switch_path = VMLocation.combine(
            [vcenter_data_model.default_datacenter, dvswitch_location.path])
        self.dv_switch_name = dvswitch_location.name
        self.default_network = VMLocation.combine([
            vcenter_data_model.default_datacenter,
            vcenter_data_model.holding_network
        ])

        mappings = self._map_requsets(holder.driverRequest.actions)
        self.logger.debug('Connectivity actions mappings: {0}'.format(
            jsonpickle.encode(mappings, unpicklable=False)))

        pool = ThreadPool()
        async_results = self._run_async_connection_actions(
            si, mappings, pool, logger)

        results = self._get_async_results(async_results, pool)
        self.logger.info('Apply connectivity changes done')
        self.logger.debug(
            'Apply connectivity has finished with the results: {0}'.format(
                jsonpickle.encode(results, unpicklable=False)))
        return results
 def _get_disconnect_excepted_results(self, request, error_msg=None):
     a = DeployDataHolder(request['driverRequest'])
     res = []
     for action in a.actions:
         r = ActionResult()
         r.actionId = action.actionId
         r.type = action.type
         r.errorMessage = error_msg
         r.infoMessage = 'VLAN Successfully removed' if not error_msg else None
         r.success = True if not error_msg else False
         r.updatedInterface = self._get_interface_name(action)
         res.append(r)
     return res
 def _set_disconnect_from_networks(self, request):
     a = DeployDataHolder(request['driverRequest'])
     res = []
     for action in a.actions:
         vnic_name = self.ConnectionCommandOrchestrator._validate_vnic_name(
             self.ConnectionCommandOrchestrator._get_vnic_name(action))
         interface = self._get_interface_name(action)
         r = VNicDeviceMapper(vnic=Mock(),
                              requested_vnic=vnic_name,
                              network=Mock(),
                              connect=False,
                              mac=interface)
         res.append(r)
     self.disconnector.disconnect_from_networks = Mock(return_value=res)
    def test_deploy_data_holder(self):
        # Arrange
        json = '''
            {
              "driverRequest": {
                "actions": [
                  {
                      "actionId": "vlan1%<=>%resourceA",
                      "type": "setVlan",
                      "actionTarget": {
                        "fullName": "Chassis1/Blade1/port1",
                        "fullAddress" : "1/2/3"
                      },
                      "connectionId" : "vlan1%<=>%resourceA",
                      "connectionParams" : {
                        "connectionParams" : "setVlanParameter",
                        "vlanIds" : ["100-200", "300"],
                        "mode" : "Trunk"
                      },
                      "connectorAttributes" : [
                            {
                                "type": "connectorAttribute",
                                "attributeName" : "QNQ",
                                "attributeValue" : "Enabled"
                            }
                      ]

                  }
                ]
              }
            }   '''

        dictionary = jsonpickle.decode(json)

        # Act
        holder = DeployDataHolder(dictionary)

        # Assert
        self.assertEqual(holder.driverRequest.actions[0].actionId, 'vlan1%<=>%resourceA')
        self.assertEqual(holder.driverRequest.actions[0].type, 'setVlan')
        self.assertEqual(holder.driverRequest.actions[0].actionTarget.fullName, 'Chassis1/Blade1/port1')
        self.assertEqual(holder.driverRequest.actions[0].actionTarget.fullAddress, '1/2/3')
        self.assertEqual(holder.driverRequest.actions[0].connectionId, 'vlan1%<=>%resourceA')
        self.assertEqual(holder.driverRequest.actions[0].connectionParams.connectionParams, 'setVlanParameter')
        self.assertEqual(holder.driverRequest.actions[0].connectionParams.vlanIds[0], '100-200')
        self.assertEqual(holder.driverRequest.actions[0].connectionParams.vlanIds[1], '300')
        self.assertEqual(holder.driverRequest.actions[0].connectionParams.mode, 'Trunk')
        self.assertEqual(holder.driverRequest.actions[0].connectorAttributes[0].type, 'connectorAttribute')
        self.assertEqual(holder.driverRequest.actions[0].connectorAttributes[0].attributeName, 'QNQ')
        self.assertEqual(holder.driverRequest.actions[0].connectorAttributes[0].attributeValue, 'Enabled')
Esempio n. 12
0
    def test_vm_deployer_image(self):
        params = DeployDataHolder({
            'app_name': 'appName',
            'vcenter_name': 'vCenter',
            'image_params': {
                "vcenter_image": "c:\image.ovf",
                "vm_cluster": "QualiSB Cluster",
                "vm_resource_pool": "LiverPool",
                "vm_storage": "eric ds cluster",
                "default_datacenter": "QualiSB",
                "vm_location": "vm_location",
                "auto_power_on": 'False',
                "vcenter_name": 'vCenter',
                "vcenter_image_arguments":
                "--compress=9,--schemaValidate,--etc",
                'ip_regex': '',
                'refresh_ip_timeout': '10',
                'auto_power_on': 'True',
                'auto_power_off': 'True',
                'wait_for_ip': 'True',
                'auto_delete': 'True',
                'autoload': 'True'
            }
        })

        connectivity = Mock()
        connectivity.address = 'vcenter ip or name'
        connectivity.user = '******'
        connectivity.password = '******'

        self.cs_helper.get_connection_details = Mock(return_value=connectivity)

        session = Mock()
        vcenter_data_model = Mock()
        vcenter_data_model.default_datacenter = 'qualisb'
        resource_context = Mock()

        res = self.deployer.deploy_from_image(
            si=self.si,
            logger=Mock(),
            session=session,
            vcenter_data_model=vcenter_data_model,
            data_holder=params,
            resource_context=resource_context)

        self.assertEqual(res.vm_name, self.name)
        self.assertEqual(res.vm_uuid, self.uuid)
        self.assertEqual(res.cloud_provider_resource_name, params.vcenter_name)
Esempio n. 13
0
    def _parse_remote_model(self, context):
        """
        parse the remote resource model and adds its full name
        :type context: models.QualiDriverModels.ResourceRemoteCommandContext

        """
        if not context.remote_endpoints:
            raise Exception('no remote resources found in context: {0}',
                            jsonpickle.encode(context, unpicklable=False))
        resource = context.remote_endpoints[0]

        dictionary = jsonpickle.decode(resource.app_context.deployed_app_json)
        holder = DeployDataHolder(dictionary)
        app_resource_detail = GenericDeployedAppResourceModel()
        app_resource_detail.vm_uuid = holder.vmdetails.uid
        app_resource_detail.cloud_provider = context.resource.fullname
        app_resource_detail.fullname = resource.fullname
        return app_resource_detail
    def test_deploy_data_holder_with_inner_list(self):
        # Arrange
        json = '''
            {
              "driverRequest": {
                "actions": [
                      [
                        "setVlanParameter",
                        ["100-200", "300"]
                      ]
                ]
              }
            }   '''

        dictionary = jsonpickle.decode(json)

        # Act
        holder = DeployDataHolder(dictionary)

        # Assert
        self.assertEqual(holder.driverRequest.actions[0][1][0], '100-200')
        self.assertEqual(holder.driverRequest.actions[0][1][1], '300')
Esempio n. 15
0
 def get_vm_details(self, context, cancellation_context, requests_json):
     requests = DeployDataHolder(jsonpickle.decode(requests_json)).items
     res = self.command_wrapper.execute_command_with_connection(
         context, self.vm_details.get_vm_details, context.resource,
         requests, cancellation_context)
     return set_command_result(result=res, unpicklable=False)