pontem 0.0.0__tar.gz
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.
- pontem-0.0.0/LICENSE +201 -0
- pontem-0.0.0/PKG-INFO +143 -0
- pontem-0.0.0/README.md +118 -0
- pontem-0.0.0/pyproject.toml +58 -0
- pontem-0.0.0/src/pontem/__init__.py +27 -0
- pontem-0.0.0/src/pontem/_config.py +87 -0
- pontem-0.0.0/src/pontem/_emit.py +302 -0
- pontem-0.0.0/src/pontem/_metrics.py +241 -0
- pontem-0.0.0/src/pontem/_sdk.py +100 -0
- pontem-0.0.0/src/pontem/log.py +106 -0
pontem-0.0.0/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 Pontem AI, Inc.
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
pontem-0.0.0/PKG-INFO
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pontem
|
|
3
|
+
Version: 0.0.0
|
|
4
|
+
Summary: Pontem edge SDK — logs, metrics, and config for edge devices
|
|
5
|
+
License: Apache-2.0
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Keywords: edge,telemetry,metrics,logging,iot
|
|
8
|
+
Author: Pontem AI, Inc.
|
|
9
|
+
Author-email: support@pontem.ai
|
|
10
|
+
Requires-Python: >=3.9
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Topic :: System :: Monitoring
|
|
20
|
+
Classifier: Typing :: Typed
|
|
21
|
+
Project-URL: Homepage, https://pontemai.com
|
|
22
|
+
Project-URL: Repository, https://github.com/pontemai/pontem-python
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
|
|
25
|
+
# Pontem Python SDK
|
|
26
|
+
|
|
27
|
+
Pontem Python SDK for logs, metrics, and config on Pontem-managed edge devices. Zero runtime dependencies.
|
|
28
|
+
|
|
29
|
+
## Installation
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
pip install pontem
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
<details>
|
|
36
|
+
<summary>Internal / Artifact Registry</summary>
|
|
37
|
+
|
|
38
|
+
One-time local setup:
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
pip install keyrings.google-artifactregistry-auth
|
|
42
|
+
gcloud auth login
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
Add the registry to your project's `pyproject.toml`:
|
|
46
|
+
|
|
47
|
+
```toml
|
|
48
|
+
[[tool.poetry.source]]
|
|
49
|
+
name = "pontem-python"
|
|
50
|
+
url = "https://us-east1-python.pkg.dev/pontem-control-prod/pontem-python/simple/"
|
|
51
|
+
priority = "supplemental"
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Then install:
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
poetry add pontem --source pontem-python
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
</details>
|
|
61
|
+
|
|
62
|
+
## Quick Start
|
|
63
|
+
|
|
64
|
+
```python
|
|
65
|
+
import pontem
|
|
66
|
+
|
|
67
|
+
pontem.init(service_name="my-service")
|
|
68
|
+
|
|
69
|
+
pontem.logger.info("model loaded", model="scoring_v3")
|
|
70
|
+
|
|
71
|
+
pontem.metrics.count("detections", class_name="apple")
|
|
72
|
+
|
|
73
|
+
with pontem.metrics.timer("model.inference"):
|
|
74
|
+
result = model.predict(frame)
|
|
75
|
+
|
|
76
|
+
pontem.shutdown()
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
## Usage
|
|
80
|
+
|
|
81
|
+
### Logging
|
|
82
|
+
|
|
83
|
+
Structured logs with OTel-aligned severity levels. Each log is written to `logs.jsonl` in the emit directory.
|
|
84
|
+
|
|
85
|
+
```python
|
|
86
|
+
pontem.logger.info("model loaded", model="scoring_v3")
|
|
87
|
+
pontem.logger.warn("high latency", latency_ms=120)
|
|
88
|
+
pontem.logger.error("inference failed", error=str(e))
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
Available levels: `trace`, `debug`, `info`, `warn`, `error`, `fatal`.
|
|
92
|
+
|
|
93
|
+
### Metrics
|
|
94
|
+
|
|
95
|
+
Metrics are aggregated in memory and flushed periodically to `metrics.jsonl`. No I/O on the caller's thread.
|
|
96
|
+
|
|
97
|
+
```python
|
|
98
|
+
# Counters — incremented, flushed as a single sum
|
|
99
|
+
pontem.metrics.count("detections", class_name="apple")
|
|
100
|
+
pontem.metrics.count("bytes_sent", len(payload))
|
|
101
|
+
|
|
102
|
+
# Histograms — records min/max/sum/count summary
|
|
103
|
+
pontem.metrics.record("payload_size", len(data), unit="bytes")
|
|
104
|
+
|
|
105
|
+
# Gauges — last value wins
|
|
106
|
+
pontem.metrics.set_gauge("gpu_temp", 72.0, unit="celsius", gpu="0")
|
|
107
|
+
|
|
108
|
+
# Timers — context manager or decorator, records to histogram
|
|
109
|
+
with pontem.metrics.timer("model.inference"):
|
|
110
|
+
result = model.predict(frame)
|
|
111
|
+
|
|
112
|
+
@pontem.metrics.timer("preprocessing")
|
|
113
|
+
def preprocess(frame):
|
|
114
|
+
...
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
### Config
|
|
118
|
+
|
|
119
|
+
Reads agent-managed config from `/etc/pontem/config/config.json` (or `$PONTEM_CONFIG_DIR`).
|
|
120
|
+
|
|
121
|
+
```python
|
|
122
|
+
threshold = pontem.config("my_namespace", "model_threshold", default=0.85)
|
|
123
|
+
|
|
124
|
+
# Reload after agent signals a config update
|
|
125
|
+
pontem.config.reload()
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
### Shutdown
|
|
129
|
+
|
|
130
|
+
Flushes remaining metrics and logs. Also registered via `atexit`.
|
|
131
|
+
|
|
132
|
+
```python
|
|
133
|
+
pontem.shutdown()
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
## Documentation
|
|
137
|
+
|
|
138
|
+
See [docs/getting-started.md](docs/getting-started.md) for a comprehensive guide including full API reference, configuration options, and troubleshooting.
|
|
139
|
+
|
|
140
|
+
## License
|
|
141
|
+
|
|
142
|
+
Apache 2.0 — see [LICENSE](LICENSE).
|
|
143
|
+
|
pontem-0.0.0/README.md
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
# Pontem Python SDK
|
|
2
|
+
|
|
3
|
+
Pontem Python SDK for logs, metrics, and config on Pontem-managed edge devices. Zero runtime dependencies.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install pontem
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
<details>
|
|
12
|
+
<summary>Internal / Artifact Registry</summary>
|
|
13
|
+
|
|
14
|
+
One-time local setup:
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
pip install keyrings.google-artifactregistry-auth
|
|
18
|
+
gcloud auth login
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Add the registry to your project's `pyproject.toml`:
|
|
22
|
+
|
|
23
|
+
```toml
|
|
24
|
+
[[tool.poetry.source]]
|
|
25
|
+
name = "pontem-python"
|
|
26
|
+
url = "https://us-east1-python.pkg.dev/pontem-control-prod/pontem-python/simple/"
|
|
27
|
+
priority = "supplemental"
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Then install:
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
poetry add pontem --source pontem-python
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
</details>
|
|
37
|
+
|
|
38
|
+
## Quick Start
|
|
39
|
+
|
|
40
|
+
```python
|
|
41
|
+
import pontem
|
|
42
|
+
|
|
43
|
+
pontem.init(service_name="my-service")
|
|
44
|
+
|
|
45
|
+
pontem.logger.info("model loaded", model="scoring_v3")
|
|
46
|
+
|
|
47
|
+
pontem.metrics.count("detections", class_name="apple")
|
|
48
|
+
|
|
49
|
+
with pontem.metrics.timer("model.inference"):
|
|
50
|
+
result = model.predict(frame)
|
|
51
|
+
|
|
52
|
+
pontem.shutdown()
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## Usage
|
|
56
|
+
|
|
57
|
+
### Logging
|
|
58
|
+
|
|
59
|
+
Structured logs with OTel-aligned severity levels. Each log is written to `logs.jsonl` in the emit directory.
|
|
60
|
+
|
|
61
|
+
```python
|
|
62
|
+
pontem.logger.info("model loaded", model="scoring_v3")
|
|
63
|
+
pontem.logger.warn("high latency", latency_ms=120)
|
|
64
|
+
pontem.logger.error("inference failed", error=str(e))
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
Available levels: `trace`, `debug`, `info`, `warn`, `error`, `fatal`.
|
|
68
|
+
|
|
69
|
+
### Metrics
|
|
70
|
+
|
|
71
|
+
Metrics are aggregated in memory and flushed periodically to `metrics.jsonl`. No I/O on the caller's thread.
|
|
72
|
+
|
|
73
|
+
```python
|
|
74
|
+
# Counters — incremented, flushed as a single sum
|
|
75
|
+
pontem.metrics.count("detections", class_name="apple")
|
|
76
|
+
pontem.metrics.count("bytes_sent", len(payload))
|
|
77
|
+
|
|
78
|
+
# Histograms — records min/max/sum/count summary
|
|
79
|
+
pontem.metrics.record("payload_size", len(data), unit="bytes")
|
|
80
|
+
|
|
81
|
+
# Gauges — last value wins
|
|
82
|
+
pontem.metrics.set_gauge("gpu_temp", 72.0, unit="celsius", gpu="0")
|
|
83
|
+
|
|
84
|
+
# Timers — context manager or decorator, records to histogram
|
|
85
|
+
with pontem.metrics.timer("model.inference"):
|
|
86
|
+
result = model.predict(frame)
|
|
87
|
+
|
|
88
|
+
@pontem.metrics.timer("preprocessing")
|
|
89
|
+
def preprocess(frame):
|
|
90
|
+
...
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
### Config
|
|
94
|
+
|
|
95
|
+
Reads agent-managed config from `/etc/pontem/config/config.json` (or `$PONTEM_CONFIG_DIR`).
|
|
96
|
+
|
|
97
|
+
```python
|
|
98
|
+
threshold = pontem.config("my_namespace", "model_threshold", default=0.85)
|
|
99
|
+
|
|
100
|
+
# Reload after agent signals a config update
|
|
101
|
+
pontem.config.reload()
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
### Shutdown
|
|
105
|
+
|
|
106
|
+
Flushes remaining metrics and logs. Also registered via `atexit`.
|
|
107
|
+
|
|
108
|
+
```python
|
|
109
|
+
pontem.shutdown()
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
## Documentation
|
|
113
|
+
|
|
114
|
+
See [docs/getting-started.md](docs/getting-started.md) for a comprehensive guide including full API reference, configuration options, and troubleshooting.
|
|
115
|
+
|
|
116
|
+
## License
|
|
117
|
+
|
|
118
|
+
Apache 2.0 — see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "pontem"
|
|
3
|
+
version = "0.0.0"
|
|
4
|
+
description = "Pontem edge SDK — logs, metrics, and config for edge devices"
|
|
5
|
+
authors = [
|
|
6
|
+
{name = "Pontem AI, Inc.", email = "support@pontem.ai"},
|
|
7
|
+
]
|
|
8
|
+
license = {text = "Apache-2.0"}
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
keywords = ["edge", "telemetry", "metrics", "logging", "iot"]
|
|
12
|
+
classifiers = [
|
|
13
|
+
"Development Status :: 4 - Beta",
|
|
14
|
+
"Intended Audience :: Developers",
|
|
15
|
+
"License :: OSI Approved :: Apache Software License",
|
|
16
|
+
"Programming Language :: Python :: 3",
|
|
17
|
+
"Programming Language :: Python :: 3.9",
|
|
18
|
+
"Programming Language :: Python :: 3.10",
|
|
19
|
+
"Programming Language :: Python :: 3.11",
|
|
20
|
+
"Programming Language :: Python :: 3.12",
|
|
21
|
+
"Topic :: System :: Monitoring",
|
|
22
|
+
"Typing :: Typed",
|
|
23
|
+
]
|
|
24
|
+
dynamic = ["version"]
|
|
25
|
+
|
|
26
|
+
[project.urls]
|
|
27
|
+
Homepage = "https://pontemai.com"
|
|
28
|
+
Repository = "https://github.com/pontemai/pontem-python"
|
|
29
|
+
|
|
30
|
+
[tool.poetry]
|
|
31
|
+
packages = [{include = "pontem", from = "src"}]
|
|
32
|
+
|
|
33
|
+
[tool.poetry.group.dev.dependencies]
|
|
34
|
+
pytest = "^8.0"
|
|
35
|
+
ruff = "^0.8"
|
|
36
|
+
|
|
37
|
+
[tool.poetry-dynamic-versioning]
|
|
38
|
+
enable = true
|
|
39
|
+
vcs = "git"
|
|
40
|
+
style = "semver"
|
|
41
|
+
strict = false
|
|
42
|
+
pattern = "^(?P<base>\\d+\\.\\d+\\.\\d+)$"
|
|
43
|
+
bump = true
|
|
44
|
+
|
|
45
|
+
[tool.ruff]
|
|
46
|
+
target-version = "py39"
|
|
47
|
+
line-length = 88
|
|
48
|
+
|
|
49
|
+
[tool.ruff.lint]
|
|
50
|
+
select = ["E", "F", "I", "UP"]
|
|
51
|
+
|
|
52
|
+
[tool.pytest.ini_options]
|
|
53
|
+
testpaths = ["tests"]
|
|
54
|
+
python_files = "test_*.py"
|
|
55
|
+
|
|
56
|
+
[build-system]
|
|
57
|
+
requires = ["poetry-core>=1.0.0", "poetry-dynamic-versioning>=1.0.0,<2.0.0"]
|
|
58
|
+
build-backend = "poetry_dynamic_versioning.backend"
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""Pontem edge SDK.
|
|
2
|
+
|
|
3
|
+
Zero dependencies. One-line install, one-line instrumentation::
|
|
4
|
+
|
|
5
|
+
import pontem
|
|
6
|
+
|
|
7
|
+
pontem.init(service_name="my-service")
|
|
8
|
+
pontem.logger.info("model loaded", model="scoring_v3")
|
|
9
|
+
|
|
10
|
+
with pontem.metrics.timer("model.inference"):
|
|
11
|
+
result = model.predict(frame)
|
|
12
|
+
|
|
13
|
+
pontem.metrics.count("detections", class_name="apple")
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from pontem._config import config
|
|
17
|
+
from pontem._metrics import metrics
|
|
18
|
+
from pontem._sdk import init, shutdown
|
|
19
|
+
from pontem.log import logger
|
|
20
|
+
|
|
21
|
+
__all__ = [
|
|
22
|
+
"init",
|
|
23
|
+
"shutdown",
|
|
24
|
+
"logger",
|
|
25
|
+
"metrics",
|
|
26
|
+
"config",
|
|
27
|
+
]
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""Configuration reader for Pontem agent-managed config."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import logging
|
|
7
|
+
import os
|
|
8
|
+
from typing import Any, TypeVar, overload
|
|
9
|
+
|
|
10
|
+
_logger = logging.getLogger("pontem.config")
|
|
11
|
+
|
|
12
|
+
T = TypeVar("T")
|
|
13
|
+
|
|
14
|
+
_DEFAULT_CONFIG_DIR = "/etc/pontem/config"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class Config:
|
|
18
|
+
"""Callable config reader with reload support.
|
|
19
|
+
|
|
20
|
+
Example::
|
|
21
|
+
|
|
22
|
+
import pontem
|
|
23
|
+
|
|
24
|
+
threshold = pontem.config("model_threshold", default=0.85)
|
|
25
|
+
pontem.config.reload() # re-read from disk
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
def __init__(self) -> None:
|
|
29
|
+
self._cache: dict[str, Any] | None = None
|
|
30
|
+
|
|
31
|
+
def _load(self) -> dict[str, Any]:
|
|
32
|
+
"""Load config from the agent-managed JSON file."""
|
|
33
|
+
if self._cache is not None:
|
|
34
|
+
return self._cache
|
|
35
|
+
|
|
36
|
+
config_dir = os.environ.get("PONTEM_CONFIG_DIR", _DEFAULT_CONFIG_DIR)
|
|
37
|
+
config_file = os.path.join(config_dir, "config.json")
|
|
38
|
+
|
|
39
|
+
try:
|
|
40
|
+
with open(config_file) as f:
|
|
41
|
+
self._cache = json.load(f)
|
|
42
|
+
except FileNotFoundError:
|
|
43
|
+
_logger.debug("No agent config at %s, using defaults", config_file)
|
|
44
|
+
self._cache = {}
|
|
45
|
+
except json.JSONDecodeError:
|
|
46
|
+
_logger.warning("Invalid JSON in %s, using defaults", config_file)
|
|
47
|
+
self._cache = {}
|
|
48
|
+
|
|
49
|
+
return self._cache
|
|
50
|
+
|
|
51
|
+
@overload
|
|
52
|
+
def __call__(self, namespace: str, key: str) -> str | None: ...
|
|
53
|
+
|
|
54
|
+
@overload
|
|
55
|
+
def __call__(self, namespace: str, key: str, *, default: T) -> T: ...
|
|
56
|
+
|
|
57
|
+
def __call__(self, namespace: str, key: str, *, default: Any = None) -> Any:
|
|
58
|
+
"""Read a config value managed by the Pontem agent.
|
|
59
|
+
|
|
60
|
+
Example::
|
|
61
|
+
|
|
62
|
+
pontem.config("x:y:z", "keyA")
|
|
63
|
+
pontem.config("x:y:z", "keyA", default=0.85)
|
|
64
|
+
|
|
65
|
+
Args:
|
|
66
|
+
namespace: Namespace prefix (e.g. ``"x:y:z"``).
|
|
67
|
+
key: Config key (e.g. ``"keyA"``).
|
|
68
|
+
default: Fallback value if key is not found.
|
|
69
|
+
"""
|
|
70
|
+
full_key = f"{namespace}:{key}"
|
|
71
|
+
|
|
72
|
+
data = self._load()
|
|
73
|
+
if full_key in data:
|
|
74
|
+
return data[full_key]
|
|
75
|
+
|
|
76
|
+
return default
|
|
77
|
+
|
|
78
|
+
def reload(self) -> None:
|
|
79
|
+
"""Force re-read of config from disk on next access.
|
|
80
|
+
|
|
81
|
+
Call after the agent signals a config update (e.g. via inotify or
|
|
82
|
+
a SIGHUP handler).
|
|
83
|
+
"""
|
|
84
|
+
self._cache = None
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
config = Config()
|
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
"""File-based telemetry emission.
|
|
2
|
+
|
|
3
|
+
Writes structured JSONL to a directory the Pontem agent watches.
|
|
4
|
+
The agent reads rotated files and ships them to the cloud.
|
|
5
|
+
|
|
6
|
+
Layout::
|
|
7
|
+
|
|
8
|
+
$PONTEM_EMIT_DIR/
|
|
9
|
+
logs.jsonl <- active (SDK writes here)
|
|
10
|
+
logs.jsonl.1713100000.gz <- rotated + compressed (agent picks up + deletes)
|
|
11
|
+
metrics.jsonl
|
|
12
|
+
metrics.jsonl.1713099000.gz
|
|
13
|
+
|
|
14
|
+
Architecture::
|
|
15
|
+
|
|
16
|
+
Caller thread Background thread (pontem-emit)
|
|
17
|
+
───────────── ──────────────────────────────
|
|
18
|
+
pontem.logger.info(...) wakes every _flush_interval
|
|
19
|
+
→ queue.put_nowait() drains log queue → batch write
|
|
20
|
+
→ returns (~2µs) collects aggregated metrics
|
|
21
|
+
writes metric summaries
|
|
22
|
+
pontem.metrics.count(...) single flush() across all files
|
|
23
|
+
→ lock, dict += 1, unlock checks sizes → rotate if needed
|
|
24
|
+
→ returns (~100ns) sleeps
|
|
25
|
+
|
|
26
|
+
* **Non-blocking** — log emit enqueues to a bounded buffer; metric
|
|
27
|
+
calls just update in-memory aggregation state.
|
|
28
|
+
* **Bounded disk** — files rotate at a size threshold; old rotated
|
|
29
|
+
files are pruned.
|
|
30
|
+
* **Thread-safe** — multiple threads can call emit/count concurrently.
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
from __future__ import annotations
|
|
34
|
+
|
|
35
|
+
import gzip
|
|
36
|
+
import json
|
|
37
|
+
import logging
|
|
38
|
+
import os
|
|
39
|
+
import queue
|
|
40
|
+
import shutil
|
|
41
|
+
import threading
|
|
42
|
+
import time
|
|
43
|
+
from collections.abc import Callable
|
|
44
|
+
from pathlib import Path
|
|
45
|
+
from typing import Any, TextIO
|
|
46
|
+
|
|
47
|
+
_logger = logging.getLogger("pontem.emit")
|
|
48
|
+
|
|
49
|
+
# -- Public state --------------------------------------------------------------
|
|
50
|
+
|
|
51
|
+
_emit_dir: Path | None = None
|
|
52
|
+
_resource: dict[str, Any] = {}
|
|
53
|
+
|
|
54
|
+
# -- Defaults ------------------------------------------------------------------
|
|
55
|
+
|
|
56
|
+
DEFAULT_MAX_FILE_BYTES = 10 * 1024 * 1024 # 10 MB per channel file
|
|
57
|
+
DEFAULT_MAX_ROTATED = 5 # keep last N rotated files per channel
|
|
58
|
+
DEFAULT_FLUSH_INTERVAL = 1.0 # seconds between background flushes
|
|
59
|
+
DEFAULT_QUEUE_SIZE = 10_000 # max buffered records before dropping
|
|
60
|
+
|
|
61
|
+
# -- Internal state ------------------------------------------------------------
|
|
62
|
+
|
|
63
|
+
_max_file_bytes = DEFAULT_MAX_FILE_BYTES
|
|
64
|
+
_max_rotated = DEFAULT_MAX_ROTATED
|
|
65
|
+
_flush_interval = DEFAULT_FLUSH_INTERVAL
|
|
66
|
+
|
|
67
|
+
_queue: queue.Queue[tuple[str, str] | None] = queue.Queue(
|
|
68
|
+
maxsize=DEFAULT_QUEUE_SIZE,
|
|
69
|
+
)
|
|
70
|
+
_thread: threading.Thread | None = None
|
|
71
|
+
_stop = threading.Event()
|
|
72
|
+
|
|
73
|
+
# Periodic callbacks — called each cycle to collect aggregated data.
|
|
74
|
+
# Each returns a list of (channel, record_dict) tuples.
|
|
75
|
+
_periodic: list[Callable[[], list[tuple[str, dict[str, Any]]]]] = []
|
|
76
|
+
|
|
77
|
+
# Accessed only from the writer thread:
|
|
78
|
+
_files: dict[str, TextIO] = {}
|
|
79
|
+
_file_sizes: dict[str, int] = {}
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def configure(
|
|
83
|
+
emit_dir: str | None = None,
|
|
84
|
+
resource: dict[str, Any] | None = None,
|
|
85
|
+
*,
|
|
86
|
+
max_file_bytes: int = DEFAULT_MAX_FILE_BYTES,
|
|
87
|
+
max_rotated_files: int = DEFAULT_MAX_ROTATED,
|
|
88
|
+
flush_interval: float = DEFAULT_FLUSH_INTERVAL,
|
|
89
|
+
) -> Path | None:
|
|
90
|
+
"""Set up the emit directory and start the background writer.
|
|
91
|
+
|
|
92
|
+
Returns the resolved path, or ``None`` if no emit directory is set.
|
|
93
|
+
"""
|
|
94
|
+
global _emit_dir, _resource, _thread
|
|
95
|
+
global _max_file_bytes, _max_rotated, _flush_interval
|
|
96
|
+
|
|
97
|
+
path = emit_dir or os.environ.get("PONTEM_EMIT_DIR")
|
|
98
|
+
if not path:
|
|
99
|
+
return None
|
|
100
|
+
|
|
101
|
+
_emit_dir = Path(path)
|
|
102
|
+
_emit_dir.mkdir(parents=True, exist_ok=True)
|
|
103
|
+
_resource = resource or {}
|
|
104
|
+
|
|
105
|
+
_max_file_bytes = max_file_bytes
|
|
106
|
+
_max_rotated = max_rotated_files
|
|
107
|
+
_flush_interval = flush_interval
|
|
108
|
+
|
|
109
|
+
# Start background writer if not already running.
|
|
110
|
+
if _thread is None or not _thread.is_alive():
|
|
111
|
+
_stop.clear()
|
|
112
|
+
_thread = threading.Thread(
|
|
113
|
+
target=_writer_loop,
|
|
114
|
+
daemon=True,
|
|
115
|
+
name="pontem-emit",
|
|
116
|
+
)
|
|
117
|
+
_thread.start()
|
|
118
|
+
|
|
119
|
+
return _emit_dir
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def register_periodic(
|
|
123
|
+
fn: Callable[[], list[tuple[str, dict[str, Any]]]],
|
|
124
|
+
) -> None:
|
|
125
|
+
"""Register a callback invoked each flush cycle.
|
|
126
|
+
|
|
127
|
+
The callback should return ``(channel, record_dict)`` tuples.
|
|
128
|
+
Used by ``_metrics._collect()`` to flush aggregated metrics.
|
|
129
|
+
"""
|
|
130
|
+
_periodic.append(fn)
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def emit(channel: str, record: dict[str, Any]) -> None:
|
|
134
|
+
"""Enqueue a telemetry record. Non-blocking; drops if buffer full.
|
|
135
|
+
|
|
136
|
+
Used for logs (each record is unique). Metrics use aggregation
|
|
137
|
+
instead — see ``_metrics.py``.
|
|
138
|
+
"""
|
|
139
|
+
if _emit_dir is None:
|
|
140
|
+
return
|
|
141
|
+
record["timestamp"] = time.time()
|
|
142
|
+
record["resource"] = _resource
|
|
143
|
+
line = json.dumps(record, separators=(",", ":"), default=str)
|
|
144
|
+
try:
|
|
145
|
+
_queue.put_nowait((channel, line))
|
|
146
|
+
except queue.Full:
|
|
147
|
+
# Back-pressure: drop rather than block the caller.
|
|
148
|
+
_logger.debug("emit queue full, dropping record on %s", channel)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def close() -> None:
|
|
152
|
+
"""Drain remaining records, flush files, and stop the writer thread."""
|
|
153
|
+
global _thread, _emit_dir
|
|
154
|
+
_stop.set()
|
|
155
|
+
if _thread is not None:
|
|
156
|
+
_thread.join(timeout=5.0)
|
|
157
|
+
if _thread.is_alive():
|
|
158
|
+
_logger.warning(
|
|
159
|
+
"pontem-emit: writer thread did not exit in 5s, "
|
|
160
|
+
"buffered data may be lost"
|
|
161
|
+
)
|
|
162
|
+
_thread = None
|
|
163
|
+
|
|
164
|
+
# Thread has exited — safe to close files from this thread.
|
|
165
|
+
for f in _files.values():
|
|
166
|
+
try:
|
|
167
|
+
f.flush()
|
|
168
|
+
f.close()
|
|
169
|
+
except OSError:
|
|
170
|
+
pass
|
|
171
|
+
_files.clear()
|
|
172
|
+
_file_sizes.clear()
|
|
173
|
+
_emit_dir = None
|
|
174
|
+
_stop.clear()
|
|
175
|
+
_periodic.clear()
|
|
176
|
+
|
|
177
|
+
# Discard any stragglers left after thread timeout.
|
|
178
|
+
while not _queue.empty():
|
|
179
|
+
try:
|
|
180
|
+
_queue.get_nowait()
|
|
181
|
+
except queue.Empty:
|
|
182
|
+
break
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
# -- Background writer ---------------------------------------------------------
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _writer_loop() -> None:
|
|
189
|
+
"""Drain queue, collect aggregated metrics, write, flush. Daemon thread."""
|
|
190
|
+
while not _stop.is_set():
|
|
191
|
+
try:
|
|
192
|
+
_drain()
|
|
193
|
+
_collect_periodic()
|
|
194
|
+
_flush_all()
|
|
195
|
+
except Exception:
|
|
196
|
+
_logger.exception("pontem-emit: error in writer loop")
|
|
197
|
+
_stop.wait(_flush_interval)
|
|
198
|
+
# Final cycle before exit.
|
|
199
|
+
try:
|
|
200
|
+
_drain()
|
|
201
|
+
_collect_periodic()
|
|
202
|
+
_flush_all()
|
|
203
|
+
except Exception:
|
|
204
|
+
_logger.exception("pontem-emit: error in final flush")
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _drain() -> None:
|
|
208
|
+
"""Pull all available records from the queue and write in batches."""
|
|
209
|
+
batches: dict[str, list[str]] = {}
|
|
210
|
+
while True:
|
|
211
|
+
try:
|
|
212
|
+
item = _queue.get_nowait()
|
|
213
|
+
except queue.Empty:
|
|
214
|
+
break
|
|
215
|
+
if item is None:
|
|
216
|
+
continue
|
|
217
|
+
channel, line = item
|
|
218
|
+
batches.setdefault(channel, []).append(line)
|
|
219
|
+
|
|
220
|
+
for channel, lines in batches.items():
|
|
221
|
+
_write_lines(channel, lines)
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def _collect_periodic() -> None:
|
|
225
|
+
"""Run registered periodic callbacks and write their output."""
|
|
226
|
+
for cb in _periodic:
|
|
227
|
+
batches: dict[str, list[str]] = {}
|
|
228
|
+
for channel, record in cb():
|
|
229
|
+
record["timestamp"] = time.time()
|
|
230
|
+
record["resource"] = _resource
|
|
231
|
+
line = json.dumps(record, separators=(",", ":"), default=str)
|
|
232
|
+
batches.setdefault(channel, []).append(line)
|
|
233
|
+
for channel, lines in batches.items():
|
|
234
|
+
_write_lines(channel, lines)
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def _flush_all() -> None:
|
|
238
|
+
"""Single flush across all open file handles.
|
|
239
|
+
|
|
240
|
+
Called once per cycle — NOT per record or per channel. Same
|
|
241
|
+
pattern as Java's AsyncAppender and Python's QueueListener.
|
|
242
|
+
"""
|
|
243
|
+
for f in _files.values():
|
|
244
|
+
f.flush()
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _write_lines(channel: str, lines: list[str]) -> None:
|
|
248
|
+
"""Write a batch of serialized JSON lines, rotating if needed.
|
|
249
|
+
|
|
250
|
+
Does NOT flush — the caller flushes once after all channels
|
|
251
|
+
are written.
|
|
252
|
+
"""
|
|
253
|
+
if _emit_dir is None:
|
|
254
|
+
return
|
|
255
|
+
|
|
256
|
+
f = _files.get(channel)
|
|
257
|
+
if f is None:
|
|
258
|
+
filepath = _emit_dir / channel
|
|
259
|
+
f = open(filepath, "a") # noqa: SIM115
|
|
260
|
+
_files[channel] = f
|
|
261
|
+
_file_sizes[channel] = os.fstat(f.fileno()).st_size
|
|
262
|
+
|
|
263
|
+
payload = "\n".join(lines) + "\n"
|
|
264
|
+
f.write(payload)
|
|
265
|
+
_file_sizes[channel] = _file_sizes.get(channel, 0) + len(payload)
|
|
266
|
+
|
|
267
|
+
if _file_sizes[channel] >= _max_file_bytes:
|
|
268
|
+
_rotate(channel)
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def _rotate(channel: str) -> None:
|
|
272
|
+
"""Close the active file, rename with timestamp, compress, prune old files."""
|
|
273
|
+
f = _files.pop(channel, None)
|
|
274
|
+
if f:
|
|
275
|
+
f.flush()
|
|
276
|
+
f.close()
|
|
277
|
+
_file_sizes.pop(channel, None)
|
|
278
|
+
|
|
279
|
+
if _emit_dir is None:
|
|
280
|
+
return
|
|
281
|
+
|
|
282
|
+
src = _emit_dir / channel
|
|
283
|
+
if src.exists():
|
|
284
|
+
dst = _emit_dir / f"{channel}.{time.time_ns()}"
|
|
285
|
+
src.rename(dst)
|
|
286
|
+
_compress_gz(dst)
|
|
287
|
+
|
|
288
|
+
# Prune oldest rotated files beyond the cap.
|
|
289
|
+
rotated = sorted(
|
|
290
|
+
_emit_dir.glob(f"{channel}.*"),
|
|
291
|
+
key=lambda p: p.stat().st_mtime,
|
|
292
|
+
)
|
|
293
|
+
while len(rotated) > _max_rotated:
|
|
294
|
+
rotated.pop(0).unlink()
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def _compress_gz(path: Path) -> None:
|
|
298
|
+
"""Gzip-compress a file in place. Replaces original with .gz."""
|
|
299
|
+
gz_path = Path(str(path) + ".gz")
|
|
300
|
+
with open(path, "rb") as f_in, gzip.open(gz_path, "wb") as f_out:
|
|
301
|
+
shutil.copyfileobj(f_in, f_out)
|
|
302
|
+
path.unlink()
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
"""Metrics instrumentation with client-side aggregation.
|
|
2
|
+
|
|
3
|
+
Metrics are accumulated in memory and flushed periodically by the
|
|
4
|
+
background emitter thread — the same pattern used by OTel's
|
|
5
|
+
``PeriodicExportingMetricReader``, Prometheus client, and Micrometer.
|
|
6
|
+
|
|
7
|
+
The caller's hot path is a lock + dict update (~100ns). No JSON
|
|
8
|
+
serialization, no queue, no disk I/O.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import functools
|
|
14
|
+
import threading
|
|
15
|
+
import time
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
# -- Aggregation state ---------------------------------------------------------
|
|
19
|
+
|
|
20
|
+
_lock = threading.Lock()
|
|
21
|
+
|
|
22
|
+
# Key: (name, unit, frozenset of attribute items)
|
|
23
|
+
_Key = tuple[str, str, frozenset[tuple[str, Any]]]
|
|
24
|
+
|
|
25
|
+
_EMPTY_ATTRS: frozenset[tuple[str, Any]] = frozenset()
|
|
26
|
+
|
|
27
|
+
_counters: dict[_Key, float] = {}
|
|
28
|
+
_gauges: dict[_Key, float] = {}
|
|
29
|
+
_histograms: dict[_Key, _HistogramAcc] = {}
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class _HistogramAcc:
|
|
33
|
+
"""Running min/max/sum/count accumulator for histogram values."""
|
|
34
|
+
|
|
35
|
+
__slots__ = ("count", "total", "mn", "mx")
|
|
36
|
+
|
|
37
|
+
def __init__(self) -> None:
|
|
38
|
+
self.count = 0
|
|
39
|
+
self.total = 0.0
|
|
40
|
+
self.mn = float("inf")
|
|
41
|
+
self.mx = float("-inf")
|
|
42
|
+
|
|
43
|
+
def add(self, value: float) -> None:
|
|
44
|
+
self.count += 1
|
|
45
|
+
self.total += value
|
|
46
|
+
if value < self.mn:
|
|
47
|
+
self.mn = value
|
|
48
|
+
if value > self.mx:
|
|
49
|
+
self.mx = value
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
# -- Timer (private) -----------------------------------------------------------
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class _Timer:
|
|
56
|
+
"""Time a block of code. Context manager and decorator.
|
|
57
|
+
|
|
58
|
+
As context manager::
|
|
59
|
+
|
|
60
|
+
with pontem.metrics.timer("model.inference"):
|
|
61
|
+
result = model.predict(frame)
|
|
62
|
+
|
|
63
|
+
As decorator::
|
|
64
|
+
|
|
65
|
+
@pontem.metrics.timer("model.inference")
|
|
66
|
+
def predict(frame):
|
|
67
|
+
...
|
|
68
|
+
|
|
69
|
+
Records elapsed seconds to a histogram.
|
|
70
|
+
"""
|
|
71
|
+
|
|
72
|
+
def __init__(self, name: str, *, unit: str = "s", **attrs: Any) -> None:
|
|
73
|
+
self._name = name
|
|
74
|
+
self._unit = unit
|
|
75
|
+
self._attrs = attrs
|
|
76
|
+
self._start: float = 0
|
|
77
|
+
|
|
78
|
+
def __enter__(self) -> _Timer:
|
|
79
|
+
self._start = time.perf_counter()
|
|
80
|
+
return self
|
|
81
|
+
|
|
82
|
+
def __exit__(self, *exc: Any) -> bool:
|
|
83
|
+
elapsed = time.perf_counter() - self._start
|
|
84
|
+
key = (
|
|
85
|
+
self._name,
|
|
86
|
+
self._unit,
|
|
87
|
+
frozenset(self._attrs.items()) if self._attrs else _EMPTY_ATTRS,
|
|
88
|
+
)
|
|
89
|
+
with _lock:
|
|
90
|
+
acc = _histograms.get(key)
|
|
91
|
+
if acc is None:
|
|
92
|
+
acc = _HistogramAcc()
|
|
93
|
+
_histograms[key] = acc
|
|
94
|
+
acc.add(elapsed)
|
|
95
|
+
return False
|
|
96
|
+
|
|
97
|
+
def __call__(self, fn: Any) -> Any:
|
|
98
|
+
@functools.wraps(fn)
|
|
99
|
+
def wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
100
|
+
with _Timer(self._name, unit=self._unit, **self._attrs):
|
|
101
|
+
return fn(*args, **kwargs)
|
|
102
|
+
|
|
103
|
+
return wrapper
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
# -- Public API ----------------------------------------------------------------
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
class Metrics:
|
|
110
|
+
"""Namespace for metric instrumentation functions."""
|
|
111
|
+
|
|
112
|
+
def count(self, name: str, amount: float = 1, **attrs: Any) -> None:
|
|
113
|
+
"""Increment a counter.
|
|
114
|
+
|
|
115
|
+
Example::
|
|
116
|
+
|
|
117
|
+
pontem.metrics.count("detections", class_name="apple")
|
|
118
|
+
pontem.metrics.count("bytes_sent", len(payload))
|
|
119
|
+
"""
|
|
120
|
+
key = (name, "", frozenset(attrs.items()) if attrs else _EMPTY_ATTRS)
|
|
121
|
+
with _lock:
|
|
122
|
+
_counters[key] = _counters.get(key, 0) + amount
|
|
123
|
+
|
|
124
|
+
def record(self, name: str, value: float, *, unit: str = "", **attrs: Any) -> None:
|
|
125
|
+
"""Record a value to a histogram.
|
|
126
|
+
|
|
127
|
+
Accumulates count/sum/min/max and flushes as a summary each
|
|
128
|
+
interval — the standard approach used by OTel and Prometheus.
|
|
129
|
+
|
|
130
|
+
Example::
|
|
131
|
+
|
|
132
|
+
pontem.metrics.record("payload_size", len(data), unit="bytes")
|
|
133
|
+
"""
|
|
134
|
+
key = (name, unit, frozenset(attrs.items()) if attrs else _EMPTY_ATTRS)
|
|
135
|
+
with _lock:
|
|
136
|
+
acc = _histograms.get(key)
|
|
137
|
+
if acc is None:
|
|
138
|
+
acc = _HistogramAcc()
|
|
139
|
+
_histograms[key] = acc
|
|
140
|
+
acc.add(value)
|
|
141
|
+
|
|
142
|
+
def set_gauge(
|
|
143
|
+
self, name: str, value: float, *, unit: str = "", **attrs: Any
|
|
144
|
+
) -> None:
|
|
145
|
+
"""Set a gauge to a point-in-time value.
|
|
146
|
+
|
|
147
|
+
Only the latest value per interval is emitted.
|
|
148
|
+
|
|
149
|
+
Example::
|
|
150
|
+
|
|
151
|
+
pontem.metrics.set_gauge("gpu_temperature", 72.0, unit="celsius", gpu="0")
|
|
152
|
+
"""
|
|
153
|
+
key = (name, unit, frozenset(attrs.items()) if attrs else _EMPTY_ATTRS)
|
|
154
|
+
with _lock:
|
|
155
|
+
_gauges[key] = value
|
|
156
|
+
|
|
157
|
+
def timer(self, name: str, *, unit: str = "s", **attrs: Any) -> _Timer:
|
|
158
|
+
"""Time a block of code. Returns a context manager / decorator.
|
|
159
|
+
|
|
160
|
+
Example::
|
|
161
|
+
|
|
162
|
+
with pontem.metrics.timer("model.inference"):
|
|
163
|
+
result = model.predict(frame)
|
|
164
|
+
"""
|
|
165
|
+
return _Timer(name, unit=unit, **attrs)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
metrics = Metrics()
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
# -- Collection (called by the emit background thread) -------------------------
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _collect() -> list[tuple[str, dict[str, Any]]]:
|
|
175
|
+
"""Swap out accumulated metrics and return serializable records.
|
|
176
|
+
|
|
177
|
+
Returns a list of ``(channel, record_dict)`` tuples. The emit
|
|
178
|
+
thread adds ``timestamp`` and ``resource`` before writing.
|
|
179
|
+
|
|
180
|
+
The lock is held only during the swap (O(1) reference swap) —
|
|
181
|
+
building output records happens outside the lock.
|
|
182
|
+
"""
|
|
183
|
+
global _counters, _gauges, _histograms
|
|
184
|
+
with _lock:
|
|
185
|
+
counters = _counters
|
|
186
|
+
_counters = {}
|
|
187
|
+
gauges = _gauges
|
|
188
|
+
_gauges = {}
|
|
189
|
+
histograms = _histograms
|
|
190
|
+
_histograms = {}
|
|
191
|
+
|
|
192
|
+
results: list[tuple[str, dict[str, Any]]] = []
|
|
193
|
+
|
|
194
|
+
for (name, unit, attrs_frozen), total in counters.items():
|
|
195
|
+
rec: dict[str, Any] = {
|
|
196
|
+
"name": name,
|
|
197
|
+
"type": "counter",
|
|
198
|
+
"value": total,
|
|
199
|
+
"attributes": dict(attrs_frozen),
|
|
200
|
+
}
|
|
201
|
+
if unit:
|
|
202
|
+
rec["unit"] = unit
|
|
203
|
+
results.append(("metrics.jsonl", rec))
|
|
204
|
+
|
|
205
|
+
for (name, unit, attrs_frozen), value in gauges.items():
|
|
206
|
+
rec = {
|
|
207
|
+
"name": name,
|
|
208
|
+
"type": "gauge",
|
|
209
|
+
"value": value,
|
|
210
|
+
"attributes": dict(attrs_frozen),
|
|
211
|
+
}
|
|
212
|
+
if unit:
|
|
213
|
+
rec["unit"] = unit
|
|
214
|
+
results.append(("metrics.jsonl", rec))
|
|
215
|
+
|
|
216
|
+
for (name, unit, attrs_frozen), acc in histograms.items():
|
|
217
|
+
rec = {
|
|
218
|
+
"name": name,
|
|
219
|
+
"type": "histogram",
|
|
220
|
+
"value": {
|
|
221
|
+
"count": acc.count,
|
|
222
|
+
"sum": acc.total,
|
|
223
|
+
"min": acc.mn,
|
|
224
|
+
"max": acc.mx,
|
|
225
|
+
},
|
|
226
|
+
"attributes": dict(attrs_frozen),
|
|
227
|
+
}
|
|
228
|
+
if unit:
|
|
229
|
+
rec["unit"] = unit
|
|
230
|
+
results.append(("metrics.jsonl", rec))
|
|
231
|
+
|
|
232
|
+
return results
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def _reset() -> None:
|
|
236
|
+
"""Clear all aggregation state. Used by tests."""
|
|
237
|
+
global _counters, _gauges, _histograms
|
|
238
|
+
with _lock:
|
|
239
|
+
_counters = {}
|
|
240
|
+
_gauges = {}
|
|
241
|
+
_histograms = {}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"""SDK initialization and lifecycle."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import atexit
|
|
6
|
+
import importlib.metadata
|
|
7
|
+
import logging
|
|
8
|
+
import os
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from pontem import _emit
|
|
12
|
+
|
|
13
|
+
_initialized = False
|
|
14
|
+
_logger = logging.getLogger("pontem.sdk")
|
|
15
|
+
|
|
16
|
+
# Environment variables the Pontem agent sets on managed devices.
|
|
17
|
+
_AGENT_ENV_MAP = {
|
|
18
|
+
"device.id": "PONTEM_DEVICE_ID",
|
|
19
|
+
"pontem.tenant.id": "PONTEM_TENANT_ID",
|
|
20
|
+
"pontem.config.version": "PONTEM_CONFIG_VERSION",
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _infer_service_version(service_name: str) -> str | None:
|
|
25
|
+
"""Read version from installed package metadata.
|
|
26
|
+
|
|
27
|
+
Tries the name as-is, then underscore ↔ hyphen normalization.
|
|
28
|
+
"""
|
|
29
|
+
candidates = {service_name}
|
|
30
|
+
candidates.add(service_name.replace("_", "-"))
|
|
31
|
+
candidates.add(service_name.replace("-", "_"))
|
|
32
|
+
|
|
33
|
+
for name in candidates:
|
|
34
|
+
try:
|
|
35
|
+
return importlib.metadata.version(name)
|
|
36
|
+
except importlib.metadata.PackageNotFoundError:
|
|
37
|
+
continue
|
|
38
|
+
return None
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def init(
|
|
42
|
+
*,
|
|
43
|
+
service_name: str,
|
|
44
|
+
service_version: str | None = None,
|
|
45
|
+
emit_dir: str | None = None,
|
|
46
|
+
) -> None:
|
|
47
|
+
"""Initialize the Pontem SDK.
|
|
48
|
+
|
|
49
|
+
Call once at startup.
|
|
50
|
+
|
|
51
|
+
Telemetry is written as JSONL to the emit directory, which the
|
|
52
|
+
Pontem agent watches and forwards to the cloud.
|
|
53
|
+
|
|
54
|
+
Args:
|
|
55
|
+
service_name: Identifies this service in all emitted telemetry.
|
|
56
|
+
service_version: Override auto-detected version.
|
|
57
|
+
emit_dir: Override ``PONTEM_EMIT_DIR`` env var and the default
|
|
58
|
+
``/opt/pontem/<service_name>/var/log``.
|
|
59
|
+
"""
|
|
60
|
+
global _initialized
|
|
61
|
+
if _initialized:
|
|
62
|
+
_logger.warning("pontem.init() already called, ignoring")
|
|
63
|
+
return
|
|
64
|
+
service_version = service_version or _infer_service_version(service_name)
|
|
65
|
+
|
|
66
|
+
# Resource attributes — attached to every emitted record.
|
|
67
|
+
resource: dict[str, Any] = {"service.name": service_name}
|
|
68
|
+
if service_version:
|
|
69
|
+
resource["service.version"] = service_version
|
|
70
|
+
for attr_key, env_var in _AGENT_ENV_MAP.items():
|
|
71
|
+
val = os.environ.get(env_var)
|
|
72
|
+
if val:
|
|
73
|
+
resource[attr_key] = val
|
|
74
|
+
|
|
75
|
+
# Default emit dir: /opt/pontem/<service_name>/var/log
|
|
76
|
+
if not emit_dir and not os.environ.get("PONTEM_EMIT_DIR"):
|
|
77
|
+
emit_dir = f"/opt/pontem/{service_name}/var/log"
|
|
78
|
+
|
|
79
|
+
path = _emit.configure(emit_dir, resource)
|
|
80
|
+
if path:
|
|
81
|
+
_logger.debug("pontem emit dir: %s", path)
|
|
82
|
+
else:
|
|
83
|
+
_logger.debug("emit dir could not be configured")
|
|
84
|
+
|
|
85
|
+
# Register metrics aggregation flush with the emit thread.
|
|
86
|
+
from pontem import _metrics
|
|
87
|
+
|
|
88
|
+
_emit.register_periodic(_metrics._collect)
|
|
89
|
+
|
|
90
|
+
atexit.register(shutdown)
|
|
91
|
+
_initialized = True
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def shutdown() -> None:
|
|
95
|
+
"""Flush aggregated metrics, drain logs, and close emit files."""
|
|
96
|
+
global _initialized
|
|
97
|
+
if not _initialized:
|
|
98
|
+
return
|
|
99
|
+
_emit.close()
|
|
100
|
+
_initialized = False
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""Structured logging.
|
|
2
|
+
|
|
3
|
+
Types::
|
|
4
|
+
|
|
5
|
+
from pontem.log import Level
|
|
6
|
+
Level.DEBUG # 5
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import enum
|
|
12
|
+
import logging
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
from pontem import _emit
|
|
16
|
+
|
|
17
|
+
_stdlib_logger = logging.getLogger("pontem")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class Level(enum.IntEnum):
|
|
21
|
+
"""Log severity levels.
|
|
22
|
+
|
|
23
|
+
Values map to OpenTelemetry SeverityNumber (1-24 scale).
|
|
24
|
+
https://opentelemetry.io/docs/specs/otel/logs/data-model/#severity-fields
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
TRACE = 1
|
|
28
|
+
DEBUG = 5
|
|
29
|
+
INFO = 9
|
|
30
|
+
WARN = 13
|
|
31
|
+
ERROR = 17
|
|
32
|
+
FATAL = 21
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
_PY_LEVEL = {
|
|
36
|
+
Level.TRACE: logging.DEBUG,
|
|
37
|
+
Level.DEBUG: logging.DEBUG,
|
|
38
|
+
Level.INFO: logging.INFO,
|
|
39
|
+
Level.WARN: logging.WARNING,
|
|
40
|
+
Level.ERROR: logging.ERROR,
|
|
41
|
+
Level.FATAL: logging.CRITICAL,
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class Logger:
|
|
46
|
+
"""Structured logger with level helpers.
|
|
47
|
+
|
|
48
|
+
Example::
|
|
49
|
+
|
|
50
|
+
import pontem
|
|
51
|
+
|
|
52
|
+
pontem.logger.info("model loaded", model="scoring_v3")
|
|
53
|
+
pontem.logger.warn("high latency", latency_ms=120)
|
|
54
|
+
|
|
55
|
+
Severity levels are available as attributes::
|
|
56
|
+
|
|
57
|
+
pontem.logger.TRACE # 1
|
|
58
|
+
pontem.logger.INFO # 9
|
|
59
|
+
"""
|
|
60
|
+
|
|
61
|
+
TRACE = Level.TRACE
|
|
62
|
+
DEBUG = Level.DEBUG
|
|
63
|
+
INFO = Level.INFO
|
|
64
|
+
WARN = Level.WARN
|
|
65
|
+
ERROR = Level.ERROR
|
|
66
|
+
FATAL = Level.FATAL
|
|
67
|
+
|
|
68
|
+
def _log(self, level: int, msg: str, **attrs: Any) -> None:
|
|
69
|
+
py_level = _PY_LEVEL.get(level, logging.INFO)
|
|
70
|
+
_stdlib_logger.log(py_level, msg, extra=attrs)
|
|
71
|
+
|
|
72
|
+
try:
|
|
73
|
+
severity_text = Level(level).name
|
|
74
|
+
except ValueError:
|
|
75
|
+
severity_text = "INFO"
|
|
76
|
+
|
|
77
|
+
_emit.emit(
|
|
78
|
+
"logs.jsonl",
|
|
79
|
+
{
|
|
80
|
+
"severityNumber": level,
|
|
81
|
+
"severityText": severity_text,
|
|
82
|
+
"body": msg,
|
|
83
|
+
"attributes": attrs or {},
|
|
84
|
+
},
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
def trace(self, msg: str, **attrs: Any) -> None:
|
|
88
|
+
self._log(Level.TRACE, msg, **attrs)
|
|
89
|
+
|
|
90
|
+
def debug(self, msg: str, **attrs: Any) -> None:
|
|
91
|
+
self._log(Level.DEBUG, msg, **attrs)
|
|
92
|
+
|
|
93
|
+
def info(self, msg: str, **attrs: Any) -> None:
|
|
94
|
+
self._log(Level.INFO, msg, **attrs)
|
|
95
|
+
|
|
96
|
+
def warn(self, msg: str, **attrs: Any) -> None:
|
|
97
|
+
self._log(Level.WARN, msg, **attrs)
|
|
98
|
+
|
|
99
|
+
def error(self, msg: str, **attrs: Any) -> None:
|
|
100
|
+
self._log(Level.ERROR, msg, **attrs)
|
|
101
|
+
|
|
102
|
+
def fatal(self, msg: str, **attrs: Any) -> None:
|
|
103
|
+
self._log(Level.FATAL, msg, **attrs)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
logger = Logger()
|