def test_01_check_template_size(self):
        """TS_BUG_009-Test the size of template created from root disk
        """


        # Validate the following:
        # 1. Deploy new VM using the template created from Volume
        # 2. VM should be in Up and Running state

        #Create template from volume
        template = Template.create(
                                   self.apiclient,
                                   self.services["template"],
                                   self.volume.id,
                                   account=self.account.name,
                                   domainid=self.account.domainid
                                )
        self.debug("Creating template with ID: %s" % template.id)
        # Volume and Template Size should be same
        self.assertEqual(
                             template.size,
                             self.volume.size,
                             "Check if size of template and volume are same"
                             )
        return
    def test_01_check_template_size(self):
        """TS_BUG_009-Test the size of template created from root disk
        """


        # Validate the following:
        # 1. Deploy new VM using the template created from Volume
        # 2. VM should be in Up and Running state

        #Create template from volume
        template = Template.create(
                                   self.apiclient,
                                   self.services["template"],
                                   self.volume.id,
                                   account=self.account.name,
                                   domainid=self.account.domainid
                                )
        self.debug("Creating template with ID: %s" % template.id)
        # Volume and Template Size should be same
        self.assertEqual(
                             template.size,
                             self.volume.size,
                             "Check if size of template and volume are same"
                             )
        return
