|
1 | 1 | import pydoc |
2 | 2 |
|
3 | 3 | import terminaltables |
| 4 | +from click import style |
4 | 5 |
|
5 | 6 | from paperspace.commands import CommandBase |
6 | 7 | from paperspace.utils import get_terminal_lines |
@@ -82,3 +83,56 @@ def _make_table(jobs): |
82 | 83 | ascii_table = terminaltables.AsciiTable(data) |
83 | 84 | table_string = ascii_table.table |
84 | 85 | return table_string |
| 86 | + |
| 87 | + |
| 88 | +class JobLogsCommand(CommandBase): |
| 89 | + last_line_number = 0 |
| 90 | + base_url = "/jobs/logs?jobId={}&line={}" |
| 91 | + |
| 92 | + is_logs_complete = False |
| 93 | + |
| 94 | + def execute(self, job_id): |
| 95 | + table_title = "Job %s logs" % job_id |
| 96 | + table_data = [("LINE", "MESSAGE")] |
| 97 | + table = terminaltables.AsciiTable(table_data, title=table_title) |
| 98 | + |
| 99 | + while not self.is_logs_complete: |
| 100 | + response = self._get_logs(job_id) |
| 101 | + |
| 102 | + try: |
| 103 | + data = response.json() |
| 104 | + if not response.ok: |
| 105 | + self.logger.log_error_response(data) |
| 106 | + return |
| 107 | + except (ValueError, KeyError) as e: |
| 108 | + if response.status_code == 204: |
| 109 | + continue |
| 110 | + self.logger.log("Error while parsing response data: {}".format(e)) |
| 111 | + return |
| 112 | + else: |
| 113 | + self._log_logs_list(data, table, table_data) |
| 114 | + |
| 115 | + def _get_logs(self, job_id): |
| 116 | + url = self.base_url.format(job_id, self.last_line_number) |
| 117 | + return self.api.get(url) |
| 118 | + |
| 119 | + def _log_logs_list(self, data, table, table_data): |
| 120 | + if not data: |
| 121 | + self.logger.log("No Logs found") |
| 122 | + else: |
| 123 | + table_str = self._make_table(data, table, table_data) |
| 124 | + if len(table_str.splitlines()) > get_terminal_lines(): |
| 125 | + pydoc.pager(table_str) |
| 126 | + else: |
| 127 | + self.logger.log(table_str) |
| 128 | + |
| 129 | + def _make_table(self, logs, table, table_data): |
| 130 | + if logs[-1].get("message") == "PSEOF": |
| 131 | + self.is_logs_complete = True |
| 132 | + else: |
| 133 | + self.last_line_number = logs[-1].get("line") |
| 134 | + |
| 135 | + for log in logs: |
| 136 | + table_data.append((style(fg="red", text=str(log.get("line"))), log.get("message"))) |
| 137 | + |
| 138 | + return table.table |
0 commit comments