-
Notifications
You must be signed in to change notification settings - Fork 755
/
usage_stats.py
289 lines (244 loc) · 9.67 KB
/
usage_stats.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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
from __future__ import annotations
import os
import typing as t
import logging
import secrets
import threading
import contextlib
from typing import TYPE_CHECKING
from datetime import datetime
from datetime import timezone
from functools import wraps
from functools import lru_cache
import attr
import requests
from simple_di import inject
from simple_di import Provide
from ...utils import compose
from .schemas import EventMeta
from .schemas import ServeInitEvent
from .schemas import TrackingPayload
from .schemas import CommonProperties
from .schemas import ServeUpdateEvent
from ...configuration import get_debug_mode
from ...configuration.containers import BentoMLContainer
if TYPE_CHECKING:
P = t.ParamSpec("P")
T = t.TypeVar("T")
AsyncFunc = t.Callable[P, t.Coroutine[t.Any, t.Any, t.Any]]
from prometheus_client.samples import Sample
from bentoml import Service
from ...server.metrics.prometheus import PrometheusClient
logger = logging.getLogger(__name__)
BENTOML_DO_NOT_TRACK = "BENTOML_DO_NOT_TRACK"
USAGE_TRACKING_URL = "https://t.bentoml.com"
SERVE_USAGE_TRACKING_INTERVAL_SECONDS = int(12 * 60 * 60) # every 12 hours
USAGE_REQUEST_TIMEOUT_SECONDS = 1
@lru_cache(maxsize=1)
def do_not_track() -> bool: # pragma: no cover
# Returns True if and only if the environment variable is defined and has value True.
# The function is cached for better performance.
return os.environ.get(BENTOML_DO_NOT_TRACK, str(False)).lower() == "true"
@lru_cache(maxsize=1)
def _usage_event_debugging() -> bool:
# For BentoML developers only - debug and print event payload if turned on
return os.environ.get("__BENTOML_DEBUG_USAGE", str(False)).lower() == "true"
def silent(func: t.Callable[P, T]) -> t.Callable[P, T]: # pragma: no cover
# Silent errors when tracking
@wraps(func)
def wrapper(*args: P.args, **kwargs: P.kwargs) -> t.Any:
try:
return func(*args, **kwargs)
except Exception as err: # pylint: disable=broad-except
if _usage_event_debugging():
if get_debug_mode():
logger.error(
f"Tracking Error: {err}", stack_info=True, stacklevel=3
)
else:
logger.info(f"Tracking Error: {err}")
else:
logger.debug(f"Tracking Error: {err}")
return wrapper
@attr.define
class ServeInfo:
serve_id: str
serve_started_timestamp: datetime
def get_serve_info() -> ServeInfo: # pragma: no cover
# Returns a safe token for serve as well as timestamp of creating this token
return ServeInfo(
serve_id=secrets.token_urlsafe(32),
serve_started_timestamp=datetime.now(timezone.utc),
)
@inject
def get_payload(
event_properties: EventMeta,
session_id: str = Provide[BentoMLContainer.session_id],
) -> t.Dict[str, t.Any]:
return TrackingPayload(
session_id=session_id,
common_properties=CommonProperties(),
event_properties=event_properties,
event_type=event_properties.event_name,
).to_dict()
@silent
def track(event_properties: EventMeta):
if do_not_track():
return
payload = get_payload(event_properties=event_properties)
if _usage_event_debugging():
# For internal debugging purpose
logger.info("Tracking Payload: %s", payload)
return
requests.post(
USAGE_TRACKING_URL, json=payload, timeout=USAGE_REQUEST_TIMEOUT_SECONDS
)
@inject
def _track_serve_init(
svc: Service,
production: bool,
grpc: bool,
serve_info: ServeInfo = Provide[BentoMLContainer.serve_info],
):
if svc.bento is not None:
bento = svc.bento
event_properties = ServeInitEvent(
serve_id=serve_info.serve_id,
serve_from_bento=True,
production=production,
grpc=grpc,
bento_creation_timestamp=bento.info.creation_time,
num_of_models=len(bento.info.models),
num_of_runners=len(svc.runners),
num_of_apis=len(bento.info.apis),
model_types=[m.module for m in bento.info.models],
runnable_types=[r.runnable_type for r in bento.info.runners],
api_input_types=[api.input_type for api in bento.info.apis],
api_output_types=[api.output_type for api in bento.info.apis],
)
else:
event_properties = ServeInitEvent(
serve_id=serve_info.serve_id,
serve_from_bento=False,
production=production,
grpc=grpc,
bento_creation_timestamp=None,
num_of_models=len(
set(
svc.models
+ [model for runner in svc.runners for model in runner.models]
)
),
num_of_runners=len(svc.runners),
num_of_apis=len(svc.apis.keys()),
runnable_types=[r.runnable_class.__name__ for r in svc.runners],
api_input_types=[api.input.__class__.__name__ for api in svc.apis.values()],
api_output_types=[
api.output.__class__.__name__ for api in svc.apis.values()
],
)
track(event_properties)
EXCLUDE_PATHS = {"/docs.json", "/livez", "/healthz", "/readyz"}
def filter_metrics(
samples: list[Sample], *filters: t.Callable[[list[Sample]], list[Sample]]
):
return [
{**sample.labels, "value": sample.value}
for sample in compose(*filters)(samples)
]
def get_metrics_report(
metrics_client: PrometheusClient,
grpc: bool = False,
) -> tuple[list[dict[str, str | float]], bool | None]:
"""
Get Prometheus metrics reports from the metrics client. This will be used to determine tracking events.
If the return metrics are legacy metrics, the metrics will have prefix BENTOML_, otherwise they will have prefix bentoml_
Args:
metrics_client: Instance of bentoml._internal.server.metrics.prometheus.PrometheusClient
grpc: Whether the metrics are for gRPC server.
Returns:
A tuple of a list of metrics and an optional boolean to determine whether the return metrics are legacy metrics.
"""
for metric in metrics_client.text_string_to_metric_families():
metric_type = t.cast("str", metric.type) # type: ignore (we need to cast due to no prometheus types)
metric_name = t.cast("str", metric.name) # type: ignore (we need to cast due to no prometheus types)
metric_samples = t.cast("list[Sample]", metric.samples) # type: ignore (we need to cast due to no prometheus types)
if metric_type != "counter":
continue
# We only care about the counter metrics.
assert metric_type == "counter"
if grpc:
_filters: list[t.Callable[[list[Sample]], list[Sample]]] = [
lambda samples: [s for s in samples if "api_name" in s.labels]
]
else:
_filters = [
lambda samples: [
s
for s in samples
if not s.labels["endpoint"].startswith("/static_content/")
],
lambda samples: [
s for s in samples if s.labels["endpoint"] not in EXCLUDE_PATHS
],
lambda samples: [s for s in samples if "endpoint" in s.labels],
]
# If metrics prefix is BENTOML_, this is legacy metrics
if metric_name.endswith("_request"):
if metric_name.startswith("BENTOML_"):
# This is the case where we have legacy metrics with
# newer metrics. We will ignore the newer metrics.
return filter_metrics(metric_samples, *_filters), True
else:
# This is the case where we only have newer metrics
assert metric_name.startswith("bentoml_")
return filter_metrics(metric_samples, *_filters), False
return [], None
@inject
@contextlib.contextmanager
def track_serve(
svc: Service,
*,
production: bool = False,
grpc: bool = False,
component: str = "standalone",
metrics_client: PrometheusClient = Provide[BentoMLContainer.metrics_client],
serve_info: ServeInfo = Provide[BentoMLContainer.serve_info],
) -> t.Generator[None, None, None]:
if do_not_track():
yield
return
_track_serve_init(svc=svc, production=production, grpc=grpc)
if _usage_event_debugging():
tracking_interval = 5
else:
tracking_interval = SERVE_USAGE_TRACKING_INTERVAL_SECONDS # pragma: no cover
stop_event = threading.Event()
@silent
def loop() -> t.NoReturn: # type: ignore
last_tracked_timestamp: datetime = serve_info.serve_started_timestamp
while not stop_event.wait(tracking_interval): # pragma: no cover
metrics_type = "not_available"
metrics, use_legacy_metrics = get_metrics_report(metrics_client, grpc=grpc)
if use_legacy_metrics is not None:
metrics_type = "legacy" if use_legacy_metrics else "current"
now = datetime.now(timezone.utc)
event_properties = ServeUpdateEvent(
serve_id=serve_info.serve_id,
production=production,
grpc=grpc,
component=component,
triggered_at=now,
duration_in_seconds=int((now - last_tracked_timestamp).total_seconds()),
metrics_type=metrics_type,
metrics=metrics,
)
last_tracked_timestamp = now
track(event_properties)
tracking_thread = threading.Thread(target=loop, daemon=True)
try:
tracking_thread.start()
yield
finally:
stop_event.set()
tracking_thread.join()