示例#3
0
    def test_01_create_template(self):
        """Test create public & private template
        """

        # Validate the following:
        # 1. database (vm_template table) should be updated
        #    with newly created template
        # 2. UI should show the newly added template
        # 3. ListTemplates API should show the newly added template

        #Create template from Virtual machine and Volume ID
        template = Template.create(
                                self.apiclient,
                                self.services["template"],
                                self.volume.id,
                                account=self.account.name,
                                domainid=self.account.domainid
                                )
        self.cleanup.append(template)

        self.debug("Created template with ID: %s" % template.id)

        list_template_response = Template.list(
                                    self.apiclient,
                                    templatefilter=\
                                    self.services["templatefilter"],
                                    id=template.id
                                    )

        self.assertEqual(
                            isinstance(list_template_response, list),
                            True,
                            "Check list response returns a valid list"
                        )
        #Verify template response to check whether template added successfully
        self.assertNotEqual(
                            len(list_template_response),
                            0,
                            "Check template available in List Templates"
                        )
        template_response = list_template_response[0]

        self.assertEqual(
                            template_response.displaytext,
                            self.services["template"]["displaytext"],
                            "Check display text of newly created template"
                        )
        name = template_response.name
        self.assertEqual(
                            name.count(self.services["template"]["name"]),
                            1,
                            "Check name of newly created template"
                        )
        self.assertEqual(
                            template_response.ostypeid,
                            self.services["template"]["ostypeid"],
                            "Check osTypeID of newly created template"
                        )
        return
    def test_01_create_template(self):
        """Test create public & private template
        """

        # Validate the following:
        # 1. database (vm_template table) should be updated
        #    with newly created template
        # 2. UI should show the newly added template
        # 3. ListTemplates API should show the newly added template

        #Create template from Virtual machine and Volume ID
        template = Template.create(
                                self.apiclient,
                                self.services["template"],
                                self.volume.id,
                                account=self.account.name,
                                domainid=self.account.domainid
                                )
        self.cleanup.append(template)

        self.debug("Created template with ID: %s" % template.id)

        list_template_response = Template.list(
                                    self.apiclient,
                                    templatefilter=\
                                    self.services["templatefilter"],
                                    id=template.id
                                    )

        self.assertEqual(
                            isinstance(list_template_response, list),
                            True,
                            "Check list response returns a valid list"
                        )
        #Verify template response to check whether template added successfully
        self.assertNotEqual(
                            len(list_template_response),
                            0,
                            "Check template available in List Templates"
                        )
        template_response = list_template_response[0]

        self.assertEqual(
                            template_response.displaytext,
                            self.services["template"]["displaytext"],
                            "Check display text of newly created template"
                        )
        name = template_response.name
        self.assertEqual(
                            name.count(self.services["template"]["name"]),
                            1,
                            "Check name of newly created template"
                        )
        self.assertEqual(
                            template_response.ostypeid,
                            self.services["template"]["ostypeid"],
                            "Check osTypeID of newly created template"
                        )
        return
    def test_05_use_private_template_in_project(self):
        """Test use of private template in a project
        """
        # 1. Create a project
        # 2. Verify that in order to use somebody's Private template for vm
        #    creation in the project, permission to use the template has to
        #    be granted to the Project (use API 'updateTemplatePermissions'
        #    with project id to achieve that).

        try:
            self.debug("Deploying VM for with public template: %s" % self.template.id)
            virtual_machine_1 = VirtualMachine.create(
                self.apiclient,
                self.services["server"],
                templateid=self.template.id,
                serviceofferingid=self.service_offering.id,
                projectid=self.project.id,
            )
            self.cleanup.append(virtual_machine_1)
            # Verify VM state
            self.assertEqual(virtual_machine_1.state, "Running", "Check VM state is Running or not")
            virtual_machine_1.stop(self.apiclient)
            # Get the Root disk of VM
            volumes = list_volumes(self.apiclient, projectid=self.project.id, type="ROOT", listall=True)
            self.assertEqual(isinstance(volumes, list), True, "Check for list volume response return valid data")
            volume = volumes[0]

            self.debug("Creating template from volume: %s" % volume.id)
            # Create a template from the ROOTDISK
            template_1 = Template.create(self.userapiclient, self.services["template"], volumeid=volume.id)

            self.cleanup.append(template_1)
            # Verify Template state
            self.assertEqual(template_1.isready, True, "Check Template is in ready state or not")

            # Update template permissions to grant permission to project
            self.debug(
                "Updating template permissions:%s to grant access to project: %s" % (template_1.id, self.project.id)
            )

            template_1.updatePermissions(self.apiclient, op="add", projectids=self.project.id)
            self.debug("Deploying VM for with privileged template: %s" % self.template.id)
            virtual_machine_2 = VirtualMachine.create(
                self.apiclient,
                self.services["server"],
                templateid=template_1.id,
                serviceofferingid=self.service_offering.id,
                projectid=self.project.id,
            )
            self.cleanup.append(virtual_machine_2)
            # Verify VM state
            self.assertEqual(virtual_machine_2.state, "Running", "Check VM state is Running or not")
        except Exception as e:
            self.fail("Exception occured: %s" % e)
        return
 def create_template(self, vm):
     self.debug("Creating guest VM template")
     list_volume = Volume.list(self.api_client, virtualmachineid=vm.id, type="ROOT", listall=True)
     if isinstance(list_volume, list):
         self.volume = list_volume[0]
     else:
         raise Exception("Exception: Unable to find root volume for VM with ID - %s" % vm.id)
     self.pw_enabled_template = Template.create(
         self.api_client,
         self.test_data["template"],
         self.volume.id,
         account=self.account.name,
         domainid=self.account.domainid,
     )
     self.assertEqual(self.pw_enabled_template.passwordenabled, True, "template is not passwordenabled")
     self.cleanup.append(self.pw_enabled_template)
     self.debug("Created guest VM template")
 def create_template(self, vm):
     self.debug("Creating template")
     list_volume = Volume.list(self.apiclient,
                               virtualmachineid=vm.id,
                               type='ROOT',
                               listall=True)
     if isinstance(list_volume, list):
         self.volume = list_volume[0]
     else:
         raise Exception("Exception: Unable to find root volume for VM with ID - %s" % vm.id)
     self.pw_enabled_template = Template.create(
         self.apiclient,
         self.test_data["template"],
         self.volume.id,
         account=self.account.name,
         domainid=self.account.domainid
     )
     self.assertEqual(self.pw_enabled_template.passwordenabled, True, "template is not passwordenabled")
     self.cleanup.append(self.pw_enabled_template)
     self.debug("Created template")
    def create_template(self, vm):
        self.debug("CREATE TEMPLATE")
        list_volume = Volume.list(self.apiclient,
                                  virtualmachineid=vm.id,
                                  type='ROOT',
                                  listall=True)
        if isinstance(list_volume, list):
            self.volume = list_volume[0]
        else:
            raise Exception("Exception: Unable to find root volume for VM: %s" % vm.id)

        self.test_data["template_pr"]["ostype"] = self.test_data["ostype_pr"]
        self.pw_enabled_template = Template.create(
            self.apiclient,
            self.test_data["template_pr"],
            self.volume.id,
            account=self.account.name,
            domainid=self.account.domainid
        )
        self.assertEqual(self.pw_enabled_template.passwordenabled, True, "template is not passwordenabled")
        self.cleanup.append(self.pw_enabled_template)
    def test_04_public_template_use_in_project(self):
        """Test Templates creation in projects
        """
        # 1. Create a project
        # 2. Verify Public templates can be used without any restriction
        # 3. Verify that template created in project can be used in project
        #    without any restrictions

        try:
            self.debug("Deploying VM for with public template: %s" % self.template.id)
            virtual_machine_1 = VirtualMachine.create(
                self.apiclient,
                self.services["server"],
                templateid=self.template.id,
                serviceofferingid=self.service_offering.id,
                projectid=self.project.id,
            )
            self.cleanup.append(virtual_machine_1)
            # Verify VM state
            self.assertEqual(virtual_machine_1.state, "Running", "Check VM state is Running or not")
            virtual_machine_1.stop(self.apiclient)
            # Get the Root disk of VM
            volumes = list_volumes(self.apiclient, projectid=self.project.id, type="ROOT", listall=True)
            self.assertEqual(isinstance(volumes, list), True, "Check for list volume response return valid data")
            volume = volumes[0]

            self.debug("Creating template from volume: %s" % volume.id)
            # Create a template from the ROOTDISK
            template_1 = Template.create(
                self.apiclient, self.services["template"], volumeid=volume.id, projectid=self.project.id
            )

            self.cleanup.append(template_1)
            # Verify Template state
            self.assertEqual(template_1.isready, True, "Check Template is in ready state or not")
        except Exception as e:
            self.fail("Exception occured: %s" % e)
        return
 def test01_template_download_URL_expire(self):
     """
     @Desc:Template files are deleted from secondary storage after download URL expires
     Step1:Deploy vm with default cent os template
     Step2:Stop the vm
     Step3:Create template from the vm's root volume
     Step4:Extract Template and wait for the download url to expire
     Step5:Deploy another vm with the template created at Step3
     Step6:Verify that vm deployment succeeds
     """
     params = [
         'extract.url.expiration.interval', 'extract.url.cleanup.interval'
     ]
     wait_time = 0
     for param in params:
         config = Configurations.list(
             self.apiClient,
             name=param,
         )
         self.assertEqual(
             validateList(config)[0], PASS,
             "Config list returned invalid response")
         wait_time = wait_time + int(config[0].value)
     self.debug("Total wait time for url expiry: %s" % wait_time)
     # Creating Virtual Machine
     self.virtual_machine = VirtualMachine.create(
         self.userapiclient,
         self.services["virtual_machine"],
         accountid=self.account.name,
         domainid=self.account.domainid,
         serviceofferingid=self.service_offering.id,
     )
     self.assertIsNotNone(self.virtual_machine,
                          "Virtual Machine creation failed")
     self.cleanup.append(self.virtual_machine)
     #Stop virtual machine
     self.virtual_machine.stop(self.userapiclient)
     list_volume = Volume.list(self.userapiclient,
                               virtualmachineid=self.virtual_machine.id,
                               type='ROOT',
                               listall=True)
     self.assertEqual(
         validateList(list_volume)[0], PASS,
         "list volumes with type ROOT returned invalid list")
     self.volume = list_volume[0]
     self.create_template = Template.create(self.userapiclient,
                                            self.services["template"],
                                            volumeid=self.volume.id,
                                            account=self.account.name,
                                            domainid=self.account.domainid)
     self.assertIsNotNone(self.create_template,
                          "Failed to create template from root volume")
     self.cleanup.append(self.create_template)
     """
     Extract template
     """
     try:
         Template.extract(self.userapiclient, self.create_template.id,
                          'HTTP_DOWNLOAD', self.zone.id)
     except Exception as e:
         self.fail("Extract template failed with error %s" % e)
     self.debug("Waiting for %s seconds for url to expire" %
                repr(wait_time + 20))
     time.sleep(wait_time + 20)
     self.debug("Waited for %s seconds for url to expire" %
                repr(wait_time + 20))
     """
     Deploy vm with the template created from the volume. After url expiration interval only
     url should be deleted not the template. To validate this deploy vm with the template
     """
     try:
         self.vm = VirtualMachine.create(
             self.userapiclient,
             self.services["virtual_machine"],
             accountid=self.account.name,
             domainid=self.account.domainid,
             serviceofferingid=self.service_offering.id,
             templateid=self.create_template.id)
         self.cleanup.append(self.vm)
     except Exception as e:
         self.fail("Template is automatically deleted after URL expired.\
                   So vm deployment failed with error: %s" % e)
     return
    def test_01_positive_test_1(self):
        """
        positive test for volume life cycle
        # 1. Deploy a vm [vm1] with shared storage and data disk
        # 2. Deploy a vm [vm2]with shared storage without data disk
        # 3.
        # 4. Create a new volume and attache to vm2
        # 5. Detach data disk from vm1 and download it
        #  Variance(1-9)
        # 6. Upload volume by providing url of downloaded volume in step 5
        # 7. Attach the volume to a different vm - vm2
        # 8. Try to delete an attached volume
        # 9. Create template from root volume of VM1
        # 10. Create new VM using the template created in step 9
        # 11. Delete the template
        # 12. Detach the disk from VM2 and re-attach the disk to VM1
        # 13.
        # 14.
        # 15.Migrate volume(detached) and then attach to a vm and live-migrate
        # 16.Upload volume of size smaller  than storage.max.volume.upload.size(leaving the negative case)
        # 17.NA
        # 18.
        # 19.NA
        # 20.Detach data disks from VM2 and delete volume

        """
        # 1. Deploy a vm [vm1] with shared storage and data disk
        self.virtual_machine_1 = VirtualMachine.create(self.userapiclient,
                                                       self.testdata["small"],
                                                       templateid=self.template.id,
                                                       accountid=self.account.name,
                                                       domainid=self.account.domainid,
                                                       serviceofferingid=self.service_offering_1.id,
                                                       zoneid=self.zone.id,
                                                       diskofferingid=self.disk_offering_1.id,
                                                       mode=self.testdata["mode"]
                                                       )
        verify_vm(self, self.virtual_machine_1.id)
        # List data volume for vm1
        list_volume = Volume.list(self.userapiclient,
                                  virtualmachineid=self.virtual_machine_1.id,
                                  type='DATADISK'
                                  )
        self.assertEqual(validateList(list_volume)[0], PASS, "Check List volume response for vm id  %s" % self.virtual_machine_1.id)
        list_data_volume_for_vm1 = list_volume[0]
        self.assertEqual(len(list_volume), 1, "There is no data disk attached to vm id:%s" % self.virtual_machine_1.id)
        self.assertEqual(list_data_volume_for_vm1.virtualmachineid, str(self.virtual_machine_1.id), "Check if volume state (attached) is reflected")
        # 2. Deploy a vm [vm2]with shared storage without data disk
        self.virtual_machine_2 = VirtualMachine.create(self.userapiclient,
                                                       self.testdata["small"],
                                                       templateid=self.template.id,
                                                       accountid=self.account.name,
                                                       domainid=self.account.domainid,
                                                       serviceofferingid=self.service_offering_1.id,
                                                       zoneid=self.zone.id,
                                                       mode=self.testdata["mode"]
                                                       )
        verify_vm(self, self.virtual_machine_2.id)

        #4. Create a new volume and attache to vm2
        self.volume = Volume.create(self.userapiclient,
                                    services=self.testdata["volume"],
                                    diskofferingid=self.disk_offering_1.id,
                                    zoneid=self.zone.id
                                    )

        list_data_volume = Volume.list(self.userapiclient,
                                       id=self.volume.id
                                       )
        self.assertEqual(validateList(list_data_volume)[0], PASS, "Check List volume response for volume %s" % self.volume.id)
        self.assertEqual(list_data_volume[0].id, self.volume.id, "check list volume response for volume id:  %s" % self.volume.id)
        self.debug("volume id %s got created successfully" % list_data_volume[0].id)
        # Attach volume to vm2
        self.virtual_machine_2.attach_volume(self.userapiclient,
                                             self.volume
                                             )
        verify_attach_volume(self, self.virtual_machine_2.id, self.volume.id)

        #Variance
        if self.zone.localstorageenabled:
            # V1.Create vm3 with local storage offering
            self.virtual_machine_local_3=VirtualMachine.create(self.userapiclient,
                                                               self.testdata["small"],
                                                               templateid=self.template.id,
                                                               accountid=self.account.name,
                                                               domainid=self.account.domainid,
                                                               serviceofferingid=self.service_offering_2.id,
                                                               zoneid=self.zone.id,
                                                               mode=self.testdata["mode"]
                                                               )
            verify_vm(self, self.virtual_machine_local_3.id)

            # V2.create two data disk on local storage
            self.local_volumes = []
            for i in range(2):

                    local_volume = Volume.create(self.userapiclient,
                                                 services=self.testdata["volume"],
                                                 diskofferingid=self.disk_offering_local.id,
                                                 zoneid=self.zone.id
                                                 )

                    list_local_data_volume = Volume.list(self.userapiclient,
                                                         id=local_volume.id
                                                         )
                    self.assertEqual(validateList(list_local_data_volume)[0], PASS, "Check List volume response for volume %s" % local_volume.id)
                    self.assertEqual(list_local_data_volume[0].id, local_volume.id, "check list volume response for volume id:  %s" % local_volume.id)
                    self.debug("volume id %s got created successfully" % list_local_data_volume[0].id)
                    self.local_volumes.append(local_volume)
            # V3.Attach local disk to vm1
            self.virtual_machine_1.attach_volume(self.userapiclient,
                                                 self.local_volumes[0]
                                                 )
            verify_attach_volume(self, self.virtual_machine_1.id, self.local_volumes[0].id)
        if self.list_storage:
            # V4.create vm4 with zone wide storage
            self.virtual_machine_zone_4 = VirtualMachine.create(self.userapiclient,
                                                                self.testdata["small"],
                                                                templateid=self.template.id,
                                                                accountid=self.account.name,
                                                                domainid=self.account.domainid,
                                                                serviceofferingid=self.tagged_so.id,
                                                                zoneid=self.zone.id,
                                                                mode=self.testdata["mode"]
                                                                )
            verify_vm(self, self.virtual_machine_zone_4.id)

            # V5.Create two data disk on zone  wide storage
            self.zone_volumes = []
            for i in range(2):

                    zone_volume = Volume.create(self.userapiclient,
                                                services=self.testdata["volume"],
                                                diskofferingid=self.disk_offering_tagged.id,
                                                zoneid=self.zone.id
                                                )

                    list_zone_data_volume = Volume.list(self.userapiclient,
                                                        id=zone_volume.id
                                                        )
                    self.assertEqual(validateList(list_zone_data_volume)[0], PASS, "Check List volume response for volume %s" % zone_volume.id)
                    self.assertEqual(list_zone_data_volume[0].id, zone_volume.id, "check list volume response for volume id:  %s" % zone_volume.id)
                    self.debug("volume id:%s got created successfully" % list_zone_data_volume[0].id)
                    self.zone_volumes.append(zone_volume)

            # V6.Attach data disk running on ZWPS to VM1 (root disk on shared)
            self.virtual_machine_1.attach_volume(self.userapiclient,
                                                 self.zone_volumes[0]
                                                 )
            verify_attach_volume(self, self.virtual_machine_1.id, self.zone_volumes[0].id)
            # V7. Create a cluster wide volume and attach to vm running on zone wide storage
            self.cluster_volume = Volume.create(self.userapiclient,
                                                services=self.testdata["volume"],
                                                diskofferingid=self.disk_offering_1.id,
                                                zoneid=self.zone.id
                                                )
            list_cluster_volume = Volume.list(self.userapiclient,
                                              id=self.cluster_volume.id
                                              )
            self.assertEqual(validateList(list_cluster_volume)[0], PASS, "Check List volume response for volume %s" % self.cluster_volume.id)
            self.assertEqual(list_cluster_volume[0].id, str(self.cluster_volume.id), "volume does not exist %s" % self.cluster_volume.id)
            self.debug("volume id %s got created successfuly" % list_cluster_volume[0].id)
            self.virtual_machine_zone_4.attach_volume(self.userapiclient,
                                                      self.cluster_volume
                                                      )
            verify_attach_volume(self, self.virtual_machine_zone_4.id, self.cluster_volume.id)
        if self.list_storage and self.zone.localstorageenabled:
            #V8.Attach zone wide volume to vm running on local storage
            self.virtual_machine_local_3.attach_volume(self.userapiclient,
                                                       self.zone_volumes[1]
                                                       )
            verify_attach_volume(self, self.virtual_machine_local_3.id, self.zone_volumes[1].id)
            # V9.Attach local volume to a vm running on zone wide storage
            self.virtual_machine_zone_4.attach_volume(self.userapiclient,
                                                      self.local_volumes[1]
                                                      )
            verify_attach_volume(self, self.virtual_machine_zone_4.id, self.local_volumes[1].id)
        # 5. Detach data disk from vm1 and download it
        self.virtual_machine_1.detach_volume(self.userapiclient,
                                             volume=list_data_volume_for_vm1
                                             )
        verify_detach_volume(self, self.virtual_machine_1.id, list_data_volume_for_vm1.id)
        # download detached volume
        self.extract_volume = Volume.extract(self.userapiclient,
                                             volume_id=list_data_volume_for_vm1.id,
                                             zoneid=self.zone.id,
                                             mode='HTTP_DOWNLOAD'
                                             )

        self.debug("extracted url is%s  :" % self.extract_volume.url)
        try:

            formatted_url = urllib.unquote_plus(self.extract_volume.url)
            self.debug("Attempting to download volume at url %s" % formatted_url)
            response = urllib.urlopen(formatted_url)
            self.debug("response from volume url %s" % response.getcode())
            fd, path = tempfile.mkstemp()
            self.debug("Saving volume %s to path %s" % (list_data_volume_for_vm1.id, path))
            os.close(fd)
            with open(path, 'wb') as fd:
                fd.write(response.read())
            self.debug("Saved volume successfully")
        except Exception:
            self.fail("Extract Volume Failed with invalid URL %s (vol id: %s)" % (self.extract_volume, list_data_volume_for_vm1.id))
        #Need to get format for downloaded volume ,for now using default format VHD
        if "OVA" in self.extract_volume.url.upper():
            self.testdata["upload_volume"]["format"] = "OVA"
        if "QCOW2" in self.extract_volume.url.upper():
            self.testdata["upload_volume"]["format"] = "QCOW2"
        # 6. Upload volume by providing url of downloaded volume in step 5
        self.upload_response = Volume.upload(self.userapiclient,
                                             zoneid=self.zone.id,
                                             url=self.extract_volume.url,
                                             services=self.testdata["upload_volume"]
                                             )
        self.upload_response.wait_for_upload(self.userapiclient
                                             )
        self.debug("uploaded volume id is %s" % self.upload_response.id)
        # 7. Attach the volume to a different vm - vm2
        self.virtual_machine_2.attach_volume(self.userapiclient,
                                             volume=self.upload_response
                                             )
        verify_attach_volume(self, self.virtual_machine_2.id, self.upload_response.id)
        # 8. Try to delete an attached volume
        try:
            self.volume.delete(self.userapiclient
                               )
            self.fail("Volume got deleted in attached state %s " % self.volume.id)
        except Exception as e:
            self.debug("Attached volume deletion failed because  %s" % e)
        #9. Create template from root volume of VM1(stop VM->create template -> start vm)

        self.virtual_machine_1.stop(self.userapiclient
                                    )

        self.list_root_disk_for_vm1 = Volume.list(self.userapiclient,
                                                  virtualmachineid=self.virtual_machine_1.id,
                                                  type='ROOT'
                                                  )
        self.assertEqual(validateList(self.list_root_disk_for_vm1)[0], PASS, "Check List volume response for vm %s" % self.virtual_machine_1.id)
        self.assertEqual(len(self.list_root_disk_for_vm1), 1, "list root disk for vm1 is empty : %s" % self.virtual_machine_1.id)
        self.template_from_vm1_root_disk = Template.create(self.userapiclient,
                                                           self.testdata["template"],
                                                           self.list_root_disk_for_vm1[0].id,
                                                           account=self.account.name,
                                                           domainid=self.account.domainid
                                                           )
        list_template = Template.list(self.userapiclient,
                                      templatefilter=self.testdata["templatefilter"],
                                      id=self.template_from_vm1_root_disk.id
                                      )
        self.assertEqual(validateList(list_template)[0], PASS, "Check List template response for template id %s" % self.template_from_vm1_root_disk.id)
        self.assertEqual(len(list_template), 1, "list template response is empty for template id  : %s" % list_template[0].id)
        self.assertEqual(list_template[0].id, self.template_from_vm1_root_disk.id, "list template id is not same as created template")
        self.debug("Template id:%s got created successfully" % self.template_from_vm1_root_disk.id)
        self.virtual_machine_1.start(self.userapiclient
                                     )
        # 10. Deploy a vm using template ,created  from vm1's root disk

        self.virtual_machine_3 = VirtualMachine.create(self.userapiclient,
                                                       self.testdata["small"],
                                                       templateid=self.template_from_vm1_root_disk.id,
                                                       accountid=self.account.name,
                                                       domainid=self.account.domainid,
                                                       serviceofferingid=self.service_offering_1.id,
                                                       zoneid=self.zone.id,
                                                       mode=self.testdata["mode"]
                                                       )
        verify_vm(self, self.virtual_machine_3.id)

        # 11.delete the template created from root disk of vm1
        try:
            self.template_from_vm1_root_disk.delete(self.userapiclient
                                                    )
            self.debug("Template id: %s got deleted successfuly" % self.template_from_vm1_root_disk.id)
        except Exception as e:
            raise Exception("Template deletion failed with error %s" % e)
        list_template = Template.list(self.userapiclient,
                                      templatefilter=self.testdata["templatefilter"],
                                      id=self.template_from_vm1_root_disk.id
                                      )
        self.assertEqual(list_template, None, "Template is not deleted, id %s:" % self.template_from_vm1_root_disk.id)
        self.debug("Template id%s got deleted successfully" % self.template_from_vm1_root_disk.id)

        # List vm and check the state of vm
        verify_vm(self, self.virtual_machine_3.id)

        #12.Detach the disk from VM2 and re-attach the disk to VM1
        self.virtual_machine_2.detach_volume(self.userapiclient,
                                             volume=self.upload_response
                                             )
        verify_detach_volume(self, self.virtual_machine_2.id, self.upload_response.id)

        self.virtual_machine_1.attach_volume(self.userapiclient,
                                             volume=self.upload_response
                                             )

        verify_attach_volume(self, self.virtual_machine_1.id, self.upload_response.id)

        # 15.Migrate volume(detached) and then attach to a vm and live-migrate
        self.migrate_volume = Volume.create(self.userapiclient,
                                            services=self.testdata["volume"],
                                            diskofferingid=self.disk_offering_1.id,
                                            zoneid=self.zone.id
                                            )
        list_volume = Volume.list(self.apiclient,
                                  id=self.migrate_volume.id
                                  )
        self.assertEqual(validateList(list_volume)[0], PASS, "Check List volume response for volume %s" % self.migrate_volume.id)
        self.assertEqual(list_volume[0].id, str(self.migrate_volume.id), "volume does not exist %s" % self.migrate_volume.id)
        self.debug("volume id %s got created successfuly" % list_volume[0].id)

        self.virtual_machine_1.attach_volume(self.userapiclient,
                                             self.migrate_volume
                                             )
        verify_attach_volume(self, self.virtual_machine_1.id, self.migrate_volume.id)

        self.virtual_machine_1.detach_volume(self.userapiclient,
                                             volume=self.migrate_volume
                                             )
        verify_detach_volume(self, self.virtual_machine_1.id, self.migrate_volume.id)

        list_volume = Volume.list(self.apiclient,
                                  id=self.migrate_volume.id
                                  )
        self.assertEqual(validateList(list_volume)[0], PASS, "Check List volume response for volume %s" % self.migrate_volume.id)
        self.assertEqual(list_volume[0].id, str(self.migrate_volume.id), "volume does not exist %s" % self.migrate_volume.id)
        self.debug("volume id %s got created successfuly" % list_volume[0].id)
        list_pool = StoragePool.list(self.apiclient,
                                     id=list_volume[0].storageid
                                     )
        self.assertEqual(validateList(list_pool)[0], PASS, "Check List pool response for storage id %s" % list_volume[0].storageid)
        self.assertGreater(len(list_pool), 0, "Check the list list storagepoolresponse for vm id:  %s" % list_volume[0].storageid)
        list_pools = StoragePool.list(self.apiclient,
                                      scope=list_pool[0].scope
                                      )
        self.assertEqual(validateList(list_pools)[0], PASS, "Check List pool response for scope %s" % list_pool[0].scope)
        self.assertGreater(len(list_pools), 0, "Check the list vm response for scope :%s" % list_volume[0].scope)
        storagepoolid = None
        for i in range(len(list_pools)):
            if list_volume[0].storageid != list_pools[i].id:
                storagepoolid = list_pools[i].id
                break
            else:
                self.debug("No pool available for volume migration ")

        if storagepoolid is not None:
            try:
                volume_migrate = Volume.migrate(self.apiclient,
                                                storageid=storagepoolid,
                                                volumeid=self.migrate_volume.id
                                                )
            except Exception as e:
                raise Exception("Volume migration failed with error %s" % e)

            self.virtual_machine_2.attach_volume(self.userapiclient,
                                                 self.migrate_volume
                                                 )
            verify_attach_volume(self, self.virtual_machine_2.id, self.migrate_volume.id)

            pool_for_migration = StoragePool.listForMigration(self.apiclient,
                                                              id=self.migrate_volume.id
                                                              )
            self.assertEqual(validateList(pool_for_migration)[0], PASS, "Check list pool For Migration response for volume %s" % self.migrate_volume.id)
            self.assertGreater(len(pool_for_migration), 0, "Check the listForMigration response for volume :%s" % self.migrate_volume.id)
            try:
                volume_migrate = Volume.migrate(self.apiclient,
                                                storageid=pool_for_migration[0].id,
                                                volumeid=self.migrate_volume.id,
                                                livemigrate=True
                                                )
            except Exception as e:
                raise Exception("Volume migration failed with error %s" % e)
        else:
            try:
                self.migrate_volume.delete(self.userapiclient
                                           )
                self.debug("volume id:%s got deleted successfully " % self.migrate_volume.id)
            except Exception as e:
                raise Exception("Volume deletion failed with error %s" % e)
        # 16.Upload volume of size smaller  than storage.max.volume.upload.size(leaving the negative case)
        self.testdata["upload_volume"]["format"] = "VHD"
        volume_upload = Volume.upload(self.userapiclient,
                                      self.testdata["upload_volume"],
                                      zoneid=self.zone.id
                                      )
        volume_upload.wait_for_upload(self.userapiclient
                                      )
        self.debug("volume id :%s got uploaded successfully is " % volume_upload.id)

        # 20.Detach data disk from vm 2 and delete the volume
        self.virtual_machine_2.detach_volume(self.userapiclient,
                                             volume=self.volume
                                             )
        verify_detach_volume(self, self.virtual_machine_2.id, self.volume.id)

        try:
            self.volume.delete(self.userapiclient
                               )
            self.debug("volume id:%s got deleted successfully " % self.volume.id)
        except Exception as e:
            raise Exception("Volume deletion failed with error %s" % e)
    def test_19_template_tag(self):
        """ Test creation, listing and deletion tag on templates
        """

        if self.hypervisor.lower() in ['lxc']:
            self.skipTest(
                "template creation from volume feature is not supported on %s"
                % self.hypervisor.lower())

        try:

            noffering = NetworkOffering.list(
                self.user_api_client,
                name="DefaultIsolatedNetworkOfferingWithSourceNatService")
            vm4network = Network.create(self.user_api_client,
                                        self.services["network"],
                                        accountid=self.account.name,
                                        domainid=self.account.domainid,
                                        networkofferingid=noffering[0].id,
                                        zoneid=self.zone.id)

            list_nw_response = Network.list(self.user_api_client,
                                            id=vm4network.id)
            self.assertEqual(
                isinstance(list_nw_response, list), True,
                "Check list response returns a valid networks list")

            vm_1 = VirtualMachine.create(
                self.user_api_client,
                self.services["small"],
                templateid=self.template.id,
                networkids=vm4network.id,
                serviceofferingid=self.service_offering.id,
                accountid=self.account.name,
                domainid=self.account.domainid,
                mode=self.services['mode'],
                startvm="true")
            time.sleep(600)
            self.debug("Stopping the virtual machine: %s" % vm_1.name)
            # Stop virtual machine
            vm_1.stop(self.user_api_client)
        except Exception as e:
            self.fail("Failed to stop VM: %s" % e)

        timeout = self.services["timeout"]
        while True:
            list_volume = Volume.list(self.user_api_client,
                                      virtualmachineid=vm_1.id,
                                      type='ROOT',
                                      listall=True)
            if isinstance(list_volume, list):
                break
            elif timeout == 0:
                raise Exception("List volumes failed.")

            time.sleep(5)
            timeout = timeout - 1

        self.volume = list_volume[0]

        self.debug("Creating template from ROOT disk of virtual machine: %s" %
                   vm_1.name)
        # Create template from volume
        template = Template.create(self.user_api_client,
                                   self.services["template"], self.volume.id)
        self.cleanup.append(template)
        self.debug("Created the template(%s). Now restarting the userVm: %s" %
                   (template.name, vm_1.name))
        vm_1.start(self.user_api_client)

        self.debug("Creating a tag for the template")
        tag = Tag.create(self.user_api_client,
                         resourceIds=template.id,
                         resourceType='Template',
                         tags={'OS': 'windows8'})
        self.debug("Tag created: %s" % tag.__dict__)

        tags = Tag.list(self.user_api_client,
                        listall=True,
                        resourceType='Template',
                        key='OS',
                        value='windows8')
        self.assertEqual(isinstance(tags, list), True,
                         "List tags should not return empty response")
        self.assertEqual(tags[0].value, 'windows8',
                         'The tag should have original value')

        Template.list(
            self.user_api_client,
            templatefilter=self.services["template"]["templatefilter"],
            listall=True,
            key='OS',
            value='windows8')

        self.debug("Deleting the created tag..")
        try:
            tag.delete(self.user_api_client,
                       resourceIds=template.id,
                       resourceType='Template',
                       tags={'OS': 'windows8'})
        except Exception as e:
            self.fail("Failed to delete the tag - %s" % e)

        self.debug("Verifying if tag is actually deleted!")
        tags = Tag.list(self.user_api_client,
                        listall=True,
                        resourceType='Template',
                        key='OS',
                        value='windows8')
        self.assertEqual(tags, None, "List tags should return empty response")
        return
