qemu_guest_agent.py 91.9 KB
Newer Older
L
Lucas Meneghel Rodrigues 已提交
1 2 3
import logging
import time
import os
4
import re
5
import base64
6 7 8

import aexpect

9
from avocado.utils import genio
10 11
from avocado.utils import path as avo_path
from avocado.utils import process
12
from avocado.core import exceptions
13

14
from virttest import error_context
15
from virttest import guest_agent
16
from virttest import utils_misc
17
from virttest import utils_disk
18
from virttest import env_process
19
from virttest import utils_net
20 21


22
class BaseVirtTest(object):
L
Lucas Meneghel Rodrigues 已提交
23

24 25 26 27 28 29 30 31 32 33 34 35
    def __init__(self, test, params, env):
        self.test = test
        self.params = params
        self.env = env

    def initialize(self, test, params, env):
        if test:
            self.test = test
        if params:
            self.params = params
        if env:
            self.env = env
36 37 38 39 40 41
        start_vm = self.params["start_vm"]
        self.start_vm = start_vm
        if self.start_vm == "yes":
            vm = self.env.get_vm(params["main_vm"])
            vm.verify_alive()
            self.vm = vm
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86

    def setup(self, test, params, env):
        if test:
            self.test = test
        if params:
            self.params = params
        if env:
            self.env = env

    def run_once(self, test, params, env):
        if test:
            self.test = test
        if params:
            self.params = params
        if env:
            self.env = env

    def before_run_once(self, test, params, env):
        pass

    def after_run_once(self, test, params, env):
        pass

    def cleanup(self, test, params, env):
        pass

    def execute(self, test, params, env):
        self.initialize(test, params, env)
        self.setup(test, params, env)
        try:
            self.before_run_once(test, params, env)
            self.run_once(test, params, env)
            self.after_run_once(test, params, env)
        finally:
            self.cleanup(test, params, env)


class QemuGuestAgentTest(BaseVirtTest):

    def __init__(self, test, params, env):
        BaseVirtTest.__init__(self, test, params, env)

        self._open_session_list = []
        self.gagent = None
        self.vm = None
87 88
        self.gagent_install_cmd = params.get("gagent_install_cmd")
        self.gagent_uninstall_cmd = params.get("gagent_uninstall_cmd")
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105

    def _get_session(self, params, vm):
        if not vm:
            vm = self.vm
        vm.verify_alive()
        timeout = int(params.get("login_timeout", 360))
        session = vm.wait_for_login(timeout=timeout)
        return session

    def _cleanup_open_session(self):
        try:
            for s in self._open_session_list:
                if s:
                    s.close()
        except Exception:
            pass

106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
    @error_context.context_aware
    def _check_ga_pkg(self, session, cmd_check_pkg):
        '''
        Check if the package is installed
        :param session: use for sending cmd
        :param cmd_check_pkg: cmd to check if ga pkg is installed
        '''
        error_context.context("Check whether qemu-ga is installed.", logging.info)
        s, o = session.cmd_status_output(cmd_check_pkg)
        return s == 0

    @error_context.context_aware
    def _check_ga_service(self, session, cmd_check_status):
        '''
        Check if the service is started.
        :param session: use for sending cmd
        :param cmd_check_status: cmd to check if ga service is started
        '''
        error_context.context("Check whether qemu-ga service is started.", logging.info)
        s, o = session.cmd_status_output(cmd_check_status)
        return s == 0

    @error_context.context_aware
129 130 131 132 133 134
    def gagent_install(self, session, vm):
        """
        install qemu-ga pkg in guest.
        :param session: use for sending cmd
        :param vm: guest object.
        """
135 136
        error_context.context("Try to install 'qemu-guest-agent' package.",
                              logging.info)
137
        s, o = session.cmd_status_output(self.gagent_install_cmd)
138
        if s:
139 140 141 142
            self.test.fail("Could not install qemu-guest-agent package"
                           " in VM '%s', detail: '%s'" % (vm.name, o))

    @error_context.context_aware
143
    def gagent_uninstall(self, session, vm):
144 145 146 147 148 149 150
        """
        uninstall qemu-ga pkg in guest.
        :param session: use for sending cmd
        :param vm: guest object.
        """
        error_context.context("Try to uninstall 'qemu-guest-agent' package.",
                              logging.info)
151
        s, o = session.cmd_status_output(self.gagent_uninstall_cmd)
152 153 154
        if s:
            self.test.fail("Could not uninstall qemu-guest-agent package "
                           "in VM '%s', detail: '%s'" % (vm.name, o))
155

156
    @error_context.context_aware
157
    def gagent_start(self, session, vm):
158
        """
159
        Start qemu-guest-agent in guest.
160
        :param session: use for sending cmd
161
        :param vm: Virtual machine object.
162
        """
163 164 165 166
        error_context.context("Try to start qemu-ga service.", logging.info)
        s, o = session.cmd_status_output(self.params["gagent_start_cmd"])
        # if start a running service, for rhel guest return code is zero,
        # for windows guest,return code is not zero
167
        if s and "already been started" not in o:
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
            self.test.fail("Could not start qemu-ga service in VM '%s',"
                           "detail: '%s'" % (vm.name, o))

    @error_context.context_aware
    def gagent_stop(self, session, vm):
        """
        Stop qemu-guest-agent in guest.
        :param session: use for sending cmd
        :param vm: Virtual machine object.
        :param args: Stop cmd.
        """
        error_context.context("Try to stop qemu-ga service.", logging.info)
        s, o = session.cmd_status_output(self.params["gagent_stop_cmd"])
        # if stop a stopped service,for rhel guest return code is zero,
        # for windows guest,return code is not zero.
        if s and "is not started" not in o:
            self.test.fail("Could not stop qemu-ga service in VM '%s', "
                           "detail: '%s'" % (vm.name, o))
186

187
    @error_context.context_aware
188 189 190 191
    def gagent_create(self, params, vm, *args):
        if self.gagent:
            return self.gagent

192
        error_context.context("Create a QemuAgent object.", logging.info)
193
        if not (args and isinstance(args, tuple) and len(args) == 2):
194
            self.test.error("Got invalid arguments for guest agent")
195 196 197

        gagent_serial_type = args[0]
        gagent_name = args[1]
198

199
        filename = vm.get_serial_console_filename(gagent_name)
200
        gagent = guest_agent.QemuAgent(vm, gagent_name, gagent_serial_type,
201
                                       filename, get_supported_cmds=True)
202 203 204 205
        self.gagent = gagent

        return self.gagent

206
    @error_context.context_aware
207
    def gagent_verify(self, params, vm):
208
        error_context.context("Check if guest agent work.", logging.info)
209 210

        if not self.gagent:
211 212
            self.test.error("Could not find guest agent object "
                            "for VM '%s'" % vm.name)
213 214 215 216

        self.gagent.verify_responsive()
        logging.info(self.gagent.cmd("guest-info"))

217
    @error_context.context_aware
218 219
    def setup(self, test, params, env):
        BaseVirtTest.setup(self, test, params, env)
220
        if self.start_vm == "yes":
221
            session = self._get_session(params, self.vm)
222
            self._open_session_list.append(session)
223 224 225 226
            if self._check_ga_pkg(session, params.get("gagent_pkg_check_cmd")):
                logging.info("qemu-ga is already installed.")
            else:
                logging.info("qemu-ga is not installed.")
227
                self.gagent_install(session, self.vm)
228 229 230 231 232

            if self._check_ga_service(session, params.get("gagent_status_cmd")):
                logging.info("qemu-ga service is already running.")
            else:
                logging.info("qemu-ga service is not running.")
233
                self.gagent_start(session, self.vm)
234 235

            args = [params.get("gagent_serial_type"), params.get("gagent_name")]
236
            self.gagent_create(params, self.vm, *args)
237 238 239

    def run_once(self, test, params, env):
        BaseVirtTest.run_once(self, test, params, env)
240
        if self.start_vm == "yes":
241
            self.gagent_verify(self.params, self.vm)
242 243 244 245 246

    def cleanup(self, test, params, env):
        self._cleanup_open_session()


247 248 249 250 251 252 253 254 255 256
class QemuGuestAgentBasicCheck(QemuGuestAgentTest):

    def __init__(self, test, params, env):
        QemuGuestAgentTest.__init__(self, test, params, env)

        self.exception_list = []

    def gagent_check_install(self, test, params, env):
        pass

257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
    @error_context.context_aware
    def gagent_check_install_uninstall(self, test, params, env):
        """
        Repeat install/uninstall qemu-ga package in guest

        :param test: kvm test object
        :param params: Dictionary with the test parameters
        :param env: Dictionary with test environment.
        """
        repeats = int(params.get("repeat_times", 1))
        logging.info("Repeat install/uninstall qemu-ga pkg for %s times" % repeats)

        if not self.vm:
            self.vm = self.env.get_vm(params["main_vm"])
            self.vm.verify_alive()

        session = self._get_session(params, self.vm)
X
Xu Han 已提交
274
        for i in range(repeats):
275
            error_context.context("Repeat: %s/%s" % (i + 1, repeats),
276 277
                                  logging.info)
            if self._check_ga_pkg(session, params.get("gagent_pkg_check_cmd")):
278 279
                self.gagent_uninstall(session, self.vm)
                self.gagent_install(session, self.vm)
280
            else:
281 282
                self.gagent_install(session, self.vm)
                self.gagent_uninstall(session, self.vm)
283 284
        session.close()

285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
    @error_context.context_aware
    def gagent_check_stop_start(self, test, params, env):
        """
        Repeat stop/restart qemu-ga service in guest.

        :param test: kvm test object
        :param params: Dictionary with the test parameters
        :param env: Dictionary with test environment.
        """
        repeats = int(params.get("repeat_times", 1))
        logging.info("Repeat stop/restart qemu-ga service for %s times" % repeats)

        if not self.vm:
            self.vm = self.env.get_vm(params["main_vm"])
            self.vm.verify_alive()
        session = self._get_session(params, self.vm)
X
Xu Han 已提交
301
        for i in range(repeats):
302 303 304 305 306 307 308 309 310
            error_context.context("Repeat: %s/%s" % (i + 1, repeats),
                                  logging.info)
            self.gagent_stop(session, self.vm)
            time.sleep(1)
            self.gagent_start(session, self.vm)
            time.sleep(1)
            self.gagent_verify(params, self.vm)
        session.close()

311
    @error_context.context_aware
312 313 314 315 316 317 318
    def gagent_check_sync(self, test, params, env):
        """
        Execute "guest-sync" command to guest agent

        Test steps:
        1) Send "guest-sync" command in the host side.

L
Lucas Meneghel Rodrigues 已提交
319 320 321
        :param test: kvm test object
        :param params: Dictionary with the test parameters
        :param env: Dictionary with test environmen.
322
        """
