charmlibs-interfaces-sloth 0.1.0__py3-none-any.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.
- charmlibs/interfaces/sloth/__init__.py +147 -0
- charmlibs/interfaces/sloth/_sloth.py +297 -0
- charmlibs/interfaces/sloth/_topology.py +105 -0
- charmlibs/interfaces/sloth/_version.py +15 -0
- charmlibs/interfaces/sloth/py.typed +0 -0
- charmlibs_interfaces_sloth-0.1.0.dist-info/METADATA +86 -0
- charmlibs_interfaces_sloth-0.1.0.dist-info/RECORD +8 -0
- charmlibs_interfaces_sloth-0.1.0.dist-info/WHEEL +4 -0
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
# Copyright 2026 Canonical Ltd.
|
|
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
|
+
r"""Sloth Provider and Requirer Library.
|
|
16
|
+
|
|
17
|
+
This library provides a way for charms to share SLO (Service Level Objective)
|
|
18
|
+
specifications with the Sloth charm, which will convert them into Prometheus
|
|
19
|
+
recording and alerting rules.
|
|
20
|
+
|
|
21
|
+
Getting Started
|
|
22
|
+
===============
|
|
23
|
+
|
|
24
|
+
Provider Side (Charms providing SLO specs)
|
|
25
|
+
-------------------------------------------
|
|
26
|
+
|
|
27
|
+
To provide SLO specifications to Sloth, use the ``SlothProvider`` class.
|
|
28
|
+
The recommended approach is to allow users to configure SLOs via ``juju config``::
|
|
29
|
+
|
|
30
|
+
from charmlibs.interfaces.sloth import SlothProvider
|
|
31
|
+
|
|
32
|
+
class MyCharm(ops.CharmBase):
|
|
33
|
+
def __init__(self, *args):
|
|
34
|
+
super().__init__(*args)
|
|
35
|
+
self.sloth_provider = SlothProvider(self)
|
|
36
|
+
self.framework.observe(self.on.config_changed, self._on_config_changed)
|
|
37
|
+
|
|
38
|
+
def _on_config_changed(self, event):
|
|
39
|
+
# Read SLO configuration from juju config
|
|
40
|
+
slo_config = self.config.get('slo_config', '')
|
|
41
|
+
if slo_config:
|
|
42
|
+
self.sloth_provider.provide_slos(slo_config)
|
|
43
|
+
|
|
44
|
+
Users can then configure SLOs using ``juju config``::
|
|
45
|
+
|
|
46
|
+
juju config my-app slo_config='
|
|
47
|
+
version: prometheus/v1
|
|
48
|
+
service: my-service
|
|
49
|
+
labels:
|
|
50
|
+
team: my-team
|
|
51
|
+
slos:
|
|
52
|
+
- name: requests-availability
|
|
53
|
+
objective: 99.9
|
|
54
|
+
description: "99.9% of requests should succeed"
|
|
55
|
+
sli:
|
|
56
|
+
events:
|
|
57
|
+
error_query: '\''sum(rate(http_requests_total{status=~"5.."}[{{.window}}]))'\''
|
|
58
|
+
total_query: '\''sum(rate(http_requests_total[{{.window}}]))'\''
|
|
59
|
+
alerting:
|
|
60
|
+
name: MyServiceHighErrorRate
|
|
61
|
+
labels:
|
|
62
|
+
severity: critical
|
|
63
|
+
'
|
|
64
|
+
|
|
65
|
+
To specify multiple SLOs for different services, separate them with YAML document
|
|
66
|
+
separators (``---``).
|
|
67
|
+
|
|
68
|
+
Requirer Side (Sloth charm)
|
|
69
|
+
----------------------------
|
|
70
|
+
|
|
71
|
+
The Sloth charm uses ``SlothRequirer`` to collect SLO specifications.
|
|
72
|
+
Validation is performed on the requirer side::
|
|
73
|
+
|
|
74
|
+
from charmlibs.interfaces.sloth import SlothRequirer
|
|
75
|
+
|
|
76
|
+
class SlothCharm(ops.CharmBase):
|
|
77
|
+
def __init__(self, *args):
|
|
78
|
+
super().__init__(*args)
|
|
79
|
+
self.sloth_requirer = SlothRequirer(self)
|
|
80
|
+
|
|
81
|
+
def _on_config_changed(self, event):
|
|
82
|
+
# Get validated SLO specs from all related charms
|
|
83
|
+
slos = self.sloth_requirer.get_slos()
|
|
84
|
+
# Process SLOs and generate rules
|
|
85
|
+
|
|
86
|
+
Relation Data Format
|
|
87
|
+
====================
|
|
88
|
+
|
|
89
|
+
SLO specifications are stored in the relation databag as YAML strings under the
|
|
90
|
+
``slo_spec`` key. Each provider unit can provide one or more SLO specifications.
|
|
91
|
+
|
|
92
|
+
For a single service::
|
|
93
|
+
|
|
94
|
+
slo_spec: |
|
|
95
|
+
version: prometheus/v1
|
|
96
|
+
service: my-service
|
|
97
|
+
labels:
|
|
98
|
+
team: my-team
|
|
99
|
+
slos:
|
|
100
|
+
- name: requests-availability
|
|
101
|
+
objective: 99.9
|
|
102
|
+
description: "99.9% of requests should succeed"
|
|
103
|
+
sli:
|
|
104
|
+
events:
|
|
105
|
+
error_query: 'sum(rate(http_requests_total{status=~"5.."}[{{.window}}]))'
|
|
106
|
+
total_query: 'sum(rate(http_requests_total[{{.window}}]))'
|
|
107
|
+
alerting:
|
|
108
|
+
name: MyServiceHighErrorRate
|
|
109
|
+
labels:
|
|
110
|
+
severity: critical
|
|
111
|
+
|
|
112
|
+
For multiple services (separated by YAML document separators)::
|
|
113
|
+
|
|
114
|
+
slo_spec: |
|
|
115
|
+
version: prometheus/v1
|
|
116
|
+
service: my-service
|
|
117
|
+
slos:
|
|
118
|
+
- name: requests-availability
|
|
119
|
+
objective: 99.9
|
|
120
|
+
---
|
|
121
|
+
version: prometheus/v1
|
|
122
|
+
service: my-other-service
|
|
123
|
+
slos:
|
|
124
|
+
- name: requests-latency
|
|
125
|
+
objective: 99.5
|
|
126
|
+
"""
|
|
127
|
+
|
|
128
|
+
from ._sloth import (
|
|
129
|
+
SLOError,
|
|
130
|
+
SLORelationData,
|
|
131
|
+
SLOSpec,
|
|
132
|
+
SlothProvider,
|
|
133
|
+
SlothRequirer,
|
|
134
|
+
SLOValidationError,
|
|
135
|
+
)
|
|
136
|
+
from ._topology import inject_topology_labels
|
|
137
|
+
from ._version import __version__ as __version__
|
|
138
|
+
|
|
139
|
+
__all__ = [
|
|
140
|
+
'SLOError',
|
|
141
|
+
'SLORelationData',
|
|
142
|
+
'SLOSpec',
|
|
143
|
+
'SLOValidationError',
|
|
144
|
+
'SlothProvider',
|
|
145
|
+
'SlothRequirer',
|
|
146
|
+
'inject_topology_labels',
|
|
147
|
+
]
|
|
@@ -0,0 +1,297 @@
|
|
|
1
|
+
# Copyright 2026 Canonical Ltd.
|
|
2
|
+
# See LICENSE file for licensing details.
|
|
3
|
+
|
|
4
|
+
"""Internal implementation of the SLO Provider and Requirer library.
|
|
5
|
+
|
|
6
|
+
This module contains the core implementation classes for the SLO interface.
|
|
7
|
+
For user-facing documentation, see the package-level docstring in __init__.py.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import copy
|
|
11
|
+
import logging
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
import ops
|
|
15
|
+
import yaml
|
|
16
|
+
from cosl import JujuTopology
|
|
17
|
+
from pydantic import BaseModel, Field, ValidationError, field_validator
|
|
18
|
+
|
|
19
|
+
from ._topology import inject_topology_labels
|
|
20
|
+
|
|
21
|
+
logger = logging.getLogger(__name__)
|
|
22
|
+
|
|
23
|
+
DEFAULT_RELATION_NAME = 'sloth'
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class SLOError(Exception):
|
|
27
|
+
"""Base exception for SLO library errors."""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class SLOValidationError(SLOError):
|
|
31
|
+
"""Validation error for SLO specifications."""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class SLOSpec(BaseModel):
|
|
35
|
+
"""Pydantic model for SLO specification validation."""
|
|
36
|
+
|
|
37
|
+
version: str = Field(description="Sloth spec version, e.g., 'prometheus/v1'")
|
|
38
|
+
service: str = Field(description='Service name for the SLO')
|
|
39
|
+
labels: dict[str, str] = Field(default_factory=dict, description='Labels for the SLO')
|
|
40
|
+
slos: list[dict[str, Any]] = Field(description='List of SLO definitions')
|
|
41
|
+
|
|
42
|
+
@field_validator('version')
|
|
43
|
+
@classmethod
|
|
44
|
+
def validate_version(cls, v: str) -> str:
|
|
45
|
+
"""Validate that version follows expected format."""
|
|
46
|
+
if not v or '/' not in v:
|
|
47
|
+
raise ValueError("Version must be in format 'prometheus/v1'")
|
|
48
|
+
return v
|
|
49
|
+
|
|
50
|
+
@field_validator('slos')
|
|
51
|
+
@classmethod
|
|
52
|
+
def validate_slos(cls, v: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
|
53
|
+
"""Validate that at least one SLO is defined."""
|
|
54
|
+
if not v:
|
|
55
|
+
raise ValueError('At least one SLO must be defined')
|
|
56
|
+
return v
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class SLORelationData(BaseModel):
|
|
60
|
+
"""Pydantic model for SLO relation data exchange.
|
|
61
|
+
|
|
62
|
+
This model represents the data stored in the relation databag for
|
|
63
|
+
exchanging SLO specifications between provider and requirer charms.
|
|
64
|
+
"""
|
|
65
|
+
|
|
66
|
+
slos: list[SLOSpec] = Field(
|
|
67
|
+
description='List of SLO specifications',
|
|
68
|
+
default_factory=lambda: [],
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class SlothProvider(ops.Object):
|
|
73
|
+
"""Provider side of the Sloth relation.
|
|
74
|
+
|
|
75
|
+
Charms should use this class to provide SLO specifications to Sloth.
|
|
76
|
+
|
|
77
|
+
Args:
|
|
78
|
+
charm: The charm instance.
|
|
79
|
+
relation_name: Name of the relation (default: "sloth").
|
|
80
|
+
inject_topology: Whether to automatically inject Juju topology labels
|
|
81
|
+
into Prometheus queries (default: True). When enabled, labels like
|
|
82
|
+
juju_application, juju_model, etc. are added to metric selectors.
|
|
83
|
+
"""
|
|
84
|
+
|
|
85
|
+
def __init__(
|
|
86
|
+
self,
|
|
87
|
+
charm: ops.CharmBase,
|
|
88
|
+
relation_name: str = DEFAULT_RELATION_NAME,
|
|
89
|
+
inject_topology: bool = True,
|
|
90
|
+
):
|
|
91
|
+
super().__init__(charm, relation_name)
|
|
92
|
+
self._charm = charm
|
|
93
|
+
self.relation_name = relation_name
|
|
94
|
+
self._inject_topology = inject_topology
|
|
95
|
+
|
|
96
|
+
def _get_topology_labels(self) -> dict[str, str]:
|
|
97
|
+
"""Get Juju topology labels for this charm.
|
|
98
|
+
|
|
99
|
+
Returns:
|
|
100
|
+
Dictionary of topology labels (juju_application, juju_model, etc.)
|
|
101
|
+
"""
|
|
102
|
+
topology = JujuTopology.from_charm(self._charm)
|
|
103
|
+
return topology.label_matcher_dict
|
|
104
|
+
|
|
105
|
+
def _inject_topology_into_slo(self, slo_spec: dict[str, Any]) -> dict[str, Any]:
|
|
106
|
+
"""Inject topology labels into SLO queries.
|
|
107
|
+
|
|
108
|
+
This method performs a deep copy of the input SLO specification and
|
|
109
|
+
injects Juju topology labels into all Prometheus queries found in the
|
|
110
|
+
SLO definitions.
|
|
111
|
+
|
|
112
|
+
Args:
|
|
113
|
+
slo_spec: SLO specification dictionary
|
|
114
|
+
|
|
115
|
+
Returns:
|
|
116
|
+
New SLO specification with topology labels injected into queries
|
|
117
|
+
"""
|
|
118
|
+
if not self._inject_topology:
|
|
119
|
+
return slo_spec
|
|
120
|
+
|
|
121
|
+
topology_labels = self._get_topology_labels()
|
|
122
|
+
|
|
123
|
+
# Deep copy to avoid modifying the original
|
|
124
|
+
slo_spec = copy.deepcopy(slo_spec)
|
|
125
|
+
|
|
126
|
+
# Inject topology into each SLO's queries
|
|
127
|
+
for slo in slo_spec.get('slos', []):
|
|
128
|
+
sli = slo.get('sli')
|
|
129
|
+
if not sli:
|
|
130
|
+
continue
|
|
131
|
+
|
|
132
|
+
events = sli.get('events')
|
|
133
|
+
if not events:
|
|
134
|
+
continue
|
|
135
|
+
|
|
136
|
+
if 'error_query' in events:
|
|
137
|
+
events['error_query'] = inject_topology_labels(
|
|
138
|
+
events['error_query'], topology_labels
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
if 'total_query' in events:
|
|
142
|
+
events['total_query'] = inject_topology_labels(
|
|
143
|
+
events['total_query'], topology_labels
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
return slo_spec
|
|
147
|
+
|
|
148
|
+
def provide_slos(self, slo_config: str) -> None:
|
|
149
|
+
"""Provide SLO specifications to Sloth as a raw YAML string.
|
|
150
|
+
|
|
151
|
+
This method accepts a raw YAML string containing one or more SLO specifications.
|
|
152
|
+
Multiple specs should be separated by YAML document separators (three dashes).
|
|
153
|
+
The YAML is validated against the SLOSpec schema before being sent.
|
|
154
|
+
|
|
155
|
+
Args:
|
|
156
|
+
slo_config: Raw YAML string containing SLO specification(s) in Sloth format.
|
|
157
|
+
Can contain multiple documents separated by three dashes.
|
|
158
|
+
|
|
159
|
+
Raises:
|
|
160
|
+
SLOValidationError: If the YAML cannot be parsed or is invalid.
|
|
161
|
+
|
|
162
|
+
Example::
|
|
163
|
+
|
|
164
|
+
slo_config = '''
|
|
165
|
+
version: prometheus/v1
|
|
166
|
+
service: my-service
|
|
167
|
+
labels:
|
|
168
|
+
team: my-team
|
|
169
|
+
slos:
|
|
170
|
+
- name: requests-availability
|
|
171
|
+
objective: 99.9
|
|
172
|
+
sli:
|
|
173
|
+
events:
|
|
174
|
+
error_query: 'sum(rate(http_requests_total{status=~"5.."}[{{.window}}]))'
|
|
175
|
+
total_query: 'sum(rate(http_requests_total[{{.window}}]))'
|
|
176
|
+
'''
|
|
177
|
+
self.slo_provider.provide_slos(slo_config)
|
|
178
|
+
"""
|
|
179
|
+
relations = self._charm.model.relations.get(self.relation_name, [])
|
|
180
|
+
if not relations:
|
|
181
|
+
logger.debug('No %s relation found', self.relation_name)
|
|
182
|
+
return
|
|
183
|
+
|
|
184
|
+
if not slo_config:
|
|
185
|
+
logger.debug('No SLO config provided')
|
|
186
|
+
return
|
|
187
|
+
|
|
188
|
+
# Parse the YAML config - it can contain multiple SLO documents (separated by ---)
|
|
189
|
+
try:
|
|
190
|
+
slo_dicts = list(yaml.safe_load_all(slo_config))
|
|
191
|
+
except yaml.YAMLError as e:
|
|
192
|
+
logger.warning('Failed to parse SLO config as YAML: %s', e)
|
|
193
|
+
raise SLOValidationError(f'Invalid YAML in slo_config: {e}') from e
|
|
194
|
+
|
|
195
|
+
# Inject topology labels into queries if enabled
|
|
196
|
+
slo_dicts = [self._inject_topology_into_slo(spec) for spec in slo_dicts]
|
|
197
|
+
|
|
198
|
+
# Validate and convert to SLOSpec instances
|
|
199
|
+
try:
|
|
200
|
+
slo_specs = [SLOSpec(**spec) for spec in slo_dicts]
|
|
201
|
+
except ValidationError as e:
|
|
202
|
+
logger.warning('Invalid SLO specification: %s', e)
|
|
203
|
+
raise SLOValidationError(f'Invalid SLO specification: {e}') from e
|
|
204
|
+
|
|
205
|
+
# Only the leader can write to the application databag
|
|
206
|
+
if not self._charm.unit.is_leader():
|
|
207
|
+
logger.debug('Not leader, skipping saving SLOs to relation')
|
|
208
|
+
return
|
|
209
|
+
|
|
210
|
+
for relation in relations:
|
|
211
|
+
# Write SLO specs to app databag using typed relation API
|
|
212
|
+
relation_data = SLORelationData(slos=slo_specs)
|
|
213
|
+
|
|
214
|
+
# Custom encoder to serialize list[SLOSpec] to YAML
|
|
215
|
+
# Note: model_dump() converts SLOSpec to dict before encoding
|
|
216
|
+
def yaml_encoder(obj: Any) -> str:
|
|
217
|
+
if isinstance(obj, list):
|
|
218
|
+
# By the time encoder is called, Pydantic has converted to dicts
|
|
219
|
+
return yaml.safe_dump(obj, default_flow_style=False)
|
|
220
|
+
return str(obj)
|
|
221
|
+
|
|
222
|
+
relation.save(relation_data, self._charm.app, encoder=yaml_encoder)
|
|
223
|
+
logger.debug(
|
|
224
|
+
'Provided SLO config to relation %s',
|
|
225
|
+
relation.id,
|
|
226
|
+
)
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
class SlothRequirer(ops.Object):
|
|
230
|
+
"""Requirer side of the Sloth relation.
|
|
231
|
+
|
|
232
|
+
The Sloth charm uses this class to collect SLO specifications from
|
|
233
|
+
related charms. Validation of SLO specs is performed on this side.
|
|
234
|
+
|
|
235
|
+
Args:
|
|
236
|
+
charm: The charm instance.
|
|
237
|
+
relation_name: Name of the relation (default: "sloth").
|
|
238
|
+
"""
|
|
239
|
+
|
|
240
|
+
def __init__(
|
|
241
|
+
self,
|
|
242
|
+
charm: ops.CharmBase,
|
|
243
|
+
relation_name: str = DEFAULT_RELATION_NAME,
|
|
244
|
+
):
|
|
245
|
+
super().__init__(charm, relation_name)
|
|
246
|
+
self._charm = charm
|
|
247
|
+
self.relation_name = relation_name
|
|
248
|
+
|
|
249
|
+
def get_slos(self) -> list[dict[str, Any]]:
|
|
250
|
+
"""Collect all SLO specifications from related charms.
|
|
251
|
+
|
|
252
|
+
Returns:
|
|
253
|
+
List of SLO specification dictionaries from all related applications.
|
|
254
|
+
Each application may provide multiple SLO specs.
|
|
255
|
+
Only valid SLO specs are returned; invalid ones are logged and skipped.
|
|
256
|
+
"""
|
|
257
|
+
slos: list[dict[str, Any]] = []
|
|
258
|
+
relations = self._charm.model.relations.get(self.relation_name, [])
|
|
259
|
+
|
|
260
|
+
for relation in relations:
|
|
261
|
+
remote_app = relation.app
|
|
262
|
+
if not remote_app:
|
|
263
|
+
continue
|
|
264
|
+
|
|
265
|
+
try:
|
|
266
|
+
# Custom decoder to parse YAML string into list[SLOSpec]
|
|
267
|
+
def yaml_decoder(yaml_str: str) -> list[SLOSpec]:
|
|
268
|
+
if not yaml_str:
|
|
269
|
+
return []
|
|
270
|
+
specs_data = yaml.safe_load(yaml_str)
|
|
271
|
+
return [SLOSpec(**spec) for spec in specs_data] if specs_data else []
|
|
272
|
+
|
|
273
|
+
# Load relation data using typed API
|
|
274
|
+
relation_data = relation.load(
|
|
275
|
+
SLORelationData,
|
|
276
|
+
remote_app,
|
|
277
|
+
decoder=yaml_decoder,
|
|
278
|
+
)
|
|
279
|
+
|
|
280
|
+
# Collect SLO specs from the typed model
|
|
281
|
+
for slo_spec in relation_data.slos:
|
|
282
|
+
slos.append(slo_spec.model_dump())
|
|
283
|
+
logger.debug(
|
|
284
|
+
"Collected SLO spec for service '%s' from %s",
|
|
285
|
+
slo_spec.service,
|
|
286
|
+
remote_app.name,
|
|
287
|
+
)
|
|
288
|
+
|
|
289
|
+
except ValidationError as e:
|
|
290
|
+
logger.warning('Invalid SLO spec from %s: %s', remote_app.name, e)
|
|
291
|
+
continue
|
|
292
|
+
except Exception as e:
|
|
293
|
+
logger.warning('Failed to load SLO spec from %s: %s', remote_app.name, e)
|
|
294
|
+
continue
|
|
295
|
+
|
|
296
|
+
logger.info('Collected %d SLO specifications', len(slos))
|
|
297
|
+
return slos
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
# Copyright 2026 Canonical Ltd.
|
|
2
|
+
# See LICENSE file for licensing details.
|
|
3
|
+
|
|
4
|
+
"""Helper utilities for topology label injection into Prometheus queries.
|
|
5
|
+
|
|
6
|
+
This module provides utilities for injecting Juju topology labels into
|
|
7
|
+
Prometheus queries, supporting the Sloth SLO specification format.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import re
|
|
11
|
+
from re import Match
|
|
12
|
+
|
|
13
|
+
# Pre-compiled regex patterns for topology injection
|
|
14
|
+
_METRIC_WITH_LABELS = re.compile(r'([a-zA-Z_:][a-zA-Z0-9_:]*)(\{[^}]*\})')
|
|
15
|
+
_METRIC_WITH_TIME = re.compile(r'([a-zA-Z_:][a-zA-Z0-9_:]*)(\[[^\]]*\])')
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _replace_labels(match: Match[str], topology_labels: str) -> str:
|
|
19
|
+
"""Replace label selectors in a metric with topology-injected labels.
|
|
20
|
+
|
|
21
|
+
Args:
|
|
22
|
+
match: Regex match object containing metric name and labels
|
|
23
|
+
topology_labels: Formatted topology labels string (e.g., 'juju_app="myapp"')
|
|
24
|
+
|
|
25
|
+
Returns:
|
|
26
|
+
Metric with topology labels injected
|
|
27
|
+
"""
|
|
28
|
+
metric_name = match.group(1)
|
|
29
|
+
labels_with_braces = match.group(2)
|
|
30
|
+
|
|
31
|
+
# Strip the braces to get just the label content
|
|
32
|
+
labels_content = labels_with_braces[1:-1] if len(labels_with_braces) > 2 else ''
|
|
33
|
+
|
|
34
|
+
if labels_content:
|
|
35
|
+
# Has existing labels, append topology
|
|
36
|
+
new_labels = f'{{{labels_content},{topology_labels}}}'
|
|
37
|
+
else:
|
|
38
|
+
# Empty labels, add topology
|
|
39
|
+
new_labels = f'{{{topology_labels}}}'
|
|
40
|
+
|
|
41
|
+
return f'{metric_name}{new_labels}'
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _replace_time(match: Match[str], topology_labels: str) -> str:
|
|
45
|
+
"""Replace time selectors in a metric with topology-injected labels.
|
|
46
|
+
|
|
47
|
+
Args:
|
|
48
|
+
match: Regex match object containing metric name and time selector
|
|
49
|
+
topology_labels: Formatted topology labels string (e.g., 'juju_app="myapp"')
|
|
50
|
+
|
|
51
|
+
Returns:
|
|
52
|
+
Metric with topology labels injected if not already present
|
|
53
|
+
"""
|
|
54
|
+
metric_name = match.group(1)
|
|
55
|
+
time_selector = match.group(2)
|
|
56
|
+
|
|
57
|
+
# Check if metric_name already ends with } (labels were added in first pass)
|
|
58
|
+
if not metric_name.endswith('}'):
|
|
59
|
+
return f'{metric_name}{{{topology_labels}}}{time_selector}'
|
|
60
|
+
|
|
61
|
+
return match.group(0)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def inject_topology_labels(query: str, topology: dict[str, str]) -> str:
|
|
65
|
+
"""Inject Juju topology labels into a Prometheus query.
|
|
66
|
+
|
|
67
|
+
This function adds Juju topology labels (juju_application, juju_model, etc.)
|
|
68
|
+
to all metric selectors in a PromQL query that don't already have them.
|
|
69
|
+
|
|
70
|
+
Only metrics with explicit selectors (either {labels} or [time]) are modified.
|
|
71
|
+
Function names like sum(), rate(), etc. are not modified.
|
|
72
|
+
|
|
73
|
+
Args:
|
|
74
|
+
query: The Prometheus query string
|
|
75
|
+
topology: Dictionary of label names to values (e.g., {"juju_application": "my-app"})
|
|
76
|
+
|
|
77
|
+
Returns:
|
|
78
|
+
Query with topology labels injected
|
|
79
|
+
|
|
80
|
+
Examples:
|
|
81
|
+
>>> inject_topology_labels(
|
|
82
|
+
... 'sum(rate(metric[5m]))',
|
|
83
|
+
... {"juju_application": "my-app"}
|
|
84
|
+
... )
|
|
85
|
+
'sum(rate(metric{juju_application="my-app"}[5m]))'
|
|
86
|
+
|
|
87
|
+
>>> inject_topology_labels(
|
|
88
|
+
... 'sum(rate(metric{existing="label"}[5m]))',
|
|
89
|
+
... {"juju_application": "my-app"}
|
|
90
|
+
... )
|
|
91
|
+
'sum(rate(metric{existing="label",juju_application="my-app"}[5m]))'
|
|
92
|
+
"""
|
|
93
|
+
if not topology:
|
|
94
|
+
return query
|
|
95
|
+
|
|
96
|
+
# Build the label matcher string
|
|
97
|
+
topology_labels = ','.join([f'{k}="{v}"' for k, v in sorted(topology.items())])
|
|
98
|
+
|
|
99
|
+
# First pass: inject into metrics with {labels}
|
|
100
|
+
query = _METRIC_WITH_LABELS.sub(lambda match: _replace_labels(match, topology_labels), query)
|
|
101
|
+
|
|
102
|
+
# Second pass: inject into metrics with [time] but no labels yet
|
|
103
|
+
query = _METRIC_WITH_TIME.sub(lambda match: _replace_time(match, topology_labels), query)
|
|
104
|
+
|
|
105
|
+
return query
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
# Copyright 2026 Canonical Ltd.
|
|
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
|
+
__version__ = '0.1.0'
|
|
File without changes
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: charmlibs-interfaces-sloth
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Sloth integration for Juju charms - SLO (Service Level Objective) management with the Sloth operator.
|
|
5
|
+
Project-URL: Repository, https://github.com/canonical/charmlibs
|
|
6
|
+
Project-URL: Issues, https://github.com/canonical/charmlibs/issues
|
|
7
|
+
Author: The Observability team at Canonical Ltd.
|
|
8
|
+
Classifier: Development Status :: 3 - Alpha
|
|
9
|
+
Classifier: Intended Audience :: Developers
|
|
10
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
11
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Requires-Python: >=3.10
|
|
14
|
+
Requires-Dist: cosl>=0.0.10
|
|
15
|
+
Requires-Dist: ops
|
|
16
|
+
Requires-Dist: pydantic>=2.0
|
|
17
|
+
Requires-Dist: pyyaml
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
|
|
20
|
+
# charmlibs.interfaces.sloth
|
|
21
|
+
|
|
22
|
+
Sloth integration library for Juju charms, providing SLO (Service Level Objective) management with the Sloth operator for generating Prometheus recording and alerting rules.
|
|
23
|
+
|
|
24
|
+
## Features
|
|
25
|
+
|
|
26
|
+
- **Provider/Requirer pattern**: Enables charms to share SLO specifications with Sloth
|
|
27
|
+
- **Raw YAML interface**: Provider passes raw YAML strings; validation happens on requirer side
|
|
28
|
+
- **Automatic topology injection**: Optionally inject Juju topology labels into Prometheus queries
|
|
29
|
+
- **Multi-service support**: Provide SLO specs for multiple services in a single YAML document
|
|
30
|
+
|
|
31
|
+
## Getting started
|
|
32
|
+
|
|
33
|
+
To install, add `charmlibs-interfaces-sloth` to your Python dependencies. Then in your Python code, import as:
|
|
34
|
+
|
|
35
|
+
```py
|
|
36
|
+
from charmlibs.interfaces.sloth import SlothProvider, SlothRequirer
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
### Provider Side
|
|
40
|
+
|
|
41
|
+
```python
|
|
42
|
+
from charmlibs.interfaces.sloth import SlothProvider
|
|
43
|
+
|
|
44
|
+
class MyCharm(ops.CharmBase):
|
|
45
|
+
def __init__(self, *args):
|
|
46
|
+
super().__init__(*args)
|
|
47
|
+
self.sloth_provider = SlothProvider(self)
|
|
48
|
+
|
|
49
|
+
def _provide_slos(self):
|
|
50
|
+
slo_config = '''
|
|
51
|
+
version: prometheus/v1
|
|
52
|
+
service: my-service
|
|
53
|
+
slos:
|
|
54
|
+
- name: requests-availability
|
|
55
|
+
objective: 99.9
|
|
56
|
+
sli:
|
|
57
|
+
events:
|
|
58
|
+
error_query: 'sum(rate(http_requests_total{status=~"5.."}[{{.window}}]))'
|
|
59
|
+
total_query: 'sum(rate(http_requests_total[{{.window}}]))'
|
|
60
|
+
'''
|
|
61
|
+
self.sloth_provider.provide_slos(slo_config)
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
### Requirer Side
|
|
65
|
+
|
|
66
|
+
```python
|
|
67
|
+
from charmlibs.interfaces.sloth import SlothRequirer
|
|
68
|
+
|
|
69
|
+
class SlothCharm(ops.CharmBase):
|
|
70
|
+
def __init__(self, *args):
|
|
71
|
+
super().__init__(*args)
|
|
72
|
+
self.sloth_requirer = SlothRequirer(self)
|
|
73
|
+
|
|
74
|
+
def _on_config_changed(self, event):
|
|
75
|
+
# Get validated SLO specs from all related charms
|
|
76
|
+
slos = self.sloth_requirer.get_slos()
|
|
77
|
+
# Process SLOs and generate rules
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
## Documentation
|
|
81
|
+
|
|
82
|
+
For complete documentation, see the [charmlibs documentation](https://documentation.ubuntu.com/charmlibs/reference/charmlibs/interfaces/sloth).
|
|
83
|
+
|
|
84
|
+
## Contributing
|
|
85
|
+
|
|
86
|
+
See [CONTRIBUTING.md](https://github.com/canonical/charmlibs/blob/main/CONTRIBUTING.md) in the repository root.
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
charmlibs/interfaces/sloth/__init__.py,sha256=T1ztWZjVQI3tAsARA-fQMFL3RAtQOM27hn5hGe15RC0,4485
|
|
2
|
+
charmlibs/interfaces/sloth/_sloth.py,sha256=74KyssDJof8fTEYMPIGvwMzAwC1kFaIEE1ezw6bMFPg,10464
|
|
3
|
+
charmlibs/interfaces/sloth/_topology.py,sha256=N2wD3GhjySl59Hb0rE_yZEOnoAe_OCGg9Jv5zchRjuw,3663
|
|
4
|
+
charmlibs/interfaces/sloth/_version.py,sha256=5KVViwTN0L0L_i_Ga_RW9UAdw3UnA5h3M_RdphpzVLA,597
|
|
5
|
+
charmlibs/interfaces/sloth/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
6
|
+
charmlibs_interfaces_sloth-0.1.0.dist-info/METADATA,sha256=Q5Ttw9MEzr5ORSvoBf4UxVZri8qL-hi7flwQcxWoet8,2987
|
|
7
|
+
charmlibs_interfaces_sloth-0.1.0.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
|
|
8
|
+
charmlibs_interfaces_sloth-0.1.0.dist-info/RECORD,,
|