示例#13
0
    def setUpClass(cls):

        cls.testClient = super(TestTemplates, cls).getClsTestClient()
        cls.api_client = cls.testClient.getApiClient()

        cls.services = Services().services
        # Get Zone, Domain and templates
        cls.domain = get_domain(cls.api_client)
        cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
        cls.services['mode'] = cls.zone.networktype
        #populate second zone id for iso copy
        cmd = listZones.listZonesCmd()
        zones = cls.api_client.listZones(cmd)
        if not isinstance(zones, list):
            raise Exception("Failed to find zones.")
        if len(zones) >= 2:
            cls.services["destzoneid"] = zones[1].id

        template = get_template(cls.api_client, cls.zone.id,
                                cls.services["ostype"])
        cls.services["virtual_machine"]["zoneid"] = cls.zone.id
        cls._cleanup = []
        try:
            cls.account = Account.create(cls.api_client,
                                         cls.services["account"],
                                         domainid=cls.domain.id)
            cls._cleanup.append(cls.account)

            cls.services["account"] = cls.account.name
            cls.service_offering = ServiceOffering.create(
                cls.api_client, cls.services["service_offering"])
            cls._cleanup.append(cls.service_offering)

            # create virtual machine
            cls.virtual_machine = VirtualMachine.create(
                cls.api_client,
                cls.services["virtual_machine"],
                templateid=template.id,
                accountid=cls.account.name,
                domainid=cls.account.domainid,
                serviceofferingid=cls.service_offering.id,
            )
            #Stop virtual machine
            cls.virtual_machine.stop(cls.api_client)

            timeout = cls.services["timeout"]

            while True:
                list_volume = Volume.list(
                    cls.api_client,
                    virtualmachineid=cls.virtual_machine.id,
                    type='ROOT',
                    listall=True)
                if isinstance(list_volume, list):
                    break
                elif timeout == 0:
                    raise Exception("List volumes failed.")

                time.sleep(5)
                timeout = timeout - 1

            cls.volume = list_volume[0]

            #Create template from volume
            cls.template = Template.create(cls.api_client,
                                           cls.services["template"],
                                           cls.volume.id)
        except Exception as e:
            cls.tearDownClass()
            raise unittest.SkipTest("Failure in setUpClass: %s" % e)
示例#14
0
                    services["displaytext"] = "Debian"
                    services["name"] = "deb"
                    if options.upload_tmpl is not None:
                        services["hypervisor"] = "KVM"
                        services["format"] = "QCOW2"
                        services["url"] = options.upload_tmpl
                    if options.upload_iso is not None:
                        services["url"] = options.upload_iso
                    services["ostype"] = "Debian GNU/Linux 7(64-bit)"
                    services["zoneid"] = zone.id
                    tmp_dict = {}
                    if options.upload_tmpl is not None:
                        my_templ = Template(tmp_dict)
                        if my_templ.register(apiClient, services) == FAILED:
                            print "Uploading template failed"
                            tc_run_logger.debug(
                                "\n=== Uploading template failed ===")
                            exit(1)
                    if options.upload_iso is not None:
                        my_templ = Iso(tmp_dict)
                        if my_templ.create(apiClient, services) == FAILED:
                            print "Uploading template failed"
                            tc_run_logger.debug(
                                "\n=== Uploading template failed ===")
                            exit(1)
                else:
                    print "Zone is not ready"
        else:
            print "No zones"
    exit(0)
    def test_16_create_template_volume(self):
        """Test Create template from volume
        """

        noffering=NetworkOffering.list(
                     self.user_api_client,
                     name="DefaultIsolatedNetworkOfferingWithSourceNatService"
                     )
        vm2network=Network.create(
                                 self.user_api_client,
                                self.services["network"],
                                accountid=self.account.name,
                                domainid=self.account.domainid,
                                networkofferingid=noffering[0].id,
                                zoneid=self.zone.id
                                 )

        list_nw_response = Network.list(
                                            self.user_api_client,
                                            id=vm2network.id
                                            )
        self.assertEqual(
                            isinstance(list_nw_response, list),
                            True,
                            "Check list response returns a valid networks list"
                        )

        templatevm = VirtualMachine.create(
                                    self.user_api_client,
                                    self.services["small"],
                                    templateid=self.template.id,
                                    accountid=self.account.name,
                                    domainid=self.account.domainid,
                                    networkids=vm2network.id,
                                    serviceofferingid=self.service_offering.id,
                                    mode=self.services['mode'],
                                    startvm="true"
                                    )
        time.sleep(600)
        vm_response = VirtualMachine.list(
                            self.user_api_client,
                            id=templatevm.id)

        self.assertNotEqual(
                            len(vm_response),
                            0,
                            "Check VMs available in List VMs response"
                        )
        vm = vm_response[0]
        self.assertEqual(
                            vm.state,
                            'Running',
                            "Check the state of VM created from Template"
                        )

        templatevm.stop(self.user_api_client,forced="false")

        vm_response = VirtualMachine.list(
                            self.user_api_client,
                            id=templatevm.id)

        vm = vm_response[0]
        self.assertEqual(
                            vm.state,
                            'Stopped',
                            "Check the state of VM is in Stopped state before creating the Template"
                        )

        list_volume_response = Volume.list(
            self.user_api_client,
            virtualmachineid=vm.id,
            type="ROOT",
            listall=True
        )

        #Create template from Virtual machine and Volume ID
        roottemplate = Template.create(
                                self.user_api_client,
                                self.services["interop"]["template"],
                                volumeid=list_volume_response[0].id,
                                account=self.account.name,
                                domainid=self.domain.id,
                                )

        time.sleep(600)

        list_template_response = Template.list(
                                    self.user_api_client,
                                    templatefilter=\
                                    self.services["templatefilter"],
                                    id=roottemplate.id
                                    )

        self.assertEqual(
                            isinstance(list_template_response, list),
                            True,
                            "Check list response returns a valid list"
                        )
        #Verify template response to check whether template added successfully
        self.assertNotEqual(
                            len(list_template_response),
                            0,
                            "Check template available in List Templates"
                        )
        template_response = list_template_response[0]

        self.assertEqual(
                            template_response.displaytext,
                            self.services["interop"]["template"]["displaytext"],
                            "Check display text of newly created template"
                        )
        name = template_response.name
        self.assertEqual(
                            name.count(self.services["interop"]["template"]["name"]),
                            1,
                            "Check name of newly created template"
                        )


        templatevm.delete(self.apiclient)
        vm2network.delete(self.user_api_client)

        vm3network=Network.create(
                                 self.user_api_client,
                                self.services["network"],
                                accountid=self.account.name,
                                domainid=self.account.domainid,
                                networkofferingid=noffering[0].id,
                                zoneid=self.zone.id
                                 )

        list_nw_response = Network.list(
                                            self.user_api_client,
                                            id=vm3network.id
                                            )
        self.assertEqual(
                            isinstance(list_nw_response, list),
                            True,
                            "Check list response returns a valid networks list"
                        )


        templatevm = VirtualMachine.create(
                                    self.user_api_client,
                                    self.services["small"],
                                    templateid=roottemplate.id,
                                    networkids=vm3network.id,
                                    serviceofferingid=self.service_offering.id,
                                    accountid=self.account.name,
                                    domainid=self.account.domainid,
                                    mode=self.services['mode'],
                                    startvm="true"
                                    )
        time.sleep(600)
        vm_response = VirtualMachine.list(
                            self.user_api_client,
                            id=templatevm.id)

        self.assertNotEqual(
                            len(vm_response),
                            0,
                            "Check VMs available in List VMs response"
                        )
        vm = vm_response[0]
        self.assertEqual(
                            vm.state,
                            'Running',
                            "Check the state of VM created from Template"
                        )

        # Delete the template
        roottemplate.delete(self.user_api_client)

        list_template_response = Template.list(
                                    self.user_api_client,
                                    templatefilter=\
                                    self.services["template"]["templatefilter"],
                                    id=roottemplate.id,
                                    zoneid=self.zone.id
                                    )
        self.assertEqual(
                            list_template_response,
                            None,
                            "Check template available in List Templates"
                        )

        templatevm.delete(self.apiclient)

        vm3network.delete(self.user_api_client)
        return
    def setUpClass(cls):
        cls.testClient = super(TestVMPasswordEnabled, cls).getClsTestClient()
        cls.api_client = cls.testClient.getApiClient()

        cls.services = Services().services
        # Get Zone, Domain and templates
        domain = get_domain(cls.api_client)
        zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
        cls.services['mode'] = zone.networktype
        template = get_template(
            cls.api_client,
            zone.id,
            cls.services["ostype"]
        )
        # Set Zones and disk offerings
        cls.services["small"]["zoneid"] = zone.id
        cls.services["small"]["template"] = template.id

        # Create VMs, NAT Rules etc
        cls.account = Account.create(
            cls.api_client,
            cls.services["account"],
            domainid=domain.id
        )

        cls.small_offering = ServiceOffering.create(
            cls.api_client,
            cls.services["service_offerings"]["small"]
        )

        cls.virtual_machine = VirtualMachine.create(
            cls.api_client,
            cls.services["small"],
            accountid=cls.account.name,
            domainid=cls.account.domainid,
            serviceofferingid=cls.small_offering.id,
            mode=cls.services["mode"]
        )

        networkid = cls.virtual_machine.nic[0].networkid
        cls.hypervisor = cls.testClient.getHypervisorInfo()

        # create egress rule to allow wget of my cloud-set-guest-password
        # script
        if zone.networktype.lower() == 'advanced':
            EgressFireWallRule.create(
                cls.api_client,
                networkid=networkid,
                protocol=cls.services["egress"]["protocol"],
                startport=cls.services["egress"]["startport"],
                endport=cls.services["egress"]["endport"],
                cidrlist=cls.services["egress"]["cidrlist"])

        cls.virtual_machine.password = cls.services["small"]["password"]
        ssh = cls.virtual_machine.get_ssh_client()

        # below steps are required to get the new password from VR
        # (reset password)
        # http://cloudstack.org/dl/cloud-set-guest-password
        # Copy this file to /etc/init.d
        # chmod +x /etc/init.d/cloud-set-guest-password
        # chkconfig --add cloud-set-guest-password

        cmds = [
            "cd /etc/init.d;wget http://people.apache.org/~tsp/cloud-set-guest-password",
            "chmod +x /etc/init.d/cloud-set-guest-password",
            "chkconfig --add cloud-set-guest-password",
        ]
        for c in cmds:
            ssh.execute(c)

        # Adding delay of 120 sec to avoid data loss due to timing issue
        time.sleep(120)

        # Stop virtual machine
        cls.virtual_machine.stop(cls.api_client)

        # Poll listVM to ensure VM is stopped properly
        timeout = cls.services["timeout"]
        while True:
            time.sleep(cls.services["sleep"])

            # Ensure that VM is in stopped state
            list_vm_response = list_virtual_machines(
                cls.api_client,
                id=cls.virtual_machine.id
            )

            if isinstance(list_vm_response, list):

                vm = list_vm_response[0]
                if vm.state == 'Stopped':
                    break

            if timeout == 0:
                raise Exception(
                    "Failed to stop VM (ID: %s) " %
                    vm.id)

            timeout = timeout - 1

        list_volume = list_volumes(
            cls.api_client,
            virtualmachineid=cls.virtual_machine.id,
            type='ROOT',
            listall=True
        )
        if isinstance(list_volume, list):
            cls.volume = list_volume[0]
        else:
            raise Exception(
                "Exception: Unable to find root volume for VM: %s" %
                cls.virtual_machine.id)

        cls.services["template"]["ostype"] = cls.services["ostype"]
        cls.services["template"]["ispublic"] = True
        # Create templates for Edit, Delete & update permissions testcases
        cls.pw_enabled_template = Template.create(
            cls.api_client,
            cls.services["template"],
            cls.volume.id,
        )
        # Delete the VM - No longer needed
        cls.virtual_machine.delete(cls.api_client, expunge=True)
        cls.services["small"]["template"] = cls.pw_enabled_template.id

        cls.vm = VirtualMachine.create(
            cls.api_client,
            cls.services["small"],
            accountid=cls.account.name,
            domainid=cls.account.domainid,
            serviceofferingid=cls.small_offering.id,
            mode=cls.services["mode"]
        )
        cls._cleanup = [
            cls.small_offering,
            cls.pw_enabled_template,
            cls.account
        ]
