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
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
# Copyright 2017 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
|
+
"""Profiler tests for TPUs."""
|
|
16
|
+
import glob
|
|
17
|
+
import json
|
|
18
|
+
import os
|
|
19
|
+
|
|
20
|
+
from absl import flags
|
|
21
|
+
from absl import logging
|
|
22
|
+
from absl.testing import absltest
|
|
23
|
+
import tensorflow.compat.v1 as tfv1
|
|
24
|
+
import tensorflow.compat.v2 as tf
|
|
25
|
+
|
|
26
|
+
from xprof.convert import raw_to_tool_data
|
|
27
|
+
from xprof.integration_tests import tf_mnist
|
|
28
|
+
from xprof.integration_tests import tf_profiler_session
|
|
29
|
+
|
|
30
|
+
FLAGS = flags.FLAGS
|
|
31
|
+
|
|
32
|
+
_EPOCHS = 1
|
|
33
|
+
_TRAIN_STEPS = 40
|
|
34
|
+
_EVAL_STEPS = 10
|
|
35
|
+
|
|
36
|
+
log_dir: str = None
|
|
37
|
+
|
|
38
|
+
LOG_DIRECTORY = flags.DEFINE_string(
|
|
39
|
+
'log_directory', None, 'Location of trace file, if already available'
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def setUpModule():
|
|
44
|
+
global log_dir
|
|
45
|
+
# Runs the profiler on mnist model, then assert on the generated trace.
|
|
46
|
+
if not LOG_DIRECTORY.value:
|
|
47
|
+
log_dir = os.path.join(FLAGS.test_tmpdir, 'tensorboard')
|
|
48
|
+
with tf_profiler_session.TensorflowProfilerSession(tf, log_dir, 0):
|
|
49
|
+
_do_mnist_training(True)
|
|
50
|
+
# Assert on the trace present at the log directory.
|
|
51
|
+
else:
|
|
52
|
+
log_dir = LOG_DIRECTORY.value
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _do_mnist_training(use_xla: bool):
|
|
56
|
+
tf.config.optimizer.set_jit(use_xla)
|
|
57
|
+
# For non xla test case, use the legacy optimizer to avoid XLA compilation.
|
|
58
|
+
optimizer = tf.keras.optimizers.legacy.Adam()
|
|
59
|
+
if use_xla:
|
|
60
|
+
optimizer = tf.keras.optimizers.Adam()
|
|
61
|
+
|
|
62
|
+
train_ds, eval_ds, _, input_shape = tf_mnist.get_input_datasets(tf)
|
|
63
|
+
|
|
64
|
+
resolver = tf.distribute.cluster_resolver.TPUClusterResolver('local')
|
|
65
|
+
tf.tpu.experimental.initialize_tpu_system(resolver)
|
|
66
|
+
strategy = tf.distribute.experimental.TPUStrategy(resolver)
|
|
67
|
+
|
|
68
|
+
with strategy.scope():
|
|
69
|
+
model = tf_mnist.get_model(tf, input_shape)
|
|
70
|
+
model.compile(
|
|
71
|
+
optimizer=optimizer,
|
|
72
|
+
loss=tf.keras.losses.categorical_crossentropy,
|
|
73
|
+
metrics=['accuracy'])
|
|
74
|
+
|
|
75
|
+
model.fit(
|
|
76
|
+
x=train_ds,
|
|
77
|
+
epochs=_EPOCHS,
|
|
78
|
+
steps_per_epoch=_TRAIN_STEPS,
|
|
79
|
+
validation_steps=_EVAL_STEPS,
|
|
80
|
+
validation_data=eval_ds)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class TpuKerasTest(absltest.TestCase):
|
|
84
|
+
|
|
85
|
+
def _get_session_snapshot(self):
|
|
86
|
+
"""Gets a session snapshot of current session. assume only one session."""
|
|
87
|
+
profile_plugin_root = os.path.join(log_dir, 'plugins/profile')
|
|
88
|
+
# The session exists under a director whose name is time-dependent.
|
|
89
|
+
profile_session_glob = os.path.join(profile_plugin_root, '*', '*.xplane.pb')
|
|
90
|
+
return glob.glob(profile_session_glob)
|
|
91
|
+
|
|
92
|
+
def test_xplane_is_present(self):
|
|
93
|
+
files = self._get_session_snapshot()
|
|
94
|
+
self.assertLen(files, 1)
|
|
95
|
+
|
|
96
|
+
def test_tools_are_in_list(self):
|
|
97
|
+
xspace_filenames = self._get_session_snapshot()
|
|
98
|
+
result = raw_to_tool_data.xspace_to_tool_names(xspace_filenames)
|
|
99
|
+
result.sort()
|
|
100
|
+
expected = [
|
|
101
|
+
'trace_viewer@',
|
|
102
|
+
'overview_page',
|
|
103
|
+
'input_pipeline_analyzer',
|
|
104
|
+
'framework_op_stats',
|
|
105
|
+
'memory_profile',
|
|
106
|
+
'op_profile',
|
|
107
|
+
'memory_viewer',
|
|
108
|
+
'graph_viewer',
|
|
109
|
+
'hlo_stats',
|
|
110
|
+
'roofline_model',
|
|
111
|
+
]
|
|
112
|
+
expected.sort()
|
|
113
|
+
self.assertListEqual(expected, result)
|
|
114
|
+
|
|
115
|
+
def test_overview_page(self):
|
|
116
|
+
xspace_filenames = self._get_session_snapshot()
|
|
117
|
+
result, _ = raw_to_tool_data.xspace_to_tool_data(xspace_filenames,
|
|
118
|
+
'overview_page', {})
|
|
119
|
+
result = json.loads(result)
|
|
120
|
+
run_environment = result[2]
|
|
121
|
+
self.assertEqual(run_environment['p']['host_count'], '1')
|
|
122
|
+
self.assertRegex(run_environment['p']['device_type'], 'TPU.*')
|
|
123
|
+
|
|
124
|
+
def test_overview_page_creates_cache(self):
|
|
125
|
+
xspace_filenames = self._get_session_snapshot()
|
|
126
|
+
raw_to_tool_data.xspace_to_tool_data(xspace_filenames, 'overview_page', {})
|
|
127
|
+
profile_plugin_root = os.path.join(log_dir, 'plugins/profile')
|
|
128
|
+
# The session exists under a director whose name is time-dependent.
|
|
129
|
+
cache_glob = os.path.join(profile_plugin_root, '*', '*.op_stats.pb')
|
|
130
|
+
self.assertNotEmpty(cache_glob)
|
|
131
|
+
|
|
132
|
+
def test_op_profile(self):
|
|
133
|
+
xspace_filenames = self._get_session_snapshot()
|
|
134
|
+
result, _ = raw_to_tool_data.xspace_to_tool_data(
|
|
135
|
+
xspace_filenames, 'op_profile', {'group_by': 'category'}
|
|
136
|
+
)
|
|
137
|
+
result = json.loads(result)
|
|
138
|
+
logging.info(result)
|
|
139
|
+
self.assertIn('byCategory', result)
|
|
140
|
+
self.assertIn('metrics', result['byCategory'])
|
|
141
|
+
overall_metrics = result['byCategory']['metrics']
|
|
142
|
+
self.assertIn('flops', overall_metrics)
|
|
143
|
+
self.assertIn('bandwidthUtils', overall_metrics)
|
|
144
|
+
self.assertGreater(overall_metrics['flops'], 0)
|
|
145
|
+
contains_value = False
|
|
146
|
+
for m in overall_metrics['bandwidthUtils']:
|
|
147
|
+
if (m > 0):
|
|
148
|
+
contains_value = True
|
|
149
|
+
self.assertTrue(contains_value)
|
|
150
|
+
|
|
151
|
+
def test_device_trace_contains_threads(self):
|
|
152
|
+
xspace_filenames = self._get_session_snapshot()
|
|
153
|
+
result, _ = raw_to_tool_data.xspace_to_tool_data(
|
|
154
|
+
xspace_filenames, 'trace_viewer', {}
|
|
155
|
+
)
|
|
156
|
+
result = json.loads(result)
|
|
157
|
+
thread_names = []
|
|
158
|
+
process_names = []
|
|
159
|
+
for event in result['traceEvents']:
|
|
160
|
+
if 'name' in event:
|
|
161
|
+
if event['name'] == 'thread_name':
|
|
162
|
+
thread_names.append((event['args']['name']))
|
|
163
|
+
elif event['name'] == 'process_name':
|
|
164
|
+
process_names.append((event['args']['name']))
|
|
165
|
+
self.assertContainsSubset(
|
|
166
|
+
[
|
|
167
|
+
'Framework Name Scope',
|
|
168
|
+
'Framework Ops',
|
|
169
|
+
'XLA Modules',
|
|
170
|
+
'XLA Ops',
|
|
171
|
+
'XLA TraceMe',
|
|
172
|
+
'Steps',
|
|
173
|
+
],
|
|
174
|
+
thread_names,
|
|
175
|
+
)
|
|
176
|
+
self.assertContainsSubset(
|
|
177
|
+
['/device:TPU:0', '/device:TPU:1', '/host:CPU'], process_names
|
|
178
|
+
)
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
if __name__ == '__main__':
|
|
182
|
+
tfv1.enable_v2_behavior()
|
|
183
|
+
absltest.main()
|
xprof/profile_io.py
ADDED
|
@@ -0,0 +1,411 @@
|
|
|
1
|
+
# Copyright 2026 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
|
+
"""File system abstraction for the TensorBoard profile plugin."""
|
|
16
|
+
|
|
17
|
+
import abc
|
|
18
|
+
from collections.abc import Mapping
|
|
19
|
+
from collections.abc import Sequence
|
|
20
|
+
import functools
|
|
21
|
+
import json
|
|
22
|
+
import logging
|
|
23
|
+
import os
|
|
24
|
+
from typing import Any
|
|
25
|
+
|
|
26
|
+
from etils import epath
|
|
27
|
+
|
|
28
|
+
logger = logging.getLogger('tensorboard.plugins.profile')
|
|
29
|
+
|
|
30
|
+
try:
|
|
31
|
+
# pylint: disable=g-import-not-at-top
|
|
32
|
+
from google.cloud import exceptions as gcs_exceptions # type: ignore
|
|
33
|
+
from google.cloud import storage # type: ignore
|
|
34
|
+
except ImportError:
|
|
35
|
+
logger.warning(
|
|
36
|
+
'Google Cloud Storage not found. GCS paths will not be supported.'
|
|
37
|
+
)
|
|
38
|
+
gcs_exceptions = None
|
|
39
|
+
storage = None
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@functools.lru_cache(maxsize=None)
|
|
43
|
+
def get_storage_client():
|
|
44
|
+
"""Returns a memoized storage client instance."""
|
|
45
|
+
if storage is None:
|
|
46
|
+
raise RuntimeError(
|
|
47
|
+
'Google Cloud Storage libraries not found. gs:// paths are not'
|
|
48
|
+
' supported.'
|
|
49
|
+
)
|
|
50
|
+
return storage.Client()
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _list_gcs_dir(storage_client, gcs_path: str):
|
|
54
|
+
"""Lists blobs and sub-directories in a GCS path."""
|
|
55
|
+
gcs_path_no_prefix = gcs_path.removeprefix('gs://')
|
|
56
|
+
bucket_name, _, prefix = gcs_path_no_prefix.partition('/')
|
|
57
|
+
if prefix and not prefix.endswith('/'):
|
|
58
|
+
prefix += '/'
|
|
59
|
+
iterator = storage_client.list_blobs(
|
|
60
|
+
bucket_name, prefix=prefix, delimiter='/'
|
|
61
|
+
)
|
|
62
|
+
return list(iterator), iterator.prefixes, bucket_name
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class ProfileFileSystem(abc.ABC):
|
|
66
|
+
"""Abstract base class for file system operations."""
|
|
67
|
+
|
|
68
|
+
def __init__(self, epath_module: Any = epath):
|
|
69
|
+
"""Initializes the instance."""
|
|
70
|
+
self._epath = epath_module
|
|
71
|
+
|
|
72
|
+
@abc.abstractmethod
|
|
73
|
+
def get_xplane_file_states(self, dir_path: str) -> Mapping[str, str] | None:
|
|
74
|
+
"""Gets the current state of XPlane files in a directory."""
|
|
75
|
+
|
|
76
|
+
@abc.abstractmethod
|
|
77
|
+
def get_xplane_basenames(self, dir_path: str) -> Sequence[str]:
|
|
78
|
+
"""Returns a list of .xplane.pb base filenames in the given path."""
|
|
79
|
+
|
|
80
|
+
@abc.abstractmethod
|
|
81
|
+
def dir_has_xplane_files(self, dir_path: str) -> bool:
|
|
82
|
+
"""Checks if the directory contains any .xplane.pb files."""
|
|
83
|
+
|
|
84
|
+
@abc.abstractmethod
|
|
85
|
+
def get_all_basenames(self, dir_path: str) -> Sequence[str]:
|
|
86
|
+
"""Returns a list of all base filenames in the given path."""
|
|
87
|
+
|
|
88
|
+
@abc.abstractmethod
|
|
89
|
+
def get_session_paths(self, dir_path: str) -> Mapping[str, str]:
|
|
90
|
+
"""Returns a map of session names to absolute paths."""
|
|
91
|
+
|
|
92
|
+
@abc.abstractmethod
|
|
93
|
+
def read_json(self, file_path: str) -> Mapping[str, Any] | None:
|
|
94
|
+
"""Reads a JSON file."""
|
|
95
|
+
|
|
96
|
+
@abc.abstractmethod
|
|
97
|
+
def write_json(self, file_path: str, data: Mapping[str, Any]) -> None:
|
|
98
|
+
"""Writes a JSON file."""
|
|
99
|
+
|
|
100
|
+
@abc.abstractmethod
|
|
101
|
+
def delete_file(self, file_path: str) -> None:
|
|
102
|
+
"""Deletes a file."""
|
|
103
|
+
|
|
104
|
+
@abc.abstractmethod
|
|
105
|
+
def read_text(self, file_path: str) -> str | None:
|
|
106
|
+
"""Reads a text file."""
|
|
107
|
+
|
|
108
|
+
@abc.abstractmethod
|
|
109
|
+
def write_text(self, file_path: str, data: str) -> None:
|
|
110
|
+
"""Writes a text file."""
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class GcsFileSystem(ProfileFileSystem):
|
|
114
|
+
"""GCS implementation of ProfileFileSystem."""
|
|
115
|
+
|
|
116
|
+
def __init__(self, epath_module: Any = epath, storage_client=None):
|
|
117
|
+
"""Initializes the instance."""
|
|
118
|
+
if storage_client is None and storage is None:
|
|
119
|
+
raise RuntimeError(
|
|
120
|
+
'Google Cloud Storage libraries not found. gs:// paths are not'
|
|
121
|
+
' supported.'
|
|
122
|
+
)
|
|
123
|
+
super().__init__(epath_module)
|
|
124
|
+
self._storage_client = (
|
|
125
|
+
storage_client if storage_client is not None else get_storage_client()
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
def get_xplane_file_states(self, dir_path: str) -> dict[str, str] | None:
|
|
129
|
+
file_identifiers = {}
|
|
130
|
+
try:
|
|
131
|
+
blobs, _, _ = _list_gcs_dir(self._storage_client, dir_path)
|
|
132
|
+
for blob in blobs:
|
|
133
|
+
if not blob.name.endswith('.xplane.pb'):
|
|
134
|
+
continue
|
|
135
|
+
md5_hash = blob.md5_hash
|
|
136
|
+
if not isinstance(md5_hash, str):
|
|
137
|
+
logger.warning(
|
|
138
|
+
'Could not find a valid md5_hash for gs://%s/%s,'
|
|
139
|
+
' cache will be invalidated.',
|
|
140
|
+
blob.bucket.name,
|
|
141
|
+
blob.name,
|
|
142
|
+
)
|
|
143
|
+
return None
|
|
144
|
+
file_identifiers[os.path.basename(blob.name)] = md5_hash
|
|
145
|
+
return file_identifiers
|
|
146
|
+
except RuntimeError:
|
|
147
|
+
return None
|
|
148
|
+
|
|
149
|
+
def get_xplane_basenames(self, dir_path: str) -> list[str]:
|
|
150
|
+
try:
|
|
151
|
+
blobs, _, _ = _list_gcs_dir(self._storage_client, dir_path)
|
|
152
|
+
return [
|
|
153
|
+
os.path.basename(blob.name)
|
|
154
|
+
for blob in blobs
|
|
155
|
+
if blob.name.endswith('.xplane.pb')
|
|
156
|
+
]
|
|
157
|
+
except RuntimeError:
|
|
158
|
+
return []
|
|
159
|
+
|
|
160
|
+
def dir_has_xplane_files(self, dir_path: str) -> bool:
|
|
161
|
+
try:
|
|
162
|
+
blobs, _, _ = _list_gcs_dir(self._storage_client, dir_path)
|
|
163
|
+
return any(blob.name.endswith('.xplane.pb') for blob in blobs)
|
|
164
|
+
except RuntimeError:
|
|
165
|
+
return False
|
|
166
|
+
|
|
167
|
+
def get_all_basenames(self, dir_path: str) -> list[str]:
|
|
168
|
+
try:
|
|
169
|
+
blobs, _, _ = _list_gcs_dir(self._storage_client, dir_path)
|
|
170
|
+
return [os.path.basename(blob.name) for blob in blobs]
|
|
171
|
+
except RuntimeError:
|
|
172
|
+
return []
|
|
173
|
+
|
|
174
|
+
def get_session_paths(self, dir_path: str) -> dict[str, str]:
|
|
175
|
+
path_by_session_name = {}
|
|
176
|
+
try:
|
|
177
|
+
_, prefixes, bucket_name = _list_gcs_dir(self._storage_client, dir_path)
|
|
178
|
+
if not bucket_name:
|
|
179
|
+
return path_by_session_name
|
|
180
|
+
for subdir_prefix in prefixes:
|
|
181
|
+
session_path_str = f'gs://{bucket_name}/{subdir_prefix}'
|
|
182
|
+
if not self.dir_has_xplane_files(session_path_str):
|
|
183
|
+
continue
|
|
184
|
+
session_name = self._epath.Path(subdir_prefix).name
|
|
185
|
+
path_by_session_name[session_name] = session_path_str
|
|
186
|
+
except RuntimeError:
|
|
187
|
+
pass
|
|
188
|
+
return path_by_session_name
|
|
189
|
+
|
|
190
|
+
def read_json(self, file_path: str) -> dict[str, Any] | None:
|
|
191
|
+
if storage is None or gcs_exceptions is None:
|
|
192
|
+
return None
|
|
193
|
+
try:
|
|
194
|
+
blob = storage.Blob.from_string(file_path, client=self._storage_client)
|
|
195
|
+
return json.loads(blob.download_as_bytes())
|
|
196
|
+
except gcs_exceptions.NotFound:
|
|
197
|
+
logger.info('File not found on GCS: %s', file_path)
|
|
198
|
+
return None
|
|
199
|
+
except (json.JSONDecodeError, gcs_exceptions.GoogleAPICallError) as e:
|
|
200
|
+
logger.exception(
|
|
201
|
+
'Error reading or decoding GCS file %s: %r, invalidating.',
|
|
202
|
+
file_path,
|
|
203
|
+
e,
|
|
204
|
+
)
|
|
205
|
+
self.delete_file(file_path)
|
|
206
|
+
return None
|
|
207
|
+
|
|
208
|
+
def write_json(self, file_path: str, data: Mapping[str, Any]) -> None:
|
|
209
|
+
if storage is None or gcs_exceptions is None:
|
|
210
|
+
return
|
|
211
|
+
try:
|
|
212
|
+
blob = storage.Blob.from_string(file_path, client=self._storage_client)
|
|
213
|
+
blob.upload_from_string(
|
|
214
|
+
json.dumps(data, sort_keys=True, indent=2),
|
|
215
|
+
content_type='application/json',
|
|
216
|
+
)
|
|
217
|
+
logger.info('File saved to GCS: %s', file_path)
|
|
218
|
+
except (TypeError, gcs_exceptions.GoogleAPICallError) as e:
|
|
219
|
+
logger.exception('Error writing GCS file %s: %r', file_path, e)
|
|
220
|
+
|
|
221
|
+
def delete_file(self, file_path: str) -> None:
|
|
222
|
+
if storage is None or gcs_exceptions is None:
|
|
223
|
+
return
|
|
224
|
+
try:
|
|
225
|
+
blob = storage.Blob.from_string(file_path, client=self._storage_client)
|
|
226
|
+
blob.delete()
|
|
227
|
+
logger.info('File deleted from GCS: %s', file_path)
|
|
228
|
+
except gcs_exceptions.NotFound:
|
|
229
|
+
pass
|
|
230
|
+
except gcs_exceptions.GoogleAPICallError as e:
|
|
231
|
+
logger.exception('Error deleting GCS file %s: %r', file_path, e)
|
|
232
|
+
|
|
233
|
+
def read_text(self, file_path: str) -> str | None:
|
|
234
|
+
if storage is None or gcs_exceptions is None:
|
|
235
|
+
return None
|
|
236
|
+
try:
|
|
237
|
+
blob = storage.Blob.from_string(file_path, client=self._storage_client)
|
|
238
|
+
return blob.download_as_bytes().decode('utf-8')
|
|
239
|
+
except gcs_exceptions.NotFound:
|
|
240
|
+
return None
|
|
241
|
+
except gcs_exceptions.GoogleAPICallError as e:
|
|
242
|
+
logger.warning(
|
|
243
|
+
'Error reading GCS file %s: %r', file_path, e, exc_info=True
|
|
244
|
+
)
|
|
245
|
+
return None
|
|
246
|
+
|
|
247
|
+
def write_text(self, file_path: str, data: str) -> None:
|
|
248
|
+
if storage is None or gcs_exceptions is None:
|
|
249
|
+
return
|
|
250
|
+
try:
|
|
251
|
+
blob = storage.Blob.from_string(file_path, client=self._storage_client)
|
|
252
|
+
blob.upload_from_string(data, content_type='text/plain')
|
|
253
|
+
except gcs_exceptions.GoogleAPICallError as e:
|
|
254
|
+
logger.error('Error writing GCS file %s: %r', file_path, e, exc_info=True)
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def _get_local_file_identifier(file_path_str: str) -> str | None:
|
|
258
|
+
"""Gets a string identifier for a local file based on mtime and size."""
|
|
259
|
+
try:
|
|
260
|
+
stat_result = os.stat(file_path_str)
|
|
261
|
+
return f'{int(stat_result.st_mtime)}-{stat_result.st_size}'
|
|
262
|
+
except FileNotFoundError:
|
|
263
|
+
logger.warning('Local file not found: %s', file_path_str)
|
|
264
|
+
return None
|
|
265
|
+
except OSError as e:
|
|
266
|
+
logger.error(
|
|
267
|
+
'OSError getting stat for local file %s: %r',
|
|
268
|
+
file_path_str,
|
|
269
|
+
e,
|
|
270
|
+
exc_info=True,
|
|
271
|
+
)
|
|
272
|
+
return None
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
class LocalFileSystem(ProfileFileSystem):
|
|
276
|
+
"""Local implementation of ProfileFileSystem."""
|
|
277
|
+
|
|
278
|
+
def get_xplane_file_states(self, dir_path: str) -> dict[str, str] | None:
|
|
279
|
+
path = self._epath.Path(dir_path)
|
|
280
|
+
file_identifiers = {}
|
|
281
|
+
try:
|
|
282
|
+
for xplane_file in path.glob('*.xplane.pb'):
|
|
283
|
+
file_id = _get_local_file_identifier(str(xplane_file))
|
|
284
|
+
if file_id is None:
|
|
285
|
+
logger.warning(
|
|
286
|
+
'Could not get identifier for %s, cache will be invalidated.',
|
|
287
|
+
xplane_file,
|
|
288
|
+
)
|
|
289
|
+
return None
|
|
290
|
+
file_identifiers[xplane_file.name] = file_id
|
|
291
|
+
return file_identifiers
|
|
292
|
+
except OSError as e:
|
|
293
|
+
logger.warning(
|
|
294
|
+
'Could not glob files in %s: %r',
|
|
295
|
+
dir_path,
|
|
296
|
+
e,
|
|
297
|
+
exc_info=True,
|
|
298
|
+
)
|
|
299
|
+
return None
|
|
300
|
+
|
|
301
|
+
def get_xplane_basenames(self, dir_path: str) -> list[str]:
|
|
302
|
+
path = self._epath.Path(dir_path)
|
|
303
|
+
try:
|
|
304
|
+
return [f.name for f in path.glob('*.xplane.pb')]
|
|
305
|
+
except OSError as e:
|
|
306
|
+
logger.warning(
|
|
307
|
+
'Cannot read asset directory: %s, OpError %s',
|
|
308
|
+
dir_path,
|
|
309
|
+
e,
|
|
310
|
+
exc_info=True,
|
|
311
|
+
)
|
|
312
|
+
return []
|
|
313
|
+
|
|
314
|
+
def dir_has_xplane_files(self, dir_path: str) -> bool:
|
|
315
|
+
path = self._epath.Path(dir_path)
|
|
316
|
+
try:
|
|
317
|
+
return any(path.glob('*.xplane.pb'))
|
|
318
|
+
except OSError:
|
|
319
|
+
return False
|
|
320
|
+
|
|
321
|
+
def get_all_basenames(self, dir_path: str) -> list[str]:
|
|
322
|
+
path = self._epath.Path(dir_path)
|
|
323
|
+
try:
|
|
324
|
+
return [f.name for f in path.iterdir()]
|
|
325
|
+
except OSError as e:
|
|
326
|
+
logger.warning(
|
|
327
|
+
'Cannot read asset directory: %s, Error %r',
|
|
328
|
+
dir_path,
|
|
329
|
+
e,
|
|
330
|
+
exc_info=True,
|
|
331
|
+
)
|
|
332
|
+
return []
|
|
333
|
+
|
|
334
|
+
def get_session_paths(self, dir_path: str) -> dict[str, str]:
|
|
335
|
+
path_by_session_name = {}
|
|
336
|
+
path = self._epath.Path(dir_path)
|
|
337
|
+
try:
|
|
338
|
+
for session in path.iterdir():
|
|
339
|
+
if self.dir_has_xplane_files(str(session)):
|
|
340
|
+
path_by_session_name[session.name] = str(session)
|
|
341
|
+
except OSError as e:
|
|
342
|
+
logger.warning(
|
|
343
|
+
'Cannot read asset directory: %s, Error %r',
|
|
344
|
+
dir_path,
|
|
345
|
+
e,
|
|
346
|
+
exc_info=True,
|
|
347
|
+
)
|
|
348
|
+
return path_by_session_name
|
|
349
|
+
|
|
350
|
+
def read_json(self, file_path: str) -> dict[str, Any] | None:
|
|
351
|
+
path = self._epath.Path(file_path)
|
|
352
|
+
try:
|
|
353
|
+
with path.open('r') as f:
|
|
354
|
+
return json.load(f)
|
|
355
|
+
except (OSError, json.JSONDecodeError) as e:
|
|
356
|
+
logger.exception(
|
|
357
|
+
'Error reading or decoding file %s: %r, invalidating.',
|
|
358
|
+
file_path,
|
|
359
|
+
e,
|
|
360
|
+
)
|
|
361
|
+
self.delete_file(file_path)
|
|
362
|
+
return None
|
|
363
|
+
|
|
364
|
+
def write_json(self, file_path: str, data: Mapping[str, Any]) -> None:
|
|
365
|
+
path = self._epath.Path(file_path)
|
|
366
|
+
try:
|
|
367
|
+
with path.open('w') as f:
|
|
368
|
+
json.dump(data, f, sort_keys=True, indent=2)
|
|
369
|
+
logger.info('File saved: %s', file_path)
|
|
370
|
+
except (OSError, TypeError) as e:
|
|
371
|
+
logger.exception('Error writing file %s: %r', file_path, e)
|
|
372
|
+
|
|
373
|
+
def delete_file(self, file_path: str) -> None:
|
|
374
|
+
path = self._epath.Path(file_path)
|
|
375
|
+
try:
|
|
376
|
+
path.unlink()
|
|
377
|
+
logger.info('File deleted: %s', file_path)
|
|
378
|
+
except FileNotFoundError:
|
|
379
|
+
pass
|
|
380
|
+
except OSError as e:
|
|
381
|
+
logger.exception('Error deleting file %s: %r', file_path, e)
|
|
382
|
+
|
|
383
|
+
def read_text(self, file_path: str) -> str | None:
|
|
384
|
+
path = self._epath.Path(file_path)
|
|
385
|
+
try:
|
|
386
|
+
with path.open('r') as f:
|
|
387
|
+
return f.read()
|
|
388
|
+
except FileNotFoundError:
|
|
389
|
+
return None
|
|
390
|
+
except OSError as e:
|
|
391
|
+
logger.warning(
|
|
392
|
+
'Cannot read text file %s: %r', file_path, e, exc_info=True
|
|
393
|
+
)
|
|
394
|
+
return None
|
|
395
|
+
|
|
396
|
+
def write_text(self, file_path: str, data: str) -> None:
|
|
397
|
+
path = self._epath.Path(file_path)
|
|
398
|
+
try:
|
|
399
|
+
with path.open('w') as f:
|
|
400
|
+
f.write(data)
|
|
401
|
+
except OSError as e:
|
|
402
|
+
logger.warning(
|
|
403
|
+
'Cannot write text file to %s: %r', file_path, e, exc_info=True
|
|
404
|
+
)
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
def get_file_system(path: str, epath_module: Any = epath) -> ProfileFileSystem:
|
|
408
|
+
"""Returns a file system abstracting remote/local file operations."""
|
|
409
|
+
if storage is not None and path.startswith('gs://'):
|
|
410
|
+
return GcsFileSystem(epath_module, storage_client=get_storage_client())
|
|
411
|
+
return LocalFileSystem(epath_module)
|