323
        error_context.context("Check guest agent command 'guest-sync'", logging.info)
324 325
        self.gagent.sync()

326
    @error_context.context_aware
327
    def __gagent_check_shutdown(self, shutdown_mode):
328 329
        error_context.context("Check guest agent command 'guest-shutdown'"
                              ", shutdown mode '%s'" % shutdown_mode, logging.info)
330
        if not self.env or not self.params:
331
            self.test.error("You should run 'setup' method before test")
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349

        if not (self.vm and self.vm.is_alive()):
            vm = self.env.get_vm(self.params["main_vm"])
            vm.verify_alive()
            self.vm = vm
        self.gagent.shutdown(shutdown_mode)

    def __gagent_check_serial_output(self, pattern):
        start_time = time.time()
        while (time.time() - start_time) < self.vm.REBOOT_TIMEOUT:
            if pattern in self.vm.serial_console.get_output():
                return True
        return False

    def gagent_check_powerdown(self, test, params, env):
        """
        Shutdown guest with guest agent command "guest-shutdown"

L
Lucas Meneghel Rodrigues 已提交
350 351 352
        :param test: kvm test object
        :param params: Dictionary with the test parameters
        :param env: Dictionary with test environmen.
353 354 355
        """
        self.__gagent_check_shutdown(self.gagent.SHUTDOWN_MODE_POWERDOWN)
        if not utils_misc.wait_for(self.vm.is_dead, self.vm.REBOOT_TIMEOUT):
356
            test.fail("Could not shutdown VM via guest agent'")
357

358
    @error_context.context_aware
359 360 361 362
    def gagent_check_reboot(self, test, params, env):
        """
        Reboot guest with guest agent command "guest-shutdown"

L
Lucas Meneghel Rodrigues 已提交
363 364 365
        :param test: kvm test object
        :param params: Dictionary with the test parameters
        :param env: Dictionary with test environmen.
366 367
        """
        self.__gagent_check_shutdown(self.gagent.SHUTDOWN_MODE_REBOOT)
368
        pattern = params["gagent_guest_reboot_pattern"]
369
        error_context.context("Verify serial output has '%s'" % pattern)
370 371
        rebooted = self.__gagent_check_serial_output(pattern)
        if not rebooted:
372
            test.fail("Could not reboot VM via guest agent")
373
        error_context.context("Try to re-login to guest after reboot")
374 375 376
        try:
            session = self._get_session(self.params, None)
            session.close()
X
Xu Han 已提交
377
        except Exception as detail:
378 379
            test.fail("Could not login to guest"
                      " detail: '%s'" % detail)
380

381
    @error_context.context_aware
382 383 384 385
    def gagent_check_halt(self, test, params, env):
        """
        Halt guest with guest agent command "guest-shutdown"

L
Lucas Meneghel Rodrigues 已提交
386 387 388
        :param test: kvm test object
        :param params: Dictionary with the test parameters
        :param env: Dictionary with test environmen.
389 390
        """
        self.__gagent_check_shutdown(self.gagent.SHUTDOWN_MODE_HALT)
391
        pattern = params["gagent_guest_shutdown_pattern"]
392
        error_context.context("Verify serial output has '%s'" % pattern)
393 394
        halted = self.__gagent_check_serial_output(pattern)
        if not halted:
395
            test.fail("Could not halt VM via guest agent")
396 397 398
        # Since VM is halted, force shutdown it.
        try:
            self.vm.destroy(gracefully=False)
X
Xu Han 已提交
399
        except Exception as detail:
400 401
            logging.warn("Got an exception when force destroying guest:"
                         " '%s'", detail)
402

403
    @error_context.context_aware
404 405 406 407 408 409 410 411
    def gagent_check_sync_delimited(self, test, params, env):
        """
        Execute "guest-sync-delimited" command to guest agent

        :param test: kvm test object
        :param params: Dictionary with the test parameters
        :param env: Dictionary with test environment.
        """
412 413
        error_context.context("Check guest agent command 'guest-sync-delimited'",
                              logging.info)
414 415
        self.gagent.sync("guest-sync-delimited")

416
    @error_context.context_aware
417 418 419 420 421 422
    def _gagent_verify_password(self, vm, new_password):
        """
        check if the password  works well for the specific user
        """
        vm.wait_for_login(password=new_password)

423
    @error_context.context_aware
424 425 426
    def gagent_check_set_user_password(self, test, params, env):
        """
        Execute "guest-set-user-password" command to guest agent
427 428 429
        :param test: kvm test object
        :param params: Dictionary with the test parameters
        :param env: Dictionary with test environment.
430 431 432
        """
        old_password = params.get("password", "")
        new_password = params.get("new_password", "123456")
433
        ga_username = params.get("ga_username", "root")
434
        crypted = params.get("crypted", "") == "yes"
435
        error_context.context("Change guest's password.")
436
        try:
437 438
            self.gagent.set_user_password(new_password, crypted, ga_username)
            error_context.context("Check if the guest could be login by new password",
439
                                  logging.info)
440 441 442
            self._gagent_verify_password(self.vm, new_password)

        except guest_agent.VAgentCmdError:
443
            test.fail("Failed to set the new password for guest")
444 445

        finally:
446 447
            error_context.context("Reset back the password of guest", logging.info)
            self.gagent.set_user_password(old_password, username=ga_username)
448

449
    @error_context.context_aware
450 451
    def gagent_check_get_vcpus(self, test, params, env):
        """
452 453 454 455 456 457
        Execute "guest-get-vcpus" command to guest agent.

        Steps:
        1) Check can-offline field of guest agent.
        2) Check cpu number.

458 459 460
        :param test: kvm test object
        :param params: Dictionary with the test parameters
        :param env: Dictionary with test environment.
461
        """
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
        error_context.context("Check can-offline field of guest agent.", logging.info)
        vcpus_info = self.gagent.get_vcpus()
        cpu_num_qga = len(vcpus_info)
        for vcpu in vcpus_info:
            if params.get("os_type") == "linux" and not vcpu["can-offline"]:
                test.fail("Linux guest cpu can't be offline from qga"
                          "which isn't expected.")
            if params.get("os_type") == "windows" and vcpu["can-offline"]:
                test.fail("Windows guest cpu can be offline from qga"
                          "which isn't expected.")

        error_context.context("Check cpu number.", logging.info)
        session = self._get_session(params, self.vm)
        output = session.cmd_output(params["get_cpu_cmd"])
        session.close()

        if params.get("os_type") == "windows":
            cpu_list = output.strip().split('\n')
            cpu_num_guest = sum(map(int, cpu_list))
        else:
            cpu_num_guest = int(output)

        if cpu_num_qga != cpu_num_guest:
            test.fail("CPU number doen't match.\n"
                      "number from guest os is %s,number from guest-agent is %s." %
                      (cpu_num_guest, cpu_num_qga))
488

489
    @error_context.context_aware
490 491 492
    def gagent_check_set_vcpus(self, test, params, env):
        """
        Execute "guest-set-vcpus" command to guest agent
493 494 495
        :param test: kvm test object
        :param params: Dictionary with the test parameters
        :param env: Dictionary with test environment.
496
        """
497
        error_context.context("get the cpu number of the testing guest")
498 499
        vcpus_info = self.gagent.get_vcpus()
        vcpus_num = len(vcpus_info)
500
        error_context.context("the vcpu number:%d" % vcpus_num, logging.info)
501
        if vcpus_num < 2:
502
            test.error("the vpus number of guest should be more than 1")
503 504 505 506 507 508 509
        vcpus_info[vcpus_num - 1]["online"] = False
        del vcpus_info[vcpus_num - 1]["can-offline"]
        action = {'vcpus': [vcpus_info[vcpus_num - 1]]}
        self.gagent.set_vcpus(action)
        # Check if the result is as expected
        vcpus_info = self.gagent.get_vcpus()
        if vcpus_info[vcpus_num - 1]["online"] is not False:
510
            test.fail("the vcpu status is not changed as expected")
511

512
    @error_context.context_aware
513 514 515 516 517 518 519 520 521 522
    def gagent_check_get_time(self, test, params, env):
        """
        Execute "guest-get-time" command to guest agent
        :param test: kvm test object
        :param params: Dictionary with the test parameters
        :param env: Dictionary with test environment.
        """
        timeout = float(params.get("login_timeout", 240))
        session = self.vm.wait_for_login(timeout=timeout)
        get_guest_time_cmd = params["get_guest_time_cmd"]
523
        error_context.context("get the time of the guest", logging.info)
524
        nanoseconds_time = self.gagent.get_time()
525 526
        error_context.context("the time get by guest-get-time is '%d' "
                              % nanoseconds_time, logging.info)
527 528
        guest_time = session.cmd_output(get_guest_time_cmd)
        if not guest_time:
529
            test.error("can't get the guest time for contrast")
530 531
        error_context.context("the time get inside guest by shell cmd is '%d' "
                              % int(guest_time), logging.info)
532 533
        delta = abs(int(guest_time) - nanoseconds_time / 1000000000)
        if delta > 3:
534 535
            test.fail("the time get by guest agent is not the same "
                      "with that by time check cmd inside guest")
536

537
    @error_context.context_aware
538 539 540 541 542 543 544 545 546 547
    def gagent_check_set_time(self, test, params, env):
        """
        Execute "guest-set-time" command to guest agent
        :param test: kvm test object
        :param params: Dictionary with the test parameters
        :param env: Dictionary with test environment.
        """
        timeout = float(params.get("login_timeout", 240))
        session = self.vm.wait_for_login(timeout=timeout)
        get_guest_time_cmd = params["get_guest_time_cmd"]
548
        error_context.context("get the time of the guest", logging.info)
549 550
        guest_time_before = session.cmd_output(get_guest_time_cmd)
        if not guest_time_before:
551
            test.error("can't get the guest time for contrast")
552 553
        error_context.context("the time before being moved back into past  is '%d' "
                              % int(guest_time_before), logging.info)
554 555 556 557
        # Need to move the guest time one week into the past
        target_time = (int(guest_time_before) - 604800) * 1000000000
        self.gagent.set_time(target_time)
        guest_time_after = session.cmd_output(get_guest_time_cmd)
558 559
        error_context.context("the time after being moved back into past  is '%d' "
                              % int(guest_time_after), logging.info)
560 561
        delta = abs(int(guest_time_after) - target_time / 1000000000)
        if delta > 3:
562
            test.fail("the time set for guest is not the same with target")