示例#17
0
    def test_08_pt_startvm_false_password_enabled_template(self):
        """ Positive test for stopped VM test path - T10

        # 1   Create a password enabled template
        # 2.  Deploy a new VM with password enabled template
        # 3.  Verify that VM is in stopped state
        # 4.  Start the VM, verify that it is in running state
        # 5.  Verify that new password is generated for the VM
        """
        vm_for_template = VirtualMachine.create(
            self.userapiclient,
            self.testdata["small"],
            templateid=self.defaultTemplateId,
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id,
            zoneid=self.zone.id,
            mode=self.zone.networktype,
            networkids=[self.networkid, ] if self.networkid else None)

        vm_for_template.password = self.testdata["virtual_machine"]["password"]
        ssh = vm_for_template.get_ssh_client()

        # below steps are required to get the new password from
        # VR(reset password)
        # http://cloudstack.org/dl/cloud-set-guest-password
        # Copy this file to /etc/init.d
        # chmod +x /etc/init.d/cloud-set-guest-password
        # chkconfig --add cloud-set-guest-password
        # similar steps to get SSH key from web so as to make it ssh enabled

        cmds = [
            "cd /etc/init.d;wget http://people.apache.org/~tsp/\
                    cloud-set-guest-password",
            "chmod +x /etc/init.d/cloud-set-guest-password",
            "chkconfig --add cloud-set-guest-password"]
        for c in cmds:
            ssh.execute(c)

        # Stop virtual machine
        vm_for_template.stop(self.userapiclient)

        list_volume = Volume.list(
            self.userapiclient,
            virtualmachineid=vm_for_template.id,
            type='ROOT',
            listall=True)

        if isinstance(list_volume, list):
            self.volume = list_volume[0]
        else:
            raise Exception(
                "Exception: Unable to find root volume for VM: %s" %
                vm_for_template.id)

        self.testdata["template"]["ostype"] = self.testdata["ostype"]
        # Create templates for Edit, Delete & update permissions testcases
        pw_ssh_enabled_template = Template.create(
            self.userapiclient,
            self.testdata["template"],
            self.volume.id,
            account=self.account.name,
            domainid=self.account.domainid
        )
        self.cleanup.append(pw_ssh_enabled_template)
        # Delete the VM - No longer needed
        vm_for_template.delete(self.apiclient)

        # Create VM in account
        virtual_machine = VirtualMachine.create(
            self.userapiclient,
            self.testdata["small"],
            templateid=self.defaultTemplateId,
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id,
            zoneid=self.zone.id,
            startvm=False,
            mode=self.zone.networktype,
            networkids=[self.networkid, ] if self.networkid else None
        )
        self.cleanup.append(virtual_machine)

        response = virtual_machine.getState(
            self.apiclient,
            VirtualMachine.STOPPED)
        self.assertEqual(response[0], PASS, response[1])

        virtual_machine.start(self.userapiclient)

        vms = virtual_machine.list(
            self.userapiclient,
            id=virtual_machine.id,
            listall=True)

        self.assertEqual(
            validateList(vms)[0],
            PASS,
            "vms list validation failed"
        )
        self.assertNotEqual(
            str(vms[0].password),
            str(virtual_machine.password),
            "New password should be generated for the VM"
        )
        return
    def test_02_template_permissions(self):
        """
        @Desc: Test to create Public Template by registering or by snapshot and volume when
        Global parameter 'allow.public.user.template' is set to  False
        @steps:
        1.Set Global parameter 'allow.public.user.template' as False. Restart Management server
        2. Create a domain
        3. Create a domain admin and a domain user
        4. Create a vm as domain user
        5. take snapshot of root disk as user vm
        6. try to create public template from snapshot . It should fail
        7. stop the VM
        8. take the public template from volume. it should fail
        9. register a public template as a domain user . it should fail
        10. create a VM  as domain admin
        11. create a snapshot of root disk as domain admin
        12 create a public template of the snapshot .it should fail
        13. Register a public template as domain admin. it should fail
        14 Stop the vm as domain admin
        15. Create a template from volume as domain admin . it should fail

        """
        self.updateConfigurAndRestart("allow.public.user.templates", "false")
        
        user_account = Account.create(
            self.apiclient,
            self.testdata["account2"],
            admin=False,
            domainid=self.domain.id
        )
        admin_user = self.account.user[0]
        self.admin_api_client = self.testClient.getUserApiClient(
            admin_user.username,
            self.domain.name)
        user = user_account.user[0]
        self.user_api_client = self.testClient.getUserApiClient(
            user.username,
            self.domain.name)

        self.testdata["templates"]["ispublic"] = True
        # Register new public template as domain user
        # Exception should be raised for registering public template
        try:
            template = Template.register(
                self.user_api_client,
                self.testdata["templates"],
                zoneid=self.zone.id,
                account=user_account.name,
                domainid=user_account.domainid,
                hypervisor=self.hypervisor
            )
            self.updateConfigurAndRestart("allow.public.user.templates", "true")
            self.fail("Template creation passed for user")
        except CloudstackAPIException  as e:
            self.assertRaises("Exception Raised : %s" % e)
        # Register new public template as domain admin
        # Exception should be raised for registering public template
        try:
            template = Template.register(
                self.admin_api_client,
                self.testdata["templates"],
                zoneid=self.zone.id,
                account=self.account.name,
                domainid=self.account.domainid,
                hypervisor=self.hypervisor
            )
            self.updateConfigurAndRestart("allow.public.user.templates", "true")
            self.fail("Template creation passed for domain admin")
        except CloudstackAPIException  as e:
            self.assertRaises("Exception Raised : %s" % e)

        user_vm_created = VirtualMachine.create(
            self.user_api_client,
            self.testdata["virtual_machine"],
            accountid=user_account.name,
            domainid=user_account.domainid,
            serviceofferingid=self.service_offering.id,
        )
        self.assertIsNotNone(user_vm_created,
                             "VM creation failed"
        )
        # Get the Root disk of VM
        volume = list_volumes(
            self.user_api_client,
            virtualmachineid=user_vm_created.id,
            type='ROOT',
            listall=True
        )
        snapshot_created = Snapshot.create(
            self.user_api_client,
            volume[0].id,
            account=user_account.name,
            domainid=user_account.domainid
        )
        self.assertIsNotNone(
            snapshot_created,
            "Snapshot creation failed"
        )
        self.debug("Creating a template from snapshot: %s" % snapshot_created.id)
        #
        # Generate public template from the snapshot
        self.testdata["template"]["ispublic"] = True
        try:
            user_template = Template.create_from_snapshot(
                self.user_api_client,
                snapshot_created,
                self.testdata["template"]
            )
            self.updateConfigurAndRestart("allow.public.user.templates", "true")
            self.fail("Template creation passed from snapshot for domain user")
        except CloudstackAPIException  as e:
            self.assertRaises("Exception Raised : %s" % e)

        VirtualMachine.stop(user_vm_created, self.user_api_client)
        list_stopped_vms_after = VirtualMachine.list(
            self.user_api_client,
            listall=self.testdata["listall"],
            domainid=user_account.domainid,
            state="Stopped")
        status = validateList(list_stopped_vms_after)
        self.assertEquals(
            PASS,
            status[0],
            "Stopped VM is not in Stopped state"
        )
        try:
            user_template = Template.create(
                self.user_api_client, self.testdata["template"],
                volume[0].id
            )
            self.updateConfigurAndRestart("allow.public.user.templates", "true")
            self.fail("Template creation passed from volume for domain user")
        except CloudstackAPIException  as e:
            self.assertRaises("Exception Raised : %s" % e)

        admin_vm_created = VirtualMachine.create(
            self.admin_api_client,
            self.testdata["virtual_machine"],
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id,
        )
        self.assertIsNotNone(
            admin_vm_created,
            "VM creation failed"
        )
        # Get the Root disk of VM
        volume = list_volumes(
            self.admin_api_client,
            virtualmachineid=admin_vm_created.id,
            type='ROOT',
            listall=True
        )
        snapshot_created = Snapshot.create(
            self.admin_api_client,
            volume[0].id,
            account=self.account.name,
            domainid=self.account.domainid
        )
        self.assertIsNotNone(
            snapshot_created,
            "Snapshot creation failed"
        )
        self.debug("Creating a template from snapshot: %s" % snapshot_created.id)
        #
        #    Generate public template from the snapshot
        try:
            admin_template = Template.create_from_snapshot(
                self.admin_api_client,
                snapshot_created,
                self.testdata["template"]
            )
            self.updateConfigurAndRestart("allow.public.user.templates", "true")
            self.fail("Template creation passed from snapshot for domain admin")
        except CloudstackAPIException  as e:
            self.assertRaises("Exception Raised : %s" % e)

        VirtualMachine.stop(admin_vm_created, self.admin_api_client)
        list_stopped_vms_after = VirtualMachine.list(
            self.admin_api_client,
            listall=self.testdata["listall"],
            domainid=self.account.domainid,
            state="Stopped")
        status = validateList(list_stopped_vms_after)
        self.assertEquals(
            PASS,
            status[0],
            "Stopped VM is not in Stopped state"
        )
        try:
            admin_template = Template.create(
                self.admin_api_client, self.testdata["template"],
                volume[0].id
            )
            self.updateConfigurAndRestart("allow.public.user.templates", "true")
            self.fail("Template creation passed from volume for domain admin")
        except CloudstackAPIException  as e:
            self.assertRaises("Exception Raised : %s" % e)

        self.updateConfigurAndRestart("allow.public.user.templates", "true")
        return
