Mike Frysinger | f1ba7ad | 2022-09-12 05:42:57 -0400 | [diff] [blame] | 1 | # Copyright 2020 The ChromiumOS Authors |
Alex Klein | e191ed6 | 2020-02-27 15:59:55 -0700 | [diff] [blame] | 2 | # Use of this source code is governed by a BSD-style license that can be |
| 3 | # found in the LICENSE file. |
| 4 | |
| 5 | """Protobuf message utilities. |
| 6 | |
| 7 | The Serializer classes are adapters to standardize the reading and writing of |
| 8 | different protobuf message serialization formats to and from a message. |
| 9 | |
| 10 | The base MessageHandler class encapsulates the functionality of reading |
| 11 | a file containing serialized data into a protobuf message instance, and |
| 12 | writing serialized data from a message instance out to a file. |
| 13 | """ |
| 14 | |
Chris McDonald | 1672ddb | 2021-07-21 11:48:23 -0600 | [diff] [blame] | 15 | import logging |
Alex Klein | e191ed6 | 2020-02-27 15:59:55 -0700 | [diff] [blame] | 16 | import os |
Kevin Shelton | d0275c8 | 2022-08-05 01:57:51 +0000 | [diff] [blame] | 17 | from typing import Optional, TYPE_CHECKING |
Alex Klein | e191ed6 | 2020-02-27 15:59:55 -0700 | [diff] [blame] | 18 | |
Mike Frysinger | 2c02406 | 2021-05-22 15:43:22 -0400 | [diff] [blame] | 19 | from chromite.third_party.google.protobuf import json_format |
Alex Klein | e191ed6 | 2020-02-27 15:59:55 -0700 | [diff] [blame] | 20 | |
| 21 | from chromite.lib import osutils |
| 22 | |
Mike Frysinger | a9b30c7 | 2020-04-18 03:36:03 -0400 | [diff] [blame] | 23 | |
Kevin Shelton | d0275c8 | 2022-08-05 01:57:51 +0000 | [diff] [blame] | 24 | if TYPE_CHECKING: |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 25 | from chromite.third_party import google |
Kevin Shelton | d0275c8 | 2022-08-05 01:57:51 +0000 | [diff] [blame] | 26 | |
Alex Klein | e191ed6 | 2020-02-27 15:59:55 -0700 | [diff] [blame] | 27 | FORMAT_BINARY = 1 |
| 28 | FORMAT_JSON = 2 |
| 29 | VALID_FORMATS = (FORMAT_BINARY, FORMAT_JSON) |
| 30 | |
| 31 | |
| 32 | class Error(Exception): |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 33 | """Base error class for the module.""" |
Alex Klein | e191ed6 | 2020-02-27 15:59:55 -0700 | [diff] [blame] | 34 | |
| 35 | |
| 36 | class InvalidHandlerError(Error): |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 37 | """Raised when a message handler has no input/output argument when needed.""" |
Alex Klein | e191ed6 | 2020-02-27 15:59:55 -0700 | [diff] [blame] | 38 | |
| 39 | |
| 40 | class InvalidInputFileError(Error): |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 41 | """Raised when the input file cannot be read.""" |
Alex Klein | e191ed6 | 2020-02-27 15:59:55 -0700 | [diff] [blame] | 42 | |
| 43 | |
| 44 | class InvalidInputFormatError(Error): |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 45 | """Raised when the passed input protobuf can't be parsed.""" |
Alex Klein | e191ed6 | 2020-02-27 15:59:55 -0700 | [diff] [blame] | 46 | |
| 47 | |
| 48 | class InvalidOutputFileError(Error): |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 49 | """Raised when the output file cannot be written.""" |
Alex Klein | e191ed6 | 2020-02-27 15:59:55 -0700 | [diff] [blame] | 50 | |
| 51 | |
| 52 | class UnknownHandlerError(Error): |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 53 | """Raised when a valid type has not been implemented yet. |
Alex Klein | e191ed6 | 2020-02-27 15:59:55 -0700 | [diff] [blame] | 54 | |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 55 | This should only ever be raised when under active development. |
| 56 | See: get_message_handler. |
| 57 | """ |
Alex Klein | e191ed6 | 2020-02-27 15:59:55 -0700 | [diff] [blame] | 58 | |
| 59 | |
| 60 | def get_message_handler(path, msg_format): |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 61 | """Get a message handler to handle the given message format.""" |
| 62 | assert msg_format in VALID_FORMATS |
Alex Klein | e191ed6 | 2020-02-27 15:59:55 -0700 | [diff] [blame] | 63 | |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 64 | if msg_format == FORMAT_BINARY: |
| 65 | return MessageHandler( |
| 66 | path=path, |
| 67 | serializer=BinarySerializer(), |
| 68 | binary=True, |
| 69 | input_arg="--input-binary", |
| 70 | output_arg="--output-binary", |
| 71 | config_arg="--config-binary", |
| 72 | ) |
| 73 | elif msg_format == FORMAT_JSON: |
| 74 | return MessageHandler( |
| 75 | path=path, |
| 76 | serializer=JsonSerializer(), |
| 77 | binary=False, |
| 78 | input_arg="--input-json", |
| 79 | output_arg="--output-json", |
| 80 | config_arg="--config-json", |
| 81 | ) |
| 82 | else: |
| 83 | # Unexpected. Your new format type needs a case in this function if |
| 84 | # you got this error. |
| 85 | raise UnknownHandlerError("Unknown format type.") |
Alex Klein | e191ed6 | 2020-02-27 15:59:55 -0700 | [diff] [blame] | 86 | |
| 87 | |
| 88 | class Serializer(object): |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 89 | """Base (and null) serializer class.""" |
Alex Klein | e191ed6 | 2020-02-27 15:59:55 -0700 | [diff] [blame] | 90 | |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 91 | def deserialize(self, data: str, message: "google.protobuf.Message"): |
| 92 | """Deserialize the data into the given message. |
Alex Klein | e191ed6 | 2020-02-27 15:59:55 -0700 | [diff] [blame] | 93 | |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 94 | Args: |
Alex Klein | a044268 | 2022-10-10 13:47:38 -0600 | [diff] [blame] | 95 | data: The message data to deserialize. |
| 96 | message: The message to load the data into. |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 97 | """ |
Alex Klein | e191ed6 | 2020-02-27 15:59:55 -0700 | [diff] [blame] | 98 | |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 99 | # pylint: disable=unused-argument |
| 100 | def serialize(self, message: "google.protobuf.Message") -> str: |
| 101 | """Serialize the message data. |
Alex Klein | e191ed6 | 2020-02-27 15:59:55 -0700 | [diff] [blame] | 102 | |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 103 | Args: |
Alex Klein | a044268 | 2022-10-10 13:47:38 -0600 | [diff] [blame] | 104 | message: The message to be serialized. |
Alex Klein | e191ed6 | 2020-02-27 15:59:55 -0700 | [diff] [blame] | 105 | |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 106 | Returns: |
Alex Klein | a044268 | 2022-10-10 13:47:38 -0600 | [diff] [blame] | 107 | The message's serialized data. |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 108 | """ |
| 109 | return "" |
Alex Klein | e191ed6 | 2020-02-27 15:59:55 -0700 | [diff] [blame] | 110 | |
| 111 | |
| 112 | class BinarySerializer(Serializer): |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 113 | """Protobuf binary serializer class.""" |
Alex Klein | e191ed6 | 2020-02-27 15:59:55 -0700 | [diff] [blame] | 114 | |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 115 | def deserialize(self, data, message): |
| 116 | """Deserialize the data into the given message. |
Alex Klein | e191ed6 | 2020-02-27 15:59:55 -0700 | [diff] [blame] | 117 | |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 118 | See: Serializer.deserialize |
| 119 | """ |
| 120 | message.ParseFromString(data) |
Alex Klein | e191ed6 | 2020-02-27 15:59:55 -0700 | [diff] [blame] | 121 | |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 122 | def serialize(self, message): |
| 123 | """Serialize the message data. |
Alex Klein | e191ed6 | 2020-02-27 15:59:55 -0700 | [diff] [blame] | 124 | |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 125 | See: Serializer.serialize |
| 126 | """ |
| 127 | return message.SerializeToString() |
Alex Klein | e191ed6 | 2020-02-27 15:59:55 -0700 | [diff] [blame] | 128 | |
| 129 | |
| 130 | class JsonSerializer(Serializer): |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 131 | """Protobuf json serializer class.""" |
Alex Klein | e191ed6 | 2020-02-27 15:59:55 -0700 | [diff] [blame] | 132 | |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 133 | def deserialize(self, data, message): |
| 134 | """Deserialize the data into the given message. |
Alex Klein | e191ed6 | 2020-02-27 15:59:55 -0700 | [diff] [blame] | 135 | |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 136 | See: Serializer.deserialize |
| 137 | """ |
| 138 | try: |
| 139 | json_format.Parse(data, message, ignore_unknown_fields=True) |
| 140 | except json_format.ParseError as e: |
| 141 | raise InvalidInputFormatError( |
| 142 | "Unable to parse the input json: %s" % e |
| 143 | ) |
Alex Klein | e191ed6 | 2020-02-27 15:59:55 -0700 | [diff] [blame] | 144 | |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 145 | def serialize(self, message): |
| 146 | """Serialize the message data. |
Alex Klein | e191ed6 | 2020-02-27 15:59:55 -0700 | [diff] [blame] | 147 | |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 148 | See: Serializer.serialize |
| 149 | """ |
| 150 | return ( |
| 151 | json_format.MessageToJson( |
| 152 | message, sort_keys=True, use_integers_for_enums=True |
| 153 | ) |
| 154 | or "{}" |
| 155 | ) |
Alex Klein | e191ed6 | 2020-02-27 15:59:55 -0700 | [diff] [blame] | 156 | |
| 157 | |
| 158 | class MessageHandler(object): |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 159 | """Class to handle message (de)serialization to and from files. |
Alex Klein | e191ed6 | 2020-02-27 15:59:55 -0700 | [diff] [blame] | 160 | |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 161 | The class is fairly tightly coupled to the build api, but we currently have |
| 162 | no other projected use cases for this, so it's handy. In particular, if we |
| 163 | scrap the "maintain the same input/output/config serialization when reexecing |
| 164 | inside the chroot" convention, this implementation is much less useful and |
| 165 | can be fairly trivially generalized. |
Alex Klein | e191ed6 | 2020-02-27 15:59:55 -0700 | [diff] [blame] | 166 | |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 167 | The instance's path is the primary path the message handler was built for. |
| 168 | For the Build API, this means one of the input/output/config arguments. In |
| 169 | practice, it's largely a convenience/shortcut so we don't have to either |
| 170 | track which input files are what types (which we know from the argument used |
| 171 | to pass them in), or create another containing data class for the |
| 172 | functionality provided by the handler and serializer classes and the build |
| 173 | api data. |
Alex Klein | e191ed6 | 2020-02-27 15:59:55 -0700 | [diff] [blame] | 174 | |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 175 | Examples: |
Alex Klein | a044268 | 2022-10-10 13:47:38 -0600 | [diff] [blame] | 176 | message_handler = MessageHandler(path, ...) |
| 177 | message = ... |
| 178 | # Parse path into message. |
| 179 | message_handler.read_into(message) |
| 180 | # Write message to a different file. |
| 181 | message_handler.write_into(message, path=other_path) |
Alex Klein | e191ed6 | 2020-02-27 15:59:55 -0700 | [diff] [blame] | 182 | """ |
Alex Klein | e191ed6 | 2020-02-27 15:59:55 -0700 | [diff] [blame] | 183 | |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 184 | def __init__( |
| 185 | self, |
| 186 | path: str, |
| 187 | serializer: Serializer, |
| 188 | binary: bool, |
| 189 | input_arg: str, |
| 190 | output_arg: str, |
| 191 | config_arg: str, |
| 192 | ): |
| 193 | """MessageHandler init. |
Alex Klein | e191ed6 | 2020-02-27 15:59:55 -0700 | [diff] [blame] | 194 | |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 195 | Args: |
Alex Klein | a044268 | 2022-10-10 13:47:38 -0600 | [diff] [blame] | 196 | path: The path to the main file associated with this handler. |
| 197 | serializer: The serializer to be used for the messages. |
| 198 | binary: Whether the serialized content is binary. |
| 199 | input_arg: The --input-x argument used for this type. Used for |
| 200 | reexecution inside the chroot. |
| 201 | output_arg: The --output-x argument used for this type. Used for |
| 202 | reexecution inside the chroot. |
| 203 | config_arg: The --config-x argument used for this type. Used for |
| 204 | reexecution inside the chroot. |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 205 | """ |
| 206 | self.path = path |
| 207 | self.serializer = serializer |
| 208 | self.read_mode = "rb" if binary else "r" |
| 209 | self.write_mode = "wb" if binary else "w" |
| 210 | self.input_arg = input_arg |
| 211 | self.output_arg = output_arg |
| 212 | self.config_arg = config_arg |
Alex Klein | e191ed6 | 2020-02-27 15:59:55 -0700 | [diff] [blame] | 213 | |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 214 | def read_into( |
| 215 | self, message: "google.protobuf.Message", path: Optional[str] = None |
| 216 | ): |
| 217 | """Read a file containing serialized data into a message. |
Alex Klein | e191ed6 | 2020-02-27 15:59:55 -0700 | [diff] [blame] | 218 | |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 219 | Args: |
Alex Klein | a044268 | 2022-10-10 13:47:38 -0600 | [diff] [blame] | 220 | message: The message to populate. |
| 221 | path: A path to read. Uses the instance's path when not given. |
Alex Klein | e191ed6 | 2020-02-27 15:59:55 -0700 | [diff] [blame] | 222 | |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 223 | Raises: |
Alex Klein | a044268 | 2022-10-10 13:47:38 -0600 | [diff] [blame] | 224 | InvalidInputFileError: When a path has not been given, does not |
| 225 | exist, or cannot be read. |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 226 | """ |
| 227 | target_path = path or self.path |
| 228 | if not target_path: |
| 229 | raise InvalidInputFileError("No input file has been specified.") |
| 230 | if not os.path.exists(target_path): |
| 231 | raise InvalidInputFileError("The input file does not exist.") |
Alex Klein | e191ed6 | 2020-02-27 15:59:55 -0700 | [diff] [blame] | 232 | |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 233 | try: |
| 234 | content = osutils.ReadFile(target_path, mode=self.read_mode) |
| 235 | except IOError as e: |
| 236 | raise InvalidInputFileError("Unable to read input file: %s" % e) |
Alex Klein | e191ed6 | 2020-02-27 15:59:55 -0700 | [diff] [blame] | 237 | |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 238 | if content: |
| 239 | self.serializer.deserialize(content, message) |
| 240 | else: |
| 241 | logging.warning( |
| 242 | "No content found in %s to deserialize.", target_path |
| 243 | ) |
Alex Klein | e191ed6 | 2020-02-27 15:59:55 -0700 | [diff] [blame] | 244 | |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 245 | def write_from( |
| 246 | self, message: "google.protobuf.Message", path: Optional[str] = None |
| 247 | ): |
| 248 | """Write serialized data from the message to a file. |
Alex Klein | e191ed6 | 2020-02-27 15:59:55 -0700 | [diff] [blame] | 249 | |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 250 | Args: |
Alex Klein | a044268 | 2022-10-10 13:47:38 -0600 | [diff] [blame] | 251 | message: The message to serialize and persist. |
| 252 | path: An optional override of the instance's path. |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 253 | |
| 254 | Raises: |
Alex Klein | a044268 | 2022-10-10 13:47:38 -0600 | [diff] [blame] | 255 | InvalidOutputFileError: When no path given, or it cannot be written to. |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 256 | """ |
| 257 | if not path and not self.path: |
| 258 | raise InvalidOutputFileError("No output file has been specified.") |
| 259 | |
| 260 | try: |
| 261 | osutils.WriteFile( |
| 262 | path or self.path, |
| 263 | self.serializer.serialize(message), |
| 264 | mode=self.write_mode, |
| 265 | ) |
| 266 | except IOError as e: |
| 267 | raise InvalidOutputFileError("Cannot write output file: %s" % e) |