563 564 565 566 567
        # Set the system time from the hwclock
        if params["os_type"] != "windows":
            move_time_cmd = params["move_time_cmd"]
            session.cmd("hwclock -w")
            guest_hwclock_after_set = session.cmd_output("date +%s")
568 569
            error_context.context("hwclock is '%d' " % int(guest_hwclock_after_set),
                                  logging.info)
570 571
            session.cmd(move_time_cmd)
            time_after_move = session.cmd_output("date +%s")
572 573
            error_context.context("the time after move back is '%d' "
                                  % int(time_after_move), logging.info)
574 575
            self.gagent.set_time()
            guest_time_after_reset = session.cmd_output(get_guest_time_cmd)
576 577
            error_context.context("the time after being reset is '%d' "
                                  % int(guest_time_after_reset), logging.info)
578
            guest_hwclock = session.cmd_output("date +%s")
579 580
            error_context.context("hwclock for compare is '%d' " % int(guest_hwclock),
                                  logging.info)
581 582
            delta = abs(int(guest_time_after_reset) - int(guest_hwclock))
            if delta > 3:
583
                test.fail("The guest time can't be set from hwclock on host")
584

585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660
    @error_context.context_aware
    def gagent_check_time_sync(self, test, params, env):
        """
        Run "guest-set-time" to sync time after stop/cont vm

        Steps:
        1) start windows time service in guest and
        change ntp server to clock.redhat.com
        2) stop vm
        3) wait 3 mins and resume vm
        4) execute "guest-set-time" cmd via qga
        5) query time offset of vm,it should be less than 3 seconds

        :param test: kvm test object
        :param params: Dictionary with the test parameters
        :param env: Dictionary with test environment.
        """
        def time_drift():
            """
            Get the time diff between host and guest
            :return: time diff
            """
            host_time = process.system_output("date +%s")
            get_guest_time_cmd = params["get_guest_time_cmd"]
            guest_time = session.cmd_output(get_guest_time_cmd)
            logging.info("Host time is %s,guest time is %s." % (host_time,
                                                                guest_time))
            time_diff = abs(int(host_time) - int(guest_time))
            return time_diff

        time_config_cmd = params["time_service_config"]
        time_service_status_cmd = params["time_service_status_cmd"]
        time_service_start_cmd = params["time_service_start_cmd"]
        time_service_stop_cmd = params["time_service_stop_cmd"]
        session = self._get_session(self.params, self.vm)
        self._open_session_list.append(session)

        error_context.context("Start windows time service.", logging.info)
        if session.cmd_status(time_service_status_cmd):
            session.cmd(time_service_start_cmd)

        error_context.context("Config time resource and restart time"
                              " service.", logging.info)
        session.cmd(time_config_cmd)
        session.cmd(time_service_stop_cmd)
        session.cmd(time_service_start_cmd)

        error_context.context("Stop the VM", logging.info)
        self.vm.pause()
        self.vm.verify_status("paused")

        pause_time = float(params["pause_time"])
        error_context.context("Sleep %s seconds." % pause_time, logging.info)
        time.sleep(pause_time)

        error_context.context("Resume the VM", logging.info)
        self.vm.resume()
        self.vm.verify_status("running")

        time_diff_before = time_drift()
        if time_diff_before < (pause_time - 5):
            test.error("Time is not paused about %s seconds." % pause_time)

        error_context.context("Execute guest-set-time cmd.", logging.info)
        self.gagent.set_time()

        logging.info("Wait a few seconds up to 30s to check guest time.")
        endtime = time.time() + 30
        while time.time() < endtime:
            time.sleep(2)
            time_diff_after = time_drift()
            if time_diff_after < 3:
                break
        else:
            test.fail("The guest time sync failed.")

661
    @error_context.context_aware
662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678
    def _get_mem_used(self, session, cmd):
        """
        get memory usage of the process

        :param session: use for sending cmd
        :param cmd: get details of the process
        """

        output = session.cmd_output(cmd)
        logging.info("The process details: %s" % output)
        try:
            memory_usage = int(output.split(" ")[-2].replace(",", ""))
            return memory_usage
        except Exception:
            raise exceptions.TestError("Get invalid memory usage by "
                                       "cmd '%s' (%s)" % (cmd, output))

679
    @error_context.context_aware
680 681 682 683 684 685 686 687 688 689 690 691 692 693 694
    def gagent_check_memory_leak(self, test, params, env):
        """
        repeat execute "guest-info" command to guest agent, check memory
        usage of the qemu-ga

        :param test: kvm test object
        :param params: Dictionary with the test parameters
        :param env: Dictionary with test environment.
        """

        timeout = float(params.get("login_timeout", 240))
        test_command = params.get("test_command", "guest-info")
        memory_usage_cmd = params.get("memory_usage_cmd",
                                      "tasklist | findstr /I qemu-ga.exe")
        session = self.vm.wait_for_login(timeout=timeout)
695 696
        error_context.context("get the memory usage of qemu-ga before run '%s'" %
                              test_command, logging.info)
697 698 699 700
        memory_usage_before = self._get_mem_used(session, memory_usage_cmd)
        session.close()
        repeats = int(params.get("repeats", 1))
        for i in range(repeats):
701 702
            error_context.context("execute '%s' %s times" % (test_command, i + 1),
                                  logging.info)
703 704 705
            return_msg = self.gagent.guest_info()
            logging.info(str(return_msg))
        self.vm.verify_alive()
706 707
        error_context.context("get the memory usage of qemu-ga after run '%s'" %
                              test_command, logging.info)
708 709 710 711 712
        session = self.vm.wait_for_login(timeout=timeout)
        memory_usage_after = self._get_mem_used(session, memory_usage_cmd)
        session.close()
        # less than 500K is acceptable.
        if memory_usage_after - memory_usage_before > 500:
713 714 715 716
            test.fail("The memory usages are different, "
                      "before run command is %skb and "
                      "after run command is %skb" % (memory_usage_before,
                                                     memory_usage_after))
717

718
    @error_context.context_aware
719 720 721 722 723 724 725 726 727 728 729 730 731 732
    def gagent_check_fstrim(self, test, params, env):
        """
        Execute "guest-fstrim" command to guest agent
        :param test: kvm test object
        :param params: Dictionary with the test parameters
        :param env: Dictionary with test environment.

        """
        def get_host_scsi_disk():
            """
            Get latest scsi disk which enulated by scsi_debug module
            Return the device name and the id in host
            """
            scsi_disk_info = process.system_output(
733 734
                avo_path.find_command('lsscsi'), shell=True)
            scsi_disk_info = scsi_disk_info.decode().splitlines()
735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756
            scsi_debug = [_ for _ in scsi_disk_info if 'scsi_debug' in _][-1]
            scsi_debug = scsi_debug.split()
            host_id = scsi_debug[0][1:-1]
            device_name = scsi_debug[-1]
            return (host_id, device_name)

        def get_guest_discard_disk(session):
            """
            Get disk without partitions in guest.
            """
            list_disk_cmd = "ls /dev/[sh]d*|sed 's/[0-9]//p'|uniq -u"
            disk = session.cmd_output(list_disk_cmd).splitlines()[0]
            return disk

        def get_provisioning_mode(device, host_id):
            """
            Get disk provisioning mode, value usually is 'writesame_16',
            depends on params for scsi_debug module.
            """
            device_name = os.path.basename(device)
            path = "/sys/block/%s/device/scsi_disk" % device_name
            path += "/%s/provisioning_mode" % host_id
757
            return genio.read_one_line(path).strip()
758 759 760 761 762 763 764

        def get_allocation_bitmap():
            """
            get block allocation bitmap
            """
            path = "/sys/bus/pseudo/drivers/scsi_debug/map"
            try:
765
                return genio.read_one_line(path).strip()
766 767 768 769 770 771 772 773 774 775 776 777 778 779 780
            except IOError:
                logging.warn("could not get bitmap info, path '%s' is "
                             "not exist", path)
            return ""

        for vm in env.get_all_vms():
            if vm:
                vm.destroy()
                env.unregister_vm(vm.name)
        host_id, disk_name = get_host_scsi_disk()
        provisioning_mode = get_provisioning_mode(disk_name, host_id)
        logging.info("Current provisioning_mode = '%s'", provisioning_mode)
        bitmap = get_allocation_bitmap()
        if bitmap:
            logging.debug("block allocation bitmap: %s" % bitmap)
781
            test.error("block allocation bitmap not empty before test.")
782 783 784 785 786 787 788 789 790 791 792
        vm_name = params["main_vm"]
        test_image = "scsi_debug"
        params["start_vm"] = "yes"
        params["image_name_%s" % test_image] = disk_name
        params["image_format_%s" % test_image] = "raw"
        params["image_raw_device_%s" % test_image] = "yes"
        params["force_create_image_%s" % test_image] = "no"
        params["drive_format_%s" % test_image] = "scsi-block"
        params["drv_extra_params_%s" % test_image] = "discard=on"
        params["images"] = " ".join([params["images"], test_image])

793
        error_context.context("boot guest with disk '%s'" % disk_name, logging.info)
794 795
        env_process.preprocess_vm(test, params, env, vm_name)

796
        self.initialize(test, params, env)
797
        self.setup(test, params, env)
798 799 800 801
        timeout = float(params.get("login_timeout", 240))
        session = self.vm.wait_for_login(timeout=timeout)
        device_name = get_guest_discard_disk(session)

802
        error_context.context("format disk '%s' in guest" % device_name, logging.info)
803 804 805 806
        format_disk_cmd = params["format_disk_cmd"]
        format_disk_cmd = format_disk_cmd.replace("DISK", device_name)
        session.cmd(format_disk_cmd)

807 808
        error_context.context("mount disk with discard options '%s'" % device_name,
                              logging.info)
809 810 811 812
        mount_disk_cmd = params["mount_disk_cmd"]
        mount_disk_cmd = mount_disk_cmd.replace("DISK", device_name)
        session.cmd(mount_disk_cmd)

813
        error_context.context("write the disk with dd command", logging.info)
814 815 816
        write_disk_cmd = params["write_disk_cmd"]
        session.cmd(write_disk_cmd)

817
        error_context.context("Delete the file created before on disk", logging.info)
818 819 820 821 822 823
        delete_file_cmd = params["delete_file_cmd"]
        session.cmd(delete_file_cmd)

        # check the bitmap before trim
        bitmap_before_trim = get_allocation_bitmap()
        if not re.match(r"\d+-\d+", bitmap_before_trim):
824
            test.fail("didn't get the bitmap of the target disk")
825 826
        error_context.context("the bitmap_before_trim is %s" % bitmap_before_trim,
                              logging.info)
827
        total_block_before_trim = abs(sum([eval(i) for i in
L
Lucas Meneghel Rodrigues 已提交
828
                                           bitmap_before_trim.split(',')]))