示例#19
0
    def test_02_create__template_new_resized_rootvolume_size(self):
        """Test create Template resized root volume

        # Validate the following

        # 1. Deploy a VM without any disk offering (only root disk)
        # 2. Perform(resize)  of the root  volume
        # 3. Stop the vm
        # 4. Create a template from  resized  root volume
        """

        result = self.setupAccounts()
        self.assertEqual(result[0], PASS, result[1])
        apiclient = self.testClient.getUserApiClient(
            UserName=self.parentd_admin.name,
            DomainName=self.parentd_admin.domain)
        self.assertNotEqual(
            apiclient, FAILED, "Failed to get api client\
                            of account: %s" % self.parentd_admin.name)

        # deploy a vm
        try:
            if self.updateclone:

                self.virtual_machine = VirtualMachine.create(
                    apiclient,
                    self.services["virtual_machine"],
                    accountid=self.parentd_admin.name,
                    domainid=self.parent_domain.id,
                    serviceofferingid=self.services_offering_vmware.id,
                    mode=self.zone.networktype)
            else:
                self.virtual_machine = VirtualMachine.create(
                    apiclient,
                    self.services["virtual_machine"],
                    accountid=self.parentd_admin.name,
                    domainid=self.parent_domain.id,
                    serviceofferingid=self.service_offering.id,
                    mode=self.zone.networktype)

            # listVirtual macine
            list_vms = VirtualMachine.list(apiclient,
                                           id=self.virtual_machine.id)
            self.debug("Verify listVirtualMachines response"
                       " for virtual machine: %s" % self.virtual_machine.id)
            res = validateList(list_vms)
            self.assertNotEqual(res[2], INVALID_INPUT, "Invalid list response")
            self.cleanup.append(self.virtual_machine)
            vm = list_vms[0]
            self.assertEqual(vm.id, self.virtual_machine.id,
                             "Virtual Machine ids do not match")
            self.assertEqual(vm.name, self.virtual_machine.name,
                             "Virtual Machine names do not match")
            self.assertEqual(vm.state,
                             "Running",
                             msg="VM is not in Running state")
            # get root vol from created vm, verify it is correct size
            list_volume_response = Volume.list(
                apiclient,
                virtualmachineid=self.virtual_machine.id,
                type='ROOT',
                listall='True')
            res = validateList(list_volume_response)
            self.assertNotEqual(
                res[2], INVALID_INPUT,
                "listVolumes returned invalid object in response")
            rootvolume = list_volume_response[0]
            newsize = (rootvolume.size >> 30) + 2
            result = self.chk_volume_resize(apiclient, vm)
            if result:
                try:
                    # create a template from stopped VM instances root volume
                    if vm.state == "Running":
                        self.virtual_machine.stop(apiclient)
                    template_from_root = Template.create(
                        apiclient,
                        self.services["template"],
                        volumeid=rootvolume.id,
                        account=self.parentd_admin.name,
                        domainid=self.parent_domain.id)
                    list_template_response = Template.list(
                        apiclient,
                        id=template_from_root.id,
                        templatefilter="all")
                    res = validateList(list_template_response)
                    self.assertNotEqual(
                        res[2], INVALID_INPUT,
                        "Check if template exists in ListTemplates")
                    # Deploy new virtual machine using template
                    self.virtual_machine2 = VirtualMachine.create(
                        apiclient,
                        self.services["virtual_machine"],
                        templateid=template_from_root.id,
                        accountid=self.parentd_admin.name,
                        domainid=self.parent_domain.id,
                        serviceofferingid=self.service_offering.id,
                    )

                    vm_response = VirtualMachine.list(
                        apiclient,
                        id=self.virtual_machine2.id,
                        account=self.parentd_admin.name,
                        domainid=self.parent_domain.id)
                    res = validateList(vm_response)
                    self.assertNotEqual(
                        res[2], INVALID_INPUT,
                        "Check for list VM response return valid list")
                    self.cleanup.append(self.virtual_machine2)
                    self.cleanup.reverse()
                    vm2 = vm_response[0]
                    self.assertEqual(
                        vm2.state, 'Running',
                        "Check the state of VM created from Template")
                    list_volume_response = Volume.list(apiclient,
                                                       virtualmachineid=vm2.id,
                                                       type='ROOT',
                                                       listall='True')
                    self.assertEqual(
                        list_volume_response[0].size,
                        (newsize * 1024 * 1024 * 1024),
                        "Check for root volume size  not matched with template size"
                    )
                except Exception as e:
                    raise Exception("Exception while resizing the "
                                    "root volume: %s" % e)

            else:
                self.debug(" volume resize failed for root volume")
        except Exception as e:
            raise Exception("Exception while performing"
                            " template creation from "
                            "resized_root_volume : %s" % e)

        return
    def test_07_templates_per_project(self):
        """Test Templates limit per project
        """
        # 1. set max no of templates per project to 1.
        # 2. Create a template in this project. Both template should be in
        #    ready state
        # 3. Try create 2nd template in the project. It should give the user
        #    appropriate error and an alert should be generated.

        # Reset the volume limits
        update_resource_limit(
                              self.apiclient,
                              2, # Volume
                              max=5,
                              projectid=self.project.id
                              )
        self.debug(
            "Updating template resource limits for domain: %s" %
                                        self.account.domainid)
        # Set usage_vm=1 for Account 1
        update_resource_limit(
                              self.apiclient,
                              4, # Template
                              max=1,
                              projectid=self.project.id
                              )

        self.debug("Deploying VM for account: %s" % self.account.name)
        virtual_machine_1 = VirtualMachine.create(
                                self.apiclient,
                                self.services["server"],
                                templateid=self.template.id,
                                serviceofferingid=self.service_offering.id,
                                projectid=self.project.id
                                )
        self.cleanup.append(virtual_machine_1)
        # Verify VM state
        self.assertEqual(
                            virtual_machine_1.state,
                            'Running',
                            "Check VM state is Running or not"
                        )
        virtual_machine_1.stop(self.apiclient)
        # Get the Root disk of VM
        volumes = list_volumes(
                            self.apiclient,
                            virtualmachineid=virtual_machine_1.id,
                            projectid=self.project.id,
                            type='ROOT'
                            )
        self.assertEqual(
                        isinstance(volumes, list),
                        True,
                        "Check for list volume response return valid data"
                        )
        volume = volumes[0]

        self.debug("Creating template from volume: %s" % volume.id)
        # Create a template from the ROOTDISK
        template_1 = Template.create(
                            self.userapiclient,
                            self.services["template"],
                            volumeid=volume.id,
                            projectid=self.project.id
                            )

        self.cleanup.append(template_1)
        # Verify Template state
        self.assertEqual(
                            template_1.isready,
                            True,
                            "Check Template is in ready state or not"
                        )

        # Exception should be raised for second template
        with self.assertRaises(Exception):
            Template.create(
                            self.userapiclient,
                            self.services["template"],
                            volumeid=volume.id,
                            projectid=self.project.id
                            )
        return
    def test_02_create__template_new_resized_rootvolume_size(self):
        """Test create Template resized root volume

        # Validate the following

        # 1. Deploy a VM without any disk offering (only root disk)
        # 2. Perform(resize)  of the root  volume
        # 3. Stop the vm
        # 4. Create a template from  resized  root volume
        """

        result = self.setupAccounts()
        self.assertEqual(result[0], PASS, result[1])
        apiclient = self.testClient.getUserApiClient(
            UserName=self.parentd_admin.name,
            DomainName=self.parentd_admin.domain)
        self.assertNotEqual(apiclient, FAILED, "Failed to get api client\
                            of account: %s" % self.parentd_admin.name)

        # deploy a vm
        try:
            if self.updateclone:

                self.virtual_machine = VirtualMachine.create(
                    apiclient, self.services["virtual_machine"],
                    accountid=self.parentd_admin.name,
                    domainid=self.parent_domain.id,
                    serviceofferingid=self.services_offering_vmware.id,
                    mode=self.zone.networktype
                )
            else:
                self.virtual_machine = VirtualMachine.create(
                    apiclient, self.services["virtual_machine"],
                    accountid=self.parentd_admin.name,
                    domainid=self.parent_domain.id,
                    serviceofferingid=self.service_offering.id,
                    mode=self.zone.networktype
                )

            # listVirtual macine
            list_vms = VirtualMachine.list(apiclient,
                                           id=self.virtual_machine.id)
            self.debug("Verify listVirtualMachines response"
                       " for virtual machine: %s" % self.virtual_machine.id
                       )
            res = validateList(list_vms)
            self.assertNotEqual(res[2], INVALID_INPUT, "Invalid list response")
            self.cleanup.append(self.virtual_machine)
            vm = list_vms[0]
            self.assertEqual(
                vm.id,
                self.virtual_machine.id,
                "Virtual Machine ids do not match"
            )
            self.assertEqual(
                vm.name,
                self.virtual_machine.name,
                "Virtual Machine names do not match"
            )
            self.assertEqual(
                vm.state,
                "Running",
                msg="VM is not in Running state"
            )
            # get root vol from created vm, verify it is correct size
            list_volume_response = Volume.list(
                apiclient,
                virtualmachineid=
                self.virtual_machine.id,
                type='ROOT',
                listall='True'
            )
            res = validateList(list_volume_response)
            self.assertNotEqual(res[2], INVALID_INPUT, "listVolumes returned invalid object in response")
            rootvolume = list_volume_response[0]
            newsize = (rootvolume.size >> 30) + 2
            result = self.chk_volume_resize(apiclient, vm)
            if result:
                try:
                    # create a template from stopped VM instances root volume
                    if vm.state == "Running":
                        self.virtual_machine.stop(apiclient)
                    template_from_root = Template.create(
                        apiclient,
                        self.services["template"],
                        volumeid=rootvolume.id,
                        account=self.parentd_admin.name,
                        domainid=self.parent_domain.id)
                    list_template_response = Template.list(
                        apiclient,
                        id=template_from_root.id,
                        templatefilter="all")
                    res = validateList(list_template_response)
                    self.assertNotEqual(res[2], INVALID_INPUT, "Check if template exists in ListTemplates")
                    # Deploy new virtual machine using template
                    self.virtual_machine2 = VirtualMachine.create(
                        apiclient,
                        self.services["virtual_machine"],
                        templateid=template_from_root.id,
                        accountid=self.parentd_admin.name,
                        domainid=self.parent_domain.id,
                        serviceofferingid=self.service_offering.id,
                    )

                    vm_response = VirtualMachine.list(
                        apiclient,
                        id=self.virtual_machine2.id,
                        account=self.parentd_admin.name,
                        domainid=self.parent_domain.id
                    )
                    res = validateList(vm_response)
                    self.assertNotEqual(res[2], INVALID_INPUT, "Check for list VM response return valid list")
                    self.cleanup.append(self.virtual_machine2)
                    self.cleanup.reverse()
                    vm2 = vm_response[0]
                    self.assertEqual(
                        vm2.state,
                        'Running',
                        "Check the state of VM created from Template"
                    )
                    list_volume_response = Volume.list(
                        apiclient,
                        virtualmachineid=vm2.id,
                        type='ROOT',
                        listall='True'
                    )
                    self.assertEqual(
                        list_volume_response[0].size,
                        (newsize * 1024 * 1024 * 1024),

                        "Check for root volume size  not matched with template size"
                    )
                except Exception as e:
                    raise Exception("Exception while resizing the "
                                    "root volume: %s" % e)

            else:
                self.debug(" volume resize failed for root volume")
        except Exception as e:
            raise Exception("Exception while performing"
                            " template creation from "
                            "resized_root_volume : %s" % e)

        return
 def test01_template_download_URL_expire(self):
     """
     @Desc:Template files are deleted from secondary storage after download URL expires
     Step1:Deploy vm with default cent os template
     Step2:Stop the vm
     Step3:Create template from the vm's root volume
     Step4:Extract Template and wait for the download url to expire
     Step5:Deploy another vm with the template created at Step3
     Step6:Verify that vm deployment succeeds
     """
     params = ["extract.url.expiration.interval", "extract.url.cleanup.interval"]
     wait_time = 0
     for param in params:
         config = Configurations.list(self.apiClient, name=param)
         self.assertEqual(validateList(config)[0], PASS, "Config list returned invalid response")
         wait_time = wait_time + int(config[0].value)
     self.debug("Total wait time for url expiry: %s" % wait_time)
     # Creating Virtual Machine
     self.virtual_machine = VirtualMachine.create(
         self.userapiclient,
         self.services["virtual_machine"],
         accountid=self.account.name,
         domainid=self.account.domainid,
         serviceofferingid=self.service_offering.id,
     )
     self.assertIsNotNone(self.virtual_machine, "Virtual Machine creation failed")
     self.cleanup.append(self.virtual_machine)
     # Stop virtual machine
     self.virtual_machine.stop(self.userapiclient)
     list_volume = Volume.list(
         self.userapiclient, virtualmachineid=self.virtual_machine.id, type="ROOT", listall=True
     )
     self.assertEqual(validateList(list_volume)[0], PASS, "list volumes with type ROOT returned invalid list")
     self.volume = list_volume[0]
     self.create_template = Template.create(
         self.userapiclient,
         self.services["template"],
         volumeid=self.volume.id,
         account=self.account.name,
         domainid=self.account.domainid,
     )
     self.assertIsNotNone(self.create_template, "Failed to create template from root volume")
     self.cleanup.append(self.create_template)
     """
     Extract template
     """
     try:
         Template.extract(self.userapiclient, self.create_template.id, "HTTP_DOWNLOAD", self.zone.id)
     except Exception as e:
         self.fail("Extract template failed with error %s" % e)
     self.debug("Waiting for %s seconds for url to expire" % repr(wait_time + 20))
     time.sleep(wait_time + 20)
     self.debug("Waited for %s seconds for url to expire" % repr(wait_time + 20))
     """
     Deploy vm with the template created from the volume. After url expiration interval only
     url should be deleted not the template. To validate this deploy vm with the template
     """
     try:
         self.vm = VirtualMachine.create(
             self.userapiclient,
             self.services["virtual_machine"],
             accountid=self.account.name,
             domainid=self.account.domainid,
             serviceofferingid=self.service_offering.id,
             templateid=self.create_template.id,
         )
         self.cleanup.append(self.vm)
     except Exception as e:
         self.fail(
             "Template is automatically deleted after URL expired.\
                   So vm deployment failed with error: %s"
             % e
         )
     return
示例#23
0
    def setUpClass(cls):
        cls.testClient = super(TestVMPasswordEnabled, cls).getClsTestClient()
        cls.api_client = cls.testClient.getApiClient()

        cls.services = Services().services
        # Get Zone, Domain and templates
        domain = get_domain(cls.api_client)
        zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
        cls.services['mode'] = zone.networktype
        template = get_template(cls.api_client, zone.id,
                                cls.services["ostype"])
        # Set Zones and disk offerings
        cls.services["small"]["zoneid"] = zone.id
        cls.services["small"]["template"] = template.id

        # Create VMs, NAT Rules etc
        cls.account = Account.create(cls.api_client,
                                     cls.services["account"],
                                     domainid=domain.id)

        cls.small_offering = ServiceOffering.create(
            cls.api_client, cls.services["service_offerings"]["small"])

        cls.virtual_machine = VirtualMachine.create(
            cls.api_client,
            cls.services["small"],
            accountid=cls.account.name,
            domainid=cls.account.domainid,
            serviceofferingid=cls.small_offering.id,
            mode=cls.services["mode"])

        networkid = cls.virtual_machine.nic[0].networkid
        cls.hypervisor = cls.testClient.getHypervisorInfo()
        if cls.hypervisor.lower() in ['lxc']:
            raise unittest.SkipTest(
                "template creation is not supported on %s" % cls.hypervisor)

        # create egress rule to allow wget of my cloud-set-guest-password
        # script
        if zone.networktype.lower() == 'advanced':
            EgressFireWallRule.create(
                cls.api_client,
                networkid=networkid,
                protocol=cls.services["egress"]["protocol"],
                startport=cls.services["egress"]["startport"],
                endport=cls.services["egress"]["endport"],
                cidrlist=cls.services["egress"]["cidrlist"])

        cls.virtual_machine.password = cls.services["small"]["password"]
        ssh = cls.virtual_machine.get_ssh_client()

        # below steps are required to get the new password from VR
        # (reset password)
        # http://cloudstack.org/dl/cloud-set-guest-password
        # Copy this file to /etc/init.d
        # chmod +x /etc/init.d/cloud-set-guest-password
        # chkconfig --add cloud-set-guest-password

        cmds = [
            "cd /etc/init.d;wget http://people.apache.org/~tsp/cloud-set-guest-password",
            "chmod +x /etc/init.d/cloud-set-guest-password",
            "chkconfig --add cloud-set-guest-password",
        ]
        for c in cmds:
            ssh.execute(c)

        # Adding delay of 120 sec to avoid data loss due to timing issue
        time.sleep(120)

        # Stop virtual machine
        cls.virtual_machine.stop(cls.api_client)

        # Poll listVM to ensure VM is stopped properly
        timeout = cls.services["timeout"]
        while True:
            time.sleep(cls.services["sleep"])

            # Ensure that VM is in stopped state
            list_vm_response = list_virtual_machines(cls.api_client,
                                                     id=cls.virtual_machine.id)

            if isinstance(list_vm_response, list):

                vm = list_vm_response[0]
                if vm.state == 'Stopped':
                    break

            if timeout == 0:
                raise Exception("Failed to stop VM (ID: %s) " % vm.id)

            timeout = timeout - 1

        list_volume = list_volumes(cls.api_client,
                                   virtualmachineid=cls.virtual_machine.id,
                                   type='ROOT',
                                   listall=True)
        if isinstance(list_volume, list):
            cls.volume = list_volume[0]
        else:
            raise Exception(
                "Exception: Unable to find root volume for VM: %s" %
                cls.virtual_machine.id)

        cls.services["template"]["ostype"] = cls.services["ostype"]
        cls.services["template"]["ispublic"] = True
        # Create templates for Edit, Delete & update permissions testcases
        cls.pw_enabled_template = Template.create(
            cls.api_client,
            cls.services["template"],
            cls.volume.id,
        )
        # Delete the VM - No longer needed
        cls.virtual_machine.delete(cls.api_client, expunge=True)
        cls.services["small"]["template"] = cls.pw_enabled_template.id

        cls.vm = VirtualMachine.create(cls.api_client,
                                       cls.services["small"],
                                       accountid=cls.account.name,
                                       domainid=cls.account.domainid,
                                       serviceofferingid=cls.small_offering.id,
                                       mode=cls.services["mode"])
        cls._cleanup = [
            cls.small_offering, cls.pw_enabled_template, cls.account
        ]
