Best Python code snippet using lisa_python
reboot.py
Source:reboot.py  
...20from .uptime import Uptime21from .who import Who22# this method is easy to stuck on reboot, so use timeout to recycle it faster.23@func_set_timeout(30)  # type: ignore24def _who_last(who: Who) -> datetime:25    return who.last_boot()26class Reboot(Tool):27    def _initialize(self, *args: Any, **kwargs: Any) -> None:28        # timeout to wait29        self._command = "/sbin/reboot"30    @property31    def command(self) -> str:32        return self._command33    @classmethod34    def _windows_tool(cls) -> Optional[Type[Tool]]:35        return WindowsReboot36    def _check_exists(self) -> bool:37        return True38    def reboot_and_check_panic(self, log_path: Path) -> None:39        try:40            self.reboot()41        except Exception as identifier:42            if self.node.features.is_supported(SerialConsole):43                # if there is any panic, fail before partial pass44                serial_console = self.node.features[SerialConsole]45                serial_console.check_panic(46                    saved_path=log_path,47                    stage="reboot",48                )49            # if node cannot be connected after reboot, it should be failed.50            if isinstance(identifier, TcpConnectionException):51                raise BadEnvironmentStateException(f"after reboot, {identifier}")52            raise identifier53    def reboot(self, time_out: int = 300) -> None:54        who = self.node.tools[Who]55        timer = create_timer()56        # who -b doesn't return correct content in Ubuntu 14.04, but uptime works.57        # uptime has no -s parameter in some distros, so not use is as default.58        try:59            last_boot_time = who.last_boot()60        except Exception:61            uptime = self.node.tools[Uptime]62            last_boot_time = uptime.since_time()63        current_boot_time = last_boot_time64        # who -b returns time without seconds.65        # so if the node rebooted in one minute, the who -b is not changed.66        # The reboot will wait forever.67        # in this case, verify the time is wait enough to prevent this problem.68        date = self.node.tools[Date]69        # boot time has no tzinfo, so remove from date result to avoid below error.70        # TypeError: can't subtract offset-naive and offset-aware datetimes71        current_delta = date.current().replace(tzinfo=None) - current_boot_time72        self._log.debug(f"delta time since last boot: {current_delta}")73        while current_delta < timedelta(minutes=1):74            # wait until one minute75            wait_seconds = 60 - current_delta.seconds + 176            self._log.debug(f"waiting {wait_seconds} seconds before rebooting")77            sleep(wait_seconds)78            current_delta = date.current().replace(tzinfo=None) - current_boot_time79        # Get reboot execution path80        # Not all distros have the same reboot execution path81        command_result = self.node.execute(82            "command -v reboot", shell=True, sudo=True, no_info_log=True83        )84        if command_result.exit_code == 0:85            self._command = command_result.stdout86        self._log.debug(f"rebooting with boot time: {last_boot_time}")87        try:88            # Reboot is not reliable, and sometime stuck,89            # like SUSE sles-15-sp1-sapcal gen1 2020.10.23.90            # In this case, use timeout to prevent hanging.91            self.run(force_run=True, sudo=True, timeout=10)92        except Exception as identifier:93            # it doesn't matter to exceptions here. The system may reboot fast94            self._log.debug(f"ignorable exception on rebooting: {identifier}")95        connected: bool = False96        # The previous steps may take longer time than time out. After that, it97        # needs to connect at least once.98        tried_times: int = 099        while (timer.elapsed(False) < time_out) or tried_times < 1:100            tried_times += 1101            try:102                self.node.close()103                current_boot_time = _who_last(who)104                connected = True105            except FunctionTimedOut as identifier:106                # The FunctionTimedOut must be caught separated, or the process107                # will exit.108                self._log.debug(f"ignorable timeout exception: {identifier}")109            except Exception as identifier:110                # error is ignorable, as ssh may be closed suddenly.111                self._log.debug(f"ignorable ssh exception: {identifier}")112            self._log.debug(f"reconnected with uptime: {current_boot_time}")113            if last_boot_time < current_boot_time:114                break115        if last_boot_time == current_boot_time:116            if connected:117                raise LisaException(...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