829 830
        error_context.context("the total_block_before_trim is %d"
                              % total_block_before_trim, logging.info)
831

832
        error_context.context("execute the guest-fstrim cmd", logging.info)
833 834 835 836 837
        self.gagent.fstrim()

        # check the bitmap after trim
        bitmap_after_trim = get_allocation_bitmap()
        if not re.match(r"\d+-\d+", bitmap_after_trim):
838
            test.fail("didn't get the bitmap of the target disk")
839 840
        error_context.context("the bitmap_after_trim is %s" % bitmap_after_trim,
                              logging.info)
841
        total_block_after_trim = abs(sum([eval(i) for i in
L
Lucas Meneghel Rodrigues 已提交
842
                                          bitmap_after_trim.split(',')]))
843 844
        error_context.context("the total_block_after_trim is %d"
                              % total_block_after_trim, logging.info)
845 846

        if total_block_after_trim > total_block_before_trim:
847 848
            test.fail("the bitmap_after_trim is lager, the command"
                      "guest-fstrim may not work")
849 850 851
        if self.vm:
            self.vm.destroy()

852
    @error_context.context_aware
853 854 855
    def gagent_check_get_interfaces(self, test, params, env):
        """
        Execute "guest-network-get-interfaces" command to guest agent
856 857 858 859 860 861 862 863 864 865 866 867 868 869 870

        Steps:
        1) login guest with serial session
        2) get the available interface name via mac address
        3) check the available interface name is the same with guest
        4) check ip address is the same with guest
        5) create a bridge interface for linux guest and check it
           from guest agent;
           disable interface for windows guest and check it
           from guest agent
        6) check "guest-network-get-interfaces" result
        7) recover the interfaces
        8) change ip address
        9) check "guest-network-get-interfaces" result

871 872 873 874
        :param test: kvm test object
        :param params: Dictionary with the test parameters
        :param env: Dictionary with test environment.
        """
875 876 877 878 879
        def get_interface(ret_list, mac_addr):
            """
            Get the available interface name.

            :return: interface name and the interface's index in ret_list
880
            """
881 882 883 884 885 886 887 888 889 890 891
            interface_name = ""
            if_index = 0
            for interface in ret_list:
                if "hardware-address" in interface and \
                                interface["hardware-address"] == mac_addr:
                    interface_name = interface["name"]
                    break
                if_index += 1
            return interface_name, if_index

        def ip_addr_check(session, mac_addr, ret_list, if_index, if_name):
892
            """
893
            Check the ip address from qga and guest inside.
894

895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931
            :param session: serial session
            :param mac_addr: mac address of nic
            :param ret_list: return list from qg
            :param if_index: the interface's index in ret
            :param if_name: interface name
            """
            guest_ip_ipv4 = utils_net.get_guest_ip_addr(session, mac_addr,
                                                        os_type)
            guest_ip_ipv6 = utils_net.get_guest_ip_addr(session, mac_addr,
                                                        os_type,
                                                        ip_version="ipv6",
                                                        linklocal=True)
            ip_lists = ret_list[if_index]["ip-addresses"]
            for ip in ip_lists:
                if ip["ip-address-type"] == "ipv4":
                    ip_addr_qga_ipv4 = ip["ip-address"]
                elif ip["ip-address-type"] == "ipv6":
                    ip_addr_qga_ipv6 = ip["ip-address"].split("%")[0]
                else:
                    test.fail("The ip address type is %s, but it should be"
                              " ipv4 or ipv6." % ip["ip-address-type"])
            if guest_ip_ipv4 != ip_addr_qga_ipv4 \
                    or guest_ip_ipv6 != ip_addr_qga_ipv6:
                test.fail("Get the wrong ip address for %s interface:\n"
                          "ipv4 address from qga is %s, the expected is %s;\n"
                          "ipv6 address from qga is %s, the expected is %s."
                          % (if_name, ip_addr_qga_ipv4,
                             guest_ip_ipv4, ip_addr_qga_ipv6,
                             guest_ip_ipv6))

        session_serial = self.vm.wait_for_serial_login()
        mac_addr = self.vm.get_mac_address()
        os_type = self.params["os_type"]

        error_context.context("Get the available interface name via"
                              " guest-network-get-interfaces cmd.",
                              logging.info)
932
        ret = self.gagent.get_network_interface()
933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005
        if_name, if_index = get_interface(ret, mac_addr)
        if not if_name:
            test.fail("Did not get the expected interface,"
                      " the network info is \n%s." % ret)

        error_context.context("Check the available interface name %s"
                              " via qga." % if_name, logging.info)
        if os_type == "linux":
            if_name_guest = utils_net.get_linux_ifname(session_serial,
                                                       mac_addr)
        else:
            if_name_guest = utils_net.get_windows_nic_attribute(
                session_serial, "macaddress", mac_addr, "netconnectionid")
        if if_name != if_name_guest:
            test.fail("Get the wrong interface name, value from qga is: %s; "
                      "the expected is: %s" % (if_name, if_name_guest))

        error_context.context("Check ip address via qga.", logging.info)
        ip_addr_check(session_serial, mac_addr, ret, if_index, if_name)

        # create a bridge interface for linux guest and check it
        #  from guest agent
        # disable interface for windows guest and check it
        #  from guest agent
        if os_type == "linux":
            error_context.context("Create a new bridge in guest and check the"
                                  "result from qga.", logging.info)
            add_brige_cmd = "ip link add name br0 type bridge"
            session_serial.cmd(add_brige_cmd)
            interfaces_after_add = self.gagent.get_network_interface()
            for interface in interfaces_after_add:
                if interface["name"] == "br0":
                    break
            else:
                test.fail("The new bridge is not checked from guest agent.")
            error_context.context("Delete the added bridge.", logging.info)
            del_brige_cmd = "ip link del br0"
            session_serial.cmd(del_brige_cmd)
        else:
            error_context.context("Set down the interface in windows guest.",
                                  logging.info)
            utils_net.disable_windows_guest_network(session_serial, if_name)
            ret_after_down = self.gagent.get_network_interface()
            if_name_down = get_interface(ret_after_down, mac_addr)[0]
            if if_name_down:
                test.fail("From qga result that the interface is still"
                          " enabled, detailed info is:\n %s"
                          % ret_after_down)
            error_context.context("Set up the interface in guest.",
                                  logging.info)
            utils_net.enable_windows_guest_network(session_serial, if_name)

        error_context.context("Change ipv4 address and check the result "
                              "from qga.", logging.info)
        # for linux guest, need to delete ip address first
        if os_type == "linux":
            ip_lists = ret[if_index]["ip-addresses"]
            for ip in ip_lists:
                if ip["ip-address-type"] == "ipv4":
                    ip_addr_qga_ipv4 = ip["ip-address"]
                    break
            session_serial.cmd("ip addr del %s dev %s" % (ip_addr_qga_ipv4,
                                                          if_name))
        utils_net.set_guest_ip_addr(session_serial, mac_addr, "192.168.10.10",
                                    os_type=os_type)
        ret_ip_change = self.gagent.get_network_interface()
        if_name_ip_change, if_index_ip_change = get_interface(
            ret_ip_change, mac_addr)
        ip_addr_check(session_serial, mac_addr, ret_ip_change,
                      if_index_ip_change, if_name_ip_change)

        if session_serial:
            session_serial.close()
1006

1007
    @error_context.context_aware
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
    def gagent_check_reboot_shutdown(self, test, params, env):
        """
        Send "shutdown,reboot" command to guest agent
        after FS freezed
        :param test: kvm test object
        :param params: Dictionary with the test parameters
        :param env: Dictionary with test environment.
        """
        vm = env.get_vm(params["main_vm"])
        vm.verify_alive()
        gagent = self.gagent
        gagent.fsfreeze()
        try:
            for mode in (gagent.SHUTDOWN_MODE_POWERDOWN, gagent.SHUTDOWN_MODE_REBOOT):
                try:
                    gagent.shutdown(mode)
                except guest_agent.VAgentCmdError as detail:
                    if not re.search('guest-shutdown has been disabled', str(detail)):
                        test.fail("This is not the desired information: ('%s')" % str(detail))
                else:
                    test.fail("agent shutdown command shouldn't succeed for freeze FS")
        finally:
            try:
                gagent.fsthaw(check_status=False)
            except Exception:
                pass

1035 1036
    def _change_bl(self, session):
        """
1037
        Some cmds are in blacklist by default,so need to change.
1038 1039 1040 1041
        Now only linux guest has this behavior,but still leave interface
        for windows guest.
        """
        if self.params.get("os_type") == "linux":