示例#24
0
    def test_02_template_permissions(self):
        """
        @Desc: Test to create Public Template by registering or by snapshot and volume when
        Global parameter 'allow.public.user.template' is set to  False
        @steps:
        1.Set Global parameter 'allow.public.user.template' as False. Restart Management server
        2. Create a domain
        3. Create a domain admin and a domain user
        4. Create a vm as domain user
        5. take snapshot of root disk as user vm
        6. try to create public template from snapshot . It should fail
        7. stop the VM
        8. take the public template from volume. it should fail
        9. register a public template as a domain user . it should fail
        10. create a VM  as domain admin
        11. create a snapshot of root disk as domain admin
        12 create a public template of the snapshot .it should fail
        13. Register a public template as domain admin. it should fail
        14 Stop the vm as domain admin
        15. Create a template from volume as domain admin . it should fail

        """
        self.updateConfigurAndRestart("allow.public.user.templates", "false")

        user_account = Account.create(self.apiclient,
                                      self.testdata["account2"],
                                      admin=False,
                                      domainid=self.domain.id)
        admin_user = self.account.user[0]
        self.admin_api_client = self.testClient.getUserApiClient(
            admin_user.username, self.domain.name)
        user = user_account.user[0]
        self.user_api_client = self.testClient.getUserApiClient(
            user.username, self.domain.name)

        self.testdata["templates"]["ispublic"] = True
        # Register new public template as domain user
        # Exception should be raised for registering public template
        try:
            template = Template.register(self.user_api_client,
                                         self.testdata["templates"],
                                         zoneid=self.zone.id,
                                         account=user_account.name,
                                         domainid=user_account.domainid,
                                         hypervisor=self.hypervisor)
            self.updateConfigurAndRestart("allow.public.user.templates",
                                          "true")
            self.fail("Template creation passed for user")
        except CloudstackAPIException as e:
            self.assertRaises("Exception Raised : %s" % e)
        # Register new public template as domain admin
        # Exception should be raised for registering public template
        try:
            template = Template.register(self.admin_api_client,
                                         self.testdata["templates"],
                                         zoneid=self.zone.id,
                                         account=self.account.name,
                                         domainid=self.account.domainid,
                                         hypervisor=self.hypervisor)
            self.updateConfigurAndRestart("allow.public.user.templates",
                                          "true")
            self.fail("Template creation passed for domain admin")
        except CloudstackAPIException as e:
            self.assertRaises("Exception Raised : %s" % e)

        if self.hypervisor.lower() in ['hyperv', 'lxc']:
            self.updateConfigurAndRestart("allow.public.user.templates",
                                          "true")
            return
        else:
            user_vm_created = VirtualMachine.create(
                self.user_api_client,
                self.testdata["virtual_machine"],
                accountid=user_account.name,
                domainid=user_account.domainid,
                serviceofferingid=self.service_offering.id,
            )
            self.assertIsNotNone(user_vm_created, "VM creation failed")
            # Get the Root disk of VM
            volume = list_volumes(self.user_api_client,
                                  virtualmachineid=user_vm_created.id,
                                  type='ROOT',
                                  listall=True)
            snapshot_created = Snapshot.create(self.user_api_client,
                                               volume[0].id,
                                               account=user_account.name,
                                               domainid=user_account.domainid)
            self.assertIsNotNone(snapshot_created, "Snapshot creation failed")
            self.debug("Creating a template from snapshot: %s" %
                       snapshot_created.id)
            #
            # Generate public template from the snapshot
            self.testdata["template"]["ispublic"] = True
            try:
                user_template = Template.create_from_snapshot(
                    self.user_api_client, snapshot_created,
                    self.testdata["template"])
                self.updateConfigurAndRestart("allow.public.user.templates",
                                              "true")
                self.fail(
                    "Template creation passed from snapshot for domain user")
            except CloudstackAPIException as e:
                self.assertRaises("Exception Raised : %s" % e)

            VirtualMachine.stop(user_vm_created, self.user_api_client)
            list_stopped_vms_after = VirtualMachine.list(
                self.user_api_client,
                listall=self.testdata["listall"],
                domainid=user_account.domainid,
                state="Stopped")
            status = validateList(list_stopped_vms_after)
            self.assertEqual(PASS, status[0],
                             "Stopped VM is not in Stopped state")
            try:
                user_template = Template.create(self.user_api_client,
                                                self.testdata["template"],
                                                volume[0].id)
                self.updateConfigurAndRestart("allow.public.user.templates",
                                              "true")
                self.fail(
                    "Template creation passed from volume for domain user")
            except CloudstackAPIException as e:
                self.assertRaises("Exception Raised : %s" % e)

            admin_vm_created = VirtualMachine.create(
                self.admin_api_client,
                self.testdata["virtual_machine"],
                accountid=self.account.name,
                domainid=self.account.domainid,
                serviceofferingid=self.service_offering.id,
            )
            self.assertIsNotNone(admin_vm_created, "VM creation failed")
            # Get the Root disk of VM
            volume = list_volumes(self.admin_api_client,
                                  virtualmachineid=admin_vm_created.id,
                                  type='ROOT',
                                  listall=True)
            snapshot_created = Snapshot.create(self.admin_api_client,
                                               volume[0].id,
                                               account=self.account.name,
                                               domainid=self.account.domainid)
            self.assertIsNotNone(snapshot_created, "Snapshot creation failed")
            self.debug("Creating a template from snapshot: %s" %
                       snapshot_created.id)
            #
            #    Generate public template from the snapshot
            try:
                admin_template = Template.create_from_snapshot(
                    self.admin_api_client, snapshot_created,
                    self.testdata["template"])
                self.updateConfigurAndRestart("allow.public.user.templates",
                                              "true")
                self.fail(
                    "Template creation passed from snapshot for domain admin")
            except CloudstackAPIException as e:
                self.assertRaises("Exception Raised : %s" % e)

            VirtualMachine.stop(admin_vm_created, self.admin_api_client)
            list_stopped_vms_after = VirtualMachine.list(
                self.admin_api_client,
                listall=self.testdata["listall"],
                domainid=self.account.domainid,
                state="Stopped")
            status = validateList(list_stopped_vms_after)
            self.assertEqual(PASS, status[0],
                             "Stopped VM is not in Stopped state")
            try:
                admin_template = Template.create(self.admin_api_client,
                                                 self.testdata["template"],
                                                 volume[0].id)
                self.updateConfigurAndRestart("allow.public.user.templates",
                                              "true")
                self.fail(
                    "Template creation passed from volume for domain admin")
            except CloudstackAPIException as e:
                self.assertRaises("Exception Raised : %s" % e)

            self.updateConfigurAndRestart("allow.public.user.templates",
                                          "true")
        return
    def test_19_template_tag(self):
        """ Test creation, listing and deletion tag on templates
        """

        try:
            
            noffering=NetworkOffering.list(
                     self.user_api_client,
                     name="DefaultIsolatedNetworkOfferingWithSourceNatService"
                     )
            vm4network=Network.create(
                                 self.user_api_client,
                                self.services["network"],
                                accountid=self.account.name,
                                domainid=self.account.domainid,
                                networkofferingid=noffering[0].id,
                                zoneid=self.zone.id
                                 )

            list_nw_response = Network.list(
                                            self.user_api_client,
                                            id=vm4network.id
                                            )
            self.assertEqual(
                            isinstance(list_nw_response, list),
                            True,
                            "Check list response returns a valid networks list"
                        )

            vm_1 = VirtualMachine.create(
                                    self.user_api_client,
                                    self.services["small"],
                                    templateid=self.template.id,
                                    networkids=vm4network.id,
                                    serviceofferingid=self.service_offering.id,
                                    accountid=self.account.name,
                                    domainid=self.account.domainid,
                                    mode=self.services['mode'],
                                    startvm="true"
                                    )
            time.sleep(600)
            self.debug("Stopping the virtual machine: %s" % vm_1.name)
            # Stop virtual machine
            vm_1.stop(self.user_api_client)
        except Exception as e:
            self.fail("Failed to stop VM: %s" % e)

        timeout = self.services["timeout"]
        while True:
            list_volume = Volume.list(
                self.user_api_client,
                virtualmachineid=vm_1.id,
                type='ROOT',
                listall=True
            )
            if isinstance(list_volume, list):
                break
            elif timeout == 0:
                raise Exception("List volumes failed.")

            time.sleep(5)
            timeout = timeout - 1

        self.volume = list_volume[0]

        self.debug("Creating template from ROOT disk of virtual machine: %s" %
                   vm_1.name)
        # Create template from volume
        template = Template.create(
            self.user_api_client,
            self.services["template"],
            self.volume.id
        )
        self.cleanup.append(template)
        self.debug("Created the template(%s). Now restarting the userVm: %s" %
                   (template.name, vm_1.name))
        vm_1.start(self.user_api_client)

        self.debug("Creating a tag for the template")
        tag = Tag.create(
            self.user_api_client,
            resourceIds=template.id,
            resourceType='Template',
            tags={'OS': 'windows8'}
        )
        self.debug("Tag created: %s" % tag.__dict__)

        tags = Tag.list(
            self.user_api_client,
            listall=True,
            resourceType='Template',
            key='OS',
            value='windows8'
        )
        self.assertEqual(
            isinstance(tags, list),
            True,
            "List tags should not return empty response"
        )
        self.assertEqual(
            tags[0].value,
            'windows8',
            'The tag should have original value'
        )

        Template.list(
            self.user_api_client,
            templatefilter=self.services["template"]["templatefilter"],
            listall=True,
            key='OS',
            value='windows8'
        )

        self.debug("Deleting the created tag..")
        try:
            tag.delete(
                self.user_api_client,
                resourceIds=template.id,
                resourceType='Template',
                tags={'OS': 'windows8'}
            )
        except Exception as e:
            self.fail("Failed to delete the tag - %s" % e)

        self.debug("Verifying if tag is actually deleted!")
        tags = Tag.list(
            self.user_api_client,
            listall=True,
            resourceType='Template',
            key='OS',
            value='windows8'
        )
        self.assertEqual(
            tags,
            None,
            "List tags should return empty response"
        )
        return
示例#26
0
    def test_09_copy_delete_template(self):
        cmd = listZones.listZonesCmd()
        zones = self.apiclient.listZones(cmd)
        if not isinstance(zones, list):
            raise Exception("Failed to find zones.")
        if len(zones) < 2:
            self.skipTest(
                "Skipping test due to there are less than two zones.")
        return

        self.sourceZone = zones[0]
        self.destZone = zones[1]

        template = Template.create(self.apiclient,
                                   self.services["template"],
                                   self.volume.id,
                                   account=self.account.name,
                                   domainid=self.account.domainid)
        self.cleanup.append(template)

        self.debug("Created template with ID: %s" % template.id)

        list_template_response = Template.list(
                                    self.apiclient,
                                    templatefilter=\
                                    self.services["templatefilter"],
                                    id=template.id
                                    )

        self.assertEqual(isinstance(list_template_response, list), True,
                         "Check list response returns a valid list")
        #Verify template response to check whether template added successfully
        self.assertNotEqual(len(list_template_response), 0,
                            "Check template available in List Templates")
        #Copy template from zone1 to zone2
        copytemplate = Template.copy(cls.apiclient,
                                     zoneid=cls.sourceZone.id,
                                     destzoneid=cls.destZone.id)
        cls._cleanup.append(cls.copytemplate)

        list_template_response = Template.list(
            self.apiclient,
            templatefilter=self.services["template"]["templatefilter"],
            id=self.template.id,
            zoneid=self.destZone.id)
        self.assertEqual(list_template_response, None,
                         "Check template available in List Templates")

        self.deltemplate = list_template_response[0]

        self.debug("Deleting template: %s" % self.deltemplate)
        # Delete the template
        self.deltemplate.delete(self.apiclient)
        self.debug("Delete template: %s successful" % self.deltemplate)

        copytemplate = Template.copy(self.apiclient,
                                     zoneid=self.sourceZone.id,
                                     destzoneid=self.destZone.id)

        removed = cls.dbclient.execute(
            "select removed from template_zone_ref where zone_id='%s' and template_id='%s';"
            % self.destZone.id, self.template.id)

        self.assertEqual(removed, NULL, "Removed state is not correct.")
        return
    def test_08_pt_startvm_false_password_enabled_template(self):
        """ Positive test for stopped VM test path - T10

        # 1   Create a password enabled template
        # 2.  Deploy a new VM with password enabled template
        # 3.  Verify that VM is in stopped state
        # 4.  Start the VM, verify that it is in running state
        # 5.  Verify that new password is generated for the VM
        """

        vm_for_template = VirtualMachine.create(
            self.userapiclient,
            self.testdata["small"],
            templateid=self.defaultTemplateId,
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id,
            zoneid=self.zone.id,
            mode=self.zone.networktype,
            networkids=[
                self.networkid,
            ] if self.networkid else None)

        vm_for_template.password = self.testdata["virtual_machine"]["password"]
        ssh = vm_for_template.get_ssh_client()

        # below steps are required to get the new password from
        # VR(reset password)
        # http://cloudstack.org/dl/cloud-set-guest-password
        # Copy this file to /etc/init.d
        # chmod +x /etc/init.d/cloud-set-guest-password
        # chkconfig --add cloud-set-guest-password
        # similar steps to get SSH key from web so as to make it ssh enabled

        cmds = [
            "cd /etc/init.d;wget http://people.apache.org/~tsp/\
                    cloud-set-guest-password",
            "chmod +x /etc/init.d/cloud-set-guest-password",
            "chkconfig --add cloud-set-guest-password"
        ]
        for c in cmds:
            ssh.execute(c)

        # Stop virtual machine
        vm_for_template.stop(self.userapiclient)

        list_volume = Volume.list(self.userapiclient,
                                  virtualmachineid=vm_for_template.id,
                                  type='ROOT',
                                  listall=True)

        if isinstance(list_volume, list):
            self.volume = list_volume[0]
        else:
            raise Exception(
                "Exception: Unable to find root volume for VM: %s" %
                vm_for_template.id)

        self.testdata["template"]["ostype"] = self.testdata["ostype"]
        # Create templates for Edit, Delete & update permissions testcases
        pw_ssh_enabled_template = Template.create(
            self.userapiclient,
            self.testdata["template"],
            self.volume.id,
            account=self.account.name,
            domainid=self.account.domainid)
        self.cleanup.append(pw_ssh_enabled_template)
        # Delete the VM - No longer needed
        vm_for_template.delete(self.apiclient)

        # Create VM in account
        virtual_machine = VirtualMachine.create(
            self.userapiclient,
            self.testdata["small"],
            templateid=self.defaultTemplateId,
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id,
            zoneid=self.zone.id,
            startvm=False,
            mode=self.zone.networktype,
            networkids=[
                self.networkid,
            ] if self.networkid else None)
        self.cleanup.append(virtual_machine)

        response = virtual_machine.getState(self.apiclient,
                                            VirtualMachine.STOPPED)
        self.assertEqual(response[0], PASS, response[1])

        virtual_machine.start(self.userapiclient)

        vms = virtual_machine.list(self.userapiclient,
                                   id=virtual_machine.id,
                                   listall=True)

        self.assertEqual(
            validateList(vms)[0], PASS, "vms list validation failed")
        self.assertNotEqual(str(vms[0].password),
                            str(virtual_machine.password),
                            "New password should be generated for the VM")
        return
示例#28
0
        if zone.allocationstate == 'Enabled':
          services = {}
          services["displaytext"] = "Debian"
          services["name"] = "deb"
          if options.upload_tmpl is not None:
            services["hypervisor"] = "KVM"
            services["format"] = "QCOW2"
            services["url"] = options.upload_tmpl
          if options.upload_iso is not None:
            services["url"] = options.upload_iso
          services["ostype"] = "Debian GNU/Linux 7(64-bit)"
          services["zoneid"] = zone.id
          tmp_dict = {}
          if options.upload_tmpl is not None:
            my_templ = Template(tmp_dict)
            if my_templ.register(apiClient, services) == FAILED:
              print "Uploading template failed"
              tc_run_logger.debug("\n=== Uploading template failed ===");
              exit(1)
          if options.upload_iso is not None:
            my_templ = Iso(tmp_dict)
            if my_templ.create(apiClient, services) == FAILED:
              print "Uploading template failed"
              tc_run_logger.debug("\n=== Uploading template failed ===");
              exit(1)
        else:
          print "Zone is not ready"
    else:
      print "No zones"
  exit(0)
示例#29
0
    def setUpClass(cls):

        cls.testClient = super(TestTemplates, cls).getClsTestClient()
        cls.api_client = cls.testClient.getApiClient()
        cls.services = Services().services
        # Get Zone, Domain and templates
        cls.domain = get_domain(cls.api_client)
        cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
        cls.services['mode'] = cls.zone.networktype
        cls._cleanup = []
        cls.unsupportedHypervisor = False
        cls.hypervisor = cls.testClient.getHypervisorInfo()
        if cls.hypervisor.lower() in ['lxc']:
            cls.unsupportedHypervisor = True
            return
        # populate second zone id for iso copy
        cmd = listZones.listZonesCmd()
        zones = cls.api_client.listZones(cmd)
        if not isinstance(zones, list):
            raise Exception("Failed to find zones.")
        if len(zones) >= 2:
            cls.services["destzoneid"] = zones[1].id

        template = get_template(
            cls.api_client,
            cls.zone.id,
            cls.services["ostype"]
        )
        cls.services["virtual_machine"]["zoneid"] = cls.zone.id
        try:
            cls.account = Account.create(
                cls.api_client,
                cls.services["account"],
                domainid=cls.domain.id
            )
            cls._cleanup.append(cls.account)

            cls.services["account"] = cls.account.name
            cls.service_offering = ServiceOffering.create(
                cls.api_client,
                cls.services["service_offering"]
            )
            cls._cleanup.append(cls.service_offering)

            # create virtual machine
            cls.virtual_machine = VirtualMachine.create(
                cls.api_client,
                cls.services["virtual_machine"],
                templateid=template.id,
                accountid=cls.account.name,
                domainid=cls.account.domainid,
                serviceofferingid=cls.service_offering.id,
            )
            # Stop virtual machine
            cls.virtual_machine.stop(cls.api_client)

            timeout = cls.services["timeout"]

            while True:
                list_volume = Volume.list(
                    cls.api_client,
                    virtualmachineid=cls.virtual_machine.id,
                    type='ROOT',
                    listall=True)
                if isinstance(list_volume, list):
                    break
                elif timeout == 0:
                    raise Exception("List volumes failed.")

                time.sleep(5)
                timeout = timeout - 1

            cls.volume = list_volume[0]

            # Create template from volume
            cls.template = Template.create(
                cls.api_client,
                cls.services["template"],
                cls.volume.id
            )
        except Exception as e:
            cls.tearDownClass()
            raise unittest.SkipTest("Failure in setUpClass: %s" % e)
示例#30
0
    def setUpClass(cls):

        testClient = super(TestTemplates, cls).getClsTestClient()
        cls.apiclient = testClient.getApiClient()
        cls._cleanup = []
        cls.services = testClient.getParsedTestDataConfig()
        cls.unsupportedHypervisor = False
        cls.hypervisor = testClient.getHypervisorInfo()
        if cls.hypervisor.lower() in ['lxc']:
            # Template creation from root volume is not supported in LXC
            cls.unsupportedHypervisor = True
            return

        # Get Zone, Domain and templates
        cls.domain = get_domain(cls.apiclient)
        cls.zone = get_zone(cls.apiclient, cls.testClient.getZoneForTests())
        cls.services['mode'] = cls.zone.networktype
        #populate second zone id for iso copy
        cls.zones = Zone.list(cls.apiclient)
        if not isinstance(cls.zones, list):
            raise Exception("Failed to find zones.")

        cls.disk_offering = DiskOffering.create(
                                    cls.apiclient,
                                    cls.services["disk_offering"]
                                    )
        template = get_template(
                            cls.apiclient,
                            cls.zone.id,
                            cls.services["ostype"]
                            )
        if template == FAILED:
            assert False, "get_template() failed to return template with description %s" % cls.services["ostype"]

        cls.services["virtual_machine"]["zoneid"] = cls.zone.id
        cls.services["volume"]["diskoffering"] = cls.disk_offering.id
        cls.services["volume"]["zoneid"] = cls.zone.id
        cls.services["template_2"]["zoneid"] = cls.zone.id
        cls.services["sourcezoneid"] = cls.zone.id

        cls.services["template"]["ostypeid"] = template.ostypeid
        cls.services["template_2"]["ostypeid"] = template.ostypeid
        cls.services["ostypeid"] = template.ostypeid
        cls.account = Account.create(
                            cls.apiclient,
                            cls.services["account"],
                            admin=True,
                            domainid=cls.domain.id
                            )
        cls.user = Account.create(
                            cls.apiclient,
                            cls.services["account"],
                            domainid=cls.domain.id
                            )
        cls.service_offering = ServiceOffering.create(
                                            cls.apiclient,
                                            cls.services["service_offerings"]["tiny"]
                                        )
        #create virtual machine
        cls.virtual_machine = VirtualMachine.create(
                                    cls.apiclient,
                                    cls.services["virtual_machine"],
                                    templateid=template.id,
                                    accountid=cls.account.name,
                                    domainid=cls.account.domainid,
                                    serviceofferingid=cls.service_offering.id,
                                    mode=cls.services["mode"]
                                    )
        #Stop virtual machine
        cls.virtual_machine.stop(cls.apiclient)

        list_volume = Volume.list(
                                   cls.apiclient,
                                   virtualmachineid=cls.virtual_machine.id,
                                   type='ROOT',
                                   listall=True
                                   )
        try:
            cls.volume = list_volume[0]
        except Exception as e:
            raise Exception(
                "Exception: Unable to find root volume foe VM: %s - %s" %
                 (cls.virtual_machine.id, e))

        #Create templates for Edit, Delete & update permissions testcases
        cls.template_1 = Template.create(
                                         cls.apiclient,
                                         cls.services["template"],
                                         cls.volume.id,
                                         account=cls.account.name,
                                         domainid=cls.account.domainid
                                         )
        cls.template_2 = Template.create(
                                         cls.apiclient,
                                         cls.services["template_2"],
                                         cls.volume.id,
                                         account=cls.account.name,
                                         domainid=cls.account.domainid
                                         )
        cls._cleanup = [
                        cls.service_offering,
                        cls.disk_offering,
                        cls.account,
                        cls.user
                        ]
示例#31
0
    def setUpClass(cls):
        testClient = super(TestListIdsParams, cls).getClsTestClient()
        cls.apiclient = testClient.getApiClient()
        cls.services = testClient.getParsedTestDataConfig()
        cls.hypervisor = testClient.getHypervisorInfo()
        cls.domain = get_domain(cls.apiclient)
        cls.zone = get_zone(cls.apiclient, testClient.getZoneForTests())

        cls.disk_offering = DiskOffering.create(cls.apiclient,
                                                cls.services["disk_offering"])

        cls.account = Account.create(cls.apiclient,
                                     cls.services["account"],
                                     domainid=cls.domain.id)
        cls.service_offering = ServiceOffering.create(
            cls.apiclient, cls.services["service_offerings"]["tiny"])

        template = get_test_template(cls.apiclient, cls.zone.id,
                                     cls.hypervisor)
        if template == FAILED:
            assert False, "get_test_template() failed to return template"

        cls.services["template"]["ostypeid"] = template.ostypeid
        cls.services["template_2"]["ostypeid"] = template.ostypeid
        cls.services["ostypeid"] = template.ostypeid
        cls.services["virtual_machine"]["zoneid"] = cls.zone.id
        cls.services["mode"] = cls.zone.networktype

        #Create 3 VMs
        cls.virtual_machine_1 = VirtualMachine.create(
            cls.apiclient,
            cls.services["virtual_machine"],
            templateid=template.id,
            accountid=cls.account.name,
            domainid=cls.account.domainid,
            serviceofferingid=cls.service_offering.id,
            mode=cls.services["mode"])
        cls.virtual_machine_2 = VirtualMachine.create(
            cls.apiclient,
            cls.services["virtual_machine"],
            templateid=template.id,
            accountid=cls.account.name,
            domainid=cls.account.domainid,
            serviceofferingid=cls.service_offering.id,
            mode=cls.services["mode"])
        cls.virtual_machine_3 = VirtualMachine.create(
            cls.apiclient,
            cls.services["virtual_machine"],
            templateid=template.id,
            accountid=cls.account.name,
            domainid=cls.account.domainid,
            serviceofferingid=cls.service_offering.id,
            mode=cls.services["mode"])

        #        Take 3 VM1 Snapshots
        #        PLEASE UNCOMMENT ONCE VM SNAPSHOT DELAY BUG AFTER VM CREATION IS FIXED
        #        cls.vmsnapshot_1 = VmSnapshot.create(
        #                                cls.apiclient,
        #                                cls.virtual_machine_1.id
        #                            )
        #        cls.vmsnapshot_2 = VmSnapshot.create(
        #                                cls.apiclient,
        #                                cls.virtual_machine_1.id
        #                            )
        #        cls.vmsnapshot_3 = VmSnapshot.create(
        #                                cls.apiclient,
        #                                cls.virtual_machine_1.id
        #                            )

        #Stop VMs
        cls.virtual_machine_1.stop(cls.apiclient)
        cls.virtual_machine_2.stop(cls.apiclient)
        cls.virtual_machine_3.stop(cls.apiclient)

        #Get ROOT volumes of 3 VMs
        vm1RootVolumeResponse = Volume.list(
            cls.apiclient,
            virtualmachineid=cls.virtual_machine_1.id,
            type='ROOT',
            listall=True)
        vm2RootVolumeResponse = Volume.list(
            cls.apiclient,
            virtualmachineid=cls.virtual_machine_2.id,
            type='ROOT',
            listall=True)
        vm3RootVolumeResponse = Volume.list(
            cls.apiclient,
            virtualmachineid=cls.virtual_machine_3.id,
            type='ROOT',
            listall=True)
        cls.vm1_root_volume = vm1RootVolumeResponse[0]
        cls.vm2_root_volume = vm2RootVolumeResponse[0]
        cls.vm3_root_volume = vm3RootVolumeResponse[0]

        #Take 3 snapshots of VM2's ROOT volume
        cls.snapshot_1 = Snapshot.create(cls.apiclient,
                                         cls.vm2_root_volume.id,
                                         account=cls.account.name,
                                         domainid=cls.account.domainid)
        cls.snapshot_2 = Snapshot.create(cls.apiclient,
                                         cls.vm2_root_volume.id,
                                         account=cls.account.name,
                                         domainid=cls.account.domainid)
        cls.snapshot_3 = Snapshot.create(cls.apiclient,
                                         cls.vm2_root_volume.id,
                                         account=cls.account.name,
                                         domainid=cls.account.domainid)

        #Create 3 templates
        cls.template_1 = Template.create(cls.apiclient,
                                         cls.services["template"],
                                         cls.vm3_root_volume.id,
                                         account=cls.account.name,
                                         domainid=cls.account.domainid)
        cls.template_2 = Template.create(cls.apiclient,
                                         cls.services["template_2"],
                                         cls.vm3_root_volume.id,
                                         account=cls.account.name,
                                         domainid=cls.account.domainid)
        cls.template_3 = Template.create(cls.apiclient,
                                         cls.services["template_2"],
                                         cls.vm3_root_volume.id,
                                         account=cls.account.name,
                                         domainid=cls.account.domainid)

        cls._cleanup = [
            cls.snapshot_3, cls.snapshot_2, cls.snapshot_1, cls.account,
            cls.disk_offering, cls.service_offering
        ]
示例#32
0
    def test_09_copy_delete_template(self):
	cmd = listZones.listZonesCmd()
        zones = self.apiclient.listZones(cmd)
        if not isinstance(zones, list):
            raise Exception("Failed to find zones.")
        if len(zones) < 2:
            self.skipTest(
                "Skipping test due to there are less than two zones.")
        return
			
	self.sourceZone = zones[0]
	self.destZone = zones[1]
            
        template = Template.create(
                                self.apiclient,
                                self.services["template"],
                                self.volume.id,
                                account=self.account.name,
                                domainid=self.account.domainid
                                )
        self.cleanup.append(template)

        self.debug("Created template with ID: %s" % template.id)

        list_template_response = Template.list(
                                    self.apiclient,
                                    templatefilter=\
                                    self.services["templatefilter"],
                                    id=template.id
                                    )

        self.assertEqual(
                            isinstance(list_template_response, list),
                            True,
                            "Check list response returns a valid list"
                        )
        #Verify template response to check whether template added successfully
        self.assertNotEqual(
                            len(list_template_response),
                            0,
                            "Check template available in List Templates"
                        )
	#Copy template from zone1 to zone2
        copytemplate = Template.copy(
            cls.apiclient,
            zoneid=cls.sourceZone.id,
            destzoneid = cls.destZone.id
        )
        cls._cleanup.append(cls.copytemplate)

        list_template_response = Template.list(
            self.apiclient,
	    templatefilter=self.services["template"]["templatefilter"],
            id=self.template.id,
            zoneid=self.destZone.id
        )
        self.assertEqual(
            list_template_response,
            None,
            "Check template available in List Templates"
        )

        self.deltemplate = list_template_response[0]

        self.debug("Deleting template: %s" % self.deltemplate)
        # Delete the template
        self.deltemplate.delete(self.apiclient)
        self.debug("Delete template: %s successful" % self.deltemplate)

        copytemplate = Template.copy(
            self.apiclient,
            zoneid=self.sourceZone.id,
            destzoneid = self.destZone.id
        )

        removed = cls.dbclient.execute("select removed from template_zone_ref where zone_id='%s' and template_id='%s';" % self.destZone.id, self.template.id)

        self.assertEqual(
            removed,
            NULL,
            "Removed state is not correct."
        )
        return
    def test_16_create_template_volume(self):
        """Test Create template from volume
        """

        noffering = NetworkOffering.list(
            self.user_api_client,
            name="DefaultIsolatedNetworkOfferingWithSourceNatService")
        vm2network = Network.create(self.user_api_client,
                                    self.services["network"],
                                    accountid=self.account.name,
                                    domainid=self.account.domainid,
                                    networkofferingid=noffering[0].id,
                                    zoneid=self.zone.id)

        list_nw_response = Network.list(self.user_api_client, id=vm2network.id)
        self.assertEqual(isinstance(list_nw_response, list), True,
                         "Check list response returns a valid networks list")

        templatevm = VirtualMachine.create(
            self.user_api_client,
            self.services["small"],
            templateid=self.template.id,
            accountid=self.account.name,
            domainid=self.account.domainid,
            networkids=vm2network.id,
            serviceofferingid=self.service_offering.id,
            mode=self.services['mode'],
            startvm="true")
        time.sleep(600)
        vm_response = VirtualMachine.list(self.user_api_client,
                                          id=templatevm.id)

        self.assertNotEqual(len(vm_response), 0,
                            "Check VMs available in List VMs response")
        vm = vm_response[0]
        self.assertEqual(vm.state, 'Running',
                         "Check the state of VM created from Template")

        templatevm.stop(self.user_api_client, forced="false")

        vm_response = VirtualMachine.list(self.user_api_client,
                                          id=templatevm.id)

        vm = vm_response[0]
        self.assertEqual(
            vm.state, 'Stopped',
            "Check the state of VM is in Stopped state before creating the Template"
        )

        list_volume_response = Volume.list(self.user_api_client,
                                           virtualmachineid=vm.id,
                                           type="ROOT",
                                           listall=True)

        #Create template from Virtual machine and Volume ID
        roottemplate = Template.create(
            self.user_api_client,
            self.services["interop"]["template"],
            volumeid=list_volume_response[0].id,
            account=self.account.name,
            domainid=self.domain.id,
        )

        time.sleep(600)

        list_template_response = Template.list(
                                    self.user_api_client,
                                    templatefilter=\
                                    self.services["templatefilter"],
                                    id=roottemplate.id
                                    )

        self.assertEqual(isinstance(list_template_response, list), True,
                         "Check list response returns a valid list")
        #Verify template response to check whether template added successfully
        self.assertNotEqual(len(list_template_response), 0,
                            "Check template available in List Templates")
        template_response = list_template_response[0]

        self.assertEqual(template_response.displaytext,
                         self.services["interop"]["template"]["displaytext"],
                         "Check display text of newly created template")
        name = template_response.name
        self.assertEqual(
            name.count(self.services["interop"]["template"]["name"]), 1,
            "Check name of newly created template")

        templatevm.delete(self.apiclient)
        vm2network.delete(self.user_api_client)

        vm3network = Network.create(self.user_api_client,
                                    self.services["network"],
                                    accountid=self.account.name,
                                    domainid=self.account.domainid,
                                    networkofferingid=noffering[0].id,
                                    zoneid=self.zone.id)

        list_nw_response = Network.list(self.user_api_client, id=vm3network.id)
        self.assertEqual(isinstance(list_nw_response, list), True,
                         "Check list response returns a valid networks list")

        templatevm = VirtualMachine.create(
            self.user_api_client,
            self.services["small"],
            templateid=roottemplate.id,
            networkids=vm3network.id,
            serviceofferingid=self.service_offering.id,
            accountid=self.account.name,
            domainid=self.account.domainid,
            mode=self.services['mode'],
            startvm="true")
        time.sleep(600)
        vm_response = VirtualMachine.list(self.user_api_client,
                                          id=templatevm.id)

        self.assertNotEqual(len(vm_response), 0,
                            "Check VMs available in List VMs response")
        vm = vm_response[0]
        self.assertEqual(vm.state, 'Running',
                         "Check the state of VM created from Template")

        # Delete the template
        roottemplate.delete(self.user_api_client)

        list_template_response = Template.list(
                                    self.user_api_client,
                                    templatefilter=\
                                    self.services["template"]["templatefilter"],
                                    id=roottemplate.id,
                                    zoneid=self.zone.id
                                    )
        self.assertEqual(list_template_response, None,
                         "Check template available in List Templates")

        templatevm.delete(self.apiclient)

        vm3network.delete(self.user_api_client)
        return
    def test_01_data_persistency_root_disk(self):
        """
        Test the timing issue of root disk data sync

        # 1. Write data to root disk of a VM
        # 2. Create a template from the root disk of VM
        # 3. Create a new VM from this template
        # 4. Check that the data is present in the new VM

        This is to test that data is persisted on root disk of VM or not
        when template is created immediately from it
        """

        ssh = self.virtual_machine.get_ssh_client()

        sampleText = "This is sample data"

        cmds = [
                "cd /root/",
                "touch testFile.txt",
                "chmod 600 testFile.txt",
                "echo %s >> testFile.txt" % sampleText
                ]
        for c in cmds:
            ssh.execute(c)

        #Stop virtual machine
        self.virtual_machine.stop(self.api_client)

        list_volume = Volume.list(
                            self.api_client,
                            virtualmachineid=self.virtual_machine.id,
                            type='ROOT',
                            listall=True)

        if isinstance(list_volume, list):
            self.volume = list_volume[0]
        else:
            raise Exception(
                "Exception: Unable to find root volume for VM: %s" %
                self.virtual_machine.id)

        self.services["template"]["ostype"] = self.services["ostype"]
        #Create templates for Edit, Delete & update permissions testcases
        customTemplate = Template.create(
                self.userapiclient,
                self.services["template"],
                self.volume.id,
                account=self.account.name,
                domainid=self.account.domainid
            )
        self.cleanup.append(customTemplate)
        # Delete the VM - No longer needed
        self.virtual_machine.delete(self.apiclient)

        virtual_machine = VirtualMachine.create(
                                    self.apiclient,
                                    self.services["virtual_machine"],
                                    templateid=customTemplate.id,
                                    accountid=self.account.name,
                                    domainid=self.account.domainid,
                                    serviceofferingid=self.service_offering.id,
                                    mode=self.services["mode"]
                                    )

        ssh = virtual_machine.get_ssh_client()

        response = ssh.execute("cat /root/testFile.txt")
        res = str(response[0])

        self.assertEqual(res, sampleText, "The data %s does not match\
                with sample test %s" %
                (res, sampleText))
        return
示例#35
0
    def setUpClass(cls):

        testClient = super(TestTemplates, cls).getClsTestClient()
        cls.apiclient = testClient.getApiClient()
        cls.services = testClient.getParsedTestDataConfig()

        # Get Zone, Domain and templates
        cls.domain = get_domain(cls.apiclient)
        cls.zone = get_zone(cls.apiclient, cls.testClient.getZoneForTests())
        cls.services['mode'] = cls.zone.networktype
        #populate second zone id for iso copy
        cmd = listZones.listZonesCmd()
        cls.zones = cls.apiclient.listZones(cmd)
        if not isinstance(cls.zones, list):
            raise Exception("Failed to find zones.")

        cls.disk_offering = DiskOffering.create(cls.apiclient,
                                                cls.services["disk_offering"])
        template = get_template(cls.apiclient, cls.zone.id,
                                cls.services["ostype"])
        if template == FAILED:
            assert False, "get_template() failed to return template with description %s" % cls.services[
                "ostype"]

        cls.services["virtual_machine"]["zoneid"] = cls.zone.id
        cls.services["volume"]["diskoffering"] = cls.disk_offering.id
        cls.services["volume"]["zoneid"] = cls.zone.id
        cls.services["template_2"]["zoneid"] = cls.zone.id
        cls.services["sourcezoneid"] = cls.zone.id

        cls.services["template"]["ostypeid"] = template.ostypeid
        cls.services["template_2"]["ostypeid"] = template.ostypeid
        cls.services["ostypeid"] = template.ostypeid
        print "Before:", cls.services
        cls.account = Account.create(cls.apiclient,
                                     cls.services["account"],
                                     admin=True,
                                     domainid=cls.domain.id)
        print "After:", cls.services
        cls.user = Account.create(cls.apiclient,
                                  cls.services["account"],
                                  domainid=cls.domain.id)
        cls.service_offering = ServiceOffering.create(
            cls.apiclient, cls.services["service_offerings"])
        #create virtual machine
        cls.virtual_machine = VirtualMachine.create(
            cls.apiclient,
            cls.services["virtual_machine"],
            templateid=template.id,
            accountid=cls.account.name,
            domainid=cls.account.domainid,
            serviceofferingid=cls.service_offering.id,
            mode=cls.services["mode"])
        #Stop virtual machine
        cls.virtual_machine.stop(cls.apiclient)

        list_volume = Volume.list(cls.apiclient,
                                  virtualmachineid=cls.virtual_machine.id,
                                  type='ROOT',
                                  listall=True)
        try:
            cls.volume = list_volume[0]
        except Exception as e:
            raise Exception(
                "Exception: Unable to find root volume foe VM: %s - %s" %
                (cls.virtual_machine.id, e))

        #Create templates for Edit, Delete & update permissions testcases
        cls.template_1 = Template.create(cls.apiclient,
                                         cls.services["template"],
                                         cls.volume.id,
                                         account=cls.account.name,
                                         domainid=cls.account.domainid)
        cls.template_2 = Template.create(cls.apiclient,
                                         cls.services["template_2"],
                                         cls.volume.id,
                                         account=cls.account.name,
                                         domainid=cls.account.domainid)
        cls._cleanup = [
            cls.service_offering, cls.disk_offering, cls.account, cls.user
        ]
    def setUpClass(cls):
        testClient = super(TestListIdsParams, cls).getClsTestClient()
        cls.apiclient = testClient.getApiClient()
        cls.services = testClient.getParsedTestDataConfig()
        cls.hypervisor = testClient.getHypervisorInfo()
        cls.domain = get_domain(cls.apiclient)
        cls.zone = get_zone(cls.apiclient, testClient.getZoneForTests())

        cls.disk_offering = DiskOffering.create(
                                    cls.apiclient,
                                    cls.services["disk_offering"]
                                    )

        cls.account = Account.create(
                            cls.apiclient,
                            cls.services["account"],
                            domainid=cls.domain.id
                            )
        cls.service_offering = ServiceOffering.create(
                                            cls.apiclient,
                                            cls.services["service_offerings"]["tiny"]
                                            )

        template = get_template(
                            cls.apiclient,
                            cls.zone.id,
                            cls.services["ostype"]
                            )
        if template == FAILED:
            assert False, "get_template() failed to return template with description %s" % cls.services["ostype"]
            
        cls.services["template"]["ostypeid"] = template.ostypeid
        cls.services["template_2"]["ostypeid"] = template.ostypeid
        cls.services["ostypeid"] = template.ostypeid
        cls.services["virtual_machine"]["zoneid"] = cls.zone.id
        cls.services["mode"] = cls.zone.networktype

        #Create 3 VMs
        cls.virtual_machine_1 = VirtualMachine.create(
                                cls.apiclient,
                                cls.services["virtual_machine"],
                                templateid=template.id,
                                accountid=cls.account.name,
                                domainid=cls.account.domainid,
                                serviceofferingid=cls.service_offering.id,
                                mode=cls.services["mode"]
                                )
        cls.virtual_machine_2 = VirtualMachine.create(
                                cls.apiclient,
                                cls.services["virtual_machine"],
                                templateid=template.id,
                                accountid=cls.account.name,
                                domainid=cls.account.domainid,
                                serviceofferingid=cls.service_offering.id,
                                mode=cls.services["mode"]
                                )
        cls.virtual_machine_3 = VirtualMachine.create(
                                cls.apiclient,
                                cls.services["virtual_machine"],
                                templateid=template.id,
                                accountid=cls.account.name,
                                domainid=cls.account.domainid,
                                serviceofferingid=cls.service_offering.id,
                                mode=cls.services["mode"]
                                )

        #Take 3 VM1 Snapshots
        #PLEASE UNCOMMENT ONCE VM SNAPSHOT DELAY BUG AFTER VM CREATION IS FIXED
        """cls.vmsnapshot_1 = VmSnapshot.create(
                                cls.apiclient,
                                cls.virtual_machine_1.id
                            )
        cls.vmsnapshot_2 = VmSnapshot.create(
                                cls.apiclient,
                                cls.virtual_machine_1.id
                            )
        cls.vmsnapshot_3 = VmSnapshot.create(
                                cls.apiclient,
                                cls.virtual_machine_1.id
                            )"""

        #Stop VMs
        cls.virtual_machine_1.stop(cls.apiclient)
        cls.virtual_machine_2.stop(cls.apiclient)
        cls.virtual_machine_3.stop(cls.apiclient)

        #Get ROOT volumes of 3 VMs        
        vm1RootVolumeResponse = Volume.list(
                                            cls.apiclient,
                                            virtualmachineid=cls.virtual_machine_1.id,
                                            type='ROOT',
                                            listall=True
                                            )
        vm2RootVolumeResponse = Volume.list(
                                            cls.apiclient,
                                            virtualmachineid=cls.virtual_machine_2.id,
                                            type='ROOT',
                                            listall=True
                                            )
        vm3RootVolumeResponse = Volume.list(
                                            cls.apiclient,
                                            virtualmachineid=cls.virtual_machine_3.id,
                                            type='ROOT',
                                            listall=True
                                            )
        cls.vm1_root_volume = vm1RootVolumeResponse[0]
        cls.vm2_root_volume = vm2RootVolumeResponse[0]
        cls.vm3_root_volume = vm3RootVolumeResponse[0]

        #Take 3 snapshots of VM2's ROOT volume
        cls.snapshot_1 = Snapshot.create(
                                         cls.apiclient,
                                         cls.vm2_root_volume.id,
                                         account=cls.account.name,
                                         domainid=cls.account.domainid
                                         )
        cls.snapshot_2 = Snapshot.create(
                                         cls.apiclient,
                                         cls.vm2_root_volume.id,
                                         account=cls.account.name,
                                         domainid=cls.account.domainid
                                         )
        cls.snapshot_3 = Snapshot.create(
                                         cls.apiclient,
                                         cls.vm2_root_volume.id,
                                         account=cls.account.name,
                                         domainid=cls.account.domainid
                                         )

        #Create 3 templates
        cls.template_1 = Template.create(
                                         cls.apiclient,
                                         cls.services["template"],
                                         cls.vm3_root_volume.id,
                                         account=cls.account.name,
                                         domainid=cls.account.domainid
                                         )
        cls.template_2 = Template.create(
                                         cls.apiclient,
                                         cls.services["template_2"],
                                         cls.vm3_root_volume.id,
                                         account=cls.account.name,
                                         domainid=cls.account.domainid
                                         )
        cls.template_3 = Template.create(
                                         cls.apiclient,
                                         cls.services["template_2"],
                                         cls.vm3_root_volume.id,
                                         account=cls.account.name,
                                         domainid=cls.account.domainid
                                         )
        
        cls._cleanup = [
                        cls.snapshot_1,
                        cls.snapshot_2,
                        cls.snapshot_3,
                        cls.account,
                        cls.disk_offering,
                        cls.service_offering
                        ]