|
| 1 | +"""Pydantic models that can parse borg 1.x's JSON output. |
| 2 | +
|
| 3 | +The two top-level models are: |
| 4 | +
|
| 5 | +- `BorgLogLine`, which parses any line of borg's logging output, |
| 6 | +- all `Borg*Result` classes, which parse the final JSON output of some borg commands. |
| 7 | +
|
| 8 | +The different types of log lines are defined in the other models. |
| 9 | +""" |
| 10 | + |
| 11 | +import json |
| 12 | +import logging |
| 13 | +import typing |
| 14 | +from datetime import datetime |
| 15 | +from pathlib import Path |
| 16 | + |
| 17 | +import pydantic |
| 18 | +import typing_extensions |
| 19 | + |
| 20 | +_log = logging.getLogger(__name__) |
| 21 | + |
| 22 | + |
| 23 | +class BaseBorgLogLine(pydantic.BaseModel): |
| 24 | + def get_level(self) -> int: |
| 25 | + """Get the log level for this line as a `logging` level value. |
| 26 | +
|
| 27 | + If this is a log message with a levelname, use it. |
| 28 | + Otherwise, progress messages get `DEBUG` level, and other messages get `INFO`. |
| 29 | + """ |
| 30 | + return logging.DEBUG |
| 31 | + |
| 32 | + |
| 33 | +class ArchiveProgressLogLine(BaseBorgLogLine): |
| 34 | + original_size: int |
| 35 | + compressed_size: int |
| 36 | + deduplicated_size: int |
| 37 | + nfiles: int |
| 38 | + path: Path |
| 39 | + time: float |
| 40 | + |
| 41 | + |
| 42 | +class FinishedArchiveProgress(BaseBorgLogLine): |
| 43 | + """JSON object printed on stdout when an archive is finished.""" |
| 44 | + |
| 45 | + time: float |
| 46 | + type: typing.Literal["archive_progress"] |
| 47 | + finished: bool |
| 48 | + |
| 49 | + |
| 50 | +class ProgressMessage(BaseBorgLogLine): |
| 51 | + operation: int |
| 52 | + msgid: typing.Optional[str] |
| 53 | + finished: bool |
| 54 | + message: typing.Optional[str] |
| 55 | + time: float |
| 56 | + |
| 57 | + |
| 58 | +class ProgressPercent(BaseBorgLogLine): |
| 59 | + operation: int |
| 60 | + msgid: str | None = pydantic.Field(None) |
| 61 | + finished: bool |
| 62 | + message: str | None = pydantic.Field(None) |
| 63 | + current: float | None = pydantic.Field(None) |
| 64 | + info: list[str] | None = pydantic.Field(None) |
| 65 | + total: float | None = pydantic.Field(None) |
| 66 | + time: float |
| 67 | + |
| 68 | + @pydantic.model_validator(mode="after") |
| 69 | + def fields_depending_on_finished(self) -> typing_extensions.Self: |
| 70 | + if self.finished: |
| 71 | + if self.message is not None: |
| 72 | + raise ValueError("message must be None if finished is True") |
| 73 | + if self.current is not None and self.total is not None and self.current != self.total: |
| 74 | + raise ValueError("current must be equal to total if finished is True") |
| 75 | + if self.info is not None: |
| 76 | + raise ValueError("info must be None if finished is True") |
| 77 | + if self.total is not None: |
| 78 | + raise ValueError("total must be None if finished is True") |
| 79 | + return self |
| 80 | + |
| 81 | + |
| 82 | +class FileStatus(BaseBorgLogLine): |
| 83 | + status: str |
| 84 | + path: Path |
| 85 | + |
| 86 | + |
| 87 | +class LogMessage(BaseBorgLogLine): |
| 88 | + time: float |
| 89 | + levelname: typing.Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] |
| 90 | + name: str |
| 91 | + message: str |
| 92 | + msgid: typing.Optional[str] |
| 93 | + |
| 94 | + def get_level(self) -> int: |
| 95 | + try: |
| 96 | + return getattr(logging, self.levelname) |
| 97 | + except AttributeError: |
| 98 | + _log.warning( |
| 99 | + "could not find log level %s, giving the following message WARNING level: %s", |
| 100 | + self.levelname, |
| 101 | + json.dumps(self), |
| 102 | + ) |
| 103 | + return logging.WARNING |
| 104 | + |
| 105 | + |
| 106 | +_BorgLogLinePossibleTypes = ( |
| 107 | + ArchiveProgressLogLine | FinishedArchiveProgress | ProgressMessage | ProgressPercent | FileStatus | LogMessage |
| 108 | +) |
| 109 | + |
| 110 | + |
| 111 | +class BorgLogLine(pydantic.RootModel[_BorgLogLinePossibleTypes]): |
| 112 | + """A log line from Borg with the `--log-json` argument.""" |
| 113 | + |
| 114 | + def get_level(self) -> int: |
| 115 | + return self.root.get_level() |
| 116 | + |
| 117 | + |
| 118 | +class _BorgArchive(pydantic.BaseModel): |
| 119 | + """Basic archive attributes.""" |
| 120 | + |
| 121 | + name: str |
| 122 | + id: str |
| 123 | + start: datetime |
| 124 | + |
| 125 | + |
| 126 | +class _BorgArchiveStatistics(pydantic.BaseModel): |
| 127 | + """Statistics of an archive.""" |
| 128 | + |
| 129 | + original_size: int |
| 130 | + compressed_size: int |
| 131 | + deduplicated_size: int |
| 132 | + nfiles: int |
| 133 | + |
| 134 | + |
| 135 | +class _BorgLimitUsage(pydantic.BaseModel): |
| 136 | + """Usage of borg limits by an archive.""" |
| 137 | + |
| 138 | + max_archive_size: float |
| 139 | + |
| 140 | + |
| 141 | +class _BorgDetailedArchive(_BorgArchive): |
| 142 | + """Archive attributes, as printed by `json info` or `json create`.""" |
| 143 | + |
| 144 | + end: datetime |
| 145 | + duration: float |
| 146 | + stats: _BorgArchiveStatistics |
| 147 | + limits: _BorgLimitUsage |
| 148 | + command_line: typing.List[str] |
| 149 | + chunker_params: typing.Any | None = None |
| 150 | + |
| 151 | + |
| 152 | +class BorgCreateResult(pydantic.BaseModel): |
| 153 | + """JSON object printed at the end of `borg create`.""" |
| 154 | + |
| 155 | + archive: _BorgDetailedArchive |
| 156 | + |
| 157 | + |
| 158 | +class BorgListResult(pydantic.BaseModel): |
| 159 | + """JSON object printed at the end of `borg list`.""" |
| 160 | + |
| 161 | + archives: typing.List[_BorgArchive] |
0 commit comments