xprof 2.22.2__py3-none-win_amd64.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- xprof/__init__.py +23 -0
- xprof/api/continuous_profiling_snapshot.py +73 -0
- xprof/convert/_pywrap_profiler_plugin.py +506 -0
- xprof/convert/csv_writer.py +139 -0
- xprof/convert/profiler_plugin_c_api.pyd +0 -0
- xprof/convert/raw_to_tool_data.py +237 -0
- xprof/convert/trace_events_json.py +105 -0
- xprof/integration_tests/tf_mnist.py +100 -0
- xprof/integration_tests/tf_profiler_session.py +40 -0
- xprof/integration_tests/tpu/tensorflow/tpu_tf2_keras_test.py +183 -0
- xprof/profile_io.py +411 -0
- xprof/profile_plugin.py +1896 -0
- xprof/profile_plugin_loader.py +82 -0
- xprof/protobuf/dcn_collective_info_pb2.py +44 -0
- xprof/protobuf/dcn_slack_analysis_pb2.py +42 -0
- xprof/protobuf/diagnostics_pb2.py +36 -0
- xprof/protobuf/event_time_fraction_analyzer_pb2.py +54 -0
- xprof/protobuf/hardware_types_pb2.py +40 -0
- xprof/protobuf/hlo_stats_pb2.py +41 -0
- xprof/protobuf/inference_stats_pb2.py +86 -0
- xprof/protobuf/input_pipeline_pb2.py +52 -0
- xprof/protobuf/kernel_stats_pb2.py +38 -0
- xprof/protobuf/memory_profile_pb2.py +56 -0
- xprof/protobuf/memory_viewer_preprocess_pb2.py +49 -0
- xprof/protobuf/op_metrics_pb2.py +71 -0
- xprof/protobuf/op_profile_pb2.py +49 -0
- xprof/protobuf/op_stats_pb2.py +75 -0
- xprof/protobuf/overview_page_pb2.py +65 -0
- xprof/protobuf/pod_stats_pb2.py +45 -0
- xprof/protobuf/pod_viewer_pb2.py +61 -0
- xprof/protobuf/power_metrics_pb2.py +38 -0
- xprof/protobuf/roofline_model_pb2.py +44 -0
- xprof/protobuf/smart_suggestion_pb2.py +38 -0
- xprof/protobuf/source_info_pb2.py +36 -0
- xprof/protobuf/source_stats_pb2.py +50 -0
- xprof/protobuf/steps_db_pb2.py +76 -0
- xprof/protobuf/task_pb2.py +37 -0
- xprof/protobuf/tf_data_stats_pb2.py +72 -0
- xprof/protobuf/tf_function_pb2.py +52 -0
- xprof/protobuf/tf_stats_pb2.py +42 -0
- xprof/protobuf/tfstreamz_pb2.py +40 -0
- xprof/protobuf/topology_pb2.py +50 -0
- xprof/protobuf/tpu_input_pipeline_pb2.py +43 -0
- xprof/protobuf/trace_data_response_pb2.py +48 -0
- xprof/protobuf/trace_events_old_pb2.py +54 -0
- xprof/protobuf/trace_events_pb2.py +64 -0
- xprof/protobuf/trace_events_raw_pb2.py +45 -0
- xprof/protobuf/trace_filter_config_pb2.py +40 -0
- xprof/server.py +359 -0
- xprof/standalone/base_plugin.py +52 -0
- xprof/standalone/context.py +22 -0
- xprof/standalone/data_provider.py +32 -0
- xprof/standalone/plugin_asset_util.py +131 -0
- xprof/standalone/plugin_event_multiplexer.py +185 -0
- xprof/standalone/tensorboard_shim.py +31 -0
- xprof/static/bundle.js +137744 -0
- xprof/static/index.html +64 -0
- xprof/static/index.js +3 -0
- xprof/static/materialicons.woff2 +0 -0
- xprof/static/styles.css +1 -0
- xprof/static/trace_viewer_index.html +3935 -0
- xprof/static/trace_viewer_index.js +15946 -0
- xprof/static/trace_viewer_v2.js +8103 -0
- xprof/static/trace_viewer_v2.wasm +0 -0
- xprof/static/zone.js +3558 -0
- xprof/version.py +18 -0
- xprof-2.22.2.dist-info/METADATA +354 -0
- xprof-2.22.2.dist-info/RECORD +71 -0
- xprof-2.22.2.dist-info/WHEEL +5 -0
- xprof-2.22.2.dist-info/entry_points.txt +5 -0
- xprof-2.22.2.dist-info/top_level.txt +1 -0
xprof/profile_plugin.py
ADDED
|
@@ -0,0 +1,1896 @@
|
|
|
1
|
+
# Copyright 2019 The TensorFlow Authors. All Rights Reserved.
|
|
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
|
+
"""The TensorBoard plugin for performance profiling."""
|
|
16
|
+
|
|
17
|
+
from __future__ import absolute_import
|
|
18
|
+
from __future__ import division
|
|
19
|
+
from __future__ import print_function
|
|
20
|
+
|
|
21
|
+
from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence
|
|
22
|
+
import concurrent.futures
|
|
23
|
+
import gzip
|
|
24
|
+
import json
|
|
25
|
+
import logging
|
|
26
|
+
import os
|
|
27
|
+
import re
|
|
28
|
+
import sys
|
|
29
|
+
import threading
|
|
30
|
+
import time
|
|
31
|
+
from typing import Any, TextIO, TypedDict
|
|
32
|
+
|
|
33
|
+
from etils import epath
|
|
34
|
+
import etils.epath.backend
|
|
35
|
+
import six
|
|
36
|
+
from werkzeug import wrappers
|
|
37
|
+
|
|
38
|
+
from xprof import profile_io
|
|
39
|
+
from xprof import version
|
|
40
|
+
from xprof.convert import raw_to_tool_data as convert
|
|
41
|
+
from xprof.standalone.tensorboard_shim import base_plugin
|
|
42
|
+
from xprof.standalone.tensorboard_shim import plugin_asset_util
|
|
43
|
+
from xprof.convert import _pywrap_profiler_plugin
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
logger = logging.getLogger('tensorboard.plugins.profile')
|
|
47
|
+
logger.setLevel(logging.INFO)
|
|
48
|
+
if not logger.handlers:
|
|
49
|
+
handler = logging.StreamHandler(sys.stderr)
|
|
50
|
+
formatter = logging.Formatter(
|
|
51
|
+
'%(levelname)s %(asctime)s [%(filename)s:%(lineno)d] %(message)s'
|
|
52
|
+
)
|
|
53
|
+
handler.setFormatter(formatter)
|
|
54
|
+
logger.addHandler(handler)
|
|
55
|
+
logger.propagate = False
|
|
56
|
+
|
|
57
|
+
try:
|
|
58
|
+
import tensorflow.compat.v2 as tf # pylint: disable=g-import-not-at-top # pytype: disable=import-error
|
|
59
|
+
|
|
60
|
+
tf.enable_v2_behavior()
|
|
61
|
+
except ImportError:
|
|
62
|
+
logger.info(
|
|
63
|
+
'Disabling some remote capture features as tensorflow is not available'
|
|
64
|
+
)
|
|
65
|
+
tf = None
|
|
66
|
+
|
|
67
|
+
# The prefix of routes provided by this plugin.
|
|
68
|
+
TB_NAME = 'plugins'
|
|
69
|
+
PLUGIN_NAME = 'profile'
|
|
70
|
+
|
|
71
|
+
BASE_ROUTE = '/'
|
|
72
|
+
INDEX_JS_ROUTE = '/index.js'
|
|
73
|
+
INDEX_HTML_ROUTE = '/index.html'
|
|
74
|
+
BUNDLE_JS_ROUTE = '/bundle.js'
|
|
75
|
+
STYLES_CSS_ROUTE = '/styles.css'
|
|
76
|
+
MATERIALICONS_WOFF2_ROUTE = '/materialicons.woff2'
|
|
77
|
+
TRACE_VIEWER_INDEX_HTML_ROUTE = '/trace_viewer_index.html'
|
|
78
|
+
TRACE_VIEWER_INDEX_JS_ROUTE = '/trace_viewer_index.js'
|
|
79
|
+
TRACE_VIEWER_V2_JS_ROUTE = '/trace_viewer_v2.js'
|
|
80
|
+
TRACE_VIEWER_V2_WASM_ROUTE = '/trace_viewer_v2.wasm'
|
|
81
|
+
ZONE_JS_ROUTE = '/zone.js'
|
|
82
|
+
DATA_ROUTE = '/data'
|
|
83
|
+
DATA_CSV_ROUTE = '/data_csv'
|
|
84
|
+
VERSION_ROUTE = '/version'
|
|
85
|
+
RUNS_ROUTE = '/runs'
|
|
86
|
+
RUN_TOOLS_ROUTE = '/run_tools'
|
|
87
|
+
HOSTS_ROUTE = '/hosts'
|
|
88
|
+
HLO_MODULE_LIST_ROUTE = '/module_list'
|
|
89
|
+
CAPTURE_ROUTE = '/capture_profile'
|
|
90
|
+
LOCAL_ROUTE = '/local'
|
|
91
|
+
CONFIG_ROUTE = '/config'
|
|
92
|
+
CACHE_VERSION_FILE = 'cache_version.txt'
|
|
93
|
+
GENERATE_CACHE_ROUTE = '/generate_cache'
|
|
94
|
+
|
|
95
|
+
# Suffixes of "^, #, @" symbols represent different input data formats for the
|
|
96
|
+
# same tool.
|
|
97
|
+
# 1) '^': data generate from XPlane.
|
|
98
|
+
# 2) '#': data is in gzip format.
|
|
99
|
+
# 3) '@': data generate from proto, or tracetable for streaming trace viewer.
|
|
100
|
+
# 4) no suffix: data is in json format, ready to feed to frontend.
|
|
101
|
+
TOOLS = {
|
|
102
|
+
'xplane': 'xplane.pb',
|
|
103
|
+
'hlo_proto': 'hlo_proto.pb',
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
ALL_HOSTS = 'ALL_HOSTS'
|
|
107
|
+
|
|
108
|
+
HostMetadata = TypedDict('HostMetadata', {'hostname': str})
|
|
109
|
+
|
|
110
|
+
_EXTENSION_TO_TOOL = {extension: tool for tool, extension in TOOLS.items()}
|
|
111
|
+
|
|
112
|
+
_FILENAME_RE = re.compile(
|
|
113
|
+
r"""
|
|
114
|
+
(?: # Start optional non-capturing group for the host.
|
|
115
|
+
(.*) # Capture group 1: The host name.
|
|
116
|
+
\. # A literal dot.
|
|
117
|
+
)? # End optional non-capturing group.
|
|
118
|
+
( # Start capture group 2: The tool extension.
|
|
119
|
+
"""
|
|
120
|
+
+ '|'.join(re.escape(v) for v in TOOLS.values())
|
|
121
|
+
+ r"""
|
|
122
|
+
) # End capture group 2.
|
|
123
|
+
""",
|
|
124
|
+
re.VERBOSE,
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
# Tools that can be generated from xplane end with ^.
|
|
129
|
+
XPLANE_TOOLS = [
|
|
130
|
+
'trace_viewer', # non-streaming before TF 2.13
|
|
131
|
+
'trace_viewer@', # streaming since TF 2.14
|
|
132
|
+
'overview_page',
|
|
133
|
+
'input_pipeline_analyzer',
|
|
134
|
+
'framework_op_stats',
|
|
135
|
+
'kernel_stats',
|
|
136
|
+
'memory_profile',
|
|
137
|
+
'pod_viewer',
|
|
138
|
+
'op_profile',
|
|
139
|
+
'hlo_stats',
|
|
140
|
+
'roofline_model',
|
|
141
|
+
'inference_profile',
|
|
142
|
+
'memory_viewer',
|
|
143
|
+
'graph_viewer',
|
|
144
|
+
'megascale_stats',
|
|
145
|
+
'perf_counters',
|
|
146
|
+
'utilization_viewer',
|
|
147
|
+
'smart_suggestion',
|
|
148
|
+
]
|
|
149
|
+
|
|
150
|
+
XPLANE_TOOLS_SET = frozenset(XPLANE_TOOLS)
|
|
151
|
+
DEFAULT_CACHE_TOOLS = ('overview_page', 'trace_viewer@')
|
|
152
|
+
|
|
153
|
+
# XPlane generated tools that support all host mode.
|
|
154
|
+
XPLANE_TOOLS_ALL_HOSTS_SUPPORTED = frozenset([
|
|
155
|
+
'input_pipeline_analyzer',
|
|
156
|
+
'framework_op_stats',
|
|
157
|
+
'kernel_stats',
|
|
158
|
+
'overview_page',
|
|
159
|
+
'pod_viewer',
|
|
160
|
+
'megascale_stats',
|
|
161
|
+
])
|
|
162
|
+
|
|
163
|
+
# XPlane generated tools that only support all host mode.
|
|
164
|
+
XPLANE_TOOLS_ALL_HOSTS_ONLY = frozenset(
|
|
165
|
+
['overview_page', 'pod_viewer', 'smart_suggestion']
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
# Rate limiter constants, the GCS quota defined below
|
|
169
|
+
# https://cloud.google.com/storage/quotas#rate-quotas.
|
|
170
|
+
# currently set to 1000 request per minute.
|
|
171
|
+
# TODO(kcai): The assumption on the average number of subdirs is not
|
|
172
|
+
# always true. If this is not sufficient, we can consider a token-based
|
|
173
|
+
# approach that counts the number of subdirs after calling iterdir.
|
|
174
|
+
MAX_GCS_REQUESTS = 1000
|
|
175
|
+
LIMIT_WINDOW_SECONDS = 60
|
|
176
|
+
AVERAGE_SUBDIR_NUMBER = 10
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def use_xplane(tool: str) -> bool:
|
|
180
|
+
return tool in XPLANE_TOOLS
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
# HLO generated tools.
|
|
184
|
+
HLO_TOOLS = frozenset(['graph_viewer', 'memory_viewer'])
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def use_hlo(tool: str) -> bool:
|
|
188
|
+
return tool in HLO_TOOLS
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def make_filename(host: str, tool: str) -> str:
|
|
192
|
+
"""Returns the name of the file containing data for the given host and tool.
|
|
193
|
+
|
|
194
|
+
Args:
|
|
195
|
+
host: Name of the host that produced the profile data, e.g., 'localhost'.
|
|
196
|
+
tool: Name of the tool, e.g., 'trace_viewer'.
|
|
197
|
+
|
|
198
|
+
Returns:
|
|
199
|
+
The host name concatenated with the tool-specific extension, e.g.,
|
|
200
|
+
'localhost.trace'.
|
|
201
|
+
"""
|
|
202
|
+
filename = str(host) + '.' if host else ''
|
|
203
|
+
if use_hlo(tool):
|
|
204
|
+
tool = 'hlo_proto'
|
|
205
|
+
elif use_xplane(tool):
|
|
206
|
+
tool = 'xplane'
|
|
207
|
+
return filename + TOOLS[tool]
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _parse_filename(filename: str) -> tuple[str | None, str | None]:
|
|
211
|
+
"""Returns the host and tool encoded in a filename in the run directory.
|
|
212
|
+
|
|
213
|
+
Args:
|
|
214
|
+
filename: Name of a file in the run directory. The name might encode a host
|
|
215
|
+
and tool, e.g., 'host.tracetable', 'host.domain.op_profile.json', or just
|
|
216
|
+
a tool, e.g., 'trace', 'tensorflow_stats.pb'.
|
|
217
|
+
|
|
218
|
+
Returns:
|
|
219
|
+
A tuple (host, tool) containing the names of the host and tool, e.g.,
|
|
220
|
+
('localhost', 'trace_viewer'). Either of the tuple's components can be None.
|
|
221
|
+
"""
|
|
222
|
+
m = _FILENAME_RE.fullmatch(filename)
|
|
223
|
+
if m is None:
|
|
224
|
+
return filename, None
|
|
225
|
+
return m.group(1), _EXTENSION_TO_TOOL[m.group(2)]
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _get_hosts(filenames: Sequence[str]) -> set[str]:
|
|
229
|
+
"""Parses a sequence of filenames and returns the set of hosts.
|
|
230
|
+
|
|
231
|
+
Args:
|
|
232
|
+
filenames: A sequence of filenames (just basenames, no directory).
|
|
233
|
+
|
|
234
|
+
Returns:
|
|
235
|
+
A set of host names encoded in the filenames.
|
|
236
|
+
"""
|
|
237
|
+
hosts = set()
|
|
238
|
+
for name in filenames:
|
|
239
|
+
host, _ = _parse_filename(name)
|
|
240
|
+
if host:
|
|
241
|
+
hosts.add(host)
|
|
242
|
+
return hosts
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def _get_tools(filenames: Sequence[str], profile_run_dir: str) -> set[str]:
|
|
246
|
+
"""Parses a sequence of filenames and returns the set of tools.
|
|
247
|
+
|
|
248
|
+
If xplane is present in the repository, add tools that can be generated by
|
|
249
|
+
xplane if we don't have a file for the tool.
|
|
250
|
+
|
|
251
|
+
Args:
|
|
252
|
+
filenames: A sequence of filenames.
|
|
253
|
+
profile_run_dir: The run directory of the profile.
|
|
254
|
+
|
|
255
|
+
Returns:
|
|
256
|
+
A set of tool names encoded in the filenames.
|
|
257
|
+
"""
|
|
258
|
+
tools = set()
|
|
259
|
+
found = set()
|
|
260
|
+
xplane_filenames = []
|
|
261
|
+
for name in filenames:
|
|
262
|
+
_, tool = _parse_filename(name)
|
|
263
|
+
if tool == 'xplane':
|
|
264
|
+
xplane_filenames.append(os.path.join(profile_run_dir, name))
|
|
265
|
+
continue
|
|
266
|
+
elif tool == 'hlo_proto':
|
|
267
|
+
continue
|
|
268
|
+
elif tool:
|
|
269
|
+
tools.add(tool)
|
|
270
|
+
if tool[-1] in ('@'):
|
|
271
|
+
found.add(tool[:-1])
|
|
272
|
+
else:
|
|
273
|
+
found.add(tool)
|
|
274
|
+
# profile_run_dir might be empty, like in cloud AI use case.
|
|
275
|
+
if not profile_run_dir:
|
|
276
|
+
if xplane_filenames:
|
|
277
|
+
for item in XPLANE_TOOLS:
|
|
278
|
+
if item[:-1] not in found:
|
|
279
|
+
tools.add(item)
|
|
280
|
+
else:
|
|
281
|
+
try:
|
|
282
|
+
if xplane_filenames:
|
|
283
|
+
return set(convert.xspace_to_tool_names(xplane_filenames))
|
|
284
|
+
except AttributeError:
|
|
285
|
+
logger.warning('XPlane converters are available after Tensorflow 2.4')
|
|
286
|
+
return tools
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
@wrappers.Request.application
|
|
290
|
+
def version_route(_: wrappers.Request) -> wrappers.Response:
|
|
291
|
+
return respond(version.__version__, 'text/plain')
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def respond(
|
|
295
|
+
body: Any,
|
|
296
|
+
content_type: str,
|
|
297
|
+
code: int = 200,
|
|
298
|
+
content_encoding: tuple[str, str] | None = None,
|
|
299
|
+
extra_headers: Mapping[str, str] | None = None,
|
|
300
|
+
) -> wrappers.Response:
|
|
301
|
+
"""Create a Werkzeug response, handling JSON serialization and CSP.
|
|
302
|
+
|
|
303
|
+
Args:
|
|
304
|
+
body: For JSON responses, a JSON-serializable object; otherwise, a raw
|
|
305
|
+
`bytes` string or Unicode `str` (which will be encoded as UTF-8).
|
|
306
|
+
content_type: Response content-type (`str`); use `application/json` to
|
|
307
|
+
automatically serialize structures.
|
|
308
|
+
code: HTTP status code (`int`).
|
|
309
|
+
content_encoding: Response Content-Encoding header ('str'); e.g. 'gzip'. If
|
|
310
|
+
the content type is not set, The data would be compressed and the content
|
|
311
|
+
encoding would be set to gzip.
|
|
312
|
+
extra_headers: Optional additional headers to add to the response.
|
|
313
|
+
|
|
314
|
+
Returns:
|
|
315
|
+
A `werkzeug.wrappers.Response` object.
|
|
316
|
+
"""
|
|
317
|
+
if content_type == 'application/json' and isinstance(
|
|
318
|
+
body, (dict, list, set, tuple)
|
|
319
|
+
):
|
|
320
|
+
body = json.dumps(body, sort_keys=True)
|
|
321
|
+
if not isinstance(body, bytes):
|
|
322
|
+
body = body.encode('utf-8')
|
|
323
|
+
csp_parts = {
|
|
324
|
+
'default-src': ["'self'"],
|
|
325
|
+
'script-src': [
|
|
326
|
+
"'self'",
|
|
327
|
+
"'unsafe-eval'",
|
|
328
|
+
"'unsafe-inline'",
|
|
329
|
+
'https://www.gstatic.com',
|
|
330
|
+
],
|
|
331
|
+
'object-src': ["'none'"],
|
|
332
|
+
'style-src': [
|
|
333
|
+
"'self'",
|
|
334
|
+
"'unsafe-inline'",
|
|
335
|
+
'https://fonts.googleapis.com',
|
|
336
|
+
'https://www.gstatic.com',
|
|
337
|
+
],
|
|
338
|
+
'font-src': [
|
|
339
|
+
"'self'",
|
|
340
|
+
'https://fonts.googleapis.com',
|
|
341
|
+
'https://fonts.gstatic.com',
|
|
342
|
+
'data:',
|
|
343
|
+
],
|
|
344
|
+
'connect-src': [
|
|
345
|
+
"'self'",
|
|
346
|
+
'data:',
|
|
347
|
+
'www.gstatic.com',
|
|
348
|
+
],
|
|
349
|
+
'img-src': [
|
|
350
|
+
"'self'",
|
|
351
|
+
'blob:',
|
|
352
|
+
'data:',
|
|
353
|
+
],
|
|
354
|
+
'frame-src': [
|
|
355
|
+
"'self'",
|
|
356
|
+
'https://ui.perfetto.dev',
|
|
357
|
+
],
|
|
358
|
+
'script-src-elem': [
|
|
359
|
+
"'self'",
|
|
360
|
+
"'unsafe-inline'",
|
|
361
|
+
# Remember to restrict on integrity when importing from jsdelivr
|
|
362
|
+
# Whitelist this domain to support hlo_graph_dumper html format
|
|
363
|
+
'https://cdn.jsdelivr.net/npm/',
|
|
364
|
+
'https://www.gstatic.com',
|
|
365
|
+
],
|
|
366
|
+
}
|
|
367
|
+
csp = ';'.join((' '.join([k] + v) for (k, v) in csp_parts.items()))
|
|
368
|
+
headers = [
|
|
369
|
+
('Content-Security-Policy', csp),
|
|
370
|
+
('X-Content-Type-Options', 'nosniff'),
|
|
371
|
+
]
|
|
372
|
+
if content_encoding:
|
|
373
|
+
headers.append(('Content-Encoding', content_encoding))
|
|
374
|
+
else:
|
|
375
|
+
headers.append(('Content-Encoding', 'gzip'))
|
|
376
|
+
body = gzip.compress(body)
|
|
377
|
+
|
|
378
|
+
if extra_headers is not None:
|
|
379
|
+
headers.extend(extra_headers.items())
|
|
380
|
+
|
|
381
|
+
return wrappers.Response(
|
|
382
|
+
body, content_type=content_type, status=code, headers=headers
|
|
383
|
+
)
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
def _plugin_assets(
|
|
387
|
+
session_dir: str, runs: Sequence[str], plugin_name: str
|
|
388
|
+
) -> dict[str, Sequence[str]]:
|
|
389
|
+
result = {}
|
|
390
|
+
for run in runs:
|
|
391
|
+
run_path = _tb_run_directory(session_dir, run)
|
|
392
|
+
assets = plugin_asset_util.ListAssets(run_path, plugin_name)
|
|
393
|
+
result[run] = assets
|
|
394
|
+
return result
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
def _tb_run_directory(session_dir: str, run: str) -> str:
|
|
398
|
+
"""Returns the TensorBoard run directory for a TensorBoard run name.
|
|
399
|
+
|
|
400
|
+
This helper returns the TensorBoard-level run directory (the one that would)
|
|
401
|
+
contain tfevents files) for a given TensorBoard run name (aka the relative
|
|
402
|
+
path from the session_dir root to this directory). For the root run '.'
|
|
403
|
+
this is the bare session_dir path; for all other runs this is the
|
|
404
|
+
session_dir joined with the run name.
|
|
405
|
+
|
|
406
|
+
Args:
|
|
407
|
+
session_dir: the TensorBoard log directory root path
|
|
408
|
+
run: the TensorBoard run name, e.g. '.' or 'train'
|
|
409
|
+
|
|
410
|
+
Returns:
|
|
411
|
+
The TensorBoard run directory path, e.g. my/session_dir or
|
|
412
|
+
my/session_dir/train.
|
|
413
|
+
"""
|
|
414
|
+
return session_dir if run == '.' else os.path.join(session_dir, run)
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
def hosts_from_xplane_filenames(
|
|
418
|
+
filenames: Sequence[str], tool: str
|
|
419
|
+
) -> Sequence[str]:
|
|
420
|
+
"""Converts a sequence of filenames to a list of host names given a tool.
|
|
421
|
+
|
|
422
|
+
Args:
|
|
423
|
+
filenames: A sequence of filenames.
|
|
424
|
+
tool: A string representing the profiling tool.
|
|
425
|
+
|
|
426
|
+
Returns:
|
|
427
|
+
A list of hostnames.
|
|
428
|
+
"""
|
|
429
|
+
hosts = _get_hosts(filenames)
|
|
430
|
+
if len(hosts) > 1:
|
|
431
|
+
if tool in XPLANE_TOOLS_ALL_HOSTS_ONLY:
|
|
432
|
+
hosts = [ALL_HOSTS]
|
|
433
|
+
elif tool in XPLANE_TOOLS_ALL_HOSTS_SUPPORTED:
|
|
434
|
+
hosts.add(ALL_HOSTS)
|
|
435
|
+
return sorted(hosts)
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
def _get_bool_arg(
|
|
439
|
+
args: Mapping[str, Any], arg_name: str, default: bool
|
|
440
|
+
) -> bool:
|
|
441
|
+
"""Gets a boolean argument from a request.
|
|
442
|
+
|
|
443
|
+
Args:
|
|
444
|
+
args: The werkzeug request arguments.
|
|
445
|
+
arg_name: The name of the argument.
|
|
446
|
+
default: The default value if the argument is not present.
|
|
447
|
+
|
|
448
|
+
Returns:
|
|
449
|
+
The boolean value of the argument.
|
|
450
|
+
"""
|
|
451
|
+
arg_str = args.get(arg_name)
|
|
452
|
+
if arg_str is None:
|
|
453
|
+
return default
|
|
454
|
+
return arg_str.lower() == 'true'
|
|
455
|
+
|
|
456
|
+
|
|
457
|
+
def _generate_csv_filename(request: wrappers.Request) -> str:
|
|
458
|
+
"""Generates a sanitized filename for the CSV export."""
|
|
459
|
+
tool = request.args.get('tag', 'data')
|
|
460
|
+
run = request.args.get('run', '')
|
|
461
|
+
host = request.args.get('host', '')
|
|
462
|
+
|
|
463
|
+
safe_tool = re.sub(r'[^a-zA-Z0-9_\-]', '_', tool)
|
|
464
|
+
safe_run = re.sub(r'[^a-zA-Z0-9_\-]', '_', run)
|
|
465
|
+
|
|
466
|
+
host_suffix = host.split('-')[-1] if host else ''
|
|
467
|
+
safe_host_suffix = re.sub(r'[^a-zA-Z0-9_\-]', '_', host_suffix)
|
|
468
|
+
|
|
469
|
+
filename_parts = (p for p in [safe_tool, safe_run, safe_host_suffix] if p)
|
|
470
|
+
return '_'.join(filename_parts) + '.csv'
|
|
471
|
+
|
|
472
|
+
|
|
473
|
+
class ToolsCache:
|
|
474
|
+
"""A cache for tool lists based on file content hashes or mtimes.
|
|
475
|
+
|
|
476
|
+
Attributes:
|
|
477
|
+
CACHE_FILE_NAME: The name of the cache file.
|
|
478
|
+
CACHE_VERSION: The version of the cache format.
|
|
479
|
+
"""
|
|
480
|
+
|
|
481
|
+
CACHE_FILE_NAME = '.cached_tools.json'
|
|
482
|
+
CACHE_VERSION = 1
|
|
483
|
+
|
|
484
|
+
def __init__(
|
|
485
|
+
self, profile_run_dir: epath.Path, fs: profile_io.ProfileFileSystem
|
|
486
|
+
):
|
|
487
|
+
"""Initializes the ToolsCache.
|
|
488
|
+
|
|
489
|
+
Args:
|
|
490
|
+
profile_run_dir: The directory containing the profile run data.
|
|
491
|
+
fs: The file system object to use for file operations.
|
|
492
|
+
"""
|
|
493
|
+
self._profile_run_dir = profile_run_dir
|
|
494
|
+
self._cache_file = self._profile_run_dir / self.CACHE_FILE_NAME
|
|
495
|
+
self._fs = fs
|
|
496
|
+
logger.info('ToolsCache initialized for %s', self._cache_file)
|
|
497
|
+
|
|
498
|
+
def load(self) -> list[str] | None:
|
|
499
|
+
"""Loads the cached list of tools if the cache is valid.
|
|
500
|
+
|
|
501
|
+
The cache is valid if the cache file exists, the version matches, and
|
|
502
|
+
the file states (hashes/mtimes) of the XPlane files have not changed.
|
|
503
|
+
|
|
504
|
+
Returns:
|
|
505
|
+
A list of tool names if the cache is valid, otherwise None.
|
|
506
|
+
"""
|
|
507
|
+
cached_data = self._fs.read_json(str(self._cache_file))
|
|
508
|
+
if cached_data is None:
|
|
509
|
+
return None
|
|
510
|
+
|
|
511
|
+
if cached_data.get('version') != self.CACHE_VERSION:
|
|
512
|
+
logger.info(
|
|
513
|
+
'ToolsCache invalid: version mismatch, expected %s, got %s.'
|
|
514
|
+
' Invalidating %s',
|
|
515
|
+
self.CACHE_VERSION,
|
|
516
|
+
cached_data.get('version'),
|
|
517
|
+
self._cache_file,
|
|
518
|
+
)
|
|
519
|
+
self.invalidate()
|
|
520
|
+
return None
|
|
521
|
+
|
|
522
|
+
current_files = self._fs.get_xplane_file_states(str(self._profile_run_dir))
|
|
523
|
+
if current_files is None:
|
|
524
|
+
logger.info(
|
|
525
|
+
'ToolsCache invalid: could not determine current file states.'
|
|
526
|
+
' Invalidating %s',
|
|
527
|
+
self._cache_file,
|
|
528
|
+
)
|
|
529
|
+
self.invalidate()
|
|
530
|
+
return None
|
|
531
|
+
|
|
532
|
+
if cached_data.get('files') != current_files:
|
|
533
|
+
logger.info(
|
|
534
|
+
'ToolsCache invalid: file states differ. Invalidating %s',
|
|
535
|
+
self._cache_file,
|
|
536
|
+
)
|
|
537
|
+
self.invalidate()
|
|
538
|
+
return None
|
|
539
|
+
|
|
540
|
+
logger.info('ToolsCache hit: %s', self._cache_file)
|
|
541
|
+
return cached_data.get('tools')
|
|
542
|
+
|
|
543
|
+
def save(self, tools: Sequence[str]) -> None:
|
|
544
|
+
"""Saves the list of tools and the current file states to the cache file.
|
|
545
|
+
|
|
546
|
+
Args:
|
|
547
|
+
tools: The list of tool names to cache.
|
|
548
|
+
"""
|
|
549
|
+
current_files_for_cache = self._fs.get_xplane_file_states(
|
|
550
|
+
str(self._profile_run_dir)
|
|
551
|
+
)
|
|
552
|
+
if current_files_for_cache is None:
|
|
553
|
+
logger.warning(
|
|
554
|
+
'ToolsCache not saved: could not get file states %s', self._cache_file
|
|
555
|
+
)
|
|
556
|
+
return
|
|
557
|
+
|
|
558
|
+
new_cache_data = {
|
|
559
|
+
'version': self.CACHE_VERSION,
|
|
560
|
+
'files': current_files_for_cache,
|
|
561
|
+
'tools': tools,
|
|
562
|
+
}
|
|
563
|
+
self._fs.write_json(str(self._cache_file), new_cache_data)
|
|
564
|
+
|
|
565
|
+
def invalidate(self) -> None:
|
|
566
|
+
"""Deletes the cache file, forcing regeneration on the next load."""
|
|
567
|
+
self._fs.delete_file(str(self._cache_file))
|
|
568
|
+
|
|
569
|
+
|
|
570
|
+
class _TfProfiler:
|
|
571
|
+
"""A helper class to encapsulate all TensorFlow-dependent profiler logic."""
|
|
572
|
+
|
|
573
|
+
def __init__(self, tf_module):
|
|
574
|
+
if not tf_module:
|
|
575
|
+
raise ImportError('TensorFlow module is not available.')
|
|
576
|
+
self.tf = tf_module
|
|
577
|
+
|
|
578
|
+
def _get_worker_list(self, cluster_resolver) -> str:
|
|
579
|
+
"""Parses TPU workers list from the cluster resolver."""
|
|
580
|
+
cluster_spec = cluster_resolver.cluster_spec()
|
|
581
|
+
task_indices = cluster_spec.task_indices('worker')
|
|
582
|
+
worker_list = [
|
|
583
|
+
cluster_spec.task_address('worker', i).replace(':8470', ':8466')
|
|
584
|
+
for i in task_indices
|
|
585
|
+
]
|
|
586
|
+
return ','.join(worker_list)
|
|
587
|
+
|
|
588
|
+
def resolve_tpu_name(
|
|
589
|
+
self, tpu_name: str, worker_list: str
|
|
590
|
+
) -> tuple[str, str, str]:
|
|
591
|
+
"""Resolves a TPU name to its master IP, service address, and worker list.
|
|
592
|
+
|
|
593
|
+
Args:
|
|
594
|
+
tpu_name: The name of the TPU to resolve.
|
|
595
|
+
worker_list: A comma-separated list of worker addresses.
|
|
596
|
+
|
|
597
|
+
Returns:
|
|
598
|
+
A tuple containing (service_addr, worker_list, master_ip).
|
|
599
|
+
"""
|
|
600
|
+
try:
|
|
601
|
+
resolver = self.tf.distribute.cluster_resolver.TPUClusterResolver(
|
|
602
|
+
tpu_name
|
|
603
|
+
)
|
|
604
|
+
master_grpc_addr = resolver.get_master()
|
|
605
|
+
except RuntimeError as err:
|
|
606
|
+
# Propagate error to be handled by the caller.
|
|
607
|
+
raise RuntimeError(
|
|
608
|
+
f'Error initializing TPUClusterResolver: {err}'
|
|
609
|
+
) from err
|
|
610
|
+
except (ValueError, TypeError) as e:
|
|
611
|
+
# Handle cases where the TPU name is invalid.
|
|
612
|
+
raise ValueError(f'No TPU found with the name: {tpu_name}') from e
|
|
613
|
+
|
|
614
|
+
if not worker_list:
|
|
615
|
+
worker_list = self._get_worker_list(resolver)
|
|
616
|
+
|
|
617
|
+
# TPU cluster resolver always returns port 8470. Replace it with 8466
|
|
618
|
+
# on which profiler service is running.
|
|
619
|
+
master_ip = master_grpc_addr.replace('grpc://', '').replace(':8470', '')
|
|
620
|
+
service_addr = f'{master_ip}:8466'
|
|
621
|
+
return service_addr, worker_list, master_ip
|
|
622
|
+
|
|
623
|
+
|
|
624
|
+
def _logging_wrapper(
|
|
625
|
+
app: Callable[
|
|
626
|
+
[
|
|
627
|
+
Mapping[str, Any],
|
|
628
|
+
Callable[[str, Sequence[tuple[str, str]], Any | None], Any],
|
|
629
|
+
],
|
|
630
|
+
Iterable[bytes],
|
|
631
|
+
],
|
|
632
|
+
clock: Callable[[], float] = time.time,
|
|
633
|
+
writer: TextIO = sys.stderr,
|
|
634
|
+
) -> Callable[
|
|
635
|
+
[
|
|
636
|
+
Mapping[str, Any],
|
|
637
|
+
Callable[[str, Sequence[tuple[str, str]], Any | None], Any],
|
|
638
|
+
],
|
|
639
|
+
Iterable[bytes],
|
|
640
|
+
]:
|
|
641
|
+
"""Wraps a WSGI application to log request timing in GKE-friendly JSON format.
|
|
642
|
+
|
|
643
|
+
Args:
|
|
644
|
+
app: The WSGI application to wrap.
|
|
645
|
+
clock: A function that returns the current time. Defaults to `time.time`.
|
|
646
|
+
writer: A file-like object to write logs to. Defaults to `sys.stderr`.
|
|
647
|
+
|
|
648
|
+
Returns:
|
|
649
|
+
A new WSGI application that logs request timing.
|
|
650
|
+
"""
|
|
651
|
+
|
|
652
|
+
def wrapper(
|
|
653
|
+
environ: Mapping[str, Any],
|
|
654
|
+
start_response: Callable[
|
|
655
|
+
[str, Sequence[tuple[str, str]], Any | None], Any
|
|
656
|
+
],
|
|
657
|
+
) -> Iterable[bytes]:
|
|
658
|
+
start_time = clock()
|
|
659
|
+
request_method = environ.get('REQUEST_METHOD', '')
|
|
660
|
+
# Reconstruct the URL as best as possible from WSGI environ.
|
|
661
|
+
url_path = environ.get('SCRIPT_NAME', '') + environ.get('PATH_INFO', '')
|
|
662
|
+
query_string = environ.get('QUERY_STRING')
|
|
663
|
+
request_url = f'{url_path}?{query_string}' if query_string else url_path
|
|
664
|
+
|
|
665
|
+
# container for status code captured from start_response
|
|
666
|
+
status_info = {'code': 200} # Default to 200 if not captured (unlikely)
|
|
667
|
+
|
|
668
|
+
def custom_start_response(
|
|
669
|
+
status: str,
|
|
670
|
+
headers: Sequence[tuple[str, str]],
|
|
671
|
+
exc_info: Any | None = None,
|
|
672
|
+
) -> Any:
|
|
673
|
+
try:
|
|
674
|
+
status_code_str, *_ = status.split(' ', 1)
|
|
675
|
+
status_info['code'] = int(status_code_str)
|
|
676
|
+
except (ValueError, IndexError):
|
|
677
|
+
logger.warning(
|
|
678
|
+
'Failed to parse status code from %r', status, exc_info=True
|
|
679
|
+
)
|
|
680
|
+
return start_response(status, headers, exc_info)
|
|
681
|
+
|
|
682
|
+
response = app(environ, custom_start_response)
|
|
683
|
+
try:
|
|
684
|
+
yield from response
|
|
685
|
+
finally:
|
|
686
|
+
duration = clock() - start_time
|
|
687
|
+
log_entry = {
|
|
688
|
+
'httpRequest': {
|
|
689
|
+
'requestMethod': request_method,
|
|
690
|
+
'requestUrl': request_url,
|
|
691
|
+
'status': status_info['code'],
|
|
692
|
+
'latency': f'{duration:.9f}s',
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
# Write raw JSON to stderr for GKE/Cloud Logging to pick up as structured
|
|
696
|
+
# payload. We use sys.stderr instead of the logging module because the
|
|
697
|
+
# latter would add text prefixes (timestamp, level, etc.) that break the
|
|
698
|
+
# JSON parsing required for the "httpRequest" field to be recognized by
|
|
699
|
+
# GKE.
|
|
700
|
+
writer.write(json.dumps(log_entry) + '\n')
|
|
701
|
+
writer.flush()
|
|
702
|
+
if hasattr(response, 'close'):
|
|
703
|
+
response.close()
|
|
704
|
+
|
|
705
|
+
return wrapper
|
|
706
|
+
|
|
707
|
+
|
|
708
|
+
class ProfilePlugin(base_plugin.TBPlugin):
|
|
709
|
+
"""Profile Plugin for TensorBoard."""
|
|
710
|
+
|
|
711
|
+
plugin_name = PLUGIN_NAME
|
|
712
|
+
|
|
713
|
+
def __init__(
|
|
714
|
+
self,
|
|
715
|
+
context,
|
|
716
|
+
*,
|
|
717
|
+
epath_module: Any = epath,
|
|
718
|
+
xspace_to_tool_data_fn: Callable[
|
|
719
|
+
[Sequence[epath.Path], str, dict[str, Any]],
|
|
720
|
+
tuple[bytes | str | None, str],
|
|
721
|
+
] = convert.xspace_to_tool_data,
|
|
722
|
+
version_module: Any = version,
|
|
723
|
+
cache_generation_executor: concurrent.futures.Executor | None = None,
|
|
724
|
+
):
|
|
725
|
+
"""Constructs a profiler plugin for TensorBoard.
|
|
726
|
+
|
|
727
|
+
This plugin adds handlers for performance-related frontends.
|
|
728
|
+
Args:
|
|
729
|
+
context: A base_plugin.TBContext instance.
|
|
730
|
+
epath_module: The epath module to use, can be injected for testing.
|
|
731
|
+
xspace_to_tool_data_fn: Function to convert xspace to tool data.
|
|
732
|
+
version_module: The version module to use, can be injected for testing.
|
|
733
|
+
cache_generation_executor: A `concurrent.futures.Executor` instance for
|
|
734
|
+
async cache generation. If None, a default executor is created.
|
|
735
|
+
"""
|
|
736
|
+
self.logdir = context.logdir
|
|
737
|
+
self.data_provider = context.data_provider
|
|
738
|
+
self.master_tpu_unsecure_channel = context.flags.master_tpu_unsecure_channel
|
|
739
|
+
self.hide_capture_profile_button = getattr(
|
|
740
|
+
context, 'hide_capture_profile_button', False
|
|
741
|
+
)
|
|
742
|
+
self.src_prefix = getattr(context, 'src_prefix', '')
|
|
743
|
+
self._epath = epath_module
|
|
744
|
+
self._xspace_to_tool_data = xspace_to_tool_data_fn
|
|
745
|
+
self._version = version_module
|
|
746
|
+
|
|
747
|
+
# Whether the plugin is active. This is an expensive computation, so we
|
|
748
|
+
# compute this asynchronously and cache positive results indefinitely.
|
|
749
|
+
self._is_active = False
|
|
750
|
+
# Lock to ensure at most one thread computes _is_active at a time.
|
|
751
|
+
self._is_active_lock = threading.Lock()
|
|
752
|
+
# Lock to protect access to _run_to_profile_run_dir.
|
|
753
|
+
self._run_dir_cache_lock = threading.Lock()
|
|
754
|
+
# Cache to map profile run name to corresponding tensorboard dir name
|
|
755
|
+
self._run_to_profile_run_dir = {}
|
|
756
|
+
self._tf_profiler = _TfProfiler(tf) if tf else None
|
|
757
|
+
# Limit to 1 worker to prevent potential Out-of-Memory (OOM) errors.
|
|
758
|
+
# Cache generation, especially for tools like trace viewer, can be
|
|
759
|
+
# memory-intensive when processing large XPlane files. Running multiple
|
|
760
|
+
# cache generation tasks in parallel increases the risk of excessive
|
|
761
|
+
# memory consumption.
|
|
762
|
+
self._cache_generation_pool = cache_generation_executor or (
|
|
763
|
+
concurrent.futures.ThreadPoolExecutor(
|
|
764
|
+
max_workers=1, thread_name_prefix='XprofCacheGen'
|
|
765
|
+
)
|
|
766
|
+
)
|
|
767
|
+
|
|
768
|
+
def _get_xplane_basenames(self, path_str: str) -> Sequence[str]:
|
|
769
|
+
"""Returns a list of .xplane.pb base filenames in the given path."""
|
|
770
|
+
fs = profile_io.get_file_system(path_str, self._epath)
|
|
771
|
+
return fs.get_xplane_basenames(path_str)
|
|
772
|
+
|
|
773
|
+
def _dir_has_xplane_files(self, path_str: str) -> bool:
|
|
774
|
+
"""Checks if the directory contains any .xplane.pb files."""
|
|
775
|
+
fs = profile_io.get_file_system(path_str, self._epath)
|
|
776
|
+
return fs.dir_has_xplane_files(path_str)
|
|
777
|
+
|
|
778
|
+
def _get_all_basenames(self, path_str: str) -> Sequence[str]:
|
|
779
|
+
"""Returns a list of all base filenames in the given path."""
|
|
780
|
+
fs = profile_io.get_file_system(path_str, self._epath)
|
|
781
|
+
return fs.get_all_basenames(path_str)
|
|
782
|
+
|
|
783
|
+
def is_active(self) -> bool:
|
|
784
|
+
"""Whether this plugin is active and has any profile data to show.
|
|
785
|
+
|
|
786
|
+
Returns:
|
|
787
|
+
Whether any run has profile data.
|
|
788
|
+
"""
|
|
789
|
+
if not self._is_active:
|
|
790
|
+
self._is_active = any(self.generate_runs())
|
|
791
|
+
return self._is_active
|
|
792
|
+
|
|
793
|
+
def _does_tool_support_multi_hosts_processing(self, tool: str) -> bool:
|
|
794
|
+
"""Returns true if the tool supports multi-hosts processing."""
|
|
795
|
+
return tool == 'trace_viewer@' or tool == 'trace_viewer'
|
|
796
|
+
|
|
797
|
+
def get_plugin_apps(
|
|
798
|
+
self,
|
|
799
|
+
) -> dict[str, Callable[[wrappers.Request], wrappers.Response]]:
|
|
800
|
+
return {
|
|
801
|
+
route: _logging_wrapper(app)
|
|
802
|
+
for route, app in {
|
|
803
|
+
BASE_ROUTE: self.default_handler,
|
|
804
|
+
INDEX_JS_ROUTE: self.static_file_route,
|
|
805
|
+
INDEX_HTML_ROUTE: self.static_file_route,
|
|
806
|
+
BUNDLE_JS_ROUTE: self.static_file_route,
|
|
807
|
+
STYLES_CSS_ROUTE: self.static_file_route,
|
|
808
|
+
MATERIALICONS_WOFF2_ROUTE: self.static_file_route,
|
|
809
|
+
TRACE_VIEWER_INDEX_HTML_ROUTE: self.static_file_route,
|
|
810
|
+
TRACE_VIEWER_INDEX_JS_ROUTE: self.static_file_route,
|
|
811
|
+
TRACE_VIEWER_V2_JS_ROUTE: self.static_file_route,
|
|
812
|
+
TRACE_VIEWER_V2_WASM_ROUTE: self.static_file_route,
|
|
813
|
+
ZONE_JS_ROUTE: self.static_file_route,
|
|
814
|
+
RUNS_ROUTE: self.runs_route,
|
|
815
|
+
RUN_TOOLS_ROUTE: self.run_tools_route,
|
|
816
|
+
HOSTS_ROUTE: self.hosts_route,
|
|
817
|
+
DATA_ROUTE: self.data_route,
|
|
818
|
+
DATA_CSV_ROUTE: self.data_csv_route,
|
|
819
|
+
VERSION_ROUTE: version_route,
|
|
820
|
+
HLO_MODULE_LIST_ROUTE: self.hlo_module_list_route,
|
|
821
|
+
CAPTURE_ROUTE: self.capture_route,
|
|
822
|
+
LOCAL_ROUTE: self.default_handler,
|
|
823
|
+
CONFIG_ROUTE: self.config_route,
|
|
824
|
+
GENERATE_CACHE_ROUTE: self.generate_cache_route,
|
|
825
|
+
}.items()
|
|
826
|
+
} # pytype: disable=bad-return-type
|
|
827
|
+
|
|
828
|
+
# pytype: disable=wrong-arg-types
|
|
829
|
+
@wrappers.Request.application
|
|
830
|
+
def default_handler(self, _: wrappers.Request) -> wrappers.Response:
|
|
831
|
+
contents = self._read_static_file_impl('index.html')
|
|
832
|
+
return respond(contents, 'text/html')
|
|
833
|
+
|
|
834
|
+
# pytype: disable=wrong-arg-types
|
|
835
|
+
@wrappers.Request.application
|
|
836
|
+
def config_route(self, _: wrappers.Request) -> wrappers.Response:
|
|
837
|
+
# pytype: enable=wrong-arg-types
|
|
838
|
+
"""Returns UI configuration details."""
|
|
839
|
+
config_data = {
|
|
840
|
+
'hideCaptureProfileButton': self.hide_capture_profile_button,
|
|
841
|
+
'srcPathPrefix': self.src_prefix,
|
|
842
|
+
}
|
|
843
|
+
logger.info('config_route: %s', config_data)
|
|
844
|
+
return respond(config_data, 'application/json')
|
|
845
|
+
|
|
846
|
+
def frontend_metadata(self):
|
|
847
|
+
return base_plugin.FrontendMetadata(es_module_path='/index.js')
|
|
848
|
+
|
|
849
|
+
def _read_static_file_impl(self, filename: str) -> bytes:
|
|
850
|
+
"""Reads contents from a filename.
|
|
851
|
+
|
|
852
|
+
Args:
|
|
853
|
+
filename (str): Name of the file.
|
|
854
|
+
|
|
855
|
+
Returns:
|
|
856
|
+
Contents of the file.
|
|
857
|
+
Raises:
|
|
858
|
+
IOError: File could not be read or found.
|
|
859
|
+
"""
|
|
860
|
+
filepath = os.path.join(os.path.dirname(__file__), 'static', filename)
|
|
861
|
+
|
|
862
|
+
try:
|
|
863
|
+
with open(filepath, 'rb') as infile:
|
|
864
|
+
contents = infile.read()
|
|
865
|
+
except IOError as io_error:
|
|
866
|
+
raise io_error
|
|
867
|
+
return contents
|
|
868
|
+
|
|
869
|
+
# pytype: disable=wrong-arg-types
|
|
870
|
+
@wrappers.Request.application
|
|
871
|
+
def static_file_route(self, request: wrappers.Request) -> wrappers.Response:
|
|
872
|
+
"""Handles static files."""
|
|
873
|
+
# pytype: enable=wrong-arg-types
|
|
874
|
+
filename = os.path.basename(request.path)
|
|
875
|
+
extension = os.path.splitext(filename)[1]
|
|
876
|
+
if extension == '.html':
|
|
877
|
+
mimetype = 'text/html'
|
|
878
|
+
elif extension == '.css':
|
|
879
|
+
mimetype = 'text/css'
|
|
880
|
+
elif extension == '.js':
|
|
881
|
+
mimetype = 'application/javascript'
|
|
882
|
+
elif extension == '.wasm':
|
|
883
|
+
mimetype = 'application/wasm'
|
|
884
|
+
else:
|
|
885
|
+
mimetype = 'application/octet-stream'
|
|
886
|
+
try:
|
|
887
|
+
contents = self._read_static_file_impl(filename)
|
|
888
|
+
except IOError:
|
|
889
|
+
return respond('Fail to read the files.', 'text/plain', code=404)
|
|
890
|
+
return respond(contents, mimetype)
|
|
891
|
+
|
|
892
|
+
# pytype: disable=wrong-arg-types
|
|
893
|
+
@wrappers.Request.application
|
|
894
|
+
def runs_route(self, request: wrappers.Request) -> wrappers.Response:
|
|
895
|
+
# pytype: enable=wrong-arg-types
|
|
896
|
+
runs = self.runs_imp(request)
|
|
897
|
+
return respond(runs, 'application/json')
|
|
898
|
+
|
|
899
|
+
def _session_dir_by_run_name_from_request(
|
|
900
|
+
self, request: wrappers.Request | None = None
|
|
901
|
+
) -> Mapping[str, str] | None:
|
|
902
|
+
"""Returns a map of run names to session directories from the request.
|
|
903
|
+
|
|
904
|
+
Args:
|
|
905
|
+
request: Optional; werkzeug request used for grabbing session_path and
|
|
906
|
+
run_path arguments.
|
|
907
|
+
"""
|
|
908
|
+
session_path_arg = request.args.get('session_path') if request else None
|
|
909
|
+
run_path_arg = (
|
|
910
|
+
request.args.get('run_path')
|
|
911
|
+
if request and not session_path_arg
|
|
912
|
+
else None
|
|
913
|
+
)
|
|
914
|
+
session_dir_by_run_name = None
|
|
915
|
+
if session_path_arg:
|
|
916
|
+
session_dir_by_run_name = {}
|
|
917
|
+
if self._dir_has_xplane_files(session_path_arg):
|
|
918
|
+
run_name = self._epath.Path(session_path_arg).name
|
|
919
|
+
session_dir_by_run_name[run_name] = session_path_arg
|
|
920
|
+
elif run_path_arg:
|
|
921
|
+
fs = profile_io.get_file_system(run_path_arg, self._epath)
|
|
922
|
+
session_dir_by_run_name = fs.get_session_paths(run_path_arg)
|
|
923
|
+
return session_dir_by_run_name
|
|
924
|
+
|
|
925
|
+
def _run_dir(
|
|
926
|
+
self, run: str, request: wrappers.Request | None = None
|
|
927
|
+
) -> str | None:
|
|
928
|
+
"""Helper that maps a frontend run name to a profile "run" directory.
|
|
929
|
+
|
|
930
|
+
The frontend run name consists of the TensorBoard run name (aka the relative
|
|
931
|
+
path from the logdir root to the directory containing the data) path-joined
|
|
932
|
+
to the Profile plugin's "run" concept (which is a subdirectory of the
|
|
933
|
+
plugins/profile directory representing an individual run of the tool), with
|
|
934
|
+
the special case that TensorBoard run is the logdir root (which is the run
|
|
935
|
+
named '.') then only the Profile plugin "run" name is used, for backwards
|
|
936
|
+
compatibility.
|
|
937
|
+
|
|
938
|
+
Args:
|
|
939
|
+
run: the frontend run name, as described above, e.g. train/run1.
|
|
940
|
+
request: Optional; werkzeug request used for grabbing session_path and
|
|
941
|
+
run_path arguments.
|
|
942
|
+
|
|
943
|
+
Returns:
|
|
944
|
+
The resolved directory path, e.g. /logdir/train/plugins/profile/run1.
|
|
945
|
+
|
|
946
|
+
Raises:
|
|
947
|
+
ValueError: If the run is not found in the run map.
|
|
948
|
+
RuntimeError: If the run directory is not found.
|
|
949
|
+
"""
|
|
950
|
+
session_dir_by_run_name = self._session_dir_by_run_name_from_request(
|
|
951
|
+
request
|
|
952
|
+
)
|
|
953
|
+
if session_dir_by_run_name is not None:
|
|
954
|
+
if run in session_dir_by_run_name:
|
|
955
|
+
return session_dir_by_run_name[run]
|
|
956
|
+
else:
|
|
957
|
+
raise ValueError(
|
|
958
|
+
f'Run {run} not found in run map: {session_dir_by_run_name}'
|
|
959
|
+
)
|
|
960
|
+
|
|
961
|
+
with self._run_dir_cache_lock:
|
|
962
|
+
if run in self._run_to_profile_run_dir:
|
|
963
|
+
return self._run_to_profile_run_dir[run]
|
|
964
|
+
|
|
965
|
+
if not self.logdir:
|
|
966
|
+
raise RuntimeError(
|
|
967
|
+
'No matching run directory for run %s. Logdir is empty.' % run
|
|
968
|
+
)
|
|
969
|
+
tb_run_name, profile_run_name = os.path.split(run.rstrip(os.sep))
|
|
970
|
+
if not tb_run_name:
|
|
971
|
+
tb_run_name = '.'
|
|
972
|
+
tb_run_directory = _tb_run_directory(self.logdir, tb_run_name)
|
|
973
|
+
if not self._epath.Path(tb_run_directory).is_dir():
|
|
974
|
+
raise RuntimeError('No matching run directory for run %s' % run)
|
|
975
|
+
plugin_directory = plugin_asset_util.PluginDirectory(
|
|
976
|
+
tb_run_directory, PLUGIN_NAME
|
|
977
|
+
)
|
|
978
|
+
return os.path.join(plugin_directory, profile_run_name)
|
|
979
|
+
|
|
980
|
+
def runs_imp(self, request: wrappers.Request | None = None) -> list[str]:
|
|
981
|
+
"""Returns a list all runs for the profile plugin.
|
|
982
|
+
|
|
983
|
+
Args:
|
|
984
|
+
request: Optional; werkzeug request used for grabbing ctx and experiment
|
|
985
|
+
id for other host implementations
|
|
986
|
+
"""
|
|
987
|
+
session_dir_by_run_name = self._session_dir_by_run_name_from_request(
|
|
988
|
+
request
|
|
989
|
+
)
|
|
990
|
+
if session_dir_by_run_name is not None:
|
|
991
|
+
runs = session_dir_by_run_name.keys()
|
|
992
|
+
else:
|
|
993
|
+
runs = self.generate_runs()
|
|
994
|
+
return sorted(runs, reverse=True)
|
|
995
|
+
|
|
996
|
+
# pytype: disable=wrong-arg-types
|
|
997
|
+
@wrappers.Request.application
|
|
998
|
+
def run_tools_route(self, request: wrappers.Request) -> wrappers.Response:
|
|
999
|
+
# pytype: enable=wrong-arg-types
|
|
1000
|
+
run = request.args.get('run')
|
|
1001
|
+
run_tools = self.run_tools_imp(run, request)
|
|
1002
|
+
return respond(run_tools, 'application/json')
|
|
1003
|
+
|
|
1004
|
+
def run_tools_imp(
|
|
1005
|
+
self, run, request: wrappers.Request | None = None
|
|
1006
|
+
) -> list[str]:
|
|
1007
|
+
"""Returns a list of tools given a single run.
|
|
1008
|
+
|
|
1009
|
+
Args:
|
|
1010
|
+
run: the frontend run name, item is list returned by runs_imp
|
|
1011
|
+
request: Optional; werkzeug request used for grabbing ctx and experiment
|
|
1012
|
+
id for other host implementations
|
|
1013
|
+
"""
|
|
1014
|
+
run_dir = self._run_dir(run, request)
|
|
1015
|
+
return list(self.generate_tools_of_run(run, run_dir))
|
|
1016
|
+
|
|
1017
|
+
def _run_host_impl(
|
|
1018
|
+
self, run: str, run_dir: str, tool: str
|
|
1019
|
+
) -> list[HostMetadata]:
|
|
1020
|
+
if not run_dir:
|
|
1021
|
+
logger.warning('Cannot find asset directory for: %s', run)
|
|
1022
|
+
return []
|
|
1023
|
+
return [
|
|
1024
|
+
{'hostname': host}
|
|
1025
|
+
for host in hosts_from_xplane_filenames(
|
|
1026
|
+
self._get_xplane_basenames(run_dir), tool
|
|
1027
|
+
)
|
|
1028
|
+
]
|
|
1029
|
+
|
|
1030
|
+
def host_impl(
|
|
1031
|
+
self, run: str, tool: str, request: wrappers.Request | None = None
|
|
1032
|
+
) -> list[HostMetadata]:
|
|
1033
|
+
"""Returns hosts metadata for the run and tool in log directory.
|
|
1034
|
+
|
|
1035
|
+
In the plugin log directory, each directory contains profile data for a
|
|
1036
|
+
single run (identified by the directory name), and files in the run
|
|
1037
|
+
directory contains data for different tools and hosts. The file that
|
|
1038
|
+
contains profile for a specific tool "x" will have extension TOOLS["x"].
|
|
1039
|
+
|
|
1040
|
+
Example:
|
|
1041
|
+
log/
|
|
1042
|
+
run1/
|
|
1043
|
+
plugins/
|
|
1044
|
+
profile/
|
|
1045
|
+
host1.trace
|
|
1046
|
+
host2.trace
|
|
1047
|
+
module1.hlo_proto.pb
|
|
1048
|
+
module2.hlo_proto.pb
|
|
1049
|
+
run2/
|
|
1050
|
+
plugins/
|
|
1051
|
+
profile/
|
|
1052
|
+
host1.trace
|
|
1053
|
+
host2.trace
|
|
1054
|
+
|
|
1055
|
+
Args:
|
|
1056
|
+
run: the frontend run name, e.g., 'run1' or 'run2' for the example above.
|
|
1057
|
+
tool: the requested tool, e.g., 'trace_viewer' for the example above.
|
|
1058
|
+
request: Optional; werkzeug request used for grabbing ctx and experiment
|
|
1059
|
+
id for other host implementations
|
|
1060
|
+
|
|
1061
|
+
Returns:
|
|
1062
|
+
A list of host names, e.g.:
|
|
1063
|
+
host_impl(run1, trace_viewer) --> [{"hostname": "host1"}, {"hostname":
|
|
1064
|
+
"host2"}]
|
|
1065
|
+
host_impl(run1, memory_viewer) --> [{"hostname": "module1"},
|
|
1066
|
+
{"hostname":
|
|
1067
|
+
"module2"}]
|
|
1068
|
+
"""
|
|
1069
|
+
run_dir = self._run_dir(run, request)
|
|
1070
|
+
return self._run_host_impl(run, run_dir, tool)
|
|
1071
|
+
|
|
1072
|
+
# pytype: disable=wrong-arg-types
|
|
1073
|
+
@wrappers.Request.application
|
|
1074
|
+
def hosts_route(self, request: wrappers.Request) -> wrappers.Response:
|
|
1075
|
+
# pytype: enable=wrong-arg-types
|
|
1076
|
+
run = request.args.get('run')
|
|
1077
|
+
tool = request.args.get('tag')
|
|
1078
|
+
hosts = self.host_impl(run, tool, request)
|
|
1079
|
+
return respond(hosts, 'application/json')
|
|
1080
|
+
|
|
1081
|
+
# pytype: disable=wrong-arg-types
|
|
1082
|
+
@wrappers.Request.application
|
|
1083
|
+
def hlo_module_list_route(
|
|
1084
|
+
self, request: wrappers.Request
|
|
1085
|
+
) -> wrappers.Response:
|
|
1086
|
+
module_names_str = self.hlo_module_list_impl(request)
|
|
1087
|
+
return respond(module_names_str, 'text/plain')
|
|
1088
|
+
|
|
1089
|
+
def _get_valid_hosts(
|
|
1090
|
+
self, run_dir: str, run: str, tool: str, hosts_param: str, host: str
|
|
1091
|
+
) -> tuple[Sequence[str], Sequence[epath.Path]]:
|
|
1092
|
+
"""Retrieves and validates the hosts and asset paths for a run and tool.
|
|
1093
|
+
|
|
1094
|
+
Args:
|
|
1095
|
+
run_dir: The run directory.
|
|
1096
|
+
run: The frontend run name.
|
|
1097
|
+
tool: The requested tool.
|
|
1098
|
+
hosts_param: Comma-separated list of selected hosts.
|
|
1099
|
+
host: The single host parameter.
|
|
1100
|
+
|
|
1101
|
+
Returns:
|
|
1102
|
+
A tuple containing (selected_hosts, asset_paths).
|
|
1103
|
+
|
|
1104
|
+
Raises:
|
|
1105
|
+
FileNotFoundError: If a required xplane file for the specified host(s)
|
|
1106
|
+
is not found.
|
|
1107
|
+
IOError: If there is an error reading asset directories.
|
|
1108
|
+
"""
|
|
1109
|
+
asset_paths = []
|
|
1110
|
+
selected_hosts = []
|
|
1111
|
+
all_xplane_files = {} # Map host to path
|
|
1112
|
+
|
|
1113
|
+
# Find all available xplane files for the run and map them by host.
|
|
1114
|
+
try:
|
|
1115
|
+
xplane_basenames = self._get_xplane_basenames(run_dir)
|
|
1116
|
+
for basename in xplane_basenames:
|
|
1117
|
+
host_name, _ = _parse_filename(basename)
|
|
1118
|
+
if host_name:
|
|
1119
|
+
all_xplane_files[host_name] = self._epath.Path(
|
|
1120
|
+
os.path.join(run_dir, basename)
|
|
1121
|
+
)
|
|
1122
|
+
except OSError as e:
|
|
1123
|
+
logger.warning('Cannot read asset directory: %s, OpError %r', run_dir, e)
|
|
1124
|
+
raise IOError(
|
|
1125
|
+
'Cannot read asset directory: %s, OpError %r' % (run_dir, e)
|
|
1126
|
+
) from e
|
|
1127
|
+
if not all_xplane_files:
|
|
1128
|
+
logger.warning('no xplane files found for run: %s, tool: %s', run, tool)
|
|
1129
|
+
raise FileNotFoundError(
|
|
1130
|
+
'No xplane file found for run: %s, tool: %s' % (run, tool)
|
|
1131
|
+
)
|
|
1132
|
+
|
|
1133
|
+
if hosts_param and self._does_tool_support_multi_hosts_processing(tool):
|
|
1134
|
+
selected_hosts = hosts_param.split(',')
|
|
1135
|
+
for selected_host in selected_hosts:
|
|
1136
|
+
if selected_host in all_xplane_files:
|
|
1137
|
+
asset_paths.append(all_xplane_files[selected_host])
|
|
1138
|
+
else:
|
|
1139
|
+
raise FileNotFoundError(
|
|
1140
|
+
'No xplane file found for host: %s in run: %s'
|
|
1141
|
+
% (selected_host, run)
|
|
1142
|
+
)
|
|
1143
|
+
elif host == ALL_HOSTS:
|
|
1144
|
+
asset_paths = list(all_xplane_files.values())
|
|
1145
|
+
selected_hosts = list(all_xplane_files.keys())
|
|
1146
|
+
elif host and host in all_xplane_files:
|
|
1147
|
+
selected_hosts = [host]
|
|
1148
|
+
asset_paths = [all_xplane_files[host]]
|
|
1149
|
+
elif host:
|
|
1150
|
+
logger.warning('No xplane file found for host: %s in run: %s', host, run)
|
|
1151
|
+
if host not in XPLANE_TOOLS_ALL_HOSTS_ONLY:
|
|
1152
|
+
raise FileNotFoundError(
|
|
1153
|
+
'No xplane file found for host: %s in run: %s' % (host, run)
|
|
1154
|
+
)
|
|
1155
|
+
# for request that does not specify host or hosts param, use all hosts.
|
|
1156
|
+
# would also be no-op for tools that is host-agnostic.
|
|
1157
|
+
elif not host and not hosts_param:
|
|
1158
|
+
selected_hosts = list(all_xplane_files.keys())
|
|
1159
|
+
asset_paths = list(all_xplane_files.values())
|
|
1160
|
+
|
|
1161
|
+
if not asset_paths:
|
|
1162
|
+
logger.warning(
|
|
1163
|
+
'No matching asset paths found for run %s, tool %s, host(s) %s / %s',
|
|
1164
|
+
run,
|
|
1165
|
+
tool,
|
|
1166
|
+
hosts_param,
|
|
1167
|
+
host,
|
|
1168
|
+
)
|
|
1169
|
+
if not host and tool not in XPLANE_TOOLS_ALL_HOSTS_ONLY:
|
|
1170
|
+
raise FileNotFoundError(
|
|
1171
|
+
'Host must be specified for tool %s in run %s' % (tool, run)
|
|
1172
|
+
)
|
|
1173
|
+
|
|
1174
|
+
return selected_hosts, asset_paths
|
|
1175
|
+
|
|
1176
|
+
def _write_cache_version_file(self, run_dir: str) -> None:
|
|
1177
|
+
"""Writes the current version to the cache version file."""
|
|
1178
|
+
try:
|
|
1179
|
+
with self._epath.Path(os.path.join(run_dir, CACHE_VERSION_FILE)).open(
|
|
1180
|
+
'w'
|
|
1181
|
+
) as f:
|
|
1182
|
+
f.write(self._version.__version__)
|
|
1183
|
+
except OSError:
|
|
1184
|
+
logger.warning(
|
|
1185
|
+
'Cannot write cache version file to %s', run_dir, exc_info=True
|
|
1186
|
+
)
|
|
1187
|
+
|
|
1188
|
+
def data_impl(
|
|
1189
|
+
self, request: wrappers.Request
|
|
1190
|
+
) -> tuple[bytes | str | None, str, str | None]:
|
|
1191
|
+
"""Retrieves and processes the tool data for a run and a host.
|
|
1192
|
+
|
|
1193
|
+
Args:
|
|
1194
|
+
request: XMLHttpRequest
|
|
1195
|
+
|
|
1196
|
+
Returns:
|
|
1197
|
+
A string that can be served to the frontend tool or None if tool,
|
|
1198
|
+
run or host is invalid.
|
|
1199
|
+
|
|
1200
|
+
Raises:
|
|
1201
|
+
FileNotFoundError: If a required xplane file for the specified host(s)
|
|
1202
|
+
is not found.
|
|
1203
|
+
IOError: If there is an error reading asset directories.
|
|
1204
|
+
AttributeError: If there is an error during xplane to tool data conversion
|
|
1205
|
+
ValueError: If xplane conversion fails due to invalid data.
|
|
1206
|
+
"""
|
|
1207
|
+
run = request.args.get('run')
|
|
1208
|
+
tool = request.args.get('tag')
|
|
1209
|
+
hosts_param = request.args.get('hosts')
|
|
1210
|
+
host = request.args.get('host')
|
|
1211
|
+
module_name = request.args.get('module_name')
|
|
1212
|
+
program_id = request.args.get('program_id')
|
|
1213
|
+
tqx = request.args.get('tqx')
|
|
1214
|
+
perfetto = _get_bool_arg(request.args, 'perfetto', False)
|
|
1215
|
+
use_saved_result = _get_bool_arg(request.args, 'use_saved_result', True)
|
|
1216
|
+
full_dma = _get_bool_arg(request.args, 'full_dma', False)
|
|
1217
|
+
enable_legacy_dcn = _get_bool_arg(request.args, 'enable_legacy_dcn', False)
|
|
1218
|
+
run_dir = self._run_dir(run, request)
|
|
1219
|
+
|
|
1220
|
+
# Check if the cache file exists and if the cache file version is less
|
|
1221
|
+
# than the current plugin version, clear the cache.
|
|
1222
|
+
try:
|
|
1223
|
+
with self._epath.Path(os.path.join(run_dir, CACHE_VERSION_FILE)).open(
|
|
1224
|
+
'r'
|
|
1225
|
+
) as f:
|
|
1226
|
+
cache_version = f.read().strip()
|
|
1227
|
+
if cache_version < self._version.__version__:
|
|
1228
|
+
use_saved_result = False
|
|
1229
|
+
except FileNotFoundError:
|
|
1230
|
+
logger.info('Cache version file not found, invalidating cache.')
|
|
1231
|
+
use_saved_result = False
|
|
1232
|
+
except OSError:
|
|
1233
|
+
logger.warning('Cannot read cache version file', exc_info=True)
|
|
1234
|
+
use_saved_result = False
|
|
1235
|
+
|
|
1236
|
+
graph_viewer_options = self._get_graph_viewer_options(request)
|
|
1237
|
+
# Host param is used by HLO tools to identify the module.
|
|
1238
|
+
params = {
|
|
1239
|
+
'graph_viewer_options': graph_viewer_options,
|
|
1240
|
+
'tqx': tqx,
|
|
1241
|
+
'perfetto': perfetto,
|
|
1242
|
+
'host': host,
|
|
1243
|
+
'module_name': module_name,
|
|
1244
|
+
'program_id': program_id,
|
|
1245
|
+
'use_saved_result': use_saved_result,
|
|
1246
|
+
}
|
|
1247
|
+
if request.args.get('group_by'):
|
|
1248
|
+
params['group_by'] = request.args.get('group_by')
|
|
1249
|
+
if request.args.get('refresh_suggestion'):
|
|
1250
|
+
params['refresh_suggestion'] = request.args.get('refresh_suggestion')
|
|
1251
|
+
content_type = 'application/json'
|
|
1252
|
+
|
|
1253
|
+
if tool not in TOOLS and not use_xplane(tool):
|
|
1254
|
+
return None, content_type, None
|
|
1255
|
+
if tool == 'memory_viewer' and request.args.get(
|
|
1256
|
+
'view_memory_allocation_timeline'
|
|
1257
|
+
):
|
|
1258
|
+
params['view_memory_allocation_timeline'] = True
|
|
1259
|
+
|
|
1260
|
+
params['memory_space'] = request.args.get('memory_space', '0')
|
|
1261
|
+
|
|
1262
|
+
if tool == 'trace_viewer@':
|
|
1263
|
+
options = {}
|
|
1264
|
+
options['resolution'] = request.args.get('resolution', 8000)
|
|
1265
|
+
options['full_dma'] = full_dma
|
|
1266
|
+
options['enable_legacy_dcn'] = enable_legacy_dcn
|
|
1267
|
+
if request.args.get('start_time_ms') is not None:
|
|
1268
|
+
options['start_time_ms'] = request.args.get('start_time_ms')
|
|
1269
|
+
if request.args.get('end_time_ms') is not None:
|
|
1270
|
+
options['end_time_ms'] = request.args.get('end_time_ms')
|
|
1271
|
+
if request.args.get('event_name') is not None:
|
|
1272
|
+
options['event_name'] = request.args.get('event_name')
|
|
1273
|
+
if request.args.get('duration_ms') is not None:
|
|
1274
|
+
options['duration_ms'] = request.args.get('duration_ms')
|
|
1275
|
+
if request.args.get('unique_id') is not None:
|
|
1276
|
+
options['unique_id'] = request.args.get('unique_id')
|
|
1277
|
+
if request.args.get('search_prefix') is not None:
|
|
1278
|
+
options['search_prefix'] = request.args.get('search_prefix')
|
|
1279
|
+
params['trace_viewer_options'] = options
|
|
1280
|
+
|
|
1281
|
+
_, content_encoding = None, None
|
|
1282
|
+
if use_xplane(tool):
|
|
1283
|
+
selected_hosts, asset_paths = self._get_valid_hosts(
|
|
1284
|
+
run_dir, run, tool, hosts_param, host
|
|
1285
|
+
)
|
|
1286
|
+
if not asset_paths:
|
|
1287
|
+
return None, content_type, None
|
|
1288
|
+
|
|
1289
|
+
params['hosts'] = selected_hosts
|
|
1290
|
+
try:
|
|
1291
|
+
data, content_type = self._xspace_to_tool_data(
|
|
1292
|
+
asset_paths,
|
|
1293
|
+
tool,
|
|
1294
|
+
params,
|
|
1295
|
+
)
|
|
1296
|
+
except AttributeError as e:
|
|
1297
|
+
logger.warning('Error generating analysis results due to %r', e)
|
|
1298
|
+
raise AttributeError(
|
|
1299
|
+
'Error generating analysis results due to %r' % e
|
|
1300
|
+
) from e
|
|
1301
|
+
except ValueError as e:
|
|
1302
|
+
logger.warning('XPlane convert to tool data failed as %r', e)
|
|
1303
|
+
raise
|
|
1304
|
+
except FileNotFoundError as e:
|
|
1305
|
+
logger.warning('XPlane convert to tool data failed as %r', e)
|
|
1306
|
+
raise
|
|
1307
|
+
|
|
1308
|
+
# Write cache version file if use_saved_result is False.
|
|
1309
|
+
if not use_saved_result:
|
|
1310
|
+
self._write_cache_version_file(run_dir)
|
|
1311
|
+
|
|
1312
|
+
return data, content_type, content_encoding
|
|
1313
|
+
|
|
1314
|
+
logger.info('%s does not use xplane', tool)
|
|
1315
|
+
return None, content_type, None
|
|
1316
|
+
|
|
1317
|
+
def hlo_module_list_impl(self, request: wrappers.Request) -> str:
|
|
1318
|
+
"""Returns a string of HLO module names concatenated by comma for the given run."""
|
|
1319
|
+
run = request.args.get('run')
|
|
1320
|
+
run_dir = self._run_dir(run, request)
|
|
1321
|
+
if not run_dir:
|
|
1322
|
+
logger.warning('Cannot find asset directory for: %s', run)
|
|
1323
|
+
return ''
|
|
1324
|
+
try:
|
|
1325
|
+
all_basenames = self._get_all_basenames(run_dir)
|
|
1326
|
+
module_list = [
|
|
1327
|
+
name
|
|
1328
|
+
for f in all_basenames
|
|
1329
|
+
if f.endswith('.hlo_proto.pb') and (name := _parse_filename(f)[0])
|
|
1330
|
+
]
|
|
1331
|
+
|
|
1332
|
+
if not module_list:
|
|
1333
|
+
xplane_basenames = self._get_xplane_basenames(run_dir)
|
|
1334
|
+
xplane_filenames = [os.path.join(run_dir, f) for f in xplane_basenames]
|
|
1335
|
+
if xplane_filenames:
|
|
1336
|
+
try:
|
|
1337
|
+
# This triggers ConvertMultiXSpaceToHloProto in the C++ backend.
|
|
1338
|
+
convert.xspace_to_tool_names(xplane_filenames)
|
|
1339
|
+
except AttributeError:
|
|
1340
|
+
logger.warning(
|
|
1341
|
+
'XPlane converters are available after Tensorflow 2.4'
|
|
1342
|
+
)
|
|
1343
|
+
|
|
1344
|
+
all_basenames = self._get_all_basenames(run_dir)
|
|
1345
|
+
module_list = [
|
|
1346
|
+
name
|
|
1347
|
+
for f in all_basenames
|
|
1348
|
+
if f.endswith('.hlo_proto.pb') and (name := _parse_filename(f)[0])
|
|
1349
|
+
]
|
|
1350
|
+
|
|
1351
|
+
return ','.join(module_list)
|
|
1352
|
+
except OSError as e:
|
|
1353
|
+
logger.warning('Cannot read asset directory: %s, OpError %r', run_dir, e)
|
|
1354
|
+
return ''
|
|
1355
|
+
|
|
1356
|
+
# pytype: disable=wrong-arg-types
|
|
1357
|
+
@wrappers.Request.application
|
|
1358
|
+
def data_route(self, request: wrappers.Request) -> wrappers.Response:
|
|
1359
|
+
"""Handlers for data."""
|
|
1360
|
+
# pytype: enable=wrong-arg-types
|
|
1361
|
+
# params
|
|
1362
|
+
# request: XMLHTTPRequest.
|
|
1363
|
+
try:
|
|
1364
|
+
data, content_type, content_encoding = self.data_impl(request)
|
|
1365
|
+
if data is None:
|
|
1366
|
+
return respond('No Data', 'text/plain', code=404)
|
|
1367
|
+
return respond(data, content_type, content_encoding=content_encoding)
|
|
1368
|
+
# Data fetch error handler
|
|
1369
|
+
except TimeoutError as e:
|
|
1370
|
+
return respond(str(e), 'text/plain', code=500)
|
|
1371
|
+
except AttributeError as e:
|
|
1372
|
+
return respond(str(e), 'text/plain', code=500)
|
|
1373
|
+
except ValueError as e:
|
|
1374
|
+
return respond(str(e), 'text/plain', code=500)
|
|
1375
|
+
except FileNotFoundError as e:
|
|
1376
|
+
return respond(str(e), 'text/plain', code=500)
|
|
1377
|
+
except IOError as e:
|
|
1378
|
+
return respond(str(e), 'text/plain', code=500)
|
|
1379
|
+
|
|
1380
|
+
# pytype: disable=wrong-arg-types
|
|
1381
|
+
@wrappers.Request.application
|
|
1382
|
+
# pytype: enable=wrong-arg-types
|
|
1383
|
+
def data_csv_route(self, request: wrappers.Request) -> wrappers.Response:
|
|
1384
|
+
"""Retrieves tool data and converts it to CSV before responding."""
|
|
1385
|
+
try:
|
|
1386
|
+
data, content_type, _ = self.data_impl(request)
|
|
1387
|
+
|
|
1388
|
+
if data is None:
|
|
1389
|
+
return respond('No Data Found', 'text/plain', code=404)
|
|
1390
|
+
|
|
1391
|
+
if content_type != 'application/json':
|
|
1392
|
+
return respond(
|
|
1393
|
+
'CSV format not supported for this tool type',
|
|
1394
|
+
'text/plain',
|
|
1395
|
+
code=400,
|
|
1396
|
+
)
|
|
1397
|
+
|
|
1398
|
+
csv_data = convert.json_to_csv_string(data)
|
|
1399
|
+
filename = _generate_csv_filename(request)
|
|
1400
|
+
|
|
1401
|
+
return respond(
|
|
1402
|
+
csv_data,
|
|
1403
|
+
'text/csv',
|
|
1404
|
+
content_encoding=None,
|
|
1405
|
+
extra_headers={
|
|
1406
|
+
'Content-Disposition': f'attachment; filename="{filename}"'
|
|
1407
|
+
},
|
|
1408
|
+
)
|
|
1409
|
+
|
|
1410
|
+
except (
|
|
1411
|
+
TimeoutError,
|
|
1412
|
+
AttributeError,
|
|
1413
|
+
ValueError,
|
|
1414
|
+
FileNotFoundError,
|
|
1415
|
+
IOError,
|
|
1416
|
+
TypeError,
|
|
1417
|
+
) as e:
|
|
1418
|
+
logger.exception('CSV conversion error')
|
|
1419
|
+
return respond(str(e), 'text/plain', code=500)
|
|
1420
|
+
|
|
1421
|
+
# pytype: disable=wrong-arg-types
|
|
1422
|
+
@wrappers.Request.application
|
|
1423
|
+
def capture_route(self, request: wrappers.Request) -> wrappers.Response:
|
|
1424
|
+
# pytype: enable=wrong-arg-types
|
|
1425
|
+
return self.capture_route_impl(request)
|
|
1426
|
+
|
|
1427
|
+
def capture_route_impl(self, request: wrappers.Request) -> wrappers.Response:
|
|
1428
|
+
"""Runs the client trace for capturing profiling information."""
|
|
1429
|
+
service_addr = request.args.get('service_addr')
|
|
1430
|
+
duration = int(request.args.get('duration', '1000'))
|
|
1431
|
+
is_tpu_name = request.args.get('is_tpu_name') == 'true'
|
|
1432
|
+
worker_list = request.args.get('worker_list')
|
|
1433
|
+
num_tracing_attempts = int(request.args.get('num_retry', '0')) + 1
|
|
1434
|
+
options = {
|
|
1435
|
+
'host_tracer_level': int(request.args.get('host_tracer_level', '2')),
|
|
1436
|
+
'device_tracer_level': int(
|
|
1437
|
+
request.args.get('device_tracer_level', '1')
|
|
1438
|
+
),
|
|
1439
|
+
'python_tracer_level': int(
|
|
1440
|
+
request.args.get('python_tracer_level', '0')
|
|
1441
|
+
),
|
|
1442
|
+
'delay_ms': int(request.args.get('delay', '0')),
|
|
1443
|
+
}
|
|
1444
|
+
|
|
1445
|
+
if is_tpu_name:
|
|
1446
|
+
if self._tf_profiler is None:
|
|
1447
|
+
return respond(
|
|
1448
|
+
{
|
|
1449
|
+
'error': (
|
|
1450
|
+
'TensorFlow is not installed, but is required to use TPU'
|
|
1451
|
+
' names.'
|
|
1452
|
+
)
|
|
1453
|
+
},
|
|
1454
|
+
'application/json',
|
|
1455
|
+
code=500,
|
|
1456
|
+
)
|
|
1457
|
+
try:
|
|
1458
|
+
# Delegate to the helper class for all TF-related logic.
|
|
1459
|
+
service_addr, worker_list, master_ip = (
|
|
1460
|
+
self._tf_profiler.resolve_tpu_name(service_addr, worker_list or '')
|
|
1461
|
+
)
|
|
1462
|
+
self.master_tpu_unsecure_channel = master_ip
|
|
1463
|
+
except (RuntimeError, ValueError) as err:
|
|
1464
|
+
return respond({'error': str(err)}, 'application/json', code=500)
|
|
1465
|
+
|
|
1466
|
+
if not self.logdir:
|
|
1467
|
+
return respond(
|
|
1468
|
+
{'error': 'logdir is not set, abort capturing.'},
|
|
1469
|
+
'application/json',
|
|
1470
|
+
code=500,
|
|
1471
|
+
)
|
|
1472
|
+
try:
|
|
1473
|
+
# The core trace call remains, now with cleanly resolved parameters.
|
|
1474
|
+
_pywrap_profiler_plugin.trace(
|
|
1475
|
+
service_addr.removeprefix('grpc://'),
|
|
1476
|
+
str(self.logdir),
|
|
1477
|
+
worker_list,
|
|
1478
|
+
True,
|
|
1479
|
+
duration,
|
|
1480
|
+
num_tracing_attempts,
|
|
1481
|
+
options,
|
|
1482
|
+
)
|
|
1483
|
+
return respond(
|
|
1484
|
+
{'result': 'Capture profile successfully. Please refresh.'},
|
|
1485
|
+
'application/json',
|
|
1486
|
+
)
|
|
1487
|
+
except Exception as e: # pylint: disable=broad-except
|
|
1488
|
+
return respond({'error': str(e)}, 'application/json', code=500)
|
|
1489
|
+
|
|
1490
|
+
def _get_graph_viewer_options(
|
|
1491
|
+
self, request: wrappers.Request
|
|
1492
|
+
) -> dict[str, Any]:
|
|
1493
|
+
node_name = request.args.get('node_name')
|
|
1494
|
+
module_name = request.args.get('module_name')
|
|
1495
|
+
graph_width_str = request.args.get('graph_width') or ''
|
|
1496
|
+
graph_width = int(graph_width_str) if graph_width_str.isdigit() else 3
|
|
1497
|
+
show_metadata = int(request.args.get('show_metadata') == 'true')
|
|
1498
|
+
merge_fusion = int(request.args.get('merge_fusion') == 'true')
|
|
1499
|
+
program_id = request.args.get('program_id')
|
|
1500
|
+
return {
|
|
1501
|
+
'node_name': node_name,
|
|
1502
|
+
'module_name': module_name,
|
|
1503
|
+
'program_id': program_id,
|
|
1504
|
+
'graph_width': graph_width,
|
|
1505
|
+
'show_metadata': show_metadata,
|
|
1506
|
+
'merge_fusion': merge_fusion,
|
|
1507
|
+
'format': request.args.get('format'),
|
|
1508
|
+
'type': request.args.get('type'),
|
|
1509
|
+
}
|
|
1510
|
+
|
|
1511
|
+
def generate_runs(self) -> Iterator[str]:
|
|
1512
|
+
"""Generator for a list of runs.
|
|
1513
|
+
|
|
1514
|
+
The "run name" here is a "frontend run name" - see _tb_run_directory() for
|
|
1515
|
+
the definition of a "frontend run name" and how it maps to a directory of
|
|
1516
|
+
profile data for a specific profile "run". The profile plugin concept of
|
|
1517
|
+
"run" is different from the normal TensorBoard run; each run in this case
|
|
1518
|
+
represents a single instance of profile data collection, more similar to a
|
|
1519
|
+
"step" of data in typical TensorBoard semantics. These runs reside in
|
|
1520
|
+
subdirectories of the plugins/profile directory within any regular
|
|
1521
|
+
TensorBoard run directory or within the session_dir root directory
|
|
1522
|
+
itself (even if it contains no tfevents file and would thus not be
|
|
1523
|
+
considered a normal TensorBoard run, for backwards compatibility).
|
|
1524
|
+
|
|
1525
|
+
`generate_runs` will get all runs first, and get tools list from
|
|
1526
|
+
`generate_tools_of_run` for a single run due to expensive processing for
|
|
1527
|
+
xspace data to parse the tools.
|
|
1528
|
+
Example:
|
|
1529
|
+
logs/
|
|
1530
|
+
plugins/
|
|
1531
|
+
profile/
|
|
1532
|
+
run1/
|
|
1533
|
+
hostA.trace
|
|
1534
|
+
train/
|
|
1535
|
+
events.out.tfevents.foo
|
|
1536
|
+
plugins/
|
|
1537
|
+
profile/
|
|
1538
|
+
run1/
|
|
1539
|
+
hostA.trace
|
|
1540
|
+
hostB.trace
|
|
1541
|
+
run2/
|
|
1542
|
+
hostA.trace
|
|
1543
|
+
validation/
|
|
1544
|
+
events.out.tfevents.foo
|
|
1545
|
+
plugins/
|
|
1546
|
+
profile/
|
|
1547
|
+
run1/
|
|
1548
|
+
hostA.trace
|
|
1549
|
+
new_job/
|
|
1550
|
+
tensorboard/
|
|
1551
|
+
plugins/
|
|
1552
|
+
profile/
|
|
1553
|
+
run1/
|
|
1554
|
+
hostA.xplane.pb
|
|
1555
|
+
Yields:
|
|
1556
|
+
A sequence of string that are "frontend run names".
|
|
1557
|
+
For the above example, this would be:
|
|
1558
|
+
"run1", "train/run1", "train/run2", "validation/run1",
|
|
1559
|
+
"new_job/tensorboard/run1"
|
|
1560
|
+
"""
|
|
1561
|
+
if not self.logdir:
|
|
1562
|
+
return
|
|
1563
|
+
|
|
1564
|
+
# Ensure that we check the root logdir and all subdirectories.
|
|
1565
|
+
# Note that we check if logdir is a directory to handle case where
|
|
1566
|
+
# it's actually a multipart directory spec, which this plugin does not
|
|
1567
|
+
# support.
|
|
1568
|
+
#
|
|
1569
|
+
# This change still enforce the requirement that the subdirectories must
|
|
1570
|
+
# end with plugins/profile directory, as enforced by TensorBoard.
|
|
1571
|
+
logdir_path = self._epath.Path(self.logdir)
|
|
1572
|
+
schemeless_logdir = str(logdir_path)
|
|
1573
|
+
if '://' in schemeless_logdir:
|
|
1574
|
+
schemeless_logdir = schemeless_logdir.split('://', 1)[1]
|
|
1575
|
+
tb_runs = {'.'}
|
|
1576
|
+
|
|
1577
|
+
if logdir_path.is_dir():
|
|
1578
|
+
try:
|
|
1579
|
+
fs = etils.epath.backend.fsspec_backend.fs(self.logdir)
|
|
1580
|
+
for path_str in fs.glob(os.path.join(self.logdir, '**', PLUGIN_NAME)):
|
|
1581
|
+
path = self._epath.Path(path_str)
|
|
1582
|
+
if fs.isdir(path) and path.parent.name == TB_NAME:
|
|
1583
|
+
tb_run_dir = path.parent.parent
|
|
1584
|
+
tb_run = tb_run_dir.relative_to(schemeless_logdir)
|
|
1585
|
+
tb_runs.add(str(tb_run))
|
|
1586
|
+
except ValueError:
|
|
1587
|
+
# gcsfs not available, fall back to legacy path walk.
|
|
1588
|
+
for cur_dir, _, _ in logdir_path.walk():
|
|
1589
|
+
if cur_dir.name == PLUGIN_NAME and cur_dir.parent.name == TB_NAME:
|
|
1590
|
+
tb_run_dir = cur_dir.parent.parent
|
|
1591
|
+
tb_run = tb_run_dir.relative_to(logdir_path)
|
|
1592
|
+
tb_runs.add(str(tb_run))
|
|
1593
|
+
tb_run_names_to_dirs = {
|
|
1594
|
+
run: _tb_run_directory(self.logdir, run) for run in tb_runs
|
|
1595
|
+
}
|
|
1596
|
+
plugin_assets = _plugin_assets(
|
|
1597
|
+
self.logdir, list(tb_run_names_to_dirs), PLUGIN_NAME
|
|
1598
|
+
)
|
|
1599
|
+
visited_runs = set()
|
|
1600
|
+
for tb_run_name, profile_runs in six.iteritems(plugin_assets):
|
|
1601
|
+
tb_run_dir = tb_run_names_to_dirs[tb_run_name]
|
|
1602
|
+
tb_plugin_dir = plugin_asset_util.PluginDirectory(tb_run_dir, PLUGIN_NAME)
|
|
1603
|
+
|
|
1604
|
+
for profile_run in profile_runs:
|
|
1605
|
+
# Remove trailing separator; some filesystem implementations emit this.
|
|
1606
|
+
profile_run = profile_run.rstrip(os.sep)
|
|
1607
|
+
if tb_run_name == '.':
|
|
1608
|
+
frontend_run = profile_run
|
|
1609
|
+
else:
|
|
1610
|
+
frontend_run = str(self._epath.Path(tb_run_name) / profile_run)
|
|
1611
|
+
profile_run_dir = str(self._epath.Path(tb_plugin_dir) / profile_run)
|
|
1612
|
+
if self._epath.Path(profile_run_dir).is_dir():
|
|
1613
|
+
with self._run_dir_cache_lock:
|
|
1614
|
+
self._run_to_profile_run_dir[frontend_run] = profile_run_dir
|
|
1615
|
+
if frontend_run not in visited_runs:
|
|
1616
|
+
visited_runs.add(frontend_run)
|
|
1617
|
+
yield frontend_run
|
|
1618
|
+
|
|
1619
|
+
def generate_tools_of_run(self, run: str, run_dir: str) -> Iterator[str]:
|
|
1620
|
+
"""Generate a list of tools given a certain run."""
|
|
1621
|
+
if not run_dir:
|
|
1622
|
+
logger.warning('Cannot find asset directory for: %s', run)
|
|
1623
|
+
return
|
|
1624
|
+
profile_run_dir = self._epath.Path(run_dir)
|
|
1625
|
+
fs = profile_io.get_file_system(run_dir, self._epath)
|
|
1626
|
+
cache = ToolsCache(profile_run_dir, fs)
|
|
1627
|
+
|
|
1628
|
+
cached_tools = cache.load()
|
|
1629
|
+
|
|
1630
|
+
if cached_tools is not None:
|
|
1631
|
+
for tool in cached_tools:
|
|
1632
|
+
yield tool
|
|
1633
|
+
return
|
|
1634
|
+
|
|
1635
|
+
# Cache is invalid or doesn't exist, regenerate
|
|
1636
|
+
tools = []
|
|
1637
|
+
all_filenames = self._get_all_basenames(run_dir)
|
|
1638
|
+
|
|
1639
|
+
if all_filenames:
|
|
1640
|
+
tools = self._get_active_tools(all_filenames, str(profile_run_dir))
|
|
1641
|
+
cache.save(tools)
|
|
1642
|
+
|
|
1643
|
+
for tool in tools:
|
|
1644
|
+
yield tool
|
|
1645
|
+
|
|
1646
|
+
def _get_active_tools(self, filenames, profile_run_dir=''):
|
|
1647
|
+
"""Get a list of tools available given the filenames created by profiler.
|
|
1648
|
+
|
|
1649
|
+
Args:
|
|
1650
|
+
filenames: List of strings that represent filenames
|
|
1651
|
+
profile_run_dir: The run directory of the profile.
|
|
1652
|
+
|
|
1653
|
+
Returns:
|
|
1654
|
+
A list of strings representing the available tools
|
|
1655
|
+
"""
|
|
1656
|
+
tool_sort_order = [
|
|
1657
|
+
'overview_page',
|
|
1658
|
+
'trace_viewer',
|
|
1659
|
+
'trace_viewer@',
|
|
1660
|
+
'graph_viewer',
|
|
1661
|
+
'op_profile',
|
|
1662
|
+
'hlo_op_profile',
|
|
1663
|
+
'input_pipeline_analyzer',
|
|
1664
|
+
'input_pipeline',
|
|
1665
|
+
'kernel_stats',
|
|
1666
|
+
'memory_profile',
|
|
1667
|
+
'memory_viewer',
|
|
1668
|
+
'roofline_model',
|
|
1669
|
+
'perf_counters',
|
|
1670
|
+
'pod_viewer',
|
|
1671
|
+
'framework_op_stats',
|
|
1672
|
+
'tensorflow_stats', # Legacy name for framework_op_stats
|
|
1673
|
+
'hlo_op_stats',
|
|
1674
|
+
'hlo_stats', # Legacy name for hlo_op_stats
|
|
1675
|
+
'inference_profile',
|
|
1676
|
+
'megascale_stats',
|
|
1677
|
+
]
|
|
1678
|
+
tools = _get_tools(filenames, profile_run_dir)
|
|
1679
|
+
if 'trace_viewer@' in tools:
|
|
1680
|
+
# streaming trace viewer always override normal trace viewer.
|
|
1681
|
+
# the trailing '@' is to inform tf-profile-dashboard.html and
|
|
1682
|
+
# tf-trace-viewer.html that stream trace viewer should be used.
|
|
1683
|
+
tools.discard('trace_viewer')
|
|
1684
|
+
|
|
1685
|
+
sorted_tools = [t for t in tool_sort_order if t in tools]
|
|
1686
|
+
remaining_tools = tools.difference(sorted_tools)
|
|
1687
|
+
sorted_tools.extend(sorted(remaining_tools))
|
|
1688
|
+
|
|
1689
|
+
return sorted_tools
|
|
1690
|
+
|
|
1691
|
+
# pytype: disable=wrong-arg-types
|
|
1692
|
+
@wrappers.Request.application
|
|
1693
|
+
def generate_cache_route(
|
|
1694
|
+
self, request: wrappers.Request
|
|
1695
|
+
) -> wrappers.Response:
|
|
1696
|
+
# pytype: enable=wrong-arg-types
|
|
1697
|
+
"""Generates tool data cache in the background."""
|
|
1698
|
+
return self._generate_cache_impl(request)
|
|
1699
|
+
|
|
1700
|
+
def _generate_cache_impl(
|
|
1701
|
+
self, request: wrappers.Request
|
|
1702
|
+
) -> wrappers.Response:
|
|
1703
|
+
"""Generates tool data cache in the background.
|
|
1704
|
+
|
|
1705
|
+
Args:
|
|
1706
|
+
request: The Werkzeug request object. `request.args` may contain the
|
|
1707
|
+
following parameters: - session_path: The path to the session directory
|
|
1708
|
+
containing XPlane files. (Required) - tools: An optional comma-separated
|
|
1709
|
+
list of tool names to generate cache for. If not provided, defaults to
|
|
1710
|
+
`DEFAULT_CACHE_TOOLS`.
|
|
1711
|
+
|
|
1712
|
+
Returns:
|
|
1713
|
+
A JSON response indicating whether the task was accepted.
|
|
1714
|
+
"""
|
|
1715
|
+
logger.info('Received generate_cache request.')
|
|
1716
|
+
if request.method != 'POST':
|
|
1717
|
+
return respond('Method Not Allowed', 'text/plain', code=405)
|
|
1718
|
+
|
|
1719
|
+
params = request.args
|
|
1720
|
+
session_path = params.get('session_path')
|
|
1721
|
+
logger.info('generate_cache called with params: %s', params)
|
|
1722
|
+
|
|
1723
|
+
if not session_path:
|
|
1724
|
+
return respond('Missing "session_path" parameter', 'text/plain', code=400)
|
|
1725
|
+
|
|
1726
|
+
try:
|
|
1727
|
+
path = self._epath.Path(session_path)
|
|
1728
|
+
xplane_basenames = self._get_xplane_basenames(session_path)
|
|
1729
|
+
asset_paths = sorted(
|
|
1730
|
+
str(path / basename) for basename in xplane_basenames
|
|
1731
|
+
)
|
|
1732
|
+
if not asset_paths:
|
|
1733
|
+
return respond(
|
|
1734
|
+
'No XPlane files found in session_path', 'text/plain', code=404
|
|
1735
|
+
)
|
|
1736
|
+
logger.info(
|
|
1737
|
+
'Found %d *.xplane.pb files in %s.', len(asset_paths), session_path
|
|
1738
|
+
)
|
|
1739
|
+
except OSError as e:
|
|
1740
|
+
logger.exception('Error listing files in session_path: %s', session_path)
|
|
1741
|
+
return respond(
|
|
1742
|
+
f'Error listing files in session_path: {e!r}', 'text/plain', code=500
|
|
1743
|
+
)
|
|
1744
|
+
|
|
1745
|
+
runs = self.runs_imp(request)
|
|
1746
|
+
if len(runs) != 1:
|
|
1747
|
+
# When 'session_path' is provided, runs_imp should return exactly one run
|
|
1748
|
+
# corresponding to the session_path's name.
|
|
1749
|
+
return respond(
|
|
1750
|
+
'Expected exactly one run for the provided session_path, but found'
|
|
1751
|
+
' %d: %s. Please ensure session_path points to a valid profile run'
|
|
1752
|
+
' directory.' % (len(runs), runs),
|
|
1753
|
+
'text/plain',
|
|
1754
|
+
code=400,
|
|
1755
|
+
)
|
|
1756
|
+
run_name = runs[0]
|
|
1757
|
+
logger.info(
|
|
1758
|
+
'Querying available tools for run %s via run_tools_imp.',
|
|
1759
|
+
run_name,
|
|
1760
|
+
)
|
|
1761
|
+
available_run_tools = set(self.run_tools_imp(run_name, request))
|
|
1762
|
+
logger.info(
|
|
1763
|
+
'Discovered tools for cache generation: %s for run %s',
|
|
1764
|
+
available_run_tools,
|
|
1765
|
+
run_name,
|
|
1766
|
+
)
|
|
1767
|
+
|
|
1768
|
+
tools_str = params.get('tools')
|
|
1769
|
+
requested_tools = (
|
|
1770
|
+
set(t.strip() for t in tools_str.split(',') if t.strip())
|
|
1771
|
+
if tools_str
|
|
1772
|
+
else set(DEFAULT_CACHE_TOOLS)
|
|
1773
|
+
)
|
|
1774
|
+
if tools_str:
|
|
1775
|
+
logger.info('Request tools for cache generation: %s', requested_tools)
|
|
1776
|
+
else:
|
|
1777
|
+
logger.info(
|
|
1778
|
+
'No tools specified in request, using default tools: %s',
|
|
1779
|
+
DEFAULT_CACHE_TOOLS,
|
|
1780
|
+
)
|
|
1781
|
+
|
|
1782
|
+
available_xplane_tools = available_run_tools.intersection(XPLANE_TOOLS_SET)
|
|
1783
|
+
|
|
1784
|
+
filtered_tools = requested_tools.intersection(available_xplane_tools)
|
|
1785
|
+
|
|
1786
|
+
skipped_tools = requested_tools.difference(filtered_tools)
|
|
1787
|
+
for tool in skipped_tools:
|
|
1788
|
+
if tool not in available_run_tools:
|
|
1789
|
+
logger.info(
|
|
1790
|
+
'Tool %s was requested for caching but is not available for run %s,'
|
|
1791
|
+
' skipping.',
|
|
1792
|
+
tool,
|
|
1793
|
+
run_name,
|
|
1794
|
+
)
|
|
1795
|
+
else:
|
|
1796
|
+
logger.warning(
|
|
1797
|
+
'Tool %s is available for run %s but not in XPLANE_TOOLS_SET,'
|
|
1798
|
+
' skipping cache generation.',
|
|
1799
|
+
tool,
|
|
1800
|
+
run_name,
|
|
1801
|
+
)
|
|
1802
|
+
|
|
1803
|
+
if not filtered_tools:
|
|
1804
|
+
return respond(
|
|
1805
|
+
'No valid XPlane tools found or specified for caching in run %s.'
|
|
1806
|
+
% run_name,
|
|
1807
|
+
'text/plain',
|
|
1808
|
+
code=400,
|
|
1809
|
+
)
|
|
1810
|
+
|
|
1811
|
+
logger.info(
|
|
1812
|
+
'Filtered tools for cache generation: %s for session %s',
|
|
1813
|
+
filtered_tools,
|
|
1814
|
+
session_path,
|
|
1815
|
+
)
|
|
1816
|
+
|
|
1817
|
+
try:
|
|
1818
|
+
logger.info(
|
|
1819
|
+
'Submitting cache generation task to thread pool for session %s...',
|
|
1820
|
+
session_path,
|
|
1821
|
+
)
|
|
1822
|
+
self._cache_generation_pool.submit(
|
|
1823
|
+
self._generate_cache_task,
|
|
1824
|
+
asset_paths=asset_paths,
|
|
1825
|
+
tool_list=sorted(list(filtered_tools)),
|
|
1826
|
+
params=params,
|
|
1827
|
+
session_path=session_path,
|
|
1828
|
+
)
|
|
1829
|
+
except RuntimeError as e:
|
|
1830
|
+
logger.exception(
|
|
1831
|
+
'Failed to schedule cache generation task for session_path: %s',
|
|
1832
|
+
session_path,
|
|
1833
|
+
)
|
|
1834
|
+
return respond(f'Failed to schedule task: {e!r}', 'text/plain', code=500)
|
|
1835
|
+
else:
|
|
1836
|
+
return respond(
|
|
1837
|
+
{'status': 'ACCEPTED', 'message': 'Cache generation started'},
|
|
1838
|
+
'application/json',
|
|
1839
|
+
code=202,
|
|
1840
|
+
)
|
|
1841
|
+
|
|
1842
|
+
def _generate_cache_task(
|
|
1843
|
+
self,
|
|
1844
|
+
*,
|
|
1845
|
+
asset_paths: Sequence[str],
|
|
1846
|
+
tool_list: Iterable[str],
|
|
1847
|
+
params: Mapping[str, Any],
|
|
1848
|
+
session_path: str,
|
|
1849
|
+
) -> None:
|
|
1850
|
+
"""Generates and caches tool data from XPlane files in a background thread.
|
|
1851
|
+
|
|
1852
|
+
Args:
|
|
1853
|
+
asset_paths: A list of paths to the XPlane files.
|
|
1854
|
+
tool_list: A list of tool names for which to generate cache.
|
|
1855
|
+
params: Additional parameters from the request.
|
|
1856
|
+
session_path: The path to the session directory.
|
|
1857
|
+
"""
|
|
1858
|
+
logger.info(
|
|
1859
|
+
'Background cache generation task started for tools: %s', tool_list
|
|
1860
|
+
)
|
|
1861
|
+
logger.info('Writing cache version file to %s', session_path)
|
|
1862
|
+
self._write_cache_version_file(session_path)
|
|
1863
|
+
|
|
1864
|
+
filenames = [os.path.basename(p) for p in asset_paths]
|
|
1865
|
+
|
|
1866
|
+
base_tool_params = dict(params)
|
|
1867
|
+
|
|
1868
|
+
for tool in tool_list:
|
|
1869
|
+
try:
|
|
1870
|
+
logger.info('Generating cache for tool %s...', tool)
|
|
1871
|
+
tool_params = base_tool_params.copy()
|
|
1872
|
+
tool_params['hosts'] = hosts_from_xplane_filenames(filenames, tool)
|
|
1873
|
+
self._xspace_to_tool_data(
|
|
1874
|
+
[self._epath.Path(p) for p in asset_paths], tool, tool_params
|
|
1875
|
+
)
|
|
1876
|
+
logger.info(
|
|
1877
|
+
'Successfully generated cache for tool %s for %d files.',
|
|
1878
|
+
tool,
|
|
1879
|
+
len(asset_paths),
|
|
1880
|
+
)
|
|
1881
|
+
# Catch all exceptions to prevent the background thread from crashing.
|
|
1882
|
+
# This ensures that even if one tool fails to generate, other tools
|
|
1883
|
+
# can still be processed. The error is logged for debugging.
|
|
1884
|
+
except (AttributeError, ValueError, OSError):
|
|
1885
|
+
logger.exception(
|
|
1886
|
+
'Background cache generation failed for tool %s in session %s',
|
|
1887
|
+
tool,
|
|
1888
|
+
session_path,
|
|
1889
|
+
)
|
|
1890
|
+
except Exception: # pylint: disable=broad-except
|
|
1891
|
+
logger.exception(
|
|
1892
|
+
'Unexpected error during background cache generation for tool %s'
|
|
1893
|
+
' in session %s',
|
|
1894
|
+
tool,
|
|
1895
|
+
session_path,
|
|
1896
|
+
)
|