1042 1043 1044 1045 1046 1047 1048 1049 1050
            black_list = self.params["black_list"]
            for black_cmd in black_list.split():
                bl_check_cmd = self.params["black_list_check_cmd"] % black_cmd
                bl_change_cmd = self.params["black_list_change_cmd"] % black_cmd
                session.cmd(bl_change_cmd)
                output = session.cmd_output(bl_check_cmd)
                if not output == "":
                    self.test.fail("Failed to change the cmd to "
                                   "white list, the output is %s" % output)
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196

            s, o = session.cmd_status_output(self.params["gagent_restart_cmd"])
            if s:
                self.test.fail("Could not restart qemu-ga in VM after changing"
                               " list, detail: %s" % o)

    def _read_check(self, ret_handle, content, count=None):
        """
        Read file and check if the content read is correct.

        :param ret_handle: file handle returned by guest-file-open
        :param count: maximum number of bytes to read
        :param content: expected content
        """
        logging.info("Read content and do check.")
        ret_read = self.gagent.guest_file_read(ret_handle, count=count)
        content_read = base64.b64decode(ret_read["buf-b64"]).decode()
        logging.info("The read content is '%s'; the real content is '%s'."
                     % (content_read, content))
        if not content_read.strip() == content.strip():
            self.test.fail("The read content is '%s'; the real content is '%s'."
                           % (content_read, content))

    def _guest_file_prepare(self):
        """
        Preparation for gagent_check_file_xxx function.
        :return: vm session and guest file full path
        """
        session = self._get_session(self.params, self.vm)
        self._open_session_list.append(session)
        logging.info("Change guest-file related cmd to white list.")
        self._change_bl(session)

        ranstr = utils_misc.generate_random_string(5)
        file_name = "qgatest" + ranstr
        guest_file = "%s%s" % (self.params["file_path"], file_name)
        return session, guest_file

    @error_context.context_aware
    def gagent_check_file_seek(self, test, params, env):
        """
        Guest-file-seek cmd test.

        Test steps:
        1) create new guest file in guest.
        2) write "hello world" to guest file.
        3) seek test
          a.seek from the file beginning position and offset is 0
           ,and read two count
          b. seek from the file beginning position and offset is 0,
           read two bytes.
          c. seek from current position and offset is 2,read 5 bytes.
          d. seek from the file end and offset is -5,read 3 bytes.
        4) close the handle

        :param test: kvm test object
        :param params: Dictionary with the test parameters
        :param env: Dictionary with test environment.
        """
        error_context.context("Change guest-file related cmd to white list"
                              " and get guest file name.")
        session, tmp_file = self._guest_file_prepare()

        error_context.context("Write content to file.", logging.info)
        content = "hello world\n"
        ret_handle = int(self.gagent.guest_file_open(tmp_file, mode="w+"))
        self.gagent.guest_file_write(ret_handle, content)
        self.gagent.guest_file_flush(ret_handle)

        error_context.context("Seek to one position and read file with "
                              "file-seek/read cmd.", logging.info)
        self.gagent.guest_file_seek(ret_handle, 0, 0)
        self._read_check(ret_handle, content)

        logging.info("Seek the position to file beginning and read all.")
        self.gagent.guest_file_seek(ret_handle, 0, 0)
        self._read_check(ret_handle, "he", 2)

        logging.info("Seek the position to file beginning, offset is 2, and read 2 bytes.")
        self.gagent.guest_file_seek(ret_handle, 2, 0)
        self._read_check(ret_handle, "ll", 2)

        logging.info("Seek to current position, offset is 2 and read 5 byte.")
        self.gagent.guest_file_seek(ret_handle, 2, 1)
        self._read_check(ret_handle, "world", 5)

        logging.info("Seek from the file end position, offset is -5 and "
                     "read 3 byte.")
        self.gagent.guest_file_seek(ret_handle, -5, 2)
        self._read_check(ret_handle, "orl", 3)

        self.gagent.guest_file_close(ret_handle)
        cmd_del_file = "%s %s" % (params["cmd_del"], tmp_file)
        session.cmd(cmd_del_file)

    @error_context.context_aware
    def gagent_check_file_write(self, test, params, env):
        """
        Guest-file-write cmd test.

        Test steps:
        1) write two counts bytes to guest file.
        2) write ten counts bytes to guest file from the file end.
        3) write more than all counts bytes to guest file.
        4) close the handle

        :param test: kvm test object
        :param params: Dictionary with the test parameters
        :param env: Dictionary with test environment.
        """
        error_context.context("Change guest-file related cmd to white list"
                              " and get guest file name.")
        session, tmp_file = self._guest_file_prepare()

        error_context.context("Create new file with mode 'w' and do file"
                              " write test", logging.info)
        ret_handle = int(self.gagent.guest_file_open(tmp_file, mode="w+"))
        content = "hello world\n"
        content_check = ""
        for cnt in range(1, 10, 2):
            error_context.context("Write %s bytes to guest file."
                                  % cnt, logging.info)
            self.gagent.guest_file_seek(ret_handle, 0, 2)
            self.gagent.guest_file_write(ret_handle, content, cnt)
            self.gagent.guest_file_flush(ret_handle)
            self.gagent.guest_file_seek(ret_handle, 0, 0)
            content_check += content[: int(cnt)]
            self._read_check(ret_handle, content_check)

        error_context.context("Write more than all counts bytes to"
                              " guest file.", logging.info)
        try:
            self.gagent.guest_file_write(ret_handle, content, 15)
        except guest_agent.VAgentCmdError as e:
            expected = "invalid for argument count"
            if expected not in e.edata["desc"]:
                self.test.fail(e)
        else:
            self.test.fail("Cmd 'guest-file-write' is executed "
                           "successfully after freezing FS! "
                           "But it should return error.")
        self.gagent.guest_file_close(ret_handle)
        cmd_del_file = "%s %s" % (params["cmd_del"], tmp_file)
        session.cmd(cmd_del_file)

    @error_context.context_aware
1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280
    def gagent_check_file_read(self, test, params, env):
        """
        Guest-file-read cmd test.

        Test steps:
        1) create a file in guest.
        2) read the file via qga command and check the result.
        3) create a big file in guest.
        4) Read the big file with an invalid count number.
        5) Read the big file with big count number.
        6) Open a none existing file of guest.

        :param test: kvm test object
        :param params: Dictionary with the test parameters
        :param env: Dictionary with test environment.
        """
        error_context.context("Change guest-file related cmd to white list"
                              " and get guest file name.")
        session, tmp_file = self._guest_file_prepare()
        content = "helloworld\n"

        error_context.context("Create a new small file in guest", logging.info)
        cmd_create_file = "echo helloworld > %s" % tmp_file
        session.cmd(cmd_create_file)
        error_context.context("Open guest file via guest-file-open with"
                              " read only mode.", logging.info)
        # default is read mode
        ret_handle = int(self.gagent.guest_file_open(tmp_file))
        error_context.context("Read the content and check the result via"
                              " guest-file cmd", logging.info)
        self._read_check(ret_handle, content)
        self.gagent.guest_file_close(ret_handle)

        error_context.context("Create a 200KB file in guest", logging.info)
        process.run("dd if=/dev/urandom of=/tmp/big_file bs=1024 count=200")
        self.vm.copy_files_to("/tmp/big_file", tmp_file)

        error_context.context("Open the big guest file via guest-file-open with"
                              " read only mode.", logging.info)
        ret_handle = int(self.gagent.guest_file_open(tmp_file))

        error_context.context("Read the big file with an invalid count number",
                              logging.info)
        try:
            self.gagent.guest_file_read(ret_handle, count=10000000000)
        except guest_agent.VAgentCmdError as detail:
            if not re.search("invalid for argument count", str(detail)):
                test.fail("Return error but is not the desired information: "
                          "('%s')" % str(detail))
        else:
            test.fail("Did not get the expected result.")

        error_context.context("Read the file with an valid big count number.",
                              logging.info)
        self.gagent.guest_file_seek(ret_handle, 0, 0)
        # if guest os resource is enough, will return no error.
        # else it will return error like "insufficient system resource"
        # which is expected
        try:
            self.gagent.guest_file_read(ret_handle, count=1000000000)
        except guest_agent.VAgentCmdError as detail:
            info_insuffi = "Insufficient system resources exist to"
            info_insuffi += " complete the requested service"
            if not re.search(info_insuffi, str(detail)):
                test.fail("Return error but is not the desired information: "
                          "('%s')" % str(detail))
        self.gagent.guest_file_close(ret_handle)

        error_context.context("Open a none existing file with read only mode.",
                              logging.info)
        try:
            self.gagent.guest_file_open("none_exist_file")
        except guest_agent.VAgentCmdError as detail:
            res_linux = "No such file or directory"
            res_windows = "system cannot find the file"
            if res_windows not in str(detail) and res_linux not in str(detail):
                test.fail("This is not the desired information: "
                          "('%s')" % str(detail))
        else:
            test.fail("Should not pass with none existing file.")

        cmd_del_file = "%s %s" % (params["cmd_del"], tmp_file)
        session.cmd(cmd_del_file)

1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325
    @error_context.context_aware
    def gagent_check_with_fsfreeze(self, test, params, env):
        """
        Try to operate guest file when fs freeze.

        Test steps:
        1) freeze fs and try to open guest file with qga cmd.
        2) after thaw fs, try to operate guest file with qga cmd.

        :param test: kvm test object
        :param params: Dictionary with the test parameters
        :param env: Dictionary with test environment.
        """
        error_context.context("Change guest-file related cmd to white list"
                              " and get guest file name.")
        session, tmp_file = self._guest_file_prepare()

        content = "hello world\n"
        error_context.context("Freeze fs and try to open guest file.",
                              logging.info)
        self.gagent.fsfreeze()
        try:
            self.gagent.guest_file_open(tmp_file, mode="a+")
        except guest_agent.VAgentCmdError as detail:
            if not re.search('guest-file-open has been disabled',
                             str(detail)):
                self.test.fail("This is not the desired information: "
                               "('%s')" % str(detail))
        else:
            self.test.fail("guest-file-open command shouldn't succeed "
                           "for freeze FS.")
        finally:
            self.gagent.fsthaw()

        error_context.context("After thaw fs, try to operate guest"
                              " file.", logging.info)
        ret_handle = int(self.gagent.guest_file_open(tmp_file, mode="a+"))
        self.gagent.guest_file_write(ret_handle, content)
        self.gagent.guest_file_flush(ret_handle)
        self.gagent.guest_file_seek(ret_handle, 0, 0)
        self._read_check(ret_handle, "hello world")
        self.gagent.guest_file_close(ret_handle)
        cmd_del_file = "%s %s" % (params["cmd_del"], tmp_file)
        session.cmd(cmd_del_file)

1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441
    @error_context.context_aware
    def gagent_check_guest_exec(self, test, params, env):
        """
        Execute a command in the guest via guest-exec cmd,
        and check status of this process.

        Steps:
        1) Change guest-exec related cmd to white list,linux guest only.
        2) Execute guest cmd and get the output.
        3) Check the cmd's result and output from return.
        4) Execute guest cmd and no need to get the output.
        5) Check the cmd's result from return.
        6) Issue an invalid guest cmd.
        7) Check the return result.
        8) Execute guest cmd with wrong args.
        9) Check the return result.

        :param test: kvm test object
        :param params: Dictionary with the test parameters
        """

        def _guest_cmd_run(guest_cmd, cmd_args=None, env_qga=None,
                           input=None, capture_output=None):
            """
            Execute guest-exec cmd and get the result in timeout.

            :param guest_cmd: path or executable name to execute
            :param cmd_args: argument list to pass to executable
            :param env_qga: environment variables to pass to executable
            :param input: data to be passed to process stdin (base64 encoded)
            :param capture_output: bool flag to enable capture of stdout/stderr
                                   of running process,defaults to false.
            :return: result of guest-exec cmd
            """

            # change cmd_args to be a list needed by guest-exec.
            if cmd_args:
                cmd_args = cmd_args.split()
            ret = self.gagent.guest_exec(path=guest_cmd, arg=cmd_args,
                                         env=env_qga, input_data=input,
                                         capture_output=capture_output)
            end_time = time.time() + float(params["guest_cmd_timeout"])
            while time.time() < end_time:
                result = self.gagent.guest_exec_status(ret["pid"])
                if result["exited"]:
                    logging.info("Guest cmd is finished.")
                    break
                time.sleep(5)

            if not result["exited"]:
                test.error("Guest cmd is still running, pls login guest to"
                           " handle it or extend your timeout.")
            # check the exitcode and output/error data result
            if result["exitcode"] == 0:
                if "out-data" in result:
                    out_data = base64.b64decode(result["out-data"]).decode()
                    logging.info("The guest cmd is executed successfully,"
                                 "the output is: \n %s." % out_data)
                elif "err-data" in result:
                    test.fail("When exitcode is 0, should not get error data.")
            else:
                if "out-data" in result:
                    test.fail("When exitcode is 1, should not get output data.")
                elif "err-data" in result:
                    err_data = base64.b64decode(result["err-data"]).decode()
                    logging.info("The guest cmd failed,"
                                 "the error info is: \n %s" % err_data)
            return result

        session = self._get_session(params, self.vm)
        self._open_session_list.append(session)

        error_context.context("Change guest-exec related cmd to white list.",
                              logging.info)
        self._change_bl(session)

        guest_cmd = params["guest_cmd"]
        guest_cmd_args = params["guest_cmd_args"]

        error_context.context("Execute guest cmd and get the output.",
                              logging.info)
        result = _guest_cmd_run(guest_cmd=guest_cmd, cmd_args=guest_cmd_args,
                                capture_output=True)

        if "out-data" not in result and "err-data" not in result:
            test.fail("There is no output in result.")

        error_context.context("Execute guest cmd and no need to get the output.",
                              logging.info)
        result = _guest_cmd_run(guest_cmd=guest_cmd, cmd_args=guest_cmd_args)

        if "out-data" in result or "err-data" in result:
            test.fail("There is output in result which is not expected.")

        error_context.context("Invalid guest cmd test.", logging.info)
        try:
            self.gagent.guest_exec(path="invalid_cmd")
        except guest_agent.VAgentCmdError as detail:
            if not re.search('Failed to execute child process', str(detail)):
                test.fail("This is not the desired information: ('%s')"
                          % str(detail))
        else:
            test.fail("Should not success for invalid cmd.")

        error_context.context("Execute guest cmd with wrong args.", logging.info)
        if params.get("os_type") == "linux":
            guest_cmd = "cd"
            guest_cmd_args = "/tmp/qga_empty_dir"
        else:
            guest_cmd = "ping"
            guest_cmd_args = "invalid-address"
        result = _guest_cmd_run(guest_cmd=guest_cmd, cmd_args=guest_cmd_args,
                                capture_output=True)
        if result["exitcode"] == 0:
            test.fail("The cmd should be failed with wrong args.")

1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456
    @error_context.context_aware
    def _action_before_fsfreeze(self, *args):
        session = self._get_session(self.params, None)
        self._open_session_list.append(session)

    @error_context.context_aware
    def _action_after_fsfreeze(self, *args):
        error_context.context("Verfiy FS is frozen in guest.", logging.info)

        if not self._open_session_list:
            self.test.error("Could not find any opened session")
        # Use the last opened session to send cmd.
        session = self._open_session_list[-1]

        try:
1457
            session.cmd(args[0], args[1])
1458 1459 1460 1461 1462
        except aexpect.ShellTimeoutError:
            logging.info("FS is frozen as expected,can't write in guest.")
        else:
            self.test.fail("FS is not frozen,still can write in guest.")

1463
    @error_context.context_aware
1464 1465 1466
    def _action_before_fsthaw(self, *args):
        pass

1467
    @error_context.context_aware
1468
    def _action_after_fsthaw(self, *args):
1469 1470 1471 1472 1473 1474 1475 1476
        error_context.context("Verify FS is thawed in guest.", logging.info)

        if not self._open_session_list:
            session = self._get_session(self.params, None)
            self._open_session_list.append(session)
        # Use the last opened session to send cmd.
        session = self._open_session_list[-1]
        try:
1477
            session.cmd(args[0], args[1])
1478 1479 1480 1481
        except aexpect.ShellTimeoutError:
            self.test.fail("FS is not thawed, still can't write in guest.")
        else:
            logging.info("FS is thawed as expected, can write in guest.")
1482

1483
    @error_context.context_aware
1484 1485 1486 1487 1488 1489 1490 1491 1492
    def gagent_check_fsfreeze(self, test, params, env):
        """
        Test guest agent commands "guest-fsfreeze-freeze/status/thaw"

        Test steps:
        1) Check the FS is thawed.
        2) Freeze the FS.
        3) Check the FS is frozen from both guest agent side and guest os side.
        4) Thaw the FS.
1493
        5) Check the FS is unfrozen from both guest agent side and guest os side.
1494

L
Lucas Meneghel Rodrigues 已提交
1495 1496 1497
        :param test: kvm test object
        :param params: Dictionary with the test parameters
        :param env: Dictionary with test environmen.
1498
        """
1499 1500 1501
        error_context.context("Check guest agent command "
                              "'guest-fsfreeze-freeze/thaw'",
                              logging.info)
1502
        write_cmd = params.get("gagent_fs_test_cmd", "")
1503
        write_cmd_timeout = int(params.get("write_cmd_timeout", 60))
1504 1505 1506 1507 1508 1509 1510
        try:
            expect_status = self.gagent.FSFREEZE_STATUS_THAWED
            self.gagent.verify_fsfreeze_status(expect_status)
        except guest_agent.VAgentFreezeStatusError:
            # Thaw guest FS if the fs status is incorrect.
            self.gagent.fsthaw(check_status=False)

1511 1512
        self._action_before_fsfreeze()
        error_context.context("Freeze the FS.", logging.info)
1513 1514
        self.gagent.fsfreeze()
        try:
1515
            self._action_after_fsfreeze(write_cmd, write_cmd_timeout)
1516
            # Next, thaw guest fs.
1517 1518
            self._action_before_fsthaw()
            error_context.context("Thaw the FS.", logging.info)
1519
            self.gagent.fsthaw()
1520
        except Exception:
1521 1522 1523
            # Thaw fs finally, avoid problem in following cases.
            try:
                self.gagent.fsthaw(check_status=False)
X
Xu Han 已提交
1524
            except Exception as detail:
1525 1526 1527
                # Ignore exception for this thaw action.
                logging.warn("Finally failed to thaw guest fs,"
                             " detail: '%s'", detail)
1528 1529
            raise

1530
        self._action_after_fsthaw(write_cmd, write_cmd_timeout)
1531

1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551
    @error_context.context_aware
    def gagent_check_thaw_unfrozen(self, test, params, env):
        """
        Thaw the unfrozen fs

        :param test: kvm test object
        :param params: Dictionary with the test parameters
        :param env: Dictionary with test environment.
        """
        error_context.context("Verify if FS is thawed", logging.info)
        expect_status = self.gagent.FSFREEZE_STATUS_THAWED
        if self.gagent.get_fsfreeze_status() != expect_status:
            # Thaw guest FS if the fs status isn't thawed.
            self.gagent.fsthaw()
        error_context.context("Thaw the unfrozen FS", logging.info)
        ret = self.gagent.fsthaw(check_status=False)
        if ret != 0:
            test.fail("The return value of thawing an unfrozen fs is %s,"
                      "it should be zero" % ret)

1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576
    @error_context.context_aware
    def gagent_check_freeze_frozen(self, test, params, env):
        """
        Freeze the frozen fs

        :param test: kvm test object
        :param params: Dictionary with the test parameters
        :param env: Dictionary with test environment.
        """
        self.gagent.fsfreeze()
        error_context.context("Freeze the frozen FS", logging.info)
        try:
            self.gagent.fsfreeze(check_status=False)
        except guest_agent.VAgentCmdError as e:
            expected = ("The command guest-fsfreeze-freeze has been disabled "
                        "for this instance")
            if expected not in e.edata["desc"]:
                test.fail(e)
        else:
            test.fail("Cmd 'guest-fsfreeze-freeze' is executed successfully "
                      "after freezing FS! But it should return error.")
        finally:
            if self.gagent.get_fsfreeze_status() == self.gagent.FSFREEZE_STATUS_FROZEN:
                self.gagent.fsthaw(check_status=False)

1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595
    @error_context.context_aware
    def gagent_check_after_init(self, test, params, env):
        """
        Check guest agent service status after running the init command
        :param test: Kvm test object
        :param params: Dictionary with the test parameters
        :param env: Dictionary with test environment
        """
        error_context.context("Run init 3 in guest", logging.info)
        session = self._get_session(params, self.vm)
        session.cmd("init 3")
        error_context.context("Check guest agent status after running init 3",
                              logging.info)
        if self._check_ga_service(session, params.get("gagent_status_cmd")):
            logging.info("Guest agent service is still running after init 3.")
        else:
            test.fail("Guest agent service is stopped after running init 3! It "
                      "should be running.")

1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648
    @error_context.context_aware
    def gagent_check_hotplug_frozen(self, test, params, env):
        """
        hotplug device with frozen fs

        :param test: kvm test object
        :param params: Dictionary with the test parameters
        :param env: Dictionary with test environment
        """
        def get_new_disk(disks_before_plug, disks_after_plug):
            """
            Get the new added disks by comparing two disk lists.
            """
            disk = list(set(disks_after_plug).difference(set(disks_before_plug)))
            return disk

        session = self._get_session(params, self.vm)
        image_size_stg0 = params["image_size_stg0"]
        try:
            if params.get("os_type") == "linux":
                disks_before_plug = utils_disk.get_linux_disks(session, True)
            error_context.context("Freeze guest fs", logging.info)
            self.gagent.fsfreeze()
            # For linux guest, waiting for it to be frozen, for windows guest,
            # waiting for it to be automatically thawed.
            time.sleep(20)
            error_context.context("Hotplug a disk to guest", logging.info)
            image_name_plug = params["images"].split()[1]
            image_params_plug = params.object_params(image_name_plug)
            devs = self.vm.devices.images_define_by_params(image_name_plug,
                                                           image_params_plug,
                                                           'disk')
            for dev in devs:
                self.vm.devices.simple_hotplug(dev, self.vm.monitor)
            disk_write_cmd = params["disk_write_cmd"]
            pause = float(params.get("virtio_block_pause", 10.0))
            error_context.context("Format and write disk", logging.info)
            if params.get("os_type") == "linux":
                new_disks = utils_misc.wait_for(lambda: get_new_disk(disks_before_plug.keys(),
                                                utils_disk.get_linux_disks(session, True).keys()), pause)
                if not new_disks:
                    test.fail("Can't detect the new hotplugged disks in guest")
                try:
                    mnt_point = utils_disk.configure_empty_disk(
                        session, new_disks[0], image_size_stg0, "linux", labeltype="msdos")
                except aexpect.ShellTimeoutError:
                    self.gagent.fsthaw()
                    mnt_point = utils_disk.configure_empty_disk(
                        session, new_disks[0], image_size_stg0, "linux", labeltype="msdos")
            elif params.get("os_type") == "windows":
                disk_index = utils_misc.wait_for(
                    lambda: utils_disk.get_windows_disks_index(session, image_size_stg0), 120)
                if disk_index:
1649 1650 1651
                    logging.info("Clear readonly for disk and online it in windows guest.")
                    if not utils_disk.update_windows_disk_attributes(session, disk_index):
                        test.error("Failed to update windows disk attributes.")
1652 1653 1654 1655 1656 1657 1658
                    mnt_point = utils_disk.configure_empty_disk(
                        session, disk_index[0], image_size_stg0, "windows", labeltype="msdos")
            session.cmd(disk_write_cmd % mnt_point[0])
            error_context.context("Unplug the added disk", logging.info)
            self.vm.devices.simple_unplug(devs[0], self.vm.monitor)
        finally:
            if self.gagent.get_fsfreeze_status() == self.gagent.FSFREEZE_STATUS_FROZEN:
1659 1660 1661 1662 1663 1664
                try:
                    self.gagent.fsthaw(check_status=False)
                except guest_agent.VAgentCmdError as detail:
                    if not re.search("fsfreeze is limited up to 10 seconds", str(detail)):
                        test.error("guest-fsfreeze-thaw cmd failed with:"
                                   "('%s')" % str(detail))
1665 1666 1667 1668 1669
            self.vm.verify_alive()
            if params.get("os_type") == "linux":
                utils_disk.umount(new_disks[0], mnt_point[0], session=session)
            session.close()

1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697
    @error_context.context_aware
    def gagent_check_path_fsfreeze_hook(self, test, params, env):
        """
        Check if the default path of fsfreeze-hook is correct

        :param test: kvm test object
        :param params: Dictionary with the test parameters
        :param env: Dictionary with test environment
        """
        session = self._get_session(params, self.vm)
        self.gagent_stop(session, self.vm)
        error_context.context("Start gagent with -F option", logging.info)
        self.gagent_start(session, self.vm)
        gagent_path_cmd = params["gagent_path_cmd"]
        error_context.context("Check if default path of fsfreeze-hook is in "
                              "output of %s" % gagent_path_cmd, logging.info)
        s, o = session.cmd_status_output(params["gagent_help_cmd"])
        help_cmd_output = o.strip().replace(')', '').split()[-1]
        s, o = session.cmd_status_output(gagent_path_cmd)
        if help_cmd_output in o:
            logging.info("The default path for script 'fsfreeze-hook' is "
                         "in output of %s." % gagent_path_cmd)
            error_context.context("Execute 'guest-fsfreeze-freeze'", logging.info)
            self.gagent.fsfreeze()
            self.gagent.fsthaw()
        else:
            test.fail("The default path of fsfreeze-hook doesn't match with expectation.")

1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732
    @error_context.context_aware
    def gagent_check_query_chardev(self, test, params, env):
        """
        Check guest agent service status through QMP 'query-chardev'

        :param test: kvm test object
        :param params: Dictionary with the test parameters
        :param env: Dictionary with test environment
        """
        def check_value_frontend_open(out, expected):
            """
            Get value of 'frontend-open' after executing 'query-chardev'
            :param out: output of executing 'query-chardev'
            :param expected: expected value of 'frontend-open'
            """
            for chardev_dict in out:
                if "org.qemu.guest_agent.0" in chardev_dict["filename"]:
                    ret = chardev_dict["frontend-open"]
                    if ret is expected:
                        break
                    else:
                        test.fail("The value of parameter 'frontend-open' "
                                  "is %s, it should be %s" % (ret, expected))
        error_context.context("Execute query-chardev when guest agent service "
                              "is on", logging.info)
        out = self.vm.monitor.query("chardev")
        check_value_frontend_open(out, True)
        session = self._get_session(params, self.vm)
        self.gagent_stop(session, self.vm)
        error_context.context("Execute query-chardev when guest agent service "
                              "is off", logging.info)
        out = self.vm.monitor.query("chardev")
        check_value_frontend_open(out, False)
        session.close()

1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765
    @error_context.context_aware
    def gagent_check_frozen_io(self, test, params, env):
        """
        fsfreeze test during disk io.

        :param test: kvm test object
        :param params: Dictionary with the test parameters
        :param env: Dictionary with test environment
        """
        error_context.context("Before freeze/thaw the FS, run the iozone test",
                              logging.info)
        session = self._get_session(self.params, None)
        self._open_session_list.append(session)
        iozone_cmd = utils_misc.set_winutils_letter(session, params["iozone_cmd"])
        session.cmd(iozone_cmd, timeout=360)
        error_context.context("Freeze the FS.", logging.info)
        try:
            self.gagent.fsfreeze()
        except guest_agent.VAgentCmdError as detail:
            if not re.search("timeout when try to receive Frozen event from"
                             " VSS provider", str(detail)):
                test.fail("guest-fsfreeze-freeze cmd failed with:"
                          "('%s')" % str(detail))
        if self.gagent.verify_fsfreeze_status(self.gagent.FSFREEZE_STATUS_FROZEN):
            try:
                self.gagent.fsthaw(check_status=False)
            except guest_agent.VAgentCmdError as detail:
                if not re.search("fsfreeze is limited up to 10 seconds", str(detail)):
                    test.error("guest-fsfreeze-thaw cmd failed with:"
                               "('%s')" % str(detail))

        self.gagent_verify(self.params, self.vm)

1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818
    @error_context.context_aware
    def gagent_check_vss_status(self, test, params, env):
        """
        Only for windows guest,check QEMU Guest Agent VSS Provider service start type
        and if it works.

        Steps:
        1) Check VSS Provider service start type.
        2) Check VSS Provider service should be in stopped status.
        3) Issue fsfreeze qga command.
        4) Check VSS Provider service should be in running status.
        5) Issue fsthaw qga command.

        :param test: kvm test object
        :param params: Dictionary with the test parameters
        :param env: Dictionary with test environment
        """
        def check_vss_info(cmd_type, key, expect_value):
            cmd_vss = "sc %s \"QEMU Guest Agent VSS Provider\" | findstr /i %s" % \
                      (cmd_type, key)
            status, output = session.cmd_status_output(cmd_vss)
            if status:
                test.error("Command to check VSS service info failed,"
                           "detailed info is:\n%s" % output)
            vss_result = output.split()[-1]
            if vss_result != expect_value:
                test.fail("The output is %s which is not expected."
                          % vss_result)

        session = self._get_session(self.params, None)
        self._open_session_list.append(session)

        error_context.context("Check VSS Provider service start type.",
                              logging.info)
        check_vss_info("qc", "START_TYPE", "DEMAND_START")

        error_context.context("Check VSS Provider status.", logging.info)
        check_vss_info("query", "STATE", "STOPPED")

        error_context.context("Freeze fs.", logging.info)
        self.gagent.fsfreeze()

        error_context.context("Check VSS Provider status after fsfreeze.", logging.info)
        check_vss_info("query", "STATE", "RUNNING")

        error_context.context("Thaw fs.", logging.info)
        try:
            self.gagent.fsthaw()
        except guest_agent.VAgentCmdError as detail:
            if not re.search("fsfreeze is limited up to 10 seconds", str(detail)):
                test.error("guest-fsfreeze-thaw cmd failed with:"
                           "('%s')" % str(detail))

1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881
    @error_context.context_aware
    def gagent_check_fsinfo(self, test, params, env):
        """
        Execute "guest-fsinfo" command to guest agent,check file system of
        mountpoint,disk's name and serial number.

        steps:
        1) check file system type of every mount point.
        2) check disk name.
        3) check disk's serial number.

        :param test: kvm test object
        :param params: Dictionary with the test parameters
        :param env: Dictionary with test environment.

        """
        session = self._get_session(params, None)
        self._open_session_list.append(session)
        serial_num = params["blk_extra_params"].split("=")[1]

        error_context.context("Check all file system info in a loop.", logging.info)
        fs_info_qga = self.gagent.get_fsinfo()
        for fs in fs_info_qga:
            mount_pt = fs["mountpoint"]
            if params["os_type"] == "windows":
                mount_pt = mount_pt[:2]

            error_context.context("Check file system type of '%s' mount point." %
                                  mount_pt, logging.info)
            fs_type_qga = fs["type"]
            cmd_get_disk = params["cmd_get_disk"] % mount_pt
            disk_info_guest = session.cmd(cmd_get_disk).strip().split()
            fs_type_guest = disk_info_guest[1]
            if fs_type_qga != fs_type_guest:
                test.fail("File System doesn't match.\n"
                          "from guest-agent is %s.\nfrom guest os is %s."
                          % (fs_type_qga, fs_type_guest))
            else:
                logging.info("File system type is %s which is expected." % fs_type_qga)

            error_context.context("Check disk name.", logging.info)
            disk_name_qga = fs["name"]
            disk_name_guest = disk_info_guest[0]
            if params["os_type"] == "linux":
                if not re.findall(r'^/\w*/\w*$', disk_name_guest):
                    disk_name_guest = session.cmd("readlink %s" % disk_name_guest).strip()
                disk_name_guest = disk_name_guest.split('/')[-1]
            if disk_name_qga != disk_name_guest:
                test.fail("Device name doesn't match.\n"
                          "from guest-agent is %s.\nit's from guest os is %s."
                          % (disk_name_qga, disk_name_guest))
            else:
                logging.info("Disk name is %s which is expected." % disk_name_qga)

            error_context.context("Check serial number of some disk.", logging.info)
            serial_qga = fs["disk"][0]["serial"]
            if not re.findall(serial_num, serial_qga):
                test.fail("Serial name is not correct via qga.\n"
                          "from guest-agent is %s.\n"
                          "but it should include %s." % (serial_qga, serial_num))
            else:
                logging.info("Serial number is %s which is expected." % serial_qga)

1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906
    @error_context.context_aware
    def gagent_check_nonexistent_cmd(self, test, params, env):
        """
        Execute "guest-fsinfo" command to guest agent, and check
        the return info.

        :param test: kvm test object
        :param params: Dictionary with the test parameters
        :param env: Dictionary with test environment.
        """
        session = self._get_session(params, None)
        self._open_session_list.append(session)
        error_context.context("Issue the no existed guest-agent "
                              "cmd via qga.", logging.info)
        cmd_wrong = params["wrong_cmd"]
        try:
            self.gagent.cmd(cmd_wrong)
        except guest_agent.VAgentCmdError as detail:
            pattern = "command %s has not been found" % cmd_wrong
            if not re.search(pattern, str(detail), re.I):
                test.fail("The error info is not correct, the return is"
                          " %s." % str(detail))
        else:
            test.fail("Should return error info.")

1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927
    @error_context.context_aware
    def gagent_check_with_migrate(self, test, params, env):
        """
        Migration test with guest agent service running.

        :param test: kvm test object
        :param params: Dictionary with the test parameters
        :param env: Dictionary with test environment.
        """
        error_context.context("Migrate guest while guest agent service is"
                              " running.", logging.info)
        self.vm.monitor.migrate_set_speed(params.get("mig_speed", "1G"))
        self.vm.migrate()
        error_context.context("Recreate a QemuAgent object after vm"
                              " migration.", logging.info)
        self.gagent = None
        args = [params.get("gagent_serial_type"), params.get("gagent_name")]
        self.gagent_create(params, self.vm, *args)
        error_context.context("Verify if guest agent works.", logging.info)
        self.gagent_verify(self.params, self.vm)

1928 1929 1930
    def run_once(self, test, params, env):
        QemuGuestAgentTest.run_once(self, test, params, env)

1931
        gagent_check_type = self.params["gagent_check_type"]
1932 1933 1934 1935 1936
        chk_type = "gagent_check_%s" % gagent_check_type
        if hasattr(self, chk_type):
            func = getattr(self, chk_type)
            func(test, params, env)
        else:
1937
            test.error("Could not find matching test, check your config file")
1938 1939


1940
class QemuGuestAgentBasicCheckWin(QemuGuestAgentBasicCheck):
L
Lucas Meneghel Rodrigues 已提交
1941

1942 1943 1944
    """
    Qemu guest agent test class for windows guest.
    """
1945 1946
    def __init__(self, test, params, env):
        QemuGuestAgentBasicCheck.__init__(self, test, params, env)
1947 1948
        self.gagent_guest_dir = params.get("gagent_guest_dir", "")
        self.qemu_ga_pkg = params.get("qemu_ga_pkg", "")
1949
        self.gagent_src_type = params.get("gagent_src_type", "url")
1950

1951
    @error_context.context_aware
1952
    def get_qga_pkg_path(self, qemu_ga_pkg, test, session, params, vm):
1953 1954 1955 1956 1957
        """
        Get the qemu-ga pkg path which will be installed.
        There are two methods to get qemu-ga pkg,one is download it
        from fedora people website,and the other is from virtio-win iso.

1958
        :param qemu_ga_pkg: qemu-ga pkg name
1959 1960 1961 1962 1963 1964
        :param test: kvm test object
        :param session: VM session.
        :param params: Dictionary with the test parameters
        :param vm: Virtual machine object.
        :return qemu_ga_pkg_path: Return the guest agent pkg path.
        """
1965 1966
        error_context.context("Get %s path where it locates." % qemu_ga_pkg,
                              logging.info)
1967

1968
        if self.gagent_src_type == "url":
1969 1970 1971 1972 1973
            gagent_host_path = params["gagent_host_path"]
            gagent_download_cmd = params["gagent_download_cmd"]

            error_context.context("Download qemu-ga.msi from website and copy "
                                  "it to guest.", logging.info)
1974
            process.system(gagent_download_cmd, float(params.get("login_timeout", 360)))
1975 1976 1977
            if not os.path.exists(gagent_host_path):
                test.error("qemu-ga.msi is not exist, maybe it is not "
                           "successfully downloaded ")
1978
            s, o = session.cmd_status_output("mkdir %s" % self.gagent_guest_dir)
1979 1980 1981 1982 1983
            if s and "already exists" not in o:
                test.error("Could not create qemu-ga directory in "
                           "VM '%s', detail: '%s'" % (vm.name, o))

            error_context.context("Copy qemu-ga.msi to guest", logging.info)
1984 1985 1986
            vm.copy_files_to(gagent_host_path, self.gagent_guest_dir)
            qemu_ga_pkg_path = r"%s\%s" % (self.gagent_guest_dir, qemu_ga_pkg)
        elif self.gagent_src_type == "virtio-win":
1987 1988 1989 1990 1991 1992 1993
            vol_virtio_key = "VolumeName like '%virtio-win%'"
            vol_virtio = utils_misc.get_win_disk_vol(session, vol_virtio_key)
            qemu_ga_pkg_path = r"%s:\%s\%s" % (vol_virtio, "guest-agent", qemu_ga_pkg)
        else:
            test.error("Only support 'url' and 'virtio-win' method to "
                       "download qga installer now.")

1994
        logging.info("The qemu-ga pkg full path is %s" % qemu_ga_pkg_path)
1995
        return qemu_ga_pkg_path
1996

1997
    @error_context.context_aware
1998 1999
    def setup(self, test, params, env):
        BaseVirtTest.setup(self, test, params, env)
2000

2001
        if self.start_vm == "yes":
2002
            session = self._get_session(params, self.vm)
2003
            self._open_session_list.append(session)
2004 2005 2006 2007 2008
            qemu_ga_pkg_path = self.get_qga_pkg_path(self.qemu_ga_pkg, test,
                                                     session, params, self.vm)
            self.gagent_install_cmd = params.get("gagent_install_cmd"
                                                 ) % qemu_ga_pkg_path

2009 2010 2011 2012
            if self._check_ga_pkg(session, params.get("gagent_pkg_check_cmd")):
                logging.info("qemu-ga is already installed.")
            else:
                logging.info("qemu-ga is not installed.")
2013
                self.gagent_install(session, self.vm)
2014 2015 2016 2017 2018

            if self._check_ga_service(session, params.get("gagent_status_cmd")):
                logging.info("qemu-ga service is already running.")
            else:
                logging.info("qemu-ga service is not running.")
2019
                self.gagent_start(session, self.vm)
2020

2021
            args = [params.get("gagent_serial_type"), params.get("gagent_name")]
2022
            self.gagent_create(params, self.vm, *args)
2023

2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142
    @error_context.context_aware
    def gagent_check_fsfreeze_vss_test(self, test, params, env):
        """
        Test guest agent commands "guest-fsfreeze-freeze/status/thaw"
        for windows guest.

        Test steps:
        1) Check the FS is thawed.
        2) Start writing file test as a background test.
        3) Freeze the FS.
        3) Check the FS is frozen from both guest agent side and guest os side.
        4) Start writing file test as a background test.
        5) Thaw the FS.
        6) Check the FS is thaw from both guest agent side and guest os side.

        :param test: kvm test object
        :param params: Dictionary with the test parameters
        :param env: Dictionary with test environment
        """
        @error_context.context_aware
        def background_start(session):
            """
            Before freeze or thaw guest file system, start a background test.
            """
            logging.info("Write time stamp to guest file per second "
                         "as a background job.")
            fswrite_cmd = utils_misc.set_winutils_letter(
                session, self.params["gagent_fs_test_cmd"])

            session.cmd(fswrite_cmd, timeout=360)

        @error_context.context_aware
        def result_check(flag, write_timeout, session):
            """
            Check if freeze or thaw guest file system works.

            :param flag: frozen or thaw
            :param write_timeout: timeout of writing to guest file
            """
            time.sleep(write_timeout)
            k_cmd = "wmic process where \"name='python.exe' and " \
                    "CommandLine Like '%fsfreeze%'\" call terminate"
            s, o = session.cmd_status_output(k_cmd)
            if s:
                self.test.error("Command '%s' failed, status: %s,"
                                " output: %s" % (k_cmd, s, o))

            error_context.context("Check guest FS status.", logging.info)
            # init fs status to 'thaw'
            fs_status = "thaw"
            file_name = "/tmp/fsfreeze_%s.txt" % flag
            process.system("rm -rf %s" % file_name)
            self.vm.copy_files_from("C:\\fsfreeze.txt", file_name)
            with open(file_name, 'r') as f:
                list_time = f.readlines()

            for i in list(range(0, len(list_time))):
                list_time[i] = list_time[i].strip()

            for i in list(range(1, len(list_time))):
                num_d = float(list_time[i]) - float(list_time[i - 1])
                if num_d > 8:
                    logging.info("Time stamp is not continuous,"
                                 " so the FS is frozen.")
                    fs_status = "frozen"
                    break
            if not fs_status == flag:
                self.test.fail("FS is not %s, it's %s." % (flag, fs_status))

        error_context.context("Check guest agent command "
                              "'guest-fsfreeze-freeze/thaw'",
                              logging.info)
        session = self._get_session(self.params, None)
        self._open_session_list.append(session)

        # make write time longer than freeze timeout
        write_timeout = int(params["freeze_timeout"]) + 10
        try:
            expect_status = self.gagent.FSFREEZE_STATUS_THAWED
            self.gagent.verify_fsfreeze_status(expect_status)
        except guest_agent.VAgentFreezeStatusError:
            # Thaw guest FS if the fs status is incorrect.
            self.gagent.fsthaw(check_status=False)

        error_context.context("Before freeze/thaw the FS, run the background "
                              "job.", logging.info)
        background_start(session)
        error_context.context("Freeze the FS.", logging.info)
        self.gagent.fsfreeze()
        try:
            error_context.context("Waiting %s, then finish writing the time "
                                  "stamp in guest file." % write_timeout)
            result_check("frozen", write_timeout, session)
            # Next, thaw guest fs.
            error_context.context("Before freeze/thaw the FS, run the background "
                                  "job.", logging.info)
            background_start(session)
            error_context.context("Thaw the FS.", logging.info)
            try:
                self.gagent.fsthaw()
            except guest_agent.VAgentCmdError as detail:
                if re.search("fsfreeze is limited up to 10 seconds", str(detail)):
                    logging.info("FS is thaw as it's limited up to 10 seconds.")
                else:
                    test.fail("guest-fsfreeze-thaw cmd failed with:"
                              "('%s')" % str(detail))
        except Exception:
            # Thaw fs finally, avoid problem in following cases.
            try:
                self.gagent.fsthaw(check_status=False)
            except Exception as detail:
                # Ignore exception for this thaw action.
                logging.warn("Finally failed to thaw guest fs,"
                             " detail: '%s'", detail)
            raise
        error_context.context("Waiting %s, then finish writing the time "
                              "stamp in guest file." % write_timeout)
        result_check("thaw", write_timeout, session)

2143

2144
def run(test, params, env):
2145 2146 2147 2148
    """
    Test qemu guest agent, this case will:
    1) Start VM with virtio serial port.
    2) Install qemu-guest-agent package in guest.
2149
    3) Run some basic test for qemu guest agent.
2150

L
Lucas Meneghel Rodrigues 已提交
2151 2152 2153
    :param test: kvm test object
    :param params: Dictionary with the test parameters
    :param env: Dictionary with test environmen.
2154
    """
2155 2156 2157 2158 2159
    if params["os_type"] == "windows":
        gagent_test = QemuGuestAgentBasicCheckWin(test, params, env)
    else:
        gagent_test = QemuGuestAgentBasicCheck(test, params, env)

2160
    gagent_test.execute(test, params, env)