-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathresources.py
259 lines (206 loc) · 8.12 KB
/
resources.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""A module for defining resource requirements for execution of transforms.
Pipeline authors can use resource hints to provide additional information to
runners about the desired aspects of the execution environment.
Resource hints can be specified on a transform level for parts of the pipeline,
or globally via --resource_hint pipeline option.
See also: PTransforms.with_resource_hints().
"""
import re
from collections.abc import Mapping
from typing import Any
from typing import Optional
from apache_beam.options.pipeline_options import PipelineOptions
from apache_beam.options.pipeline_options import StandardOptions
from apache_beam.portability.common_urns import resource_hints
__all__ = [
'ResourceHint',
'AcceleratorHint',
'MinRamHint',
'CpuCountHint',
'MaxActiveBundlesPerWorkerHint',
'merge_resource_hints',
'parse_resource_hints',
'resource_hints_from_options',
]
class ResourceHint:
"""A superclass to define resource hints."""
# A unique URN, one per Resource Hint class.
urn: Optional[str] = None
_urn_to_known_hints: dict[str, type] = {}
_name_to_known_hints: dict[str, type] = {}
@classmethod
def parse(cls, value: str) -> dict[str, bytes]:
"""Describes how to parse the hint.
Override to specify a custom parsing logic."""
assert cls.urn is not None
# Override this method to have a custom parsing logic.
return {cls.urn: ResourceHint._parse_str(value)}
@classmethod
def get_merged_value(cls, outer_value: bytes, inner_value: bytes) -> bytes:
"""Reconciles values of a hint when the hint specified on a transform is
also defined in an outer context, for example on a composite transform, or
specified in the transform's execution environment.
Override to specify a custom merging logic.
"""
# Defaults to the inner value as it is the most specific one.
return inner_value
@staticmethod
def get_by_urn(urn):
return ResourceHint._urn_to_known_hints[urn]
@staticmethod
def get_by_name(name):
return ResourceHint._name_to_known_hints[name]
@staticmethod
def is_registered(name):
return name in ResourceHint._name_to_known_hints
@staticmethod
def register_resource_hint(hint_name: str, hint_class: type) -> None:
assert issubclass(hint_class, ResourceHint)
assert hint_class.urn is not None
ResourceHint._name_to_known_hints[hint_name] = hint_class
ResourceHint._urn_to_known_hints[hint_class.urn] = hint_class
@staticmethod
def _parse_str(value):
if not isinstance(value, str):
raise ValueError("Input must be a string.")
return value.encode('ascii')
@staticmethod
def _parse_int(value):
if isinstance(value, str):
value = int(value)
if not isinstance(value, int):
raise ValueError("Input must be an integer.")
return str(value).encode('ascii')
@staticmethod
def _parse_storage_size_str(value):
"""Parses a human-friendly storage size string into a number of bytes.
"""
if isinstance(value, int):
return ResourceHint._parse_int(value)
if not isinstance(value, str):
raise ValueError("Input must be a string or integer.")
value = value.strip().replace(" ", "")
units = {
'PiB': 2**50,
'TiB': 2**40,
'GiB': 2**30,
'MiB': 2**20,
'KiB': 2**10,
'PB': 10**15,
'TB': 10**12,
'GB': 10**9,
'MB': 10**6,
'KB': 10**3,
'B': 1,
}
match = re.match(r'.*?(\D+)$', value)
if not match:
raise ValueError("Unrecognized value pattern.")
suffix = match.group(1)
if suffix not in units:
raise ValueError("Unrecognized unit.")
multiplier = units[suffix]
value = value[:-len(suffix)]
return str(round(float(value) * multiplier)).encode('ascii')
@staticmethod
def _use_max(v1, v2):
return str(max(int(v1), int(v2))).encode('ascii')
@staticmethod
def _use_sum(v1, v2):
return str(int(v1) + int(v2)).encode('ascii')
class AcceleratorHint(ResourceHint):
"""Describes desired hardware accelerators in execution environment."""
urn = resource_hints.ACCELERATOR.urn
ResourceHint.register_resource_hint('accelerator', AcceleratorHint)
class MinRamHint(ResourceHint):
"""Describes min RAM requirements for transform's execution environment."""
urn = resource_hints.MIN_RAM_BYTES.urn
@classmethod
def parse(cls, value: str) -> dict[str, bytes]:
return {cls.urn: ResourceHint._parse_storage_size_str(value)}
@classmethod
def get_merged_value(cls, outer_value: bytes, inner_value: bytes) -> bytes:
return ResourceHint._use_max(outer_value, inner_value)
ResourceHint.register_resource_hint('min_ram', MinRamHint)
# Alias for interoperability with SDKs preferring camelCase.
ResourceHint.register_resource_hint('minRam', MinRamHint)
class CpuCountHint(ResourceHint):
"""Describes number of CPUs available in transform's execution environment."""
urn = resource_hints.CPU_COUNT.urn
@classmethod
def get_merged_value(cls, outer_value: bytes, inner_value: bytes) -> bytes:
return ResourceHint._use_max(outer_value, inner_value)
ResourceHint.register_resource_hint('cpu_count', CpuCountHint)
# Alias for interoperability with SDKs preferring camelCase.
ResourceHint.register_resource_hint('cpuCount', CpuCountHint)
class MaxActiveBundlesPerWorkerHint(ResourceHint):
"""
Describes max active bundles processed in parallel
in transform's execution environment.
"""
urn = resource_hints.MAX_ACTIVE_BUNDLES_PER_WORKER.urn
@classmethod
def get_merged_value(cls, outer_value: bytes, inner_value: bytes) -> bytes:
return ResourceHint._use_sum(outer_value, inner_value)
ResourceHint.register_resource_hint(
'max_active_bundles_per_worker', MaxActiveBundlesPerWorkerHint)
# Alias for interoperability with SDKs preferring camelCase.
ResourceHint.register_resource_hint(
'MaxActiveBundlesPerWorker', MaxActiveBundlesPerWorkerHint)
# Alias for common typo.
ResourceHint.register_resource_hint(
'max_active_bundle_per_worker', MaxActiveBundlesPerWorkerHint)
ResourceHint.register_resource_hint(
'MaxActiveBundlePerWorker', MaxActiveBundlesPerWorkerHint)
def parse_resource_hints(hints: dict[Any, Any]) -> dict[str, bytes]:
parsed_hints = {}
for hint, value in hints.items():
try:
hint_cls = ResourceHint.get_by_name(hint)
try:
parsed_hints.update(hint_cls.parse(value))
except ValueError:
raise ValueError(f"Resource hint {hint} has invalid value {value}.")
except KeyError:
raise ValueError(f"Unknown resource hint: {hint}.")
return parsed_hints
def resource_hints_from_options(
options: Optional[PipelineOptions]) -> dict[str, bytes]:
if options is None:
return {}
hints = {}
option_specified_hints = options.view_as(StandardOptions).resource_hints
for hint in option_specified_hints:
if '=' in hint:
k, v = hint.split('=', maxsplit=1)
hints[k] = v
else:
hints[hint] = None
return parse_resource_hints(hints)
def merge_resource_hints(
outer_hints: Mapping[str, bytes],
inner_hints: Mapping[str, bytes]) -> dict[str, bytes]:
merged_hints = dict(inner_hints)
for urn, outer_value in outer_hints.items():
if urn in inner_hints:
merged_value = ResourceHint.get_by_urn(urn).get_merged_value(
outer_value=outer_value, inner_value=inner_hints[urn])
else:
merged_value = outer_value
merged_hints[urn] = merged_value
return merged_hints