-
-
Notifications
You must be signed in to change notification settings - Fork 864
Expand file tree
/
Copy pathtelemetry.py
More file actions
380 lines (324 loc) · 10.6 KB
/
telemetry.py
File metadata and controls
380 lines (324 loc) · 10.6 KB
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
# Copyright (c) 2014-present PlatformIO <contact@platformio.org>
#
# Licensed 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.
import atexit
import os
import queue
import re
import sys
import threading
import time
import traceback
from collections import deque
import requests
from platformio import __title__, __version__, app, exception, fs, util
from platformio.cli import PlatformioCLI
from platformio.debug.config.base import DebugConfigBase
from platformio.http import HTTPSession
from platformio.proc import is_ci
KEEP_MAX_REPORTS = 100
SEND_MAX_EVENTS = 25
class MeasurementProtocol:
def __init__(self, events=None):
self.client_id = app.get_cid()
self._events = events or []
self._user_properties = {}
self.set_user_property("systype", util.get_systype())
created_at = app.get_state_item("created_at", None)
if created_at:
self.set_user_property("created_at", int(created_at))
@staticmethod
def event_to_dict(name, params, timestamp=None):
event = {"name": name, "params": params}
if timestamp is not None:
event["timestamp"] = timestamp
return event
def set_user_property(self, name, value):
self._user_properties[name] = value
def add_event(self, name, params):
self._events.append(self.event_to_dict(name, params))
def to_payload(self):
return {
"client_id": self.client_id,
"user_properties": self._user_properties,
"events": self._events,
}
@util.singleton
class TelemetryLogger:
def __init__(self):
self._events = deque()
self._sender_thread = None
self._sender_queue = queue.Queue()
self._sender_terminated = False
self._http_session = HTTPSession()
self._http_offline = False
def close(self):
self._http_session.close()
def log_event(self, name, params, timestamp=None, instant_sending=False):
if not app.get_setting("enable_telemetry") or app.get_session_var(
"pause_telemetry"
):
return None
timestamp = timestamp or int(time.time())
self._events.append(
MeasurementProtocol.event_to_dict(name, params, timestamp=timestamp)
)
if self._http_offline: # if network is off-line
return False
if instant_sending:
self.send()
return True
def send(self):
if not self._events or self._sender_terminated:
return
if not self._sender_thread:
self._sender_thread = threading.Thread(
target=self._sender_worker, daemon=True
)
self._sender_thread.start()
while self._events:
events = []
try:
while len(events) < SEND_MAX_EVENTS:
events.append(self._events.popleft())
except IndexError:
pass
self._sender_queue.put(events)
def _sender_worker(self):
while True:
if self._sender_terminated:
return
try:
events = self._sender_queue.get()
if not self._commit_events(events):
self._events.extend(events)
self._sender_queue.task_done()
except (queue.Empty, ValueError):
pass
def _commit_events(self, events):
if self._http_offline:
return False
mp = MeasurementProtocol(events)
payload = mp.to_payload()
# print("_commit_payload", payload)
try:
r = self._http_session.post(
"https://collector.platformio.org/collect",
json=payload,
timeout=(2, 5), # connect, read
)
r.raise_for_status()
return True
except requests.exceptions.HTTPError as exc:
# skip Bad Request
if exc.response.status_code >= 400 and exc.response.status_code < 500:
return True
except: # pylint: disable=bare-except
pass
self._http_offline = True
return False
def terminate_sender(self):
self._sender_terminated = True
def is_sending(self):
return self._sender_queue.unfinished_tasks
def get_unsent_events(self):
result = list(self._events)
try:
while True:
result.extend(self._sender_queue.get_nowait())
except queue.Empty:
pass
return result
def log_event(name, params, instant_sending=False):
TelemetryLogger().log_event(name, params, instant_sending=instant_sending)
def on_cmd_start(cmd_ctx):
process_postponed_logs()
log_command(cmd_ctx)
def on_exit():
TelemetryLogger().send()
def log_command(ctx):
params = {
"path_args": PlatformioCLI.reveal_cmd_path_args(ctx),
}
if is_ci():
params["ci_actor"] = resolve_ci_actor() or "Unknown"
log_event("cmd_run", params)
def resolve_ci_actor():
known_cis = (
"GITHUB_ACTIONS",
"TRAVIS",
"APPVEYOR",
"GITLAB_CI",
"CIRCLECI",
"SHIPPABLE",
"DRONE",
)
for name in known_cis:
if os.getenv(name, "false").lower() == "true":
return name
return None
def dump_project_env_params(config, env, platform):
non_sensitive_data = [
"platform",
"framework",
"board",
"upload_protocol",
"check_tool",
"debug_tool",
"test_framework",
]
section = f"env:{env}"
params = {
option: config.get(section, option)
for option in non_sensitive_data
if config.has_option(section, option)
}
params["pid"] = app.get_project_id(os.path.dirname(config.path))
params["platform_name"] = platform.name
params["platform_version"] = platform.version
return params
def log_platform_run(platform, project_config, project_env, targets=None):
params = dump_project_env_params(project_config, project_env, platform)
if targets:
params["targets"] = targets
log_event("platform_run", params, instant_sending=True)
def log_exception(exc):
skip_conditions = [
isinstance(exc, cls)
for cls in (
IOError,
exception.ReturnErrorCode,
exception.UserSideException,
)
]
skip_conditions.append(not isinstance(exc, Exception))
if any(skip_conditions):
return
is_fatal = any(
[
not isinstance(exc, exception.PlatformioException),
"Error" in exc.__class__.__name__,
]
)
def _strip_module_path(match):
module_path = match.group(1).replace(fs.get_source_dir() + os.sep, "")
sp_folder_name = "site-packages"
sp_pos = module_path.find(sp_folder_name)
if sp_pos != -1:
module_path = module_path[sp_pos + len(sp_folder_name) + 1 :]
module_path = fs.to_unix_path(module_path)
return f'File "{module_path}",'
trace = re.sub(
r'File "([^"]+)",',
_strip_module_path,
traceback.format_exc(),
flags=re.MULTILINE,
)
params = {
"name": exc.__class__.__name__,
"description": str(exc),
"traceback": trace,
"cmd_args": sys.argv[1:],
"is_fatal": is_fatal,
}
log_event("exception", params)
def log_debug_started(debug_config: DebugConfigBase):
log_event(
"debug_started",
dump_project_env_params(
debug_config.project_config, debug_config.env_name, debug_config.platform
),
)
def log_debug_exception(exc, debug_config: DebugConfigBase):
# cleanup sensitive information, such as paths
description = fs.to_unix_path(str(exc))
description = re.sub(
r'(^|\s+|")(?:[a-z]\:)?((/[^"/]+)+)(\s+|"|$)',
lambda m: " %s " % os.path.join(*m.group(2).split("/")[-2:]),
description,
re.I | re.M,
)
params = {
"name": exc.__class__.__name__,
"description": description.strip(),
}
params.update(
dump_project_env_params(
debug_config.project_config, debug_config.env_name, debug_config.platform
)
)
log_event("debug_exception", params)
@atexit.register
def _finalize():
timeout = 1000 # msec
elapsed = 0
telemetry = TelemetryLogger()
telemetry.terminate_sender()
try:
while elapsed < timeout:
if not telemetry.is_sending():
break
time.sleep(0.2)
elapsed += 200
except KeyboardInterrupt:
pass
postpone_events(telemetry.get_unsent_events())
telemetry.close()
def load_postponed_events():
state_path = app.resolve_state_path(
"cache_dir", "telemetry.json", ensure_dir_exists=False
)
if not os.path.isfile(state_path):
return []
with app.State(state_path) as state:
return state.get("events", [])
def save_postponed_events(events):
state_path = app.resolve_state_path("cache_dir", "telemetry.json")
if not events:
try:
if os.path.isfile(state_path):
os.remove(state_path)
except: # pylint: disable=bare-except
pass
return None
with app.State(state_path, lock=True) as state:
state["events"] = events
state.modified = True
return True
def postpone_events(events):
if not events:
return None
postponed_events = load_postponed_events() or []
timestamp = int(time.time())
for event in events:
if "timestamp" not in event:
event["timestamp"] = timestamp
postponed_events.append(event)
save_postponed_events(postponed_events[KEEP_MAX_REPORTS * -1 :])
return True
def process_postponed_logs():
events = load_postponed_events()
if not events:
return None
save_postponed_events([]) # clean
telemetry = TelemetryLogger()
for event in events:
if set(["name", "params", "timestamp"]) <= set(event.keys()):
telemetry.log_event(
event["name"],
event["params"],
timestamp=event["timestamp"],
instant_sending=False,
)
telemetry.send()
return True