|
| 1 | +import pydoc |
| 2 | + |
| 3 | +import terminaltables |
| 4 | +from colorclass import Color |
| 5 | + |
1 | 6 | from paperspace.commands import CommandBase |
| 7 | +from paperspace.utils import get_terminal_lines |
| 8 | + |
| 9 | + |
| 10 | +class ListLogsCommand(CommandBase): |
| 11 | + last_line_number = 0 |
| 12 | + base_url = "/jobs/logs?jobId={}&line={}" |
2 | 13 |
|
| 14 | + is_logs_complete = False |
| 15 | + |
| 16 | + def execute(self, job_id): |
| 17 | + table_data = [("LINE", "MESSAGE")] |
| 18 | + table = terminaltables.AsciiTable(table_data, title=f"Job {job_id} logs") |
| 19 | + |
| 20 | + while not self.is_logs_complete: |
| 21 | + response = self._get_logs(job_id) |
3 | 22 |
|
4 | | -class LogsCommandBase(CommandBase): |
5 | | - def _log_message(self, response, success_msg_template, error_msg): |
6 | | - if response.ok: |
7 | 23 | try: |
8 | | - handle = response.json() |
9 | | - except (ValueError, KeyError): |
10 | | - self.logger.log(success_msg_template) |
| 24 | + data = response.json() |
| 25 | + if not response.ok: |
| 26 | + self.logger.log_error_response(data) |
| 27 | + return |
| 28 | + except (ValueError, KeyError) as e: |
| 29 | + if response.status_code == 204: |
| 30 | + continue |
| 31 | + self.logger.log("Error while parsing response data: {}".format(e)) |
| 32 | + return |
11 | 33 | else: |
12 | | - msg = success_msg_template.format(**handle) |
13 | | - self.logger.log(msg) |
| 34 | + self._log_logs_list(data, table, table_data) |
| 35 | + |
| 36 | + def _get_logs(self, job_id): |
| 37 | + url = self.base_url.format(job_id, self.last_line_number) |
| 38 | + return self.api.get(url) |
| 39 | + |
| 40 | + def _log_logs_list(self, data, table, table_data): |
| 41 | + if not data: |
| 42 | + self.logger.log("No Logs found") |
14 | 43 | else: |
15 | | - try: |
16 | | - data = response.json() |
17 | | - self.logger.log_error_response(data) |
18 | | - except ValueError: |
19 | | - self.logger.log(error_msg) |
| 44 | + table_str = self._make_table(data, table, table_data) |
| 45 | + if len(table_str.splitlines()) > get_terminal_lines(): |
| 46 | + pydoc.pager(table_str) |
| 47 | + else: |
| 48 | + self.logger.log(table_str) |
| 49 | + |
| 50 | + def _make_table(self, logs, table, table_data): |
| 51 | + if logs[-1].get("message") == "PSEOF": |
| 52 | + self.is_logs_complete = True |
| 53 | + else: |
| 54 | + self.last_line_number = logs[-1].get("line") |
20 | 55 |
|
| 56 | + for log in logs: |
| 57 | + table_data.append((Color.colorize("red", log.get("line")), log.get("message"))) |
21 | 58 |
|
22 | | -class ListLogsCommand(LogsCommandBase): |
23 | | - def execute(self, job_id): |
24 | | - url = f"/jobs/logs?jobId={job_id}" |
25 | | - response = self.api.get(url) |
26 | | - self._log_message( |
27 | | - response, |
28 | | - "Job logs retrieved", |
29 | | - "Unknown error while retrieving job logs" |
30 | | - ) |
| 59 | + return table.table |
0 commit comments