blob: 820cbac0532b4cd008ed9ac8c46818ba3de48409 [file] [log] [blame]
Ian Kasprzak30bc3542020-12-23 10:08:20 -08001# 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
17The git trace2 EVENT format is defined at:
18https://www.kernel.org/pub/software/scm/git/docs/technical/api-trace2.html#_event_format
19https://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
31import datetime
Josh Steadmon244c9a72022-03-08 10:24:43 -080032import errno
Ian Kasprzak30bc3542020-12-23 10:08:20 -080033import json
34import os
Josh Steadmon244c9a72022-03-08 10:24:43 -080035import socket
Ian Kasprzak30bc3542020-12-23 10:08:20 -080036import sys
37import tempfile
38import threading
39
40from git_command import GitCommand, RepoSourceVersion
41
42
43class EventLog(object):
Gavin Makea2e3302023-03-11 06:46:20 +000044 """Event log that records events that occurred during a repo invocation.
Ian Kasprzak30bc3542020-12-23 10:08:20 -080045
Gavin Makea2e3302023-03-11 06:46:20 +000046 Events are written to the log as a consecutive JSON entries, one per line.
47 Entries follow the git trace2 EVENT format.
Ian Kasprzak30bc3542020-12-23 10:08:20 -080048
Gavin Makea2e3302023-03-11 06:46:20 +000049 Each entry contains the following common keys:
50 - event: The event name
51 - sid: session-id - Unique string to allow process instance to be
52 identified.
53 - thread: The thread name.
54 - time: is the UTC time of the event.
Ian Kasprzak30bc3542020-12-23 10:08:20 -080055
Gavin Makea2e3302023-03-11 06:46:20 +000056 Valid 'event' names and event specific fields are documented here:
57 https://git-scm.com/docs/api-trace2#_event_format
Josh Steadmon244c9a72022-03-08 10:24:43 -080058 """
59
Gavin Makea2e3302023-03-11 06:46:20 +000060 def __init__(self, env=None):
61 """Initializes the event log."""
62 self._log = []
63 # Try to get session-id (sid) from environment (setup in repo launcher).
64 KEY = "GIT_TRACE2_PARENT_SID"
65 if env is None:
66 env = os.environ
Josh Steadmon244c9a72022-03-08 10:24:43 -080067
Josip Sokcevic2ad5d502023-05-15 12:54:10 -070068 self.start = datetime.datetime.utcnow()
Ian Kasprzak30bc3542020-12-23 10:08:20 -080069
Gavin Makea2e3302023-03-11 06:46:20 +000070 # Save both our sid component and the complete sid.
71 # We use our sid component (self._sid) as the unique filename prefix and
72 # the full sid (self._full_sid) in the log itself.
73 self._sid = "repo-%s-P%08x" % (
Josip Sokcevic2ad5d502023-05-15 12:54:10 -070074 self.start.strftime("%Y%m%dT%H%M%SZ"),
Gavin Makea2e3302023-03-11 06:46:20 +000075 os.getpid(),
76 )
77 parent_sid = env.get(KEY)
78 # Append our sid component to the parent sid (if it exists).
79 if parent_sid is not None:
80 self._full_sid = parent_sid + "/" + self._sid
81 else:
82 self._full_sid = self._sid
Ian Kasprzak30bc3542020-12-23 10:08:20 -080083
Gavin Makea2e3302023-03-11 06:46:20 +000084 # Set/update the environment variable.
85 # Environment handling across systems is messy.
Josh Steadmon244c9a72022-03-08 10:24:43 -080086 try:
Gavin Makea2e3302023-03-11 06:46:20 +000087 env[KEY] = self._full_sid
88 except UnicodeEncodeError:
89 env[KEY] = self._full_sid.encode()
90
91 # Add a version event to front of the log.
92 self._AddVersionEvent()
93
94 @property
95 def full_sid(self):
96 return self._full_sid
97
98 def _AddVersionEvent(self):
99 """Adds a 'version' event at the beginning of current log."""
100 version_event = self._CreateEventDict("version")
101 version_event["evt"] = "2"
102 version_event["exe"] = RepoSourceVersion()
103 self._log.insert(0, version_event)
104
105 def _CreateEventDict(self, event_name):
106 """Returns a dictionary with common keys/values for git trace2 events.
107
108 Args:
109 event_name: The event name.
110
111 Returns:
112 Dictionary with the common event fields populated.
113 """
114 return {
115 "event": event_name,
116 "sid": self._full_sid,
117 "thread": threading.current_thread().name,
118 "time": datetime.datetime.utcnow().isoformat() + "Z",
119 }
120
121 def StartEvent(self):
122 """Append a 'start' event to the current log."""
123 start_event = self._CreateEventDict("start")
124 start_event["argv"] = sys.argv
125 self._log.append(start_event)
126
127 def ExitEvent(self, result):
128 """Append an 'exit' event to the current log.
129
130 Args:
131 result: Exit code of the event
132 """
133 exit_event = self._CreateEventDict("exit")
134
135 # Consider 'None' success (consistent with event_log result handling).
136 if result is None:
137 result = 0
138 exit_event["code"] = result
Josip Sokcevic2ad5d502023-05-15 12:54:10 -0700139 time_delta = datetime.datetime.utcnow() - self.start
140 exit_event["t_abs"] = time_delta.total_seconds()
Gavin Makea2e3302023-03-11 06:46:20 +0000141 self._log.append(exit_event)
142
143 def CommandEvent(self, name, subcommands):
144 """Append a 'command' event to the current log.
145
146 Args:
147 name: Name of the primary command (ex: repo, git)
148 subcommands: List of the sub-commands (ex: version, init, sync)
149 """
150 command_event = self._CreateEventDict("command")
151 command_event["name"] = name
152 command_event["subcommands"] = subcommands
153 self._log.append(command_event)
154
155 def LogConfigEvents(self, config, event_dict_name):
156 """Append a |event_dict_name| event for each config key in |config|.
157
158 Args:
159 config: Configuration dictionary.
160 event_dict_name: Name of the event dictionary for items to be logged
161 under.
162 """
163 for param, value in config.items():
164 event = self._CreateEventDict(event_dict_name)
165 event["param"] = param
166 event["value"] = value
167 self._log.append(event)
168
169 def DefParamRepoEvents(self, config):
170 """Append 'def_param' events for repo config keys to the current log.
171
172 This appends one event for each repo.* config key.
173
174 Args:
175 config: Repo configuration dictionary
176 """
177 # Only output the repo.* config parameters.
178 repo_config = {k: v for k, v in config.items() if k.startswith("repo.")}
179 self.LogConfigEvents(repo_config, "def_param")
180
181 def GetDataEventName(self, value):
182 """Returns 'data-json' if the value is an array else returns 'data'."""
183 return "data-json" if value[0] == "[" and value[-1] == "]" else "data"
184
185 def LogDataConfigEvents(self, config, prefix):
186 """Append a 'data' event for each entry in |config| to the current log.
187
188 For each keyX and valueX of the config, "key" field of the event is
189 '|prefix|/keyX' and the "value" of the "key" field is valueX.
190
191 Args:
192 config: Configuration dictionary.
193 prefix: Prefix for each key that is logged.
194 """
195 for key, value in config.items():
196 event = self._CreateEventDict(self.GetDataEventName(value))
197 event["key"] = f"{prefix}/{key}"
198 event["value"] = value
199 self._log.append(event)
200
201 def ErrorEvent(self, msg, fmt):
202 """Append a 'error' event to the current log."""
203 error_event = self._CreateEventDict("error")
204 error_event["msg"] = msg
205 error_event["fmt"] = fmt
206 self._log.append(error_event)
207
208 def _GetEventTargetPath(self):
209 """Get the 'trace2.eventtarget' path from git configuration.
210
211 Returns:
212 path: git config's 'trace2.eventtarget' path if it exists, or None
213 """
214 path = None
215 cmd = ["config", "--get", "trace2.eventtarget"]
216 # TODO(https://crbug.com/gerrit/13706): Use GitConfig when it supports
217 # system git config variables.
218 p = GitCommand(
219 None, cmd, capture_stdout=True, capture_stderr=True, bare=True
220 )
221 retval = p.Wait()
222 if retval == 0:
223 # Strip trailing carriage-return in path.
224 path = p.stdout.rstrip("\n")
225 elif retval != 1:
226 # `git config --get` is documented to produce an exit status of `1`
227 # if the requested variable is not present in the configuration.
228 # Report any other return value as an error.
229 print(
230 "repo: error: 'git config --get' call failed with return code: "
231 "%r, stderr: %r" % (retval, p.stderr),
232 file=sys.stderr,
233 )
234 return path
235
236 def _WriteLog(self, write_fn):
237 """Writes the log out using a provided writer function.
238
239 Generate compact JSON output for each item in the log, and write it
240 using write_fn.
241
242 Args:
243 write_fn: A function that accepts byts and writes them to a
244 destination.
245 """
246
247 for e in self._log:
248 # Dump in compact encoding mode.
249 # See 'Compact encoding' in Python docs:
250 # https://docs.python.org/3/library/json.html#module-json
251 write_fn(
252 json.dumps(e, indent=None, separators=(",", ":")).encode(
253 "utf-8"
254 )
255 + b"\n"
256 )
257
258 def Write(self, path=None):
259 """Writes the log out to a file or socket.
260
261 Log is only written if 'path' or 'git config --get trace2.eventtarget'
262 provide a valid path (or socket) to write logs to.
263
264 Logging filename format follows the git trace2 style of being a unique
265 (exclusive writable) file.
266
267 Args:
268 path: Path to where logs should be written. The path may have a
269 prefix of the form "af_unix:[{stream|dgram}:]", in which case
270 the path is treated as a Unix domain socket. See
271 https://git-scm.com/docs/api-trace2#_enabling_a_target for
272 details.
273
274 Returns:
275 log_path: Path to the log file or socket if log is written,
276 otherwise None
277 """
278 log_path = None
279 # If no logging path is specified, get the path from
280 # 'trace2.eventtarget'.
281 if path is None:
282 path = self._GetEventTargetPath()
283
284 # If no logging path is specified, exit.
285 if path is None:
Josh Steadmon244c9a72022-03-08 10:24:43 -0800286 return None
Josh Steadmon244c9a72022-03-08 10:24:43 -0800287
Gavin Makea2e3302023-03-11 06:46:20 +0000288 path_is_socket = False
289 socket_type = None
290 if isinstance(path, str):
291 parts = path.split(":", 1)
292 if parts[0] == "af_unix" and len(parts) == 2:
293 path_is_socket = True
294 path = parts[1]
295 parts = path.split(":", 1)
296 if parts[0] == "stream" and len(parts) == 2:
297 socket_type = socket.SOCK_STREAM
298 path = parts[1]
299 elif parts[0] == "dgram" and len(parts) == 2:
300 socket_type = socket.SOCK_DGRAM
301 path = parts[1]
302 else:
303 # Get absolute path.
304 path = os.path.abspath(os.path.expanduser(path))
305 else:
306 raise TypeError("path: str required but got %s." % type(path))
307
308 # Git trace2 requires a directory to write log to.
309
310 # TODO(https://crbug.com/gerrit/13706): Support file (append) mode also.
311 if not (path_is_socket or os.path.isdir(path)):
312 return None
313
314 if path_is_socket:
315 if socket_type == socket.SOCK_STREAM or socket_type is None:
316 try:
317 with socket.socket(
318 socket.AF_UNIX, socket.SOCK_STREAM
319 ) as sock:
320 sock.connect(path)
321 self._WriteLog(sock.sendall)
322 return f"af_unix:stream:{path}"
323 except OSError as err:
324 # If we tried to connect to a DGRAM socket using STREAM,
325 # ignore the attempt and continue to DGRAM below. Otherwise,
326 # issue a warning.
327 if err.errno != errno.EPROTOTYPE:
328 print(
329 f"repo: warning: git trace2 logging failed: {err}",
330 file=sys.stderr,
331 )
332 return None
333 if socket_type == socket.SOCK_DGRAM or socket_type is None:
334 try:
335 with socket.socket(
336 socket.AF_UNIX, socket.SOCK_DGRAM
337 ) as sock:
338 self._WriteLog(lambda bs: sock.sendto(bs, path))
339 return f"af_unix:dgram:{path}"
340 except OSError as err:
341 print(
342 f"repo: warning: git trace2 logging failed: {err}",
343 file=sys.stderr,
344 )
345 return None
346 # Tried to open a socket but couldn't connect (SOCK_STREAM) or write
347 # (SOCK_DGRAM).
348 print(
349 "repo: warning: git trace2 logging failed: could not write to "
350 "socket",
351 file=sys.stderr,
352 )
353 return None
354
355 # Path is an absolute path
356 # Use NamedTemporaryFile to generate a unique filename as required by
357 # git trace2.
358 try:
359 with tempfile.NamedTemporaryFile(
360 mode="xb", prefix=self._sid, dir=path, delete=False
361 ) as f:
362 # TODO(https://crbug.com/gerrit/13706): Support writing events
363 # as they occur.
364 self._WriteLog(f.write)
365 log_path = f.name
366 except FileExistsError as err:
367 print(
368 "repo: warning: git trace2 logging failed: %r" % err,
369 file=sys.stderr,
370 )
371 return None
372 return log_path