Skip to content

Commit

Permalink
chore: Bump o11y libs and remove juju topology (#252)
Browse files Browse the repository at this point in the history
  • Loading branch information
orfeas-k authored Apr 29, 2024
1 parent 0fc1e97 commit f18f83a
Show file tree
Hide file tree
Showing 7 changed files with 75 additions and 276 deletions.
17 changes: 9 additions & 8 deletions lib/charms/grafana_k8s/v0/grafana_dashboard.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ def __init__(self, *args):
# Increment this PATCH version before using `charmcraft publish-lib` or reset
# to 0 if you are raising the major API version

LIBPATCH = 32
LIBPATCH = 35

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -665,14 +665,14 @@ def _template_panels(
continue
if not existing_templates:
datasource = panel.get("datasource")
if type(datasource) == str:
if isinstance(datasource, str):
if "loki" in datasource:
panel["datasource"] = "${lokids}"
elif "grafana" in datasource:
continue
else:
panel["datasource"] = "${prometheusds}"
elif type(datasource) == dict:
elif isinstance(datasource, dict):
# In dashboards exported by Grafana 9, datasource type is dict
dstype = datasource.get("type", "")
if dstype == "loki":
Expand All @@ -686,7 +686,7 @@ def _template_panels(
logger.error("Unknown datasource format: skipping")
continue
else:
if type(panel["datasource"]) == str:
if isinstance(panel["datasource"], str):
if panel["datasource"].lower() in replacements.values():
# Already a known template variable
continue
Expand All @@ -701,7 +701,7 @@ def _template_panels(
if replacement:
used_replacements.append(ds)
panel["datasource"] = replacement or panel["datasource"]
elif type(panel["datasource"]) == dict:
elif isinstance(panel["datasource"], dict):
dstype = panel["datasource"].get("type", "")
if panel["datasource"].get("uid", "").lower() in replacements.values():
# Already a known template variable
Expand Down Expand Up @@ -790,7 +790,7 @@ def _inject_labels(content: str, topology: dict, transformer: "CosTool") -> str:

# We need to use an index so we can insert the changed element back later
for panel_idx, panel in enumerate(panels):
if type(panel) is not dict:
if not isinstance(panel, dict):
continue

# Use the index to insert it back in the same location
Expand Down Expand Up @@ -831,11 +831,11 @@ def _modify_panel(panel: dict, topology: dict, transformer: "CosTool") -> dict:
if "datasource" not in panel.keys():
continue

if type(panel["datasource"]) == str:
if isinstance(panel["datasource"], str):
if panel["datasource"] not in known_datasources:
continue
querytype = known_datasources[panel["datasource"]]
elif type(panel["datasource"]) == dict:
elif isinstance(panel["datasource"], dict):
if panel["datasource"]["uid"] not in known_datasources:
continue
querytype = known_datasources[panel["datasource"]["uid"]]
Expand Down Expand Up @@ -1195,6 +1195,7 @@ def _on_grafana_dashboard_relation_created(self, event: RelationCreatedEvent) ->
`grafana_dashboaard` relationship is joined
"""
if self._charm.unit.is_leader():
self._update_all_dashboards_from_dir()
self._upset_dashboards_on_relation(event.relation)

def _on_grafana_dashboard_relation_changed(self, event: RelationChangedEvent) -> None:
Expand Down
20 changes: 11 additions & 9 deletions lib/charms/observability_libs/v0/metrics_endpoint_discovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ def _on_endpoints_change(self, event):
from pathlib import Path
from typing import Dict, Iterable

from lightkube import Client
from lightkube import Client # pyright: ignore
from lightkube.resources.core_v1 import Pod
from ops.charm import CharmBase, CharmEvents
from ops.framework import EventBase, EventSource, Object, StoredState
Expand All @@ -62,7 +62,7 @@ def _on_endpoints_change(self, event):

# Increment this PATCH version before using `charmcraft publish-lib` or reset
# to 0 if you are raising the major API version
LIBPATCH = 4
LIBPATCH = 7

# File path where metrics endpoint change data is written for exchange
# between the discovery process and the materialised event.
Expand Down Expand Up @@ -199,7 +199,7 @@ def main():
"""
labels, run_cmd, unit, charm_dir = sys.argv[1:]

client = Client()
client = Client() # pyright: ignore
labels = json.loads(labels)

for change, entity in client.watch(Pod, namespace="*", labels=labels):
Expand All @@ -208,18 +208,20 @@ def main():
Path(PAYLOAD_FILE_PATH).unlink()
meta = entity.metadata
metrics_path = ""
if entity.metadata.annotations.get("prometheus.io/path", ""):
metrics_path = entity.metadata.annotations.get("prometheus.io/path", "")
if entity.metadata.annotations.get("prometheus.io/path", ""): # pyright: ignore
metrics_path = entity.metadata.annotations.get( # pyright: ignore
"prometheus.io/path", ""
)

target_ports = []
for c in filter(lambda c: c.ports is not None, entity.spec.containers):
for p in filter(lambda p: p.name == "metrics", c.ports):
for c in filter(lambda c: c.ports is not None, entity.spec.containers): # pyright: ignore
for p in filter(lambda p: p.name == "metrics", c.ports): # pyright: ignore
target_ports.append("*:{}".format(p.containerPort))

payload = {
"change": change,
"namespace": meta.namespace,
"name": meta.name,
"namespace": meta.namespace, # pyright: ignore
"name": meta.name, # pyright: ignore
"path": metrics_path,
"targets": target_ports or ["*:80"],
}
Expand Down
10 changes: 5 additions & 5 deletions lib/charms/observability_libs/v1/kubernetes_service_patch.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ def setUp(self, *unused):
from types import MethodType
from typing import List, Literal, Optional, Union

from lightkube import ApiError, Client
from lightkube import ApiError, Client # pyright: ignore
from lightkube.core import exceptions
from lightkube.models.core_v1 import ServicePort, ServiceSpec
from lightkube.models.meta_v1 import ObjectMeta
Expand All @@ -146,7 +146,7 @@ def setUp(self, *unused):

# Increment this PATCH version before using `charmcraft publish-lib` or reset
# to 0 if you are raising the major API version
LIBPATCH = 7
LIBPATCH = 9

ServiceType = Literal["ClusterIP", "LoadBalancer"]

Expand Down Expand Up @@ -268,7 +268,7 @@ def _patch(self, _) -> None:
PatchFailed: if patching fails due to lack of permissions, or otherwise.
"""
try:
client = Client()
client = Client() # pyright: ignore
except exceptions.ConfigError as e:
logger.warning("Error creating k8s client: %s", e)
return
Expand Down Expand Up @@ -300,7 +300,7 @@ def is_patched(self) -> bool:
Returns:
bool: A boolean indicating if the service patch has been applied.
"""
client = Client()
client = Client() # pyright: ignore
return self._is_patched(client)

def _is_patched(self, client: Client) -> bool:
Expand All @@ -314,7 +314,7 @@ def _is_patched(self, client: Client) -> bool:
raise

# Construct a list of expected ports, should the patch be applied
expected_ports = [(p.port, p.targetPort) for p in self.service.spec.ports]
expected_ports = [(p.port, p.targetPort) for p in self.service.spec.ports] # type: ignore[attr-defined]
# Construct a list in the same manner, using the fetched service
fetched_ports = [
(p.port, p.targetPort) for p in service.spec.ports # type: ignore[attr-defined]
Expand Down
Loading

0 comments on commit f18f83a

Please sign in to comment.