Jason Chang | f19b310 | 2023-09-01 16:07:34 -0700 | [diff] [blame] | 1 | # Copyright (C) 2020 The Android Open Source Project |
| 2 | # |
| 3 | # Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | # you may not use this file except in compliance with the License. |
| 5 | # You may obtain a copy of the License at |
| 6 | # |
| 7 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | # |
| 9 | # Unless required by applicable law or agreed to in writing, software |
| 10 | # distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | # See the License for the specific language governing permissions and |
| 13 | # limitations under the License. |
| 14 | |
| 15 | """Provide event logging in the git trace2 EVENT format. |
| 16 | |
| 17 | The git trace2 EVENT format is defined at: |
| 18 | https://www.kernel.org/pub/software/scm/git/docs/technical/api-trace2.html#_event_format |
| 19 | https://git-scm.com/docs/api-trace2#_the_event_format_target |
| 20 | |
| 21 | Usage: |
| 22 | |
| 23 | git_trace_log = EventLog() |
| 24 | git_trace_log.StartEvent() |
| 25 | ... |
| 26 | git_trace_log.ExitEvent() |
| 27 | git_trace_log.Write() |
| 28 | """ |
| 29 | |
| 30 | |
| 31 | import datetime |
| 32 | import errno |
| 33 | import json |
| 34 | import os |
| 35 | import socket |
| 36 | import sys |
| 37 | import tempfile |
| 38 | import threading |
| 39 | |
| 40 | |
| 41 | # BaseEventLog __init__ Counter that is consistent within the same process |
| 42 | p_init_count = 0 |
| 43 | |
| 44 | |
Mike Frysinger | d4aee65 | 2023-10-19 05:13:32 -0400 | [diff] [blame] | 45 | class BaseEventLog: |
Jason Chang | f19b310 | 2023-09-01 16:07:34 -0700 | [diff] [blame] | 46 | """Event log that records events that occurred during a repo invocation. |
| 47 | |
| 48 | Events are written to the log as a consecutive JSON entries, one per line. |
| 49 | Entries follow the git trace2 EVENT format. |
| 50 | |
| 51 | Each entry contains the following common keys: |
| 52 | - event: The event name |
| 53 | - sid: session-id - Unique string to allow process instance to be |
| 54 | identified. |
| 55 | - thread: The thread name. |
| 56 | - time: is the UTC time of the event. |
| 57 | |
| 58 | Valid 'event' names and event specific fields are documented here: |
| 59 | https://git-scm.com/docs/api-trace2#_event_format |
| 60 | """ |
| 61 | |
| 62 | def __init__( |
| 63 | self, env=None, repo_source_version=None, add_init_count=False |
| 64 | ): |
| 65 | """Initializes the event log.""" |
| 66 | global p_init_count |
| 67 | p_init_count += 1 |
| 68 | self._log = [] |
| 69 | # Try to get session-id (sid) from environment (setup in repo launcher). |
| 70 | KEY = "GIT_TRACE2_PARENT_SID" |
| 71 | if env is None: |
| 72 | env = os.environ |
| 73 | |
LuK1337 | aadd12c | 2023-09-16 09:36:49 +0200 | [diff] [blame] | 74 | self.start = datetime.datetime.now(datetime.timezone.utc) |
Jason Chang | f19b310 | 2023-09-01 16:07:34 -0700 | [diff] [blame] | 75 | |
| 76 | # Save both our sid component and the complete sid. |
| 77 | # We use our sid component (self._sid) as the unique filename prefix and |
| 78 | # the full sid (self._full_sid) in the log itself. |
Jason R. Coombs | b32ccbb | 2023-09-29 11:04:49 -0400 | [diff] [blame^] | 79 | self._sid = ( |
| 80 | f"repo-{self.start.strftime('%Y%m%dT%H%M%SZ')}-P{os.getpid():08x}" |
Jason Chang | f19b310 | 2023-09-01 16:07:34 -0700 | [diff] [blame] | 81 | ) |
| 82 | |
| 83 | if add_init_count: |
| 84 | self._sid = f"{self._sid}-{p_init_count}" |
| 85 | |
| 86 | parent_sid = env.get(KEY) |
| 87 | # Append our sid component to the parent sid (if it exists). |
| 88 | if parent_sid is not None: |
| 89 | self._full_sid = parent_sid + "/" + self._sid |
| 90 | else: |
| 91 | self._full_sid = self._sid |
| 92 | |
| 93 | # Set/update the environment variable. |
| 94 | # Environment handling across systems is messy. |
| 95 | try: |
| 96 | env[KEY] = self._full_sid |
| 97 | except UnicodeEncodeError: |
| 98 | env[KEY] = self._full_sid.encode() |
| 99 | |
| 100 | if repo_source_version is not None: |
| 101 | # Add a version event to front of the log. |
| 102 | self._AddVersionEvent(repo_source_version) |
| 103 | |
| 104 | @property |
| 105 | def full_sid(self): |
| 106 | return self._full_sid |
| 107 | |
| 108 | def _AddVersionEvent(self, repo_source_version): |
| 109 | """Adds a 'version' event at the beginning of current log.""" |
| 110 | version_event = self._CreateEventDict("version") |
| 111 | version_event["evt"] = "2" |
| 112 | version_event["exe"] = repo_source_version |
| 113 | self._log.insert(0, version_event) |
| 114 | |
| 115 | def _CreateEventDict(self, event_name): |
| 116 | """Returns a dictionary with common keys/values for git trace2 events. |
| 117 | |
| 118 | Args: |
| 119 | event_name: The event name. |
| 120 | |
| 121 | Returns: |
| 122 | Dictionary with the common event fields populated. |
| 123 | """ |
| 124 | return { |
| 125 | "event": event_name, |
| 126 | "sid": self._full_sid, |
| 127 | "thread": threading.current_thread().name, |
LuK1337 | aadd12c | 2023-09-16 09:36:49 +0200 | [diff] [blame] | 128 | "time": datetime.datetime.now(datetime.timezone.utc).isoformat(), |
Jason Chang | f19b310 | 2023-09-01 16:07:34 -0700 | [diff] [blame] | 129 | } |
| 130 | |
| 131 | def StartEvent(self): |
| 132 | """Append a 'start' event to the current log.""" |
| 133 | start_event = self._CreateEventDict("start") |
| 134 | start_event["argv"] = sys.argv |
| 135 | self._log.append(start_event) |
| 136 | |
| 137 | def ExitEvent(self, result): |
| 138 | """Append an 'exit' event to the current log. |
| 139 | |
| 140 | Args: |
| 141 | result: Exit code of the event |
| 142 | """ |
| 143 | exit_event = self._CreateEventDict("exit") |
| 144 | |
| 145 | # Consider 'None' success (consistent with event_log result handling). |
| 146 | if result is None: |
| 147 | result = 0 |
| 148 | exit_event["code"] = result |
LuK1337 | aadd12c | 2023-09-16 09:36:49 +0200 | [diff] [blame] | 149 | time_delta = datetime.datetime.now(datetime.timezone.utc) - self.start |
Jason Chang | f19b310 | 2023-09-01 16:07:34 -0700 | [diff] [blame] | 150 | exit_event["t_abs"] = time_delta.total_seconds() |
| 151 | self._log.append(exit_event) |
| 152 | |
| 153 | def CommandEvent(self, name, subcommands): |
| 154 | """Append a 'command' event to the current log. |
| 155 | |
| 156 | Args: |
| 157 | name: Name of the primary command (ex: repo, git) |
| 158 | subcommands: List of the sub-commands (ex: version, init, sync) |
| 159 | """ |
| 160 | command_event = self._CreateEventDict("command") |
| 161 | command_event["name"] = name |
| 162 | command_event["subcommands"] = subcommands |
| 163 | self._log.append(command_event) |
| 164 | |
| 165 | def LogConfigEvents(self, config, event_dict_name): |
| 166 | """Append a |event_dict_name| event for each config key in |config|. |
| 167 | |
| 168 | Args: |
| 169 | config: Configuration dictionary. |
| 170 | event_dict_name: Name of the event dictionary for items to be logged |
| 171 | under. |
| 172 | """ |
| 173 | for param, value in config.items(): |
| 174 | event = self._CreateEventDict(event_dict_name) |
| 175 | event["param"] = param |
| 176 | event["value"] = value |
| 177 | self._log.append(event) |
| 178 | |
| 179 | def DefParamRepoEvents(self, config): |
| 180 | """Append 'def_param' events for repo config keys to the current log. |
| 181 | |
| 182 | This appends one event for each repo.* config key. |
| 183 | |
| 184 | Args: |
| 185 | config: Repo configuration dictionary |
| 186 | """ |
| 187 | # Only output the repo.* config parameters. |
| 188 | repo_config = {k: v for k, v in config.items() if k.startswith("repo.")} |
| 189 | self.LogConfigEvents(repo_config, "def_param") |
| 190 | |
| 191 | def GetDataEventName(self, value): |
| 192 | """Returns 'data-json' if the value is an array else returns 'data'.""" |
| 193 | return "data-json" if value[0] == "[" and value[-1] == "]" else "data" |
| 194 | |
| 195 | def LogDataConfigEvents(self, config, prefix): |
| 196 | """Append a 'data' event for each entry in |config| to the current log. |
| 197 | |
| 198 | For each keyX and valueX of the config, "key" field of the event is |
| 199 | '|prefix|/keyX' and the "value" of the "key" field is valueX. |
| 200 | |
| 201 | Args: |
| 202 | config: Configuration dictionary. |
| 203 | prefix: Prefix for each key that is logged. |
| 204 | """ |
| 205 | for key, value in config.items(): |
| 206 | event = self._CreateEventDict(self.GetDataEventName(value)) |
| 207 | event["key"] = f"{prefix}/{key}" |
| 208 | event["value"] = value |
| 209 | self._log.append(event) |
| 210 | |
| 211 | def ErrorEvent(self, msg, fmt=None): |
| 212 | """Append a 'error' event to the current log.""" |
| 213 | error_event = self._CreateEventDict("error") |
| 214 | if fmt is None: |
| 215 | fmt = msg |
| 216 | error_event["msg"] = f"RepoErrorEvent:{msg}" |
| 217 | error_event["fmt"] = f"RepoErrorEvent:{fmt}" |
| 218 | self._log.append(error_event) |
| 219 | |
| 220 | def _WriteLog(self, write_fn): |
| 221 | """Writes the log out using a provided writer function. |
| 222 | |
| 223 | Generate compact JSON output for each item in the log, and write it |
| 224 | using write_fn. |
| 225 | |
| 226 | Args: |
| 227 | write_fn: A function that accepts byts and writes them to a |
| 228 | destination. |
| 229 | """ |
| 230 | |
| 231 | for e in self._log: |
| 232 | # Dump in compact encoding mode. |
| 233 | # See 'Compact encoding' in Python docs: |
| 234 | # https://docs.python.org/3/library/json.html#module-json |
| 235 | write_fn( |
| 236 | json.dumps(e, indent=None, separators=(",", ":")).encode( |
| 237 | "utf-8" |
| 238 | ) |
| 239 | + b"\n" |
| 240 | ) |
| 241 | |
| 242 | def Write(self, path=None): |
| 243 | """Writes the log out to a file or socket. |
| 244 | |
| 245 | Log is only written if 'path' or 'git config --get trace2.eventtarget' |
| 246 | provide a valid path (or socket) to write logs to. |
| 247 | |
| 248 | Logging filename format follows the git trace2 style of being a unique |
| 249 | (exclusive writable) file. |
| 250 | |
| 251 | Args: |
| 252 | path: Path to where logs should be written. The path may have a |
| 253 | prefix of the form "af_unix:[{stream|dgram}:]", in which case |
| 254 | the path is treated as a Unix domain socket. See |
| 255 | https://git-scm.com/docs/api-trace2#_enabling_a_target for |
| 256 | details. |
| 257 | |
| 258 | Returns: |
| 259 | log_path: Path to the log file or socket if log is written, |
| 260 | otherwise None |
| 261 | """ |
| 262 | log_path = None |
| 263 | # If no logging path is specified, exit. |
| 264 | if path is None: |
| 265 | return None |
| 266 | |
| 267 | path_is_socket = False |
| 268 | socket_type = None |
| 269 | if isinstance(path, str): |
| 270 | parts = path.split(":", 1) |
| 271 | if parts[0] == "af_unix" and len(parts) == 2: |
| 272 | path_is_socket = True |
| 273 | path = parts[1] |
| 274 | parts = path.split(":", 1) |
| 275 | if parts[0] == "stream" and len(parts) == 2: |
| 276 | socket_type = socket.SOCK_STREAM |
| 277 | path = parts[1] |
| 278 | elif parts[0] == "dgram" and len(parts) == 2: |
| 279 | socket_type = socket.SOCK_DGRAM |
| 280 | path = parts[1] |
| 281 | else: |
| 282 | # Get absolute path. |
| 283 | path = os.path.abspath(os.path.expanduser(path)) |
| 284 | else: |
| 285 | raise TypeError("path: str required but got %s." % type(path)) |
| 286 | |
| 287 | # Git trace2 requires a directory to write log to. |
| 288 | |
| 289 | # TODO(https://crbug.com/gerrit/13706): Support file (append) mode also. |
| 290 | if not (path_is_socket or os.path.isdir(path)): |
| 291 | return None |
| 292 | |
| 293 | if path_is_socket: |
| 294 | if socket_type == socket.SOCK_STREAM or socket_type is None: |
| 295 | try: |
| 296 | with socket.socket( |
| 297 | socket.AF_UNIX, socket.SOCK_STREAM |
| 298 | ) as sock: |
| 299 | sock.connect(path) |
| 300 | self._WriteLog(sock.sendall) |
| 301 | return f"af_unix:stream:{path}" |
| 302 | except OSError as err: |
| 303 | # If we tried to connect to a DGRAM socket using STREAM, |
| 304 | # ignore the attempt and continue to DGRAM below. Otherwise, |
| 305 | # issue a warning. |
| 306 | if err.errno != errno.EPROTOTYPE: |
| 307 | print( |
| 308 | f"repo: warning: git trace2 logging failed: {err}", |
| 309 | file=sys.stderr, |
| 310 | ) |
| 311 | return None |
| 312 | if socket_type == socket.SOCK_DGRAM or socket_type is None: |
| 313 | try: |
| 314 | with socket.socket( |
| 315 | socket.AF_UNIX, socket.SOCK_DGRAM |
| 316 | ) as sock: |
| 317 | self._WriteLog(lambda bs: sock.sendto(bs, path)) |
| 318 | return f"af_unix:dgram:{path}" |
| 319 | except OSError as err: |
| 320 | print( |
| 321 | f"repo: warning: git trace2 logging failed: {err}", |
| 322 | file=sys.stderr, |
| 323 | ) |
| 324 | return None |
| 325 | # Tried to open a socket but couldn't connect (SOCK_STREAM) or write |
| 326 | # (SOCK_DGRAM). |
| 327 | print( |
| 328 | "repo: warning: git trace2 logging failed: could not write to " |
| 329 | "socket", |
| 330 | file=sys.stderr, |
| 331 | ) |
| 332 | return None |
| 333 | |
| 334 | # Path is an absolute path |
| 335 | # Use NamedTemporaryFile to generate a unique filename as required by |
| 336 | # git trace2. |
| 337 | try: |
| 338 | with tempfile.NamedTemporaryFile( |
| 339 | mode="xb", prefix=self._sid, dir=path, delete=False |
| 340 | ) as f: |
| 341 | # TODO(https://crbug.com/gerrit/13706): Support writing events |
| 342 | # as they occur. |
| 343 | self._WriteLog(f.write) |
| 344 | log_path = f.name |
| 345 | except FileExistsError as err: |
| 346 | print( |
| 347 | "repo: warning: git trace2 logging failed: %r" % err, |
| 348 | file=sys.stderr, |
| 349 | ) |
| 350 | return None |
| 351 | return log_path |