Exemplo n.º 1
0
 def setUp(self):
     account = AzureAccount(self.params)
     account.login()
     cloud = Setup(self.params, self.name)
     self.vm = cloud.vm
     pre_delete = False
     pre_stop = False
     self.case_short_name = re.findall(r"Test.(.*)", self.name.name)[0]
     if self.case_short_name == "test_create_vm_all":
         cloud.vm.vm_name += "-all"
         cloud.vm.authentication_type = "all"
         self.vm.create()
         self.session = cloud.init_session()
         return
     if self.case_short_name == "test_create_vm_password":
         self.vm.vm_name += "-password"
         self.vm.authentication_type = "password"
         self.vm.generate_ssh_keys = False
         self.vm.ssh_key_value = None
         self.vm.create()
         self.session = cloud.init_session()
         return
     if self.case_short_name == "test_create_vm_sshkey":
         if self.vm.exists():
             self.vm.delete(wait=True)
         self.vm.create(wait=True)
         self.session = cloud.init_session()
     if self.case_short_name == "test_start_vm":
         pre_stop = True
     self.session = cloud.init_vm(pre_delete=pre_delete, pre_stop=pre_stop)
Exemplo n.º 2
0
 def setUp(self):
     account = AzureAccount(self.params)
     account.login()
     self.case_short_name = re.findall(r"Test.(.*)", self.name.name)[0]
     cloud = Setup(self.params, self.name)
     self.vm = cloud.vm
     self.session = cloud.init_vm()
     if "interrupt_ctrl_c" in self.name.name:
         self.session1 = cloud.init_session()
         self.session1.connect()
     status, output = self.session.cmd_status_output('sudo su -')
     self.assertEqual(status, 0,
                      "User [root] login failed\n{}".format(str(output)))
 def setUp(self):
     account = AzureAccount(self.params)
     account.login()
     self.case_short_name = re.findall(r"Test.(.*)", self.name.name)[0]
     cloud = Setup(self.params, self.name)
     self.vm = cloud.vm
     self.session = cloud.init_vm()
     if "interrupt_ctrl_c" in self.name.name:
         self.session1 = cloud.init_session()
         self.session1.connect()
     status, output = self.session.cmd_status_output('sudo su -')
     self.assertEqual(status, 0,
                      "User [root] login failed\n{}".format(str(output)))
     # Must stop NetworkManager or it will regenerate /etc/resolv.conf in RHEL-8.4
     if "test_waagent_depro" in self.case_short_name:
         self.session.cmd_output("systemctl stop NetworkManager")
Exemplo n.º 4
0
 def setUp(self):
     account = AzureAccount(self.params)
     account.login()
     self.case_short_name = re.findall(r"Test.(.*)", self.name.name)[0]
     self.project = self.params.get("rhel_ver", "*/VM/*")
     if self.case_short_name == "test_connectivity_check":
         if LooseVersion(self.project) >= LooseVersion("8.0"):
             self.cancel("RHEL-8 doesn't have network service. Skip.")
     cloud = Setup(self.params, self.name)
     self.vm = cloud.vm
     if self.case_short_name == "test_provision_vm_with_multiple_nics":
         self.vm.vm_name += "2nics"
         if self.vm.exists():
             self.vm.delete()
         publicip_name = self.vm.vm_name + "publicip"
         publicip = AzurePublicIP(self.params, name=publicip_name)
         if not publicip.exists():
             publicip.create()
         nic_name_list = []
         for n in range(0, 2):
             nic_name = "{}nic{}".format(self.vm.vm_name, n)
             subnet = self.vm.subnet if n == 0 else self.vm.subnet + str(n)
             n_publicip = publicip_name if n == 0 else None
             nic = AzureNIC(self.params,
                            name=nic_name,
                            subnet=subnet,
                            vnet=self.vm.vnet_name,
                            publicip=n_publicip)
             if not nic.exists():
                 nic.create()
             nic_name_list.append(nic_name)
         self.vm.nics = ' '.join(nic_name_list)
         self.session = cloud.init_session()
         return
     if self.case_short_name == "test_provision_vm_with_sriov_nic":
         self.vm.vm_name += "sriov"
         if self.vm.exists():
             self.vm.delete()
         publicip_name = self.vm.vm_name + "publicip"
         publicip = AzurePublicIP(self.params, name=publicip_name)
         if not publicip.exists():
             publicip.create()
         self.vm.nics = "{}nic".format(self.vm.vm_name)
         nic = AzureNIC(self.params,
                        name=self.vm.nics,
                        subnet=self.vm.subnet,
                        vnet=self.vm.vnet_name,
                        publicip=publicip_name,
                        sriov=True)
         if not nic.exists():
             nic.create()
         self.session = cloud.init_session()
         self.vm.size = "Standard_D3_v2"
         return
     if self.name.name.endswith("test_provision_vm_with_ipv6"):
         self.vm.vm_name += "ipv6"
         # if self.vm.exists():
         #     self.vm.delete()
         publicip_name = self.vm.vm_name + "publicip"
         publicip = AzurePublicIP(self.params,
                                  name=publicip_name)
         if not publicip.exists():
             publicip.create()
         self.vm.nics = "{}nic".format(self.vm.vm_name)
         nic = AzureNIC(self.params,
                        name=self.vm.nics,
                        subnet=self.vm.subnet,
                        vnet=self.vm.vnet_name,
                        publicip=publicip_name)
         if not nic.exists():
             nic.create()
         ipv6_config = AzureNicIpConfig(self.params,
                                        name=self.vm.nics+"ipv6",
                                        nic_name=self.vm.nics,
                                        ip_version="IPv6")
         if not ipv6_config.exists():
             ipv6_config.create()
         self.session = cloud.init_session()
         return
     self.session = cloud.init_vm()
     self.session.cmd_output("sudo su -")
     self.username = self.vm.vm_username
Exemplo n.º 5
0
class LifeCycleTest(Test):
    def setUp(self):
        self.cloud = Setup(self.params, self.name)
        self.vm = self.cloud.vm
        pre_delete = False
        pre_stop = False
        if self.name.name.endswith("test_create_vm_password"):
            if self.vm.exists():
                self.vm.delete(wait=True)
            self.session = self.cloud.init_session()
            return
        if self.name.name.endswith("test_create_vm_sshkey"):
            pre_delete = True
        if self.name.name.endswith("test_start_vm"):
            pre_stop = True
        self.session = self.cloud.init_vm(pre_delete=pre_delete,
                                          pre_stop=pre_stop)

    # TODO Add test_modify_instance_type for Alibaba cloud
    def test_create_vm_password(self):
        import base64
        user_data = """\
#cloud-config

user: {0}
password: {1}
chpasswd: {{ expire: False }}

ssh_pwauth: 1
""".format(self.vm.vm_username, self.vm.vm_password)
        self.vm.user_data = base64.b64encode(user_data.encode())
        self.vm.keypair = None
        self.vm.create(wait=True)
        if self.vm.is_stopped():
            self.vm.start(wait=True)
        self.session.connect(authentication="password")
        output = self.session.cmd_output('whoami')
        self.assertEqual(
            self.vm.vm_username, output, "Create VM with password error: \
output of cmd `who` unexpected -> %s" % output)
        # Test change password for Alibaba cloud
        if self.cloud.cloud_provider == 'alibaba':
            self.vm.vm_password = "******"
            self.vm.reset_password(new_password=self.vm.vm_password)
            self.vm.reboot(wait=True)
            self.session = self.cloud.init_session()
            self.session.connect(authentication="password")
            output = self.session.cmd_output('whoami')
            self.assertEqual(
                self.vm.vm_username, output, "Start VM error after change \
password: output of cmd `who` unexpected -> %s" % output)

    def test_create_vm_sshkey(self):
        output = self.session.cmd_output('whoami')
        self.assertEqual(
            self.vm.vm_username, output,
            "Create VM with sshkey error: output of cmd `who` unexpected -> %s"
            % output)

    def test_start_vm(self):
        self.vm.start(wait=True)
        self.session.connect(timeout=300)
        output = self.session.cmd_output('whoami')
        self.assertEqual(
            self.vm.vm_username, output,
            "Start VM error: output of cmd `who` unexpected -> %s" % output)

    def test_pause_unpause_vm(self):
        self.vm.pause(wait=True)
        self.vm.unpause(wait=True)
        output = self.session.cmd_output('whoami')
        self.assertEqual(
            self.vm.vm_username, output,
            "Pause/Unpause VM error: output of cmd `who` unexpected -> %s" %
            output)

    def test_reboot_vm(self):
        before = self.session.cmd_output('last reboot')
        self.vm.reboot(wait=True)
        self.session.connect(timeout=300)
        output = self.session.cmd_output('whoami')
        self.assertEqual(
            self.vm.vm_username, output,
            "Reboot VM error: output of cmd `who` unexpected -> %s" % output)
        after = self.session.cmd_output('last reboot')
        self.assertNotEqual(
            before, after,
            "Reboot VM error: before -> %s; after -> %s" % (before, after))

    def test_reboot_inside_vm(self):
        before = self.session.cmd_output('last reboot')
        self.session.send_line('sudo reboot')
        time.sleep(10)
        self.session.connect(timeout=300)
        output = self.session.cmd_output('whoami')
        self.assertEqual(
            self.vm.vm_username, output,
            "Reboot VM error: output of cmd `who` unexpected -> %s" % output)
        after = self.session.cmd_output('last reboot')
        self.assertNotEqual(
            before, after,
            "Reboot VM error: before -> %s; after -> %s" % (before, after))

    def test_stop_vm(self):
        self.vm.stop(wait=True)
        self.assertTrue(self.vm.is_stopped(),
                        "Stop VM error: VM status is not SHUTOFF")

    def test_delete_vm(self):
        self.vm.delete(wait=True)
        self.assertFalse(self.vm.exists(), "Delete VM error: VM still exists")

    def tearDown(self):
        if self.name.name.endswith("create_vm_password"):
            self.vm.delete(wait=True)
        self.session.close()
 def setUp(self):
     account = AzureAccount(self.params)
     account.login()
     self.project = self.params.get("rhel_ver", "*/VM/*")
     self.case_short_name = re.findall(r"Test.(.*)", self.name.name)[0]
     self.pwd = os.path.abspath(os.path.dirname(__file__))
     if self.case_short_name == "test_cloudinit_provision_gen2_vm":
         if LooseVersion(self.project) < LooseVersion('7.8'):
             self.cancel(
                 "Skip case because RHEL-{} ondemand image doesn't support gen2".format(self.project))
         cloud = Setup(self.params, self.name, size="DS2_v2")
     else:
         cloud = Setup(self.params, self.name)
     if self.case_short_name == "test_cloudinit_provision_gen2_vm":
         self.image = AzureImage(self.params, generation="V2")
         self.image.create()
         cloud.vm.image = self.image.name
         cloud.vm.vm_name += "-gen2"
         cloud.vm.use_unmanaged_disk = False
     self.vm = cloud.vm
     self.package = self.params.get("packages", "*/Other/*")
     if self.case_short_name in [
             "test_cloudinit_login_with_password",
             "test_cloudinit_login_with_publickey",
             "test_cloudinit_save_and_handle_customdata_script",
             "test_cloudinit_save_and_handle_customdata_cloudinit_config",
             "test_cloudinit_assign_identity",
     ]:
         if self.vm.exists():
             self.vm.delete()
         self.session = cloud.init_session()
         return
     if self.case_short_name == \
             "test_cloudinit_provision_vm_with_multiple_nics":
         self.vm.vm_name += "2nics"
         if self.vm.exists():
             self.vm.delete()
         publicip_name = self.vm.vm_name + "publicip"
         publicip = AzurePublicIP(self.params, name=publicip_name)
         if not publicip.exists():
             publicip.create()
         nic_name_list = []
         for n in range(0, 2):
             nic_name = "{}nic{}".format(self.vm.vm_name, n)
             subnet = self.vm.subnet if n == 0 else self.vm.subnet + str(n)
             n_publicip = publicip_name if n == 0 else None
             nic = AzureNIC(self.params,
                            name=nic_name,
                            subnet=subnet,
                            vnet=self.vm.vnet_name,
                            publicip=n_publicip)
             if not nic.exists():
                 nic.create()
             nic_name_list.append(nic_name)
         self.vm.nics = ' '.join(nic_name_list)
         self.session = cloud.init_session()
         return
     if self.case_short_name == "test_cloudinit_provision_vm_with_sriov_nic":
         self.vm.vm_name += "sriov"
         if self.vm.exists():
             self.vm.delete()
         publicip_name = self.vm.vm_name + "publicip"
         publicip = AzurePublicIP(self.params, name=publicip_name)
         if not publicip.exists():
             publicip.create()
         self.vm.nics = "{}nic".format(self.vm.vm_name)
         nic = AzureNIC(self.params,
                        name=self.vm.nics,
                        subnet=self.vm.subnet,
                        vnet=self.vm.vnet_name,
                        publicip=publicip_name,
                        sriov=True)
         if not nic.exists():
             nic.create()
         self.session = cloud.init_session()
         self.vm.size = "Standard_D3_v2"
         return
     if self.name.name.endswith("test_cloudinit_provision_vm_with_ipv6"):
         self.vm.vm_name += "ipv6"
         if self.vm.exists():
             self.vm.delete()
         publicip_name = self.vm.vm_name + "publicip"
         publicip = AzurePublicIP(self.params,
                                  name=publicip_name)
         if not publicip.exists():
             publicip.create()
         self.vm.nics = "{}nic".format(self.vm.vm_name)
         nic = AzureNIC(self.params,
                        name=self.vm.nics,
                        subnet=self.vm.subnet,
                        vnet=self.vm.vnet_name,
                        publicip=publicip_name)
         if not nic.exists():
             nic.create()
         ipv6_config = AzureNicIpConfig(self.params,
                                        name=self.vm.nics+"ipv6",
                                        nic_name=self.vm.nics,
                                        ip_version="IPv6")
         if not ipv6_config.exists():
             ipv6_config.create()
         self.session = cloud.init_session()
         return
     self.session = cloud.init_vm()
     if self.case_short_name == "test_cloudinit_upgrade_downgrade_package":
         rhel7_old_pkg_url = "http://download.eng.bos.redhat.com/brewroot/vol/rhel-7/packages/cloud-init/18.2/1.el7/x86_64/cloud-init-18.2-1.el7.x86_64.rpm"
         rhel8_old_pkg_url = "http://download.eng.bos.redhat.com/brewroot/vol/rhel-8/packages/cloud-init/18.2/1.el8/noarch/cloud-init-18.2-1.el8.noarch.rpm"
         try:
             self.assertEqual(0, self.session.cmd_status_output("ls /tmp/{}".format(self.package))[0],
                              "No new pakcage in guest VM")
             import requests
             if str(self.project).startswith('7'):
                 old_pkg_url = rhel7_old_pkg_url
             elif str(self.project).startswith('8'):
                 old_pkg_url = rhel8_old_pkg_url
             self.old_pkg = old_pkg_url.split('/')[-1]
             if not os.path.exists("/tmp/{}".format(self.old_pkg)):
                 r = requests.get(old_pkg_url, allow_redirects=True)
                 open("/tmp/{}".format(self.old_pkg), 'wb').write(r.content)
             self.session.copy_files_to(
                 local_path="/tmp/{}".format(self.old_pkg),
                 remote_path="/tmp/{}".format(self.old_pkg))
             self.assertEqual(0, self.session.cmd_status_output("ls /tmp/{}".format(self.old_pkg))[0],
                              "No old pakcage in guest VM")
         except:
             self.cancel(
                 "No old or new package in guest VM. Skip this case.")
Exemplo n.º 7
0
class CloudinitTest(Test):
    def setUp(self):
        self.cloud = Setup(self.params, self.name, create_timeout=300)
        self.vm = self.cloud.vm
        self.ssh_wait_timeout = 600
        pre_delete = False
        pre_stop = False
        if self.name.name.endswith(
                "test_cloudinit_create_vm_login_repeatedly"):
            return
        if self.name.name.endswith("test_cloudinit_login_with_password"):
            if self.vm.exists():
                self.vm.delete(wait=True)
            self.session = self.cloud.init_session()
            return
        if self.name.name.endswith("test_cloudinit_login_with_publickey"):
            pre_delete = True
        self.session = self.cloud.init_vm(pre_delete=pre_delete,
                                          pre_stop=pre_stop)

    def test_cloudinit_login_with_publickey(self):
        """
        :avocado: tags=tier1,cloudinit
        RHEL7-103831 - CLOUDINIT-TC: VM can successfully login
        after provisioning(with public key authentication)
        1. Create a VM with only public key authentication
        2. Login with publickey, should have sudo privilege
        """
        output = self.session.cmd_output('whoami')
        self.assertEqual(
            self.vm.vm_username, output,
            "Login VM with publickey error: output of cmd `whoami` unexpected -> %s"
            % output)
        self.assertIn(
            "%s ALL=(ALL) NOPASSWD:ALL" % self.vm.vm_username,
            self.session.cmd_output(
                "sudo cat /etc/sudoers.d/90-cloud-init-users"),
            "No sudo privilege")

    def test_cloudinit_check_hostname(self):
        """
        :avocado: tags=tier1,cloudinit
        RHEL7-103833 - CLOUDINIT-TC: Successfully set VM hostname
        """
        output = self.session.cmd_output("hostname").split('.')[0]
        self.assertEqual(output, self.vm.vm_name.replace('_', '-'),
                         "The hostname is wrong")

    def test_cloudinit_check_services_status(self):
        '''
        :avocado: tags=tier1,cloudinit
        RHEL-188130 - CLOUDINIT-TC: Check cloud-init services status
        check if four cloud-init services are active
        '''
        self.session.connect(timeout=self.ssh_wait_timeout)
        utils_lib.run_cmd(self,
                          'cloud-init -v',
                          msg='Get cloud-init version',
                          is_get_console=False)
        cmd = "sudo systemctl is-active cloud-init-local.service"
        utils_lib.run_cmd(self,
                          cmd,
                          expect_ret=0,
                          expect_kw='active',
                          is_get_console=False)
        cmd = "sudo systemctl is-active cloud-init.service"
        utils_lib.run_cmd(self,
                          cmd,
                          expect_ret=0,
                          expect_kw='active',
                          is_get_console=False)
        cmd = "sudo systemctl is-active cloud-config.service"
        utils_lib.run_cmd(self,
                          cmd,
                          expect_ret=0,
                          expect_kw='active',
                          is_get_console=False)
        cmd = "sudo systemctl is-active cloud-final.service"
        utils_lib.run_cmd(self,
                          cmd,
                          expect_ret=0,
                          expect_kw='active',
                          is_get_console=False)

    def test_cloudinit_check_log_no_traceback(self):
        '''
        :avocado: tags=tier2,cloudinit
        RHEL-188134 - CLOUDINIT-TC: Check no "Traceback" keyword in /var/log/cloud-init.log
        check no traceback log in cloudinit logs
        '''
        self.session.connect(timeout=self.ssh_wait_timeout)
        cmd = 'sudo cat /var/log/cloud-init.log'
        utils_lib.run_cmd(self,
                          cmd,
                          expect_ret=0,
                          expect_not_kw='Traceback',
                          msg='check /var/log/cloud-init.log',
                          is_get_console=False)
        if 'release 7' not in utils_lib.run_cmd(self,
                                                'sudo cat /etc/redhat-release',
                                                is_get_console=False):
            cmd = 'sudo cat /var/log/cloud-init-output.log'
            utils_lib.run_cmd(self,
                              cmd,
                              expect_ret=0,
                              expect_not_kw='Traceback',
                              msg='check /var/log/cloud-init-output.log',
                              is_get_console=False)

    def test_cloudinit_check_log_no_unexpected(self):
        '''
        :avocado: tags=tier2,cloudinit
        RHEL-188135 - CLOUDINIT-TC: Check no "unexpected" keyword in /var/log/cloud-init.log
        bz#: 1827207
        check no unexpected error log in cloudinit logs
        '''
        self.session.connect(timeout=self.ssh_wait_timeout)
        cmd = 'sudo cat /var/log/cloud-init.log'
        utils_lib.run_cmd(self,
                          cmd,
                          expect_ret=0,
                          expect_not_kw='unexpected',
                          msg='check /var/log/cloud-init.log',
                          is_get_console=False)
        if 'release 7' not in utils_lib.run_cmd(self,
                                                'sudo cat /etc/redhat-release',
                                                is_get_console=False):
            cmd = 'sudo cat /var/log/cloud-init-output.log'
            utils_lib.run_cmd(self,
                              cmd,
                              expect_ret=0,
                              expect_not_kw='unexpected',
                              msg='check /var/log/cloud-init-output.log',
                              is_get_console=False)

    def test_cloudinit_check_log_no_critical(self):
        '''
        :avocado: tags=tier1,cloudinit
        RHEL-188131 - CLOUDINIT-TC: Check no "CRITICAL" level message in /var/log/cloud-init.log
        bz#: 1827207
        check no critical log in cloudinit logs
        '''
        self.session.connect(timeout=self.ssh_wait_timeout)
        cmd = 'sudo cat /var/log/cloud-init.log'
        utils_lib.run_cmd(self,
                          cmd,
                          expect_ret=0,
                          expect_not_kw='CRITICAL',
                          msg='check /var/log/cloud-init.log',
                          is_get_console=False)
        if 'release 7' not in utils_lib.run_cmd(self,
                                                'sudo cat /etc/redhat-release',
                                                is_get_console=False):
            cmd = 'sudo cat /var/log/cloud-init-output.log'
            utils_lib.run_cmd(self,
                              cmd,
                              expect_ret=0,
                              expect_not_kw='CRITICAL',
                              msg='check /var/log/cloud-init-output.log',
                              is_get_console=False)

    def test_cloudinit_check_log_no_warn(self):
        '''
        :avocado: tags=tier2,cloudinit
        RHEL-188133 - CLOUDINIT-TC: Check no "WARNING" level message in /var/log/cloud-init.log
        bz#: 1821999
        check no warning log in cloudinit logs
        '''
        self.session.connect(timeout=self.ssh_wait_timeout)
        cmd = 'sudo cat /var/log/cloud-init.log'
        utils_lib.run_cmd(self,
                          cmd,
                          expect_ret=0,
                          expect_not_kw='WARNING',
                          msg='check /var/log/cloud-init.log',
                          is_get_console=False)
        if 'release 7' not in utils_lib.run_cmd(self,
                                                'sudo cat /etc/redhat-release',
                                                is_get_console=False):
            cmd = 'sudo cat /var/log/cloud-init-output.log'
            utils_lib.run_cmd(self,
                              cmd,
                              expect_ret=0,
                              expect_not_kw='WARNING',
                              msg='check /var/log/cloud-init-output.log',
                              is_get_console=False)

    def test_cloudinit_check_log_no_error(self):
        '''
        :avocado: tags=tier2,cloudinit
        RHEL-188132 - CLOUDINIT-TC: Check no "ERROR" level message in /var/log/cloud-init.log
        bz#: 1821999
        check no error log in cloudinit logs
        '''
        self.session.connect(timeout=self.ssh_wait_timeout)
        cmd = 'sudo cat /var/log/cloud-init.log'
        utils_lib.run_cmd(self,
                          cmd,
                          expect_ret=0,
                          expect_not_kw='ERROR',
                          msg='check /var/log/cloud-init.log',
                          is_get_console=False)
        if 'release 7' not in utils_lib.run_cmd(self,
                                                'sudo cat /etc/redhat-release',
                                                is_get_console=False):
            cmd = 'sudo cat /var/log/cloud-init-output.log'
            utils_lib.run_cmd(self,
                              cmd,
                              expect_ret=0,
                              expect_not_kw='ERROR',
                              msg='check /var/log/cloud-init-output.log',
                              is_get_console=False)

    def test_cloudinit_check_instance_data_json(self):
        """
        :avocado: tags=tier2,cloudinit
        RHEL-182312 - CLOUDINIT-TC:cloud-init can successfully write data to instance-data.json
        bz#: 1744526
        """
        self.session.connect(timeout=self.ssh_wait_timeout)
        cmd = 'ls -l /run/cloud-init/instance-data.json'
        utils_lib.run_cmd(self,
                          cmd,
                          expect_ret=0,
                          expect_not_kw='No such file or directory',
                          msg='check /run/cloud-init/instance-data.json',
                          is_get_console=False)

    def test_cloudinit_create_vm_login_repeatedly(self):
        """
        :avocado: tags=tier3,cloudinit,test_cloudinit_create_vm_login_repeatedly
        RHEL-188320 - CLOUDINIT-TC:create vm and login repeately
        bz#: 1803928
        create vm and login with ssh-key, run 50 times, because of race condition bug
        """
        pre_delete = True
        for x in range(50):
            self.log.info(str(x) + " run: create VM and login")
            self.session = self.cloud.init_vm(pre_delete=pre_delete,
                                              pre_stop=False)
            output = self.session.cmd_output('whoami')
            self.assertEqual(
                self.vm.vm_username, output,
                str(x) +
                " run: Login VM with publickey error: output of cmd `whoami` unexpected -> %s"
                % output)
            time.sleep(30)

    def test_cloudutils_growpart_resize_partition_first_boot(self):
        """
        :avocado: tags=tier1,cloud_utils_growpart
        RHEL-188669: CLOUDINIT-TC:[cloud-utils-growpart]resize partition during VM first boot
        """
        self.log.info(
            "RHEL-188669: CLOUDINIT-TC:[cloud-utils-growpart]resize partition \
during VM first boot")
        self.session.cmd_output("sudo su -")
        device = "/dev/vda"
        # Partition Table: gpt, partition number is 3
        # Partition Table: msdos, partition number is 1
        part_type = self.session.cmd_output(
            "parted -s %s print|grep 'Partition Table'|awk '{print $3}'" %
            device)
        part_number = "3" if part_type == "gpt" else "1"
        # VM flavor m1.medium, size 40G
        self.assertEqual(
            "42.9GB",
            self.session.cmd_output(
                "parted -s %s print|grep ' %s '|awk '{print $3}'" %
                (device, part_number)),
            "Fail to resize partition during first boot")

    def _growpart_auto_resize_partition(self, label):
        """
        :param label: msdos/gpt
        """
        self.session.cmd_output("sudo su -")
        self.assertEqual(
            self.session.cmd_status_output("which growpart")[0], 0,
            "No growpart command.")

        device = "/tmp/testdisk"
        if os.path.exists(device):
            self.session.cmd_output("rm -f {}".format(device))
        self.session.cmd_output("truncate -s 2G {}".format(device))
        self.session.cmd_output("parted -s {} mklabel {}".format(
            device, label))
        part_type = "primary" if label == "msdos" else ""
        part_name = "xfs" if label == "gpt" else ""
        # 1 partition
        self.session.cmd_output("parted -s {} mkpart {} {} 0 1000".format(
            device, part_type, part_name))
        self.session.cmd_output("parted -s {} print".format(device))
        self.assertEqual(
            self.session.cmd_status_output("growpart {} 1".format(device))[0],
            0, "Fail to run growpart")
        self.assertEqual(
            "2147MB",
            self.session.cmd_output(
                "parted -s %s print|grep ' 1 '|awk '{print $3}'" % device),
            "Fail to resize partition")
        # 2 partitions
        self.session.cmd_output("parted -s {} rm 1".format(device))
        self.session.cmd_output("parted -s {} mkpart {} {} 0 1000".format(
            device, part_type, part_name))
        self.session.cmd_output("parted -s {} mkpart {} {} 1800 1900".format(
            device, part_type, part_name))
        self.session.cmd_output("parted -s {} print".format(device))
        exit_status, output = self.session.cmd_status_output(
            "growpart {} 1".format(device))
        self.assertEqual(exit_status, 0,
                         "Run growpart failed: {}".format(output))
        self.assertEqual(
            "1800MB",
            self.session.cmd_output(
                "parted -s %s print|grep ' 1 '|awk '{print $3}'" % device),
            "Fail to resize partition")

    def test_cloudutils_growpart_auto_resize_partition_in_gpt(self):
        """
        :avocado: tags=tier1,cloud_utils_growpart
        RHEL-171053: CLOUDINIT-TC: [cloud-utils-growpart] Auto resize\
                     partition in gpt
        BZ#1695091
        """
        self.log.info("RHEL-171053: CLOUDINIT-TC: [cloud-utils-growpart] \
Auto resize partition in gpt")
        self._growpart_auto_resize_partition("gpt")

    def test_cloudutils_growpart_auto_resize_partition_in_mbr(self):
        """
        :avocado: tags=tier1,cloud_utils_growpart
        RHEL-188633: CLOUDINIT-TC: [cloud-utils-growpart] Auto resize\
                     partition in MBR
        """
        self.log.info(
            "RHEL-188633: CLOUDINIT-TC: [cloud-utils-growpart] Auto resize\
                     partition in MBR")
        self._growpart_auto_resize_partition("msdos")

    def test_cloudinit_login_with_password(self):
        """
        :avocado: tags=tier1,cloudinit
        RHEL7-103830: CLOUDINIT-TC: VM can successfully login
        after provisioning(with password authentication)
        1. Create a VM with only password authentication
        2. Login with password, should have sudo privilege
        """
        import base64
        self.log.info("RHEL7-103830: CLOUDINIT-TC: VM can successfully login "
                      "after provisioning(with password authentication)")

        user_data = """\
#cloud-config

user: {0}
password: {1}
chpasswd: {{ expire: False }}
ssh_pwauth: 1
""".format(self.vm.vm_username, self.vm.vm_password)
        self.vm.user_data = base64.b64encode(
            user_data.encode('utf-8')).decode('utf-8')
        self.vm.keypair = None
        self.vm.create(wait=True)
        self.session.connect(authentication="password")
        self.assertEqual(self.vm.vm_username,
                         self.session.cmd_output("whoami"),
                         "Fail to login with password")
        self.assertIn(
            "%s ALL=(ALL) NOPASSWD:ALL" % self.vm.vm_username,
            self.session.cmd_output(
                "sudo cat /etc/sudoers.d/90-cloud-init-users"),
            "No sudo privilege")

    def tearDown(self):
        self.session.close()
class LifeCycleTest(Test):
    def setUp(self):
        self.cloud = Setup(self.params, self.name)
        self.vm = self.cloud.vm
        pre_delete = False
        pre_stop = False
        if self.name.name.endswith("test_create_vm_password"):
            if self.vm.exists():
                self.vm.delete(wait=True)
            self.session = self.cloud.init_session()
            return
        if self.name.name.endswith("test_create_vm_sshkey"):
            pre_delete = True
        if self.name.name.endswith("test_start_vm"):
            pre_stop = True
        self.session = self.cloud.init_vm(pre_delete=pre_delete,
                                          pre_stop=pre_stop)

    def test_create_vm_password(self):
        self.vm.ssh_pubkey = None
        self.vm.create(wait=True)
        if self.vm.is_stopped():
            self.vm.start(wait=True)
        self.session.connect(authentication="password")
        output = self.session.cmd_output('whoami')
        self.assertEqual(
            self.vm.vm_username, output, "Create VM with password error: \
output of cmd `who` unexpected -> %s" % output)

    def test_create_vm_sshkey(self):
        output = self.session.cmd_output('whoami')
        self.assertEqual(
            self.vm.vm_username, output,
            "Create VM with sshkey error: output of cmd `who` unexpected -> %s"
            % output)

    def test_start_vm(self):
        self.vm.start(wait=True)
        self.session.connect(timeout=300)
        output = self.session.cmd_output('whoami')
        self.assertEqual(
            self.vm.vm_username, output,
            "Start VM error: output of cmd `who` unexpected -> %s" % output)

    def test_reboot_vm(self):
        before = self.session.cmd_output('last reboot')
        self.vm.reboot(wait=True)
        self.session.connect(timeout=300)
        output = self.session.cmd_output('whoami')
        self.assertEqual(
            self.vm.vm_username, output,
            "Reboot VM error: output of cmd `who` unexpected -> %s" % output)
        after = self.session.cmd_output('last reboot')
        self.assertNotEqual(
            before, after,
            "Reboot VM error: before -> %s; after -> %s" % (before, after))

    def test_reboot_inside_vm(self):
        before = self.session.cmd_output('last reboot')
        self.session.send_line('sudo reboot')
        time.sleep(10)
        self.session.connect(timeout=300)
        output = self.session.cmd_output('whoami')
        self.assertEqual(
            self.vm.vm_username, output,
            "Reboot VM error: output of cmd `who` unexpected -> %s" % output)
        after = self.session.cmd_output('last reboot')
        self.assertNotEqual(
            before, after,
            "Reboot VM error: before -> %s; after -> %s" % (before, after))

    def test_stop_vm(self):
        self.vm.stop(wait=True)
        self.assertTrue(self.vm.is_stopped(),
                        "Stop VM error: VM status is not SHUTOFF")

    def test_delete_vm(self):
        self.vm.delete(wait=True)
        self.assertFalse(self.vm.exists(), "Delete VM error: VM still exists")

    def tearDown(self):
        if self.name.name.endswith("create_vm_password"):
            self.vm.delete(wait=True)
        self.session.close()