Revert "Feature 11071: Modular OSM installation. Remove charms, juju and lxd"
This reverts commit a0f0d8ef4f2aa0dd227ecb651002490b66498bab.
Change-Id: I92394e4074dad4e457c107c58e4ebc17d507f8b2
Signed-off-by: garciadeblas <gerardo.garciadeblas@telefonica.com>
diff --git a/installers/charm/mongodb-exporter/.gitignore b/installers/charm/mongodb-exporter/.gitignore
new file mode 100644
index 0000000..2885df2
--- /dev/null
+++ b/installers/charm/mongodb-exporter/.gitignore
@@ -0,0 +1,30 @@
+# Copyright 2021 Canonical Ltd.
+#
+# 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.
+#
+# For those usages not covered by the Apache License, Version 2.0 please
+# contact: legal@canonical.com
+#
+# To get in touch with the maintainers, please contact:
+# osm-charmers@lists.launchpad.net
+##
+
+venv
+.vscode
+build
+*.charm
+.coverage
+coverage.xml
+.stestr
+cover
+release
\ No newline at end of file
diff --git a/installers/charm/mongodb-exporter/.jujuignore b/installers/charm/mongodb-exporter/.jujuignore
new file mode 100644
index 0000000..3ae3e7d
--- /dev/null
+++ b/installers/charm/mongodb-exporter/.jujuignore
@@ -0,0 +1,34 @@
+# Copyright 2021 Canonical Ltd.
+#
+# 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.
+#
+# For those usages not covered by the Apache License, Version 2.0 please
+# contact: legal@canonical.com
+#
+# To get in touch with the maintainers, please contact:
+# osm-charmers@lists.launchpad.net
+##
+
+venv
+.vscode
+build
+*.charm
+.coverage
+coverage.xml
+.gitignore
+.stestr
+cover
+release
+tests/
+requirements*
+tox.ini
diff --git a/installers/charm/mongodb-exporter/.yamllint.yaml b/installers/charm/mongodb-exporter/.yamllint.yaml
new file mode 100644
index 0000000..d71fb69
--- /dev/null
+++ b/installers/charm/mongodb-exporter/.yamllint.yaml
@@ -0,0 +1,34 @@
+# Copyright 2021 Canonical Ltd.
+#
+# 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.
+#
+# For those usages not covered by the Apache License, Version 2.0 please
+# contact: legal@canonical.com
+#
+# To get in touch with the maintainers, please contact:
+# osm-charmers@lists.launchpad.net
+##
+
+---
+extends: default
+
+yaml-files:
+ - "*.yaml"
+ - "*.yml"
+ - ".yamllint"
+ignore: |
+ .tox
+ cover/
+ build/
+ venv
+ release/
diff --git a/installers/charm/mongodb-exporter/README.md b/installers/charm/mongodb-exporter/README.md
new file mode 100644
index 0000000..84df4c9
--- /dev/null
+++ b/installers/charm/mongodb-exporter/README.md
@@ -0,0 +1,23 @@
+<!-- Copyright 2021 Canonical Ltd.
+
+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.
+
+For those usages not covered by the Apache License, Version 2.0 please
+contact: legal@canonical.com
+
+To get in touch with the maintainers, please contact:
+osm-charmers@lists.launchpad.net -->
+
+# Prometheus Mongodb Exporter operator Charm for Kubernetes
+
+## Requirements
diff --git a/installers/charm/mongodb-exporter/charmcraft.yaml b/installers/charm/mongodb-exporter/charmcraft.yaml
new file mode 100644
index 0000000..0a285a9
--- /dev/null
+++ b/installers/charm/mongodb-exporter/charmcraft.yaml
@@ -0,0 +1,37 @@
+# Copyright 2021 Canonical Ltd.
+#
+# 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.
+#
+# For those usages not covered by the Apache License, Version 2.0 please
+# contact: legal@canonical.com
+#
+# To get in touch with the maintainers, please contact:
+# osm-charmers@lists.launchpad.net
+##
+
+type: charm
+bases:
+ - build-on:
+ - name: ubuntu
+ channel: "20.04"
+ architectures: ["amd64"]
+ run-on:
+ - name: ubuntu
+ channel: "20.04"
+ architectures:
+ - amd64
+ - aarch64
+ - arm64
+parts:
+ charm:
+ build-packages: [git]
diff --git a/installers/charm/mongodb-exporter/config.yaml b/installers/charm/mongodb-exporter/config.yaml
new file mode 100644
index 0000000..fe5cd63
--- /dev/null
+++ b/installers/charm/mongodb-exporter/config.yaml
@@ -0,0 +1,61 @@
+# Copyright 2021 Canonical Ltd.
+#
+# 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.
+#
+# For those usages not covered by the Apache License, Version 2.0 please
+# contact: legal@canonical.com
+#
+# To get in touch with the maintainers, please contact:
+# osm-charmers@lists.launchpad.net
+##
+
+options:
+ ingress_class:
+ type: string
+ description: |
+ Ingress class name. This is useful for selecting the ingress to be used
+ in case there are multiple ingresses in the underlying k8s clusters.
+ ingress_whitelist_source_range:
+ type: string
+ description: |
+ A comma-separated list of CIDRs to store in the
+ ingress.kubernetes.io/whitelist-source-range annotation.
+
+ This can be used to lock down access to
+ Keystone based on source IP address.
+ default: ""
+ tls_secret_name:
+ type: string
+ description: TLS Secret name
+ default: ""
+ site_url:
+ type: string
+ description: Ingress URL
+ default: ""
+ cluster_issuer:
+ type: string
+ description: Name of the cluster issuer for TLS certificates
+ default: ""
+ mongodb_uri:
+ type: string
+ description: MongoDB URI (external database)
+ image_pull_policy:
+ type: string
+ description: |
+ ImagePullPolicy configuration for the pod.
+ Possible values: always, ifnotpresent, never
+ default: always
+ security_context:
+ description: Enables the security context of the pods
+ type: boolean
+ default: false
diff --git a/installers/charm/mongodb-exporter/metadata.yaml b/installers/charm/mongodb-exporter/metadata.yaml
new file mode 100644
index 0000000..c3a0b77
--- /dev/null
+++ b/installers/charm/mongodb-exporter/metadata.yaml
@@ -0,0 +1,49 @@
+# Copyright 2021 Canonical Ltd.
+#
+# 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.
+#
+# For those usages not covered by the Apache License, Version 2.0 please
+# contact: legal@canonical.com
+#
+# To get in touch with the maintainers, please contact:
+# osm-charmers@lists.launchpad.net
+##
+
+name: mongodb-exporter-k8s
+summary: OSM Prometheus Mongodb Exporter
+description: |
+ A CAAS charm to deploy OSM's Prometheus Mongodb Exporter.
+series:
+ - kubernetes
+tags:
+ - kubernetes
+ - osm
+ - prometheus
+ - mongodb-exporter
+min-juju-version: 2.8.0
+deployment:
+ type: stateless
+ service: cluster
+resources:
+ image:
+ type: oci-image
+ description: Image of mongodb-exporter
+ upstream-source: "bitnami/mongodb-exporter:0.30.0"
+provides:
+ prometheus-scrape:
+ interface: prometheus
+ grafana-dashboard:
+ interface: grafana-dashboard
+requires:
+ mongodb:
+ interface: mongodb
diff --git a/installers/charm/mongodb-exporter/requirements-test.txt b/installers/charm/mongodb-exporter/requirements-test.txt
new file mode 100644
index 0000000..316f6d2
--- /dev/null
+++ b/installers/charm/mongodb-exporter/requirements-test.txt
@@ -0,0 +1,21 @@
+# Copyright 2021 Canonical Ltd.
+#
+# 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.
+#
+# For those usages not covered by the Apache License, Version 2.0 please
+# contact: legal@canonical.com
+#
+# To get in touch with the maintainers, please contact:
+# osm-charmers@lists.launchpad.net
+
+mock==4.0.3
diff --git a/installers/charm/mongodb-exporter/requirements.txt b/installers/charm/mongodb-exporter/requirements.txt
new file mode 100644
index 0000000..8bb93ad
--- /dev/null
+++ b/installers/charm/mongodb-exporter/requirements.txt
@@ -0,0 +1,22 @@
+# Copyright 2021 Canonical Ltd.
+#
+# 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.
+#
+# For those usages not covered by the Apache License, Version 2.0 please
+# contact: legal@canonical.com
+#
+# To get in touch with the maintainers, please contact:
+# osm-charmers@lists.launchpad.net
+##
+
+git+https://github.com/charmed-osm/ops-lib-charmed-osm/@master
diff --git a/installers/charm/mongodb-exporter/src/charm.py b/installers/charm/mongodb-exporter/src/charm.py
new file mode 100755
index 0000000..0ee127c
--- /dev/null
+++ b/installers/charm/mongodb-exporter/src/charm.py
@@ -0,0 +1,275 @@
+#!/usr/bin/env python3
+# Copyright 2021 Canonical Ltd.
+#
+# 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.
+#
+# For those usages not covered by the Apache License, Version 2.0 please
+# contact: legal@canonical.com
+#
+# To get in touch with the maintainers, please contact:
+# osm-charmers@lists.launchpad.net
+##
+
+# pylint: disable=E0213
+
+from ipaddress import ip_network
+import logging
+from pathlib import Path
+from typing import NoReturn, Optional
+from urllib.parse import urlparse
+
+from ops.main import main
+from opslib.osm.charm import CharmedOsmBase, RelationsMissing
+from opslib.osm.interfaces.grafana import GrafanaDashboardTarget
+from opslib.osm.interfaces.mongo import MongoClient
+from opslib.osm.interfaces.prometheus import PrometheusScrapeTarget
+from opslib.osm.pod import (
+ ContainerV3Builder,
+ IngressResourceV3Builder,
+ PodRestartPolicy,
+ PodSpecV3Builder,
+)
+from opslib.osm.validator import ModelValidator, validator
+
+
+logger = logging.getLogger(__name__)
+
+PORT = 9216
+
+
+class ConfigModel(ModelValidator):
+ site_url: Optional[str]
+ cluster_issuer: Optional[str]
+ ingress_class: Optional[str]
+ ingress_whitelist_source_range: Optional[str]
+ tls_secret_name: Optional[str]
+ mongodb_uri: Optional[str]
+ image_pull_policy: str
+ security_context: bool
+
+ @validator("site_url")
+ def validate_site_url(cls, v):
+ if v:
+ parsed = urlparse(v)
+ if not parsed.scheme.startswith("http"):
+ raise ValueError("value must start with http")
+ return v
+
+ @validator("ingress_whitelist_source_range")
+ def validate_ingress_whitelist_source_range(cls, v):
+ if v:
+ ip_network(v)
+ return v
+
+ @validator("mongodb_uri")
+ def validate_mongodb_uri(cls, v):
+ if v and not v.startswith("mongodb://"):
+ raise ValueError("mongodb_uri is not properly formed")
+ return v
+
+ @validator("image_pull_policy")
+ def validate_image_pull_policy(cls, v):
+ values = {
+ "always": "Always",
+ "ifnotpresent": "IfNotPresent",
+ "never": "Never",
+ }
+ v = v.lower()
+ if v not in values.keys():
+ raise ValueError("value must be always, ifnotpresent or never")
+ return values[v]
+
+
+class MongodbExporterCharm(CharmedOsmBase):
+ def __init__(self, *args) -> NoReturn:
+ super().__init__(*args, oci_image="image")
+
+ # Provision Kafka relation to exchange information
+ self.mongodb_client = MongoClient(self, "mongodb")
+ self.framework.observe(self.on["mongodb"].relation_changed, self.configure_pod)
+ self.framework.observe(self.on["mongodb"].relation_broken, self.configure_pod)
+
+ # Register relation to provide a Scraping Target
+ self.scrape_target = PrometheusScrapeTarget(self, "prometheus-scrape")
+ self.framework.observe(
+ self.on["prometheus-scrape"].relation_joined, self._publish_scrape_info
+ )
+
+ # Register relation to provide a Dasboard Target
+ self.dashboard_target = GrafanaDashboardTarget(self, "grafana-dashboard")
+ self.framework.observe(
+ self.on["grafana-dashboard"].relation_joined, self._publish_dashboard_info
+ )
+
+ def _publish_scrape_info(self, event) -> NoReturn:
+ """Publishes scraping information for Prometheus.
+
+ Args:
+ event (EventBase): Prometheus relation event.
+ """
+ if self.unit.is_leader():
+ hostname = (
+ urlparse(self.model.config["site_url"]).hostname
+ if self.model.config["site_url"]
+ else self.model.app.name
+ )
+ port = str(PORT)
+ if self.model.config.get("site_url", "").startswith("https://"):
+ port = "443"
+ elif self.model.config.get("site_url", "").startswith("http://"):
+ port = "80"
+
+ self.scrape_target.publish_info(
+ hostname=hostname,
+ port=port,
+ metrics_path="/metrics",
+ scrape_interval="30s",
+ scrape_timeout="15s",
+ )
+
+ def _publish_dashboard_info(self, event) -> NoReturn:
+ """Publish dashboards for Grafana.
+
+ Args:
+ event (EventBase): Grafana relation event.
+ """
+ if self.unit.is_leader():
+ self.dashboard_target.publish_info(
+ name="osm-mongodb",
+ dashboard=Path("templates/mongodb_exporter_dashboard.json").read_text(),
+ )
+
+ def _check_missing_dependencies(self, config: ConfigModel):
+ """Check if there is any relation missing.
+
+ Args:
+ config (ConfigModel): object with configuration information.
+
+ Raises:
+ RelationsMissing: if kafka is missing.
+ """
+ missing_relations = []
+
+ if not config.mongodb_uri and self.mongodb_client.is_missing_data_in_unit():
+ missing_relations.append("mongodb")
+
+ if missing_relations:
+ raise RelationsMissing(missing_relations)
+
+ def build_pod_spec(self, image_info):
+ """Build the PodSpec to be used.
+
+ Args:
+ image_info (str): container image information.
+
+ Returns:
+ Dict: PodSpec information.
+ """
+ # Validate config
+ config = ConfigModel(**dict(self.config))
+
+ if config.mongodb_uri and not self.mongodb_client.is_missing_data_in_unit():
+ raise Exception("Mongodb data cannot be provided via config and relation")
+
+ # Check relations
+ self._check_missing_dependencies(config)
+
+ unparsed = (
+ config.mongodb_uri
+ if config.mongodb_uri
+ else self.mongodb_client.connection_string
+ )
+ parsed = urlparse(unparsed)
+ mongodb_uri = f"mongodb://{parsed.netloc.split(',')[0]}{parsed.path}"
+ if parsed.query:
+ mongodb_uri += f"?{parsed.query}"
+
+ # Create Builder for the PodSpec
+ pod_spec_builder = PodSpecV3Builder(
+ enable_security_context=config.security_context
+ )
+
+ # Add secrets to the pod
+ mongodb_secret_name = f"{self.app.name}-mongodb-secret"
+ pod_spec_builder.add_secret(mongodb_secret_name, {"uri": mongodb_uri})
+
+ # Build container
+ container_builder = ContainerV3Builder(
+ self.app.name,
+ image_info,
+ config.image_pull_policy,
+ run_as_non_root=config.security_context,
+ )
+ container_builder.add_port(name="exporter", port=PORT)
+ container_builder.add_http_readiness_probe(
+ path="/api/health",
+ port=PORT,
+ initial_delay_seconds=10,
+ period_seconds=10,
+ timeout_seconds=5,
+ success_threshold=1,
+ failure_threshold=3,
+ )
+ container_builder.add_http_liveness_probe(
+ path="/api/health",
+ port=PORT,
+ initial_delay_seconds=60,
+ timeout_seconds=30,
+ failure_threshold=10,
+ )
+
+ container_builder.add_secret_envs(mongodb_secret_name, {"MONGODB_URI": "uri"})
+ container = container_builder.build()
+
+ # Add container to PodSpec
+ pod_spec_builder.add_container(container)
+
+ # Add Pod restart policy
+ restart_policy = PodRestartPolicy()
+ restart_policy.add_secrets(secret_names=(mongodb_secret_name,))
+ pod_spec_builder.set_restart_policy(restart_policy)
+
+ # Add ingress resources to PodSpec if site url exists
+ if config.site_url:
+ parsed = urlparse(config.site_url)
+ annotations = {}
+ if config.ingress_class:
+ annotations["kubernetes.io/ingress.class"] = config.ingress_class
+ ingress_resource_builder = IngressResourceV3Builder(
+ f"{self.app.name}-ingress", annotations
+ )
+
+ if config.ingress_whitelist_source_range:
+ annotations[
+ "nginx.ingress.kubernetes.io/whitelist-source-range"
+ ] = config.ingress_whitelist_source_range
+
+ if config.cluster_issuer:
+ annotations["cert-manager.io/cluster-issuer"] = config.cluster_issuer
+
+ if parsed.scheme == "https":
+ ingress_resource_builder.add_tls(
+ [parsed.hostname], config.tls_secret_name
+ )
+ else:
+ annotations["nginx.ingress.kubernetes.io/ssl-redirect"] = "false"
+
+ ingress_resource_builder.add_rule(parsed.hostname, self.app.name, PORT)
+ ingress_resource = ingress_resource_builder.build()
+ pod_spec_builder.add_ingress_resource(ingress_resource)
+
+ return pod_spec_builder.build()
+
+
+if __name__ == "__main__":
+ main(MongodbExporterCharm)
diff --git a/installers/charm/mongodb-exporter/src/pod_spec.py b/installers/charm/mongodb-exporter/src/pod_spec.py
new file mode 100644
index 0000000..ff42e02
--- /dev/null
+++ b/installers/charm/mongodb-exporter/src/pod_spec.py
@@ -0,0 +1,305 @@
+#!/usr/bin/env python3
+# Copyright 2021 Canonical Ltd.
+#
+# 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.
+#
+# For those usages not covered by the Apache License, Version 2.0 please
+# contact: legal@canonical.com
+#
+# To get in touch with the maintainers, please contact:
+# osm-charmers@lists.launchpad.net
+##
+
+from ipaddress import ip_network
+import logging
+from typing import Any, Dict, List
+from urllib.parse import urlparse
+
+logger = logging.getLogger(__name__)
+
+
+def _validate_ip_network(network: str) -> bool:
+ """Validate IP network.
+
+ Args:
+ network (str): IP network range.
+
+ Returns:
+ bool: True if valid, false otherwise.
+ """
+ if not network:
+ return True
+
+ try:
+ ip_network(network)
+ except ValueError:
+ return False
+
+ return True
+
+
+def _validate_data(config_data: Dict[str, Any], relation_data: Dict[str, Any]) -> bool:
+ """Validates passed information.
+
+ Args:
+ config_data (Dict[str, Any]): configuration information.
+ relation_data (Dict[str, Any]): relation information
+
+ Raises:
+ ValueError: when config and/or relation data is not valid.
+ """
+ config_validators = {
+ "site_url": lambda value, _: isinstance(value, str)
+ if value is not None
+ else True,
+ "cluster_issuer": lambda value, _: isinstance(value, str)
+ if value is not None
+ else True,
+ "ingress_whitelist_source_range": lambda value, _: _validate_ip_network(value),
+ "tls_secret_name": lambda value, _: isinstance(value, str)
+ if value is not None
+ else True,
+ }
+ relation_validators = {
+ "mongodb_connection_string": lambda value, _: (
+ isinstance(value, str) and value.startswith("mongodb://")
+ )
+ }
+ problems = []
+
+ for key, validator in config_validators.items():
+ valid = validator(config_data.get(key), config_data)
+
+ if not valid:
+ problems.append(key)
+
+ for key, validator in relation_validators.items():
+ valid = validator(relation_data.get(key), relation_data)
+
+ if not valid:
+ problems.append(key)
+
+ if len(problems) > 0:
+ raise ValueError("Errors found in: {}".format(", ".join(problems)))
+
+ return True
+
+
+def _make_pod_ports(port: int) -> List[Dict[str, Any]]:
+ """Generate pod ports details.
+
+ Args:
+ port (int): port to expose.
+
+ Returns:
+ List[Dict[str, Any]]: pod port details.
+ """
+ return [
+ {
+ "name": "mongo-exporter",
+ "containerPort": port,
+ "protocol": "TCP",
+ }
+ ]
+
+
+def _make_pod_envconfig(
+ config: Dict[str, Any], relation_state: Dict[str, Any]
+) -> Dict[str, Any]:
+ """Generate pod environment configuration.
+
+ Args:
+ config (Dict[str, Any]): configuration information.
+ relation_state (Dict[str, Any]): relation state information.
+
+ Returns:
+ Dict[str, Any]: pod environment configuration.
+ """
+ parsed = urlparse(relation_state.get("mongodb_connection_string"))
+
+ envconfig = {
+ "MONGODB_URI": f"mongodb://{parsed.netloc.split(',')[0]}{parsed.path}",
+ }
+
+ if parsed.query:
+ envconfig["MONGODB_URI"] += f"?{parsed.query}"
+
+ return envconfig
+
+
+def _make_pod_ingress_resources(
+ config: Dict[str, Any], app_name: str, port: int
+) -> List[Dict[str, Any]]:
+ """Generate pod ingress resources.
+
+ Args:
+ config (Dict[str, Any]): configuration information.
+ app_name (str): application name.
+ port (int): port to expose.
+
+ Returns:
+ List[Dict[str, Any]]: pod ingress resources.
+ """
+ site_url = config.get("site_url")
+
+ if not site_url:
+ return
+
+ parsed = urlparse(site_url)
+
+ if not parsed.scheme.startswith("http"):
+ return
+
+ ingress_whitelist_source_range = config["ingress_whitelist_source_range"]
+ cluster_issuer = config["cluster_issuer"]
+
+ annotations = {}
+
+ if ingress_whitelist_source_range:
+ annotations[
+ "nginx.ingress.kubernetes.io/whitelist-source-range"
+ ] = ingress_whitelist_source_range
+
+ if cluster_issuer:
+ annotations["cert-manager.io/cluster-issuer"] = cluster_issuer
+
+ ingress_spec_tls = None
+
+ if parsed.scheme == "https":
+ ingress_spec_tls = [{"hosts": [parsed.hostname]}]
+ tls_secret_name = config["tls_secret_name"]
+ if tls_secret_name:
+ ingress_spec_tls[0]["secretName"] = tls_secret_name
+ else:
+ annotations["nginx.ingress.kubernetes.io/ssl-redirect"] = "false"
+
+ ingress = {
+ "name": "{}-ingress".format(app_name),
+ "annotations": annotations,
+ "spec": {
+ "rules": [
+ {
+ "host": parsed.hostname,
+ "http": {
+ "paths": [
+ {
+ "path": "/",
+ "backend": {
+ "serviceName": app_name,
+ "servicePort": port,
+ },
+ }
+ ]
+ },
+ }
+ ]
+ },
+ }
+ if ingress_spec_tls:
+ ingress["spec"]["tls"] = ingress_spec_tls
+
+ return [ingress]
+
+
+def _make_readiness_probe(port: int) -> Dict[str, Any]:
+ """Generate readiness probe.
+
+ Args:
+ port (int): service port.
+
+ Returns:
+ Dict[str, Any]: readiness probe.
+ """
+ return {
+ "httpGet": {
+ "path": "/api/health",
+ "port": port,
+ },
+ "initialDelaySeconds": 10,
+ "periodSeconds": 10,
+ "timeoutSeconds": 5,
+ "successThreshold": 1,
+ "failureThreshold": 3,
+ }
+
+
+def _make_liveness_probe(port: int) -> Dict[str, Any]:
+ """Generate liveness probe.
+
+ Args:
+ port (int): service port.
+
+ Returns:
+ Dict[str, Any]: liveness probe.
+ """
+ return {
+ "httpGet": {
+ "path": "/api/health",
+ "port": port,
+ },
+ "initialDelaySeconds": 60,
+ "timeoutSeconds": 30,
+ "failureThreshold": 10,
+ }
+
+
+def make_pod_spec(
+ image_info: Dict[str, str],
+ config: Dict[str, Any],
+ relation_state: Dict[str, Any],
+ app_name: str = "mongodb-exporter",
+ port: int = 9216,
+) -> Dict[str, Any]:
+ """Generate the pod spec information.
+
+ Args:
+ image_info (Dict[str, str]): Object provided by
+ OCIImageResource("image").fetch().
+ config (Dict[str, Any]): Configuration information.
+ relation_state (Dict[str, Any]): Relation state information.
+ app_name (str, optional): Application name. Defaults to "ro".
+ port (int, optional): Port for the container. Defaults to 9090.
+
+ Returns:
+ Dict[str, Any]: Pod spec dictionary for the charm.
+ """
+ if not image_info:
+ return None
+
+ _validate_data(config, relation_state)
+
+ ports = _make_pod_ports(port)
+ env_config = _make_pod_envconfig(config, relation_state)
+ readiness_probe = _make_readiness_probe(port)
+ liveness_probe = _make_liveness_probe(port)
+ ingress_resources = _make_pod_ingress_resources(config, app_name, port)
+
+ return {
+ "version": 3,
+ "containers": [
+ {
+ "name": app_name,
+ "imageDetails": image_info,
+ "imagePullPolicy": "Always",
+ "ports": ports,
+ "envConfig": env_config,
+ "kubernetes": {
+ "readinessProbe": readiness_probe,
+ "livenessProbe": liveness_probe,
+ },
+ }
+ ],
+ "kubernetesResources": {
+ "ingressResources": ingress_resources or [],
+ },
+ }
diff --git a/installers/charm/mongodb-exporter/templates/mongodb_exporter_dashboard.json b/installers/charm/mongodb-exporter/templates/mongodb_exporter_dashboard.json
new file mode 100644
index 0000000..c6c64c2
--- /dev/null
+++ b/installers/charm/mongodb-exporter/templates/mongodb_exporter_dashboard.json
@@ -0,0 +1,938 @@
+{
+ "annotations": {
+ "list": [
+ {
+ "builtIn": 1,
+ "datasource": "-- Grafana --",
+ "enable": true,
+ "hide": true,
+ "iconColor": "rgba(0, 211, 255, 1)",
+ "name": "Annotations & Alerts",
+ "type": "dashboard"
+ }
+ ]
+ },
+ "description": "MongoDB Prometheus Exporter Dashboard.",
+ "editable": true,
+ "gnetId": 2583,
+ "graphTooltip": 1,
+ "id": 1,
+ "iteration": 1615141074039,
+ "links": [],
+ "panels": [
+ {
+ "collapsed": false,
+ "datasource": null,
+ "gridPos": {
+ "h": 1,
+ "w": 24,
+ "x": 0,
+ "y": 0
+ },
+ "id": 22,
+ "panels": [],
+ "repeat": "env",
+ "title": "Health",
+ "type": "row"
+ },
+ {
+ "cacheTimeout": null,
+ "colorBackground": false,
+ "colorValue": true,
+ "colors": [
+ "rgba(245, 54, 54, 0.9)",
+ "rgba(237, 129, 40, 0.89)",
+ "rgba(50, 172, 45, 0.97)"
+ ],
+ "datasource": "prometheus - Juju generated source",
+ "decimals": null,
+ "fieldConfig": {
+ "defaults": {
+ "custom": {}
+ },
+ "overrides": []
+ },
+ "format": "s",
+ "gauge": {
+ "maxValue": 100,
+ "minValue": 0,
+ "show": false,
+ "thresholdLabels": false,
+ "thresholdMarkers": true
+ },
+ "gridPos": {
+ "h": 4,
+ "w": 12,
+ "x": 0,
+ "y": 1
+ },
+ "id": 10,
+ "interval": null,
+ "links": [],
+ "mappingType": 1,
+ "mappingTypes": [
+ {
+ "name": "value to text",
+ "value": 1
+ },
+ {
+ "name": "range to text",
+ "value": 2
+ }
+ ],
+ "maxDataPoints": 100,
+ "nullPointMode": "connected",
+ "nullText": null,
+ "postfix": "",
+ "postfixFontSize": "50%",
+ "prefix": "",
+ "prefixFontSize": "50%",
+ "rangeMaps": [
+ {
+ "from": "null",
+ "text": "N/A",
+ "to": "null"
+ }
+ ],
+ "sparkline": {
+ "fillColor": "rgba(31, 118, 189, 0.18)",
+ "full": false,
+ "lineColor": "rgb(31, 120, 193)",
+ "show": false
+ },
+ "tableColumn": "",
+ "targets": [
+ {
+ "expr": "mongodb_ss_uptime{}",
+ "format": "time_series",
+ "interval": "",
+ "intervalFactor": 2,
+ "legendFormat": "",
+ "refId": "A",
+ "step": 1800
+ }
+ ],
+ "thresholds": "0,360",
+ "title": "Uptime",
+ "type": "singlestat",
+ "valueFontSize": "80%",
+ "valueMaps": [
+ {
+ "op": "=",
+ "text": "N/A",
+ "value": "null"
+ }
+ ],
+ "valueName": "current"
+ },
+ {
+ "cacheTimeout": null,
+ "colorBackground": false,
+ "colorValue": false,
+ "colors": [
+ "rgba(245, 54, 54, 0.9)",
+ "rgba(237, 129, 40, 0.89)",
+ "rgba(50, 172, 45, 0.97)"
+ ],
+ "datasource": "prometheus - Juju generated source",
+ "fieldConfig": {
+ "defaults": {
+ "custom": {}
+ },
+ "overrides": []
+ },
+ "format": "none",
+ "gauge": {
+ "maxValue": 100,
+ "minValue": 0,
+ "show": false,
+ "thresholdLabels": false,
+ "thresholdMarkers": true
+ },
+ "gridPos": {
+ "h": 4,
+ "w": 12,
+ "x": 12,
+ "y": 1
+ },
+ "id": 1,
+ "interval": null,
+ "links": [],
+ "mappingType": 1,
+ "mappingTypes": [
+ {
+ "name": "value to text",
+ "value": 1
+ },
+ {
+ "name": "range to text",
+ "value": 2
+ }
+ ],
+ "maxDataPoints": 100,
+ "nullPointMode": "connected",
+ "nullText": null,
+ "postfix": "",
+ "postfixFontSize": "50%",
+ "prefix": "",
+ "prefixFontSize": "50%",
+ "rangeMaps": [
+ {
+ "from": "null",
+ "text": "N/A",
+ "to": "null"
+ }
+ ],
+ "sparkline": {
+ "fillColor": "rgba(31, 118, 189, 0.18)",
+ "full": true,
+ "lineColor": "rgb(31, 120, 193)",
+ "show": true
+ },
+ "tableColumn": "",
+ "targets": [
+ {
+ "expr": "mongodb_ss_connections{conn_type=\"current\"}",
+ "format": "time_series",
+ "interval": "",
+ "intervalFactor": 2,
+ "legendFormat": "",
+ "metric": "mongodb_connections",
+ "refId": "A",
+ "step": 1800
+ }
+ ],
+ "thresholds": "",
+ "title": "Open Connections",
+ "type": "singlestat",
+ "valueFontSize": "80%",
+ "valueMaps": [
+ {
+ "op": "=",
+ "text": "N/A",
+ "value": "null"
+ }
+ ],
+ "valueName": "avg"
+ },
+ {
+ "collapsed": false,
+ "datasource": null,
+ "gridPos": {
+ "h": 1,
+ "w": 24,
+ "x": 0,
+ "y": 5
+ },
+ "id": 20,
+ "panels": [],
+ "repeat": "env",
+ "title": "Operations",
+ "type": "row"
+ },
+ {
+ "aliasColors": {},
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "prometheus - Juju generated source",
+ "fieldConfig": {
+ "defaults": {
+ "custom": {},
+ "links": []
+ },
+ "overrides": []
+ },
+ "fill": 1,
+ "fillGradient": 0,
+ "gridPos": {
+ "h": 6,
+ "w": 10,
+ "x": 0,
+ "y": 6
+ },
+ "hiddenSeries": false,
+ "id": 7,
+ "legend": {
+ "avg": false,
+ "current": false,
+ "max": false,
+ "min": false,
+ "show": true,
+ "total": false,
+ "values": false
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "nullPointMode": "null",
+ "options": {
+ "alertThreshold": true
+ },
+ "percentage": false,
+ "pluginVersion": "7.4.3",
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "seriesOverrides": [],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "rate(mongodb_ss_opcounters[$interval])",
+ "format": "time_series",
+ "interval": "",
+ "intervalFactor": 2,
+ "legendFormat": "{{legacy_op_type}}",
+ "refId": "A",
+ "step": 240
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "Query Operations",
+ "tooltip": {
+ "shared": true,
+ "sort": 0,
+ "value_type": "individual"
+ },
+ "type": "graph",
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "yaxes": [
+ {
+ "$$hashKey": "object:670",
+ "format": "ops",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ },
+ {
+ "$$hashKey": "object:671",
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ },
+ {
+ "aliasColors": {},
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "prometheus - Juju generated source",
+ "fieldConfig": {
+ "defaults": {
+ "custom": {},
+ "links": []
+ },
+ "overrides": []
+ },
+ "fill": 1,
+ "fillGradient": 0,
+ "gridPos": {
+ "h": 6,
+ "w": 8,
+ "x": 10,
+ "y": 6
+ },
+ "hiddenSeries": false,
+ "id": 9,
+ "legend": {
+ "avg": false,
+ "current": false,
+ "max": false,
+ "min": false,
+ "show": true,
+ "total": false,
+ "values": false
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "nullPointMode": "null",
+ "options": {
+ "alertThreshold": true
+ },
+ "percentage": false,
+ "pluginVersion": "7.4.3",
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "seriesOverrides": [
+ {
+ "alias": "returned",
+ "yaxis": 1
+ }
+ ],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "rate(mongodb_ss_metrics_document[$interval])",
+ "format": "time_series",
+ "interval": "",
+ "intervalFactor": 2,
+ "legendFormat": "{{doc_op_type}}",
+ "refId": "A",
+ "step": 240
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "Document Operations",
+ "tooltip": {
+ "shared": true,
+ "sort": 0,
+ "value_type": "individual"
+ },
+ "type": "graph",
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "yaxes": [
+ {
+ "$$hashKey": "object:699",
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ },
+ {
+ "$$hashKey": "object:700",
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ },
+ {
+ "aliasColors": {},
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "prometheus - Juju generated source",
+ "fieldConfig": {
+ "defaults": {
+ "custom": {},
+ "links": []
+ },
+ "overrides": []
+ },
+ "fill": 1,
+ "fillGradient": 0,
+ "gridPos": {
+ "h": 6,
+ "w": 6,
+ "x": 18,
+ "y": 6
+ },
+ "hiddenSeries": false,
+ "id": 8,
+ "legend": {
+ "avg": false,
+ "current": false,
+ "max": false,
+ "min": false,
+ "show": true,
+ "total": false,
+ "values": false
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "nullPointMode": "null",
+ "options": {
+ "alertThreshold": true
+ },
+ "percentage": false,
+ "pluginVersion": "7.4.3",
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "seriesOverrides": [],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "rate(mongodb_ss_opcounters[$interval])",
+ "format": "time_series",
+ "interval": "",
+ "intervalFactor": 2,
+ "legendFormat": "{{legacy_op_type}}",
+ "refId": "A",
+ "step": 600
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "Document Query Executor",
+ "tooltip": {
+ "shared": true,
+ "sort": 0,
+ "value_type": "individual"
+ },
+ "type": "graph",
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "yaxes": [
+ {
+ "$$hashKey": "object:728",
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ },
+ {
+ "$$hashKey": "object:729",
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ },
+ {
+ "collapsed": false,
+ "datasource": null,
+ "gridPos": {
+ "h": 1,
+ "w": 24,
+ "x": 0,
+ "y": 12
+ },
+ "id": 23,
+ "panels": [],
+ "repeat": null,
+ "title": "Resources",
+ "type": "row"
+ },
+ {
+ "aliasColors": {},
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "prometheus - Juju generated source",
+ "fieldConfig": {
+ "defaults": {
+ "custom": {},
+ "links": []
+ },
+ "overrides": []
+ },
+ "fill": 1,
+ "fillGradient": 0,
+ "gridPos": {
+ "h": 6,
+ "w": 12,
+ "x": 0,
+ "y": 13
+ },
+ "hiddenSeries": false,
+ "id": 4,
+ "legend": {
+ "alignAsTable": false,
+ "avg": false,
+ "current": true,
+ "hideEmpty": false,
+ "hideZero": false,
+ "max": false,
+ "min": false,
+ "rightSide": false,
+ "show": true,
+ "total": false,
+ "values": true
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "nullPointMode": "null",
+ "options": {
+ "alertThreshold": true
+ },
+ "percentage": false,
+ "pluginVersion": "7.4.3",
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "seriesOverrides": [],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "mongodb_ss_mem_resident",
+ "format": "time_series",
+ "interval": "",
+ "intervalFactor": 2,
+ "legendFormat": "Resident",
+ "refId": "A",
+ "step": 240
+ },
+ {
+ "expr": "mongodb_ss_mem_virtual",
+ "hide": false,
+ "interval": "",
+ "legendFormat": "Virtual",
+ "refId": "B"
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "Memory",
+ "tooltip": {
+ "shared": false,
+ "sort": 0,
+ "value_type": "individual"
+ },
+ "type": "graph",
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": [
+ "total"
+ ]
+ },
+ "yaxes": [
+ {
+ "$$hashKey": "object:523",
+ "format": "decmbytes",
+ "label": "",
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ },
+ {
+ "$$hashKey": "object:524",
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ },
+ {
+ "aliasColors": {},
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "prometheus - Juju generated source",
+ "fieldConfig": {
+ "defaults": {
+ "custom": {},
+ "links": []
+ },
+ "overrides": []
+ },
+ "fill": 1,
+ "fillGradient": 0,
+ "gridPos": {
+ "h": 6,
+ "w": 12,
+ "x": 12,
+ "y": 13
+ },
+ "hiddenSeries": false,
+ "id": 5,
+ "legend": {
+ "avg": false,
+ "current": false,
+ "max": false,
+ "min": false,
+ "show": true,
+ "total": false,
+ "values": false
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "nullPointMode": "null",
+ "options": {
+ "alertThreshold": true
+ },
+ "percentage": false,
+ "pluginVersion": "7.4.3",
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "seriesOverrides": [],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "rate(mongodb_ss_network_bytesOut[$interval])",
+ "format": "time_series",
+ "interval": "",
+ "intervalFactor": 2,
+ "legendFormat": "Out",
+ "metric": "mongodb_metrics_operation_total",
+ "refId": "A",
+ "step": 240
+ },
+ {
+ "expr": "rate(mongodb_ss_network_bytesIn[$interval])",
+ "hide": false,
+ "interval": "",
+ "intervalFactor": 2,
+ "legendFormat": "In",
+ "refId": "B"
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "Network I/O",
+ "tooltip": {
+ "shared": true,
+ "sort": 0,
+ "value_type": "individual"
+ },
+ "type": "graph",
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "yaxes": [
+ {
+ "$$hashKey": "object:579",
+ "format": "decbytes",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ },
+ {
+ "$$hashKey": "object:580",
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ }
+ ],
+ "refresh": "5s",
+ "schemaVersion": 27,
+ "style": "dark",
+ "tags": [],
+ "templating": {
+ "list": [
+ {
+ "allValue": null,
+ "current": {
+ "selected": true,
+ "text": [
+ "All"
+ ],
+ "value": [
+ "$__all"
+ ]
+ },
+ "datasource": "prometheus - Juju generated source",
+ "definition": "",
+ "description": null,
+ "error": null,
+ "hide": 0,
+ "includeAll": true,
+ "label": "instance",
+ "multi": true,
+ "name": "instance",
+ "options": [],
+ "query": {
+ "query": "label_values(mongodb_connections, instance)",
+ "refId": "prometheus - Juju generated source-instance-Variable-Query"
+ },
+ "refresh": 1,
+ "regex": "",
+ "skipUrlSync": false,
+ "sort": 1,
+ "tagValuesQuery": "/.*-(.*?)-.*/",
+ "tags": [],
+ "tagsQuery": "label_values(mongodb_connections, instance)",
+ "type": "query",
+ "useTags": false
+ },
+ {
+ "auto": true,
+ "auto_count": 30,
+ "auto_min": "10s",
+ "current": {
+ "selected": false,
+ "text": "auto",
+ "value": "$__auto_interval_interval"
+ },
+ "description": null,
+ "error": null,
+ "hide": 0,
+ "label": null,
+ "name": "interval",
+ "options": [
+ {
+ "selected": true,
+ "text": "auto",
+ "value": "$__auto_interval_interval"
+ },
+ {
+ "selected": false,
+ "text": "1m",
+ "value": "1m"
+ },
+ {
+ "selected": false,
+ "text": "10m",
+ "value": "10m"
+ },
+ {
+ "selected": false,
+ "text": "30m",
+ "value": "30m"
+ },
+ {
+ "selected": false,
+ "text": "1h",
+ "value": "1h"
+ },
+ {
+ "selected": false,
+ "text": "6h",
+ "value": "6h"
+ },
+ {
+ "selected": false,
+ "text": "12h",
+ "value": "12h"
+ },
+ {
+ "selected": false,
+ "text": "1d",
+ "value": "1d"
+ },
+ {
+ "selected": false,
+ "text": "7d",
+ "value": "7d"
+ },
+ {
+ "selected": false,
+ "text": "14d",
+ "value": "14d"
+ },
+ {
+ "selected": false,
+ "text": "30d",
+ "value": "30d"
+ }
+ ],
+ "query": "1m,10m,30m,1h,6h,12h,1d,7d,14d,30d",
+ "refresh": 2,
+ "skipUrlSync": false,
+ "type": "interval"
+ }
+ ]
+ },
+ "time": {
+ "from": "now/d",
+ "to": "now"
+ },
+ "timepicker": {
+ "refresh_intervals": [
+ "5s",
+ "10s",
+ "30s",
+ "1m",
+ "5m",
+ "15m",
+ "30m",
+ "1h",
+ "2h",
+ "1d"
+ ],
+ "time_options": [
+ "5m",
+ "15m",
+ "1h",
+ "6h",
+ "12h",
+ "24h",
+ "2d",
+ "7d",
+ "30d"
+ ]
+ },
+ "timezone": "browser",
+ "title": "MongoDB",
+ "uid": "HEK4NbtZk",
+ "version": 17
+}
\ No newline at end of file
diff --git a/installers/charm/mongodb-exporter/tests/__init__.py b/installers/charm/mongodb-exporter/tests/__init__.py
new file mode 100644
index 0000000..90dc417
--- /dev/null
+++ b/installers/charm/mongodb-exporter/tests/__init__.py
@@ -0,0 +1,39 @@
+#!/usr/bin/env python3
+# Copyright 2021 Canonical Ltd.
+#
+# 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.
+#
+# For those usages not covered by the Apache License, Version 2.0 please
+# contact: legal@canonical.com
+#
+# To get in touch with the maintainers, please contact:
+# osm-charmers@lists.launchpad.net
+##
+
+"""Init mocking for unit tests."""
+
+import sys
+
+import mock
+
+
+class OCIImageResourceErrorMock(Exception):
+ pass
+
+
+sys.path.append("src")
+
+oci_image = mock.MagicMock()
+oci_image.OCIImageResourceError = OCIImageResourceErrorMock
+sys.modules["oci_image"] = oci_image
+sys.modules["oci_image"].OCIImageResource().fetch.return_value = {}
diff --git a/installers/charm/mongodb-exporter/tests/test_charm.py b/installers/charm/mongodb-exporter/tests/test_charm.py
new file mode 100644
index 0000000..1675f5f
--- /dev/null
+++ b/installers/charm/mongodb-exporter/tests/test_charm.py
@@ -0,0 +1,583 @@
+#!/usr/bin/env python3
+# Copyright 2021 Canonical Ltd.
+#
+# 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.
+#
+# For those usages not covered by the Apache License, Version 2.0 please
+# contact: legal@canonical.com
+#
+# To get in touch with the maintainers, please contact:
+# osm-charmers@lists.launchpad.net
+##
+
+import sys
+from typing import NoReturn
+import unittest
+
+from charm import MongodbExporterCharm
+from ops.model import ActiveStatus, BlockedStatus
+from ops.testing import Harness
+
+
+class TestCharm(unittest.TestCase):
+ """Mongodb Exporter Charm unit tests."""
+
+ def setUp(self) -> NoReturn:
+ """Test setup"""
+ self.image_info = sys.modules["oci_image"].OCIImageResource().fetch()
+ self.harness = Harness(MongodbExporterCharm)
+ self.harness.set_leader(is_leader=True)
+ self.harness.begin()
+ self.config = {
+ "ingress_whitelist_source_range": "",
+ "tls_secret_name": "",
+ "site_url": "https://mongodb-exporter.192.168.100.100.nip.io",
+ "cluster_issuer": "vault-issuer",
+ }
+ self.harness.update_config(self.config)
+
+ def test_config_changed_no_relations(
+ self,
+ ) -> NoReturn:
+ """Test ingress resources without HTTP."""
+
+ self.harness.charm.on.config_changed.emit()
+
+ # Assertions
+ self.assertIsInstance(self.harness.charm.unit.status, BlockedStatus)
+ print(self.harness.charm.unit.status.message)
+ self.assertTrue(
+ all(
+ relation in self.harness.charm.unit.status.message
+ for relation in ["mongodb"]
+ )
+ )
+
+ def test_config_changed_non_leader(
+ self,
+ ) -> NoReturn:
+ """Test ingress resources without HTTP."""
+ self.harness.set_leader(is_leader=False)
+ self.harness.charm.on.config_changed.emit()
+
+ # Assertions
+ self.assertIsInstance(self.harness.charm.unit.status, ActiveStatus)
+
+ def test_with_relations(
+ self,
+ ) -> NoReturn:
+ "Test with relations"
+ self.initialize_mongo_relation()
+
+ # Verifying status
+ self.assertNotIsInstance(self.harness.charm.unit.status, BlockedStatus)
+
+ def test_with_config(
+ self,
+ ) -> NoReturn:
+ "Test with config"
+ self.initialize_mongo_relation()
+
+ # Verifying status
+ self.assertNotIsInstance(self.harness.charm.unit.status, BlockedStatus)
+
+ def test_mongodb_exception_relation_and_config(
+ self,
+ ) -> NoReturn:
+ self.initialize_mongo_config()
+ self.initialize_mongo_relation()
+
+ # Verifying status
+ self.assertIsInstance(self.harness.charm.unit.status, BlockedStatus)
+
+ def initialize_mongo_relation(self):
+ mongodb_relation_id = self.harness.add_relation("mongodb", "mongodb")
+ self.harness.add_relation_unit(mongodb_relation_id, "mongodb/0")
+ self.harness.update_relation_data(
+ mongodb_relation_id,
+ "mongodb/0",
+ {"connection_string": "mongodb://mongo:27017"},
+ )
+
+ def initialize_mongo_config(self):
+ self.harness.update_config({"mongodb_uri": "mongodb://mongo:27017"})
+
+
+if __name__ == "__main__":
+ unittest.main()
+
+
+# class TestCharm(unittest.TestCase):
+# """Mongodb Exporter Charm unit tests."""
+#
+# def setUp(self) -> NoReturn:
+# """Test setup"""
+# self.harness = Harness(MongodbExporterCharm)
+# self.harness.set_leader(is_leader=True)
+# self.harness.begin()
+#
+# def test_on_start_without_relations(self) -> NoReturn:
+# """Test installation without any relation."""
+# self.harness.charm.on.start.emit()
+#
+# # Verifying status
+# self.assertIsInstance(self.harness.charm.unit.status, BlockedStatus)
+#
+# # Verifying status message
+# self.assertGreater(len(self.harness.charm.unit.status.message), 0)
+# self.assertTrue(
+# self.harness.charm.unit.status.message.startswith("Waiting for ")
+# )
+# self.assertIn("mongodb", self.harness.charm.unit.status.message)
+# self.assertTrue(self.harness.charm.unit.status.message.endswith(" relation"))
+#
+# def test_on_start_with_relations_without_http(self) -> NoReturn:
+# """Test deployment."""
+# expected_result = {
+# "version": 3,
+# "containers": [
+# {
+# "name": "mongodb-exporter",
+# "imageDetails": self.harness.charm.image.fetch(),
+# "imagePullPolicy": "Always",
+# "ports": [
+# {
+# "name": "mongo-exporter",
+# "containerPort": 9216,
+# "protocol": "TCP",
+# }
+# ],
+# "envConfig": {
+# "MONGODB_URI": "mongodb://mongo",
+# },
+# "kubernetes": {
+# "readinessProbe": {
+# "httpGet": {
+# "path": "/api/health",
+# "port": 9216,
+# },
+# "initialDelaySeconds": 10,
+# "periodSeconds": 10,
+# "timeoutSeconds": 5,
+# "successThreshold": 1,
+# "failureThreshold": 3,
+# },
+# "livenessProbe": {
+# "httpGet": {
+# "path": "/api/health",
+# "port": 9216,
+# },
+# "initialDelaySeconds": 60,
+# "timeoutSeconds": 30,
+# "failureThreshold": 10,
+# },
+# },
+# },
+# ],
+# "kubernetesResources": {"ingressResources": []},
+# }
+#
+# self.harness.charm.on.start.emit()
+#
+# # Initializing the mongodb relation
+# relation_id = self.harness.add_relation("mongodb", "mongodb")
+# self.harness.add_relation_unit(relation_id, "mongodb/0")
+# self.harness.update_relation_data(
+# relation_id,
+# "mongodb/0",
+# {
+# "connection_string": "mongodb://mongo",
+# },
+# )
+#
+# # Verifying status
+# self.assertNotIsInstance(self.harness.charm.unit.status, BlockedStatus)
+#
+# pod_spec, _ = self.harness.get_pod_spec()
+#
+# self.assertDictEqual(expected_result, pod_spec)
+#
+# def test_ingress_resources_with_http(self) -> NoReturn:
+# """Test ingress resources with HTTP."""
+# expected_result = {
+# "version": 3,
+# "containers": [
+# {
+# "name": "mongodb-exporter",
+# "imageDetails": self.harness.charm.image.fetch(),
+# "imagePullPolicy": "Always",
+# "ports": [
+# {
+# "name": "mongo-exporter",
+# "containerPort": 9216,
+# "protocol": "TCP",
+# }
+# ],
+# "envConfig": {
+# "MONGODB_URI": "mongodb://mongo",
+# },
+# "kubernetes": {
+# "readinessProbe": {
+# "httpGet": {
+# "path": "/api/health",
+# "port": 9216,
+# },
+# "initialDelaySeconds": 10,
+# "periodSeconds": 10,
+# "timeoutSeconds": 5,
+# "successThreshold": 1,
+# "failureThreshold": 3,
+# },
+# "livenessProbe": {
+# "httpGet": {
+# "path": "/api/health",
+# "port": 9216,
+# },
+# "initialDelaySeconds": 60,
+# "timeoutSeconds": 30,
+# "failureThreshold": 10,
+# },
+# },
+# },
+# ],
+# "kubernetesResources": {
+# "ingressResources": [
+# {
+# "name": "mongodb-exporter-ingress",
+# "annotations": {
+# "nginx.ingress.kubernetes.io/ssl-redirect": "false",
+# },
+# "spec": {
+# "rules": [
+# {
+# "host": "mongodb-exporter",
+# "http": {
+# "paths": [
+# {
+# "path": "/",
+# "backend": {
+# "serviceName": "mongodb-exporter",
+# "servicePort": 9216,
+# },
+# }
+# ]
+# },
+# }
+# ]
+# },
+# }
+# ],
+# },
+# }
+#
+# self.harness.charm.on.start.emit()
+#
+# # Initializing the mongodb relation
+# relation_id = self.harness.add_relation("mongodb", "mongodb")
+# self.harness.add_relation_unit(relation_id, "mongodb/0")
+# self.harness.update_relation_data(
+# relation_id,
+# "mongodb/0",
+# {
+# "connection_string": "mongodb://mongo",
+# },
+# )
+#
+# self.harness.update_config({"site_url": "http://mongodb-exporter"})
+#
+# pod_spec, _ = self.harness.get_pod_spec()
+#
+# self.assertDictEqual(expected_result, pod_spec)
+#
+# def test_ingress_resources_with_https(self) -> NoReturn:
+# """Test ingress resources with HTTPS."""
+# expected_result = {
+# "version": 3,
+# "containers": [
+# {
+# "name": "mongodb-exporter",
+# "imageDetails": self.harness.charm.image.fetch(),
+# "imagePullPolicy": "Always",
+# "ports": [
+# {
+# "name": "mongo-exporter",
+# "containerPort": 9216,
+# "protocol": "TCP",
+# }
+# ],
+# "envConfig": {
+# "MONGODB_URI": "mongodb://mongo",
+# },
+# "kubernetes": {
+# "readinessProbe": {
+# "httpGet": {
+# "path": "/api/health",
+# "port": 9216,
+# },
+# "initialDelaySeconds": 10,
+# "periodSeconds": 10,
+# "timeoutSeconds": 5,
+# "successThreshold": 1,
+# "failureThreshold": 3,
+# },
+# "livenessProbe": {
+# "httpGet": {
+# "path": "/api/health",
+# "port": 9216,
+# },
+# "initialDelaySeconds": 60,
+# "timeoutSeconds": 30,
+# "failureThreshold": 10,
+# },
+# },
+# },
+# ],
+# "kubernetesResources": {
+# "ingressResources": [
+# {
+# "name": "mongodb-exporter-ingress",
+# "annotations": {},
+# "spec": {
+# "rules": [
+# {
+# "host": "mongodb-exporter",
+# "http": {
+# "paths": [
+# {
+# "path": "/",
+# "backend": {
+# "serviceName": "mongodb-exporter",
+# "servicePort": 9216,
+# },
+# }
+# ]
+# },
+# }
+# ],
+# "tls": [
+# {
+# "hosts": ["mongodb-exporter"],
+# "secretName": "mongodb-exporter",
+# }
+# ],
+# },
+# }
+# ],
+# },
+# }
+#
+# self.harness.charm.on.start.emit()
+#
+# # Initializing the mongodb relation
+# relation_id = self.harness.add_relation("mongodb", "mongodb")
+# self.harness.add_relation_unit(relation_id, "mongodb/0")
+# self.harness.update_relation_data(
+# relation_id,
+# "mongodb/0",
+# {
+# "connection_string": "mongodb://mongo",
+# },
+# )
+#
+# self.harness.update_config(
+# {
+# "site_url": "https://mongodb-exporter",
+# "tls_secret_name": "mongodb-exporter",
+# }
+# )
+#
+# pod_spec, _ = self.harness.get_pod_spec()
+#
+# self.assertDictEqual(expected_result, pod_spec)
+#
+# def test_ingress_resources_with_https_and_ingress_whitelist(self) -> NoReturn:
+# """Test ingress resources with HTTPS and ingress whitelist."""
+# expected_result = {
+# "version": 3,
+# "containers": [
+# {
+# "name": "mongodb-exporter",
+# "imageDetails": self.harness.charm.image.fetch(),
+# "imagePullPolicy": "Always",
+# "ports": [
+# {
+# "name": "mongo-exporter",
+# "containerPort": 9216,
+# "protocol": "TCP",
+# }
+# ],
+# "envConfig": {
+# "MONGODB_URI": "mongodb://mongo",
+# },
+# "kubernetes": {
+# "readinessProbe": {
+# "httpGet": {
+# "path": "/api/health",
+# "port": 9216,
+# },
+# "initialDelaySeconds": 10,
+# "periodSeconds": 10,
+# "timeoutSeconds": 5,
+# "successThreshold": 1,
+# "failureThreshold": 3,
+# },
+# "livenessProbe": {
+# "httpGet": {
+# "path": "/api/health",
+# "port": 9216,
+# },
+# "initialDelaySeconds": 60,
+# "timeoutSeconds": 30,
+# "failureThreshold": 10,
+# },
+# },
+# },
+# ],
+# "kubernetesResources": {
+# "ingressResources": [
+# {
+# "name": "mongodb-exporter-ingress",
+# "annotations": {
+# "nginx.ingress.kubernetes.io/whitelist-source-range": "0.0.0.0/0",
+# },
+# "spec": {
+# "rules": [
+# {
+# "host": "mongodb-exporter",
+# "http": {
+# "paths": [
+# {
+# "path": "/",
+# "backend": {
+# "serviceName": "mongodb-exporter",
+# "servicePort": 9216,
+# },
+# }
+# ]
+# },
+# }
+# ],
+# "tls": [
+# {
+# "hosts": ["mongodb-exporter"],
+# "secretName": "mongodb-exporter",
+# }
+# ],
+# },
+# }
+# ],
+# },
+# }
+#
+# self.harness.charm.on.start.emit()
+#
+# # Initializing the mongodb relation
+# relation_id = self.harness.add_relation("mongodb", "mongodb")
+# self.harness.add_relation_unit(relation_id, "mongodb/0")
+# self.harness.update_relation_data(
+# relation_id,
+# "mongodb/0",
+# {
+# "connection_string": "mongodb://mongo",
+# },
+# )
+#
+# self.harness.update_config(
+# {
+# "site_url": "https://mongodb-exporter",
+# "tls_secret_name": "mongodb-exporter",
+# "ingress_whitelist_source_range": "0.0.0.0/0",
+# }
+# )
+#
+# pod_spec, _ = self.harness.get_pod_spec()
+#
+# self.assertDictEqual(expected_result, pod_spec)
+#
+# def test_on_mongodb_unit_relation_changed(self) -> NoReturn:
+# """Test to see if mongodb relation is updated."""
+# self.harness.charm.on.start.emit()
+#
+# # Initializing the mongodb relation
+# relation_id = self.harness.add_relation("mongodb", "mongodb")
+# self.harness.add_relation_unit(relation_id, "mongodb/0")
+# self.harness.update_relation_data(
+# relation_id,
+# "mongodb/0",
+# {
+# "connection_string": "mongodb://mongo",
+# },
+# )
+#
+# # Verifying status
+# self.assertNotIsInstance(self.harness.charm.unit.status, BlockedStatus)
+#
+# def test_publish_scrape_info(self) -> NoReturn:
+# """Test to see if scrape relation is updated."""
+# expected_result = {
+# "hostname": "mongodb-exporter",
+# "port": "9216",
+# "metrics_path": "/metrics",
+# "scrape_interval": "30s",
+# "scrape_timeout": "15s",
+# }
+#
+# self.harness.charm.on.start.emit()
+#
+# relation_id = self.harness.add_relation("prometheus-scrape", "prometheus")
+# self.harness.add_relation_unit(relation_id, "prometheus/0")
+# relation_data = self.harness.get_relation_data(
+# relation_id, "mongodb-exporter/0"
+# )
+#
+# self.assertDictEqual(expected_result, relation_data)
+#
+# def test_publish_scrape_info_with_site_url(self) -> NoReturn:
+# """Test to see if target relation is updated."""
+# expected_result = {
+# "hostname": "mongodb-exporter-osm",
+# "port": "80",
+# "metrics_path": "/metrics",
+# "scrape_interval": "30s",
+# "scrape_timeout": "15s",
+# }
+#
+# self.harness.charm.on.start.emit()
+#
+# self.harness.update_config({"site_url": "http://mongodb-exporter-osm"})
+#
+# relation_id = self.harness.add_relation("prometheus-scrape", "prometheus")
+# self.harness.add_relation_unit(relation_id, "prometheus/0")
+# relation_data = self.harness.get_relation_data(
+# relation_id, "mongodb-exporter/0"
+# )
+#
+# self.assertDictEqual(expected_result, relation_data)
+#
+# def test_publish_dashboard_info(self) -> NoReturn:
+# """Test to see if dashboard relation is updated."""
+# self.harness.charm.on.start.emit()
+#
+# relation_id = self.harness.add_relation("grafana-dashboard", "grafana")
+# self.harness.add_relation_unit(relation_id, "grafana/0")
+# relation_data = self.harness.get_relation_data(
+# relation_id, "mongodb-exporter/0"
+# )
+#
+# self.assertEqual("osm-mongodb", relation_data["name"])
+# self.assertTrue("dashboard" in relation_data)
+# self.assertTrue(len(relation_data["dashboard"]) > 0)
+#
+#
+# if __name__ == "__main__":
+# unittest.main()
diff --git a/installers/charm/mongodb-exporter/tests/test_pod_spec.py b/installers/charm/mongodb-exporter/tests/test_pod_spec.py
new file mode 100644
index 0000000..94ab6fb
--- /dev/null
+++ b/installers/charm/mongodb-exporter/tests/test_pod_spec.py
@@ -0,0 +1,489 @@
+#!/usr/bin/env python3
+# Copyright 2021 Canonical Ltd.
+#
+# 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.
+#
+# For those usages not covered by the Apache License, Version 2.0 please
+# contact: legal@canonical.com
+#
+# To get in touch with the maintainers, please contact:
+# osm-charmers@lists.launchpad.net
+##
+
+from typing import NoReturn
+import unittest
+
+import pod_spec
+
+
+class TestPodSpec(unittest.TestCase):
+ """Pod spec unit tests."""
+
+ def test_make_pod_ports(self) -> NoReturn:
+ """Testing make pod ports."""
+ port = 9216
+
+ expected_result = [
+ {
+ "name": "mongo-exporter",
+ "containerPort": port,
+ "protocol": "TCP",
+ }
+ ]
+
+ pod_ports = pod_spec._make_pod_ports(port)
+
+ self.assertListEqual(expected_result, pod_ports)
+
+ def test_make_pod_envconfig(self) -> NoReturn:
+ """Teting make pod envconfig."""
+ config = {}
+ relation_state = {
+ "mongodb_connection_string": "mongodb://mongo",
+ }
+
+ expected_result = {"MONGODB_URI": "mongodb://mongo"}
+
+ pod_envconfig = pod_spec._make_pod_envconfig(config, relation_state)
+
+ self.assertDictEqual(expected_result, pod_envconfig)
+
+ def test_make_pod_ingress_resources_without_site_url(self) -> NoReturn:
+ """Testing make pod ingress resources without site_url."""
+ config = {
+ "site_url": "",
+ "cluster_issuer": "",
+ }
+ app_name = "mongodb-exporter"
+ port = 9216
+
+ pod_ingress_resources = pod_spec._make_pod_ingress_resources(
+ config, app_name, port
+ )
+
+ self.assertIsNone(pod_ingress_resources)
+
+ def test_make_pod_ingress_resources(self) -> NoReturn:
+ """Testing make pod ingress resources."""
+ config = {
+ "site_url": "http://mongodb-exporter",
+ "cluster_issuer": "",
+ "ingress_whitelist_source_range": "",
+ }
+ app_name = "mongodb-exporter"
+ port = 9216
+
+ expected_result = [
+ {
+ "name": f"{app_name}-ingress",
+ "annotations": {
+ "nginx.ingress.kubernetes.io/ssl-redirect": "false",
+ },
+ "spec": {
+ "rules": [
+ {
+ "host": app_name,
+ "http": {
+ "paths": [
+ {
+ "path": "/",
+ "backend": {
+ "serviceName": app_name,
+ "servicePort": port,
+ },
+ }
+ ]
+ },
+ }
+ ]
+ },
+ }
+ ]
+
+ pod_ingress_resources = pod_spec._make_pod_ingress_resources(
+ config, app_name, port
+ )
+
+ self.assertListEqual(expected_result, pod_ingress_resources)
+
+ def test_make_pod_ingress_resources_with_whitelist_source_range(self) -> NoReturn:
+ """Testing make pod ingress resources with whitelist_source_range."""
+ config = {
+ "site_url": "http://mongodb-exporter",
+ "cluster_issuer": "",
+ "ingress_whitelist_source_range": "0.0.0.0/0",
+ }
+ app_name = "mongodb-exporter"
+ port = 9216
+
+ expected_result = [
+ {
+ "name": f"{app_name}-ingress",
+ "annotations": {
+ "nginx.ingress.kubernetes.io/ssl-redirect": "false",
+ "nginx.ingress.kubernetes.io/whitelist-source-range": config[
+ "ingress_whitelist_source_range"
+ ],
+ },
+ "spec": {
+ "rules": [
+ {
+ "host": app_name,
+ "http": {
+ "paths": [
+ {
+ "path": "/",
+ "backend": {
+ "serviceName": app_name,
+ "servicePort": port,
+ },
+ }
+ ]
+ },
+ }
+ ]
+ },
+ }
+ ]
+
+ pod_ingress_resources = pod_spec._make_pod_ingress_resources(
+ config, app_name, port
+ )
+
+ self.assertListEqual(expected_result, pod_ingress_resources)
+
+ def test_make_pod_ingress_resources_with_https(self) -> NoReturn:
+ """Testing make pod ingress resources with HTTPs."""
+ config = {
+ "site_url": "https://mongodb-exporter",
+ "cluster_issuer": "",
+ "ingress_whitelist_source_range": "",
+ "tls_secret_name": "",
+ }
+ app_name = "mongodb-exporter"
+ port = 9216
+
+ expected_result = [
+ {
+ "name": f"{app_name}-ingress",
+ "annotations": {},
+ "spec": {
+ "rules": [
+ {
+ "host": app_name,
+ "http": {
+ "paths": [
+ {
+ "path": "/",
+ "backend": {
+ "serviceName": app_name,
+ "servicePort": port,
+ },
+ }
+ ]
+ },
+ }
+ ],
+ "tls": [{"hosts": [app_name]}],
+ },
+ }
+ ]
+
+ pod_ingress_resources = pod_spec._make_pod_ingress_resources(
+ config, app_name, port
+ )
+
+ self.assertListEqual(expected_result, pod_ingress_resources)
+
+ def test_make_pod_ingress_resources_with_https_tls_secret_name(self) -> NoReturn:
+ """Testing make pod ingress resources with HTTPs and TLS secret name."""
+ config = {
+ "site_url": "https://mongodb-exporter",
+ "cluster_issuer": "",
+ "ingress_whitelist_source_range": "",
+ "tls_secret_name": "secret_name",
+ }
+ app_name = "mongodb-exporter"
+ port = 9216
+
+ expected_result = [
+ {
+ "name": f"{app_name}-ingress",
+ "annotations": {},
+ "spec": {
+ "rules": [
+ {
+ "host": app_name,
+ "http": {
+ "paths": [
+ {
+ "path": "/",
+ "backend": {
+ "serviceName": app_name,
+ "servicePort": port,
+ },
+ }
+ ]
+ },
+ }
+ ],
+ "tls": [
+ {"hosts": [app_name], "secretName": config["tls_secret_name"]}
+ ],
+ },
+ }
+ ]
+
+ pod_ingress_resources = pod_spec._make_pod_ingress_resources(
+ config, app_name, port
+ )
+
+ self.assertListEqual(expected_result, pod_ingress_resources)
+
+ def test_make_readiness_probe(self) -> NoReturn:
+ """Testing make readiness probe."""
+ port = 9216
+
+ expected_result = {
+ "httpGet": {
+ "path": "/api/health",
+ "port": port,
+ },
+ "initialDelaySeconds": 10,
+ "periodSeconds": 10,
+ "timeoutSeconds": 5,
+ "successThreshold": 1,
+ "failureThreshold": 3,
+ }
+
+ readiness_probe = pod_spec._make_readiness_probe(port)
+
+ self.assertDictEqual(expected_result, readiness_probe)
+
+ def test_make_liveness_probe(self) -> NoReturn:
+ """Testing make liveness probe."""
+ port = 9216
+
+ expected_result = {
+ "httpGet": {
+ "path": "/api/health",
+ "port": port,
+ },
+ "initialDelaySeconds": 60,
+ "timeoutSeconds": 30,
+ "failureThreshold": 10,
+ }
+
+ liveness_probe = pod_spec._make_liveness_probe(port)
+
+ self.assertDictEqual(expected_result, liveness_probe)
+
+ def test_make_pod_spec(self) -> NoReturn:
+ """Testing make pod spec."""
+ image_info = {"upstream-source": "bitnami/mongodb-exporter:latest"}
+ config = {
+ "site_url": "",
+ "cluster_issuer": "",
+ }
+ relation_state = {
+ "mongodb_connection_string": "mongodb://mongo",
+ }
+ app_name = "mongodb-exporter"
+ port = 9216
+
+ expected_result = {
+ "version": 3,
+ "containers": [
+ {
+ "name": app_name,
+ "imageDetails": image_info,
+ "imagePullPolicy": "Always",
+ "ports": [
+ {
+ "name": "mongo-exporter",
+ "containerPort": port,
+ "protocol": "TCP",
+ }
+ ],
+ "envConfig": {
+ "MONGODB_URI": "mongodb://mongo",
+ },
+ "kubernetes": {
+ "readinessProbe": {
+ "httpGet": {
+ "path": "/api/health",
+ "port": port,
+ },
+ "initialDelaySeconds": 10,
+ "periodSeconds": 10,
+ "timeoutSeconds": 5,
+ "successThreshold": 1,
+ "failureThreshold": 3,
+ },
+ "livenessProbe": {
+ "httpGet": {
+ "path": "/api/health",
+ "port": port,
+ },
+ "initialDelaySeconds": 60,
+ "timeoutSeconds": 30,
+ "failureThreshold": 10,
+ },
+ },
+ }
+ ],
+ "kubernetesResources": {"ingressResources": []},
+ }
+
+ spec = pod_spec.make_pod_spec(
+ image_info, config, relation_state, app_name, port
+ )
+
+ self.assertDictEqual(expected_result, spec)
+
+ def test_make_pod_spec_with_ingress(self) -> NoReturn:
+ """Testing make pod spec."""
+ image_info = {"upstream-source": "bitnami/mongodb-exporter:latest"}
+ config = {
+ "site_url": "https://mongodb-exporter",
+ "cluster_issuer": "",
+ "tls_secret_name": "mongodb-exporter",
+ "ingress_whitelist_source_range": "0.0.0.0/0",
+ }
+ relation_state = {
+ "mongodb_connection_string": "mongodb://mongo",
+ }
+ app_name = "mongodb-exporter"
+ port = 9216
+
+ expected_result = {
+ "version": 3,
+ "containers": [
+ {
+ "name": app_name,
+ "imageDetails": image_info,
+ "imagePullPolicy": "Always",
+ "ports": [
+ {
+ "name": "mongo-exporter",
+ "containerPort": port,
+ "protocol": "TCP",
+ }
+ ],
+ "envConfig": {
+ "MONGODB_URI": "mongodb://mongo",
+ },
+ "kubernetes": {
+ "readinessProbe": {
+ "httpGet": {
+ "path": "/api/health",
+ "port": port,
+ },
+ "initialDelaySeconds": 10,
+ "periodSeconds": 10,
+ "timeoutSeconds": 5,
+ "successThreshold": 1,
+ "failureThreshold": 3,
+ },
+ "livenessProbe": {
+ "httpGet": {
+ "path": "/api/health",
+ "port": port,
+ },
+ "initialDelaySeconds": 60,
+ "timeoutSeconds": 30,
+ "failureThreshold": 10,
+ },
+ },
+ }
+ ],
+ "kubernetesResources": {
+ "ingressResources": [
+ {
+ "name": "{}-ingress".format(app_name),
+ "annotations": {
+ "nginx.ingress.kubernetes.io/whitelist-source-range": config.get(
+ "ingress_whitelist_source_range"
+ ),
+ },
+ "spec": {
+ "rules": [
+ {
+ "host": app_name,
+ "http": {
+ "paths": [
+ {
+ "path": "/",
+ "backend": {
+ "serviceName": app_name,
+ "servicePort": port,
+ },
+ }
+ ]
+ },
+ }
+ ],
+ "tls": [
+ {
+ "hosts": [app_name],
+ "secretName": config.get("tls_secret_name"),
+ }
+ ],
+ },
+ }
+ ],
+ },
+ }
+
+ spec = pod_spec.make_pod_spec(
+ image_info, config, relation_state, app_name, port
+ )
+
+ self.assertDictEqual(expected_result, spec)
+
+ def test_make_pod_spec_without_image_info(self) -> NoReturn:
+ """Testing make pod spec without image_info."""
+ image_info = None
+ config = {
+ "site_url": "",
+ "cluster_issuer": "",
+ }
+ relation_state = {
+ "mongodb_connection_string": "mongodb://mongo",
+ }
+ app_name = "mongodb-exporter"
+ port = 9216
+
+ spec = pod_spec.make_pod_spec(
+ image_info, config, relation_state, app_name, port
+ )
+
+ self.assertIsNone(spec)
+
+ def test_make_pod_spec_without_relation_state(self) -> NoReturn:
+ """Testing make pod spec without relation_state."""
+ image_info = {"upstream-source": "bitnami/mongodb-exporter:latest"}
+ config = {
+ "site_url": "",
+ "cluster_issuer": "",
+ }
+ relation_state = {}
+ app_name = "mongodb-exporter"
+ port = 9216
+
+ with self.assertRaises(ValueError):
+ pod_spec.make_pod_spec(image_info, config, relation_state, app_name, port)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/installers/charm/mongodb-exporter/tox.ini b/installers/charm/mongodb-exporter/tox.ini
new file mode 100644
index 0000000..4c7970d
--- /dev/null
+++ b/installers/charm/mongodb-exporter/tox.ini
@@ -0,0 +1,126 @@
+# Copyright 2021 Canonical Ltd.
+#
+# 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.
+#
+# For those usages not covered by the Apache License, Version 2.0 please
+# contact: legal@canonical.com
+#
+# To get in touch with the maintainers, please contact:
+# osm-charmers@lists.launchpad.net
+##
+#######################################################################################
+
+[tox]
+envlist = black, cover, flake8, pylint, yamllint, safety
+skipsdist = true
+
+[tox:jenkins]
+toxworkdir = /tmp/.tox
+
+[testenv]
+basepython = python3.8
+setenv = VIRTUAL_ENV={envdir}
+ PYTHONDONTWRITEBYTECODE = 1
+deps = -r{toxinidir}/requirements.txt
+
+
+#######################################################################################
+[testenv:black]
+deps = black
+commands =
+ black --check --diff src/ tests/
+
+
+#######################################################################################
+[testenv:cover]
+deps = {[testenv]deps}
+ -r{toxinidir}/requirements-test.txt
+ coverage
+ nose2
+commands =
+ sh -c 'rm -f nosetests.xml'
+ coverage erase
+ nose2 -C --coverage src
+ coverage report --omit='*tests*'
+ coverage html -d ./cover --omit='*tests*'
+ coverage xml -o coverage.xml --omit=*tests*
+whitelist_externals = sh
+
+
+#######################################################################################
+[testenv:flake8]
+deps = flake8
+ flake8-import-order
+commands =
+ flake8 src/ tests/
+
+
+#######################################################################################
+[testenv:pylint]
+deps = {[testenv]deps}
+ -r{toxinidir}/requirements-test.txt
+ pylint==2.10.2
+commands =
+ pylint -E src/ tests/
+
+
+#######################################################################################
+[testenv:safety]
+setenv =
+ LC_ALL=C.UTF-8
+ LANG=C.UTF-8
+deps = {[testenv]deps}
+ safety
+commands =
+ - safety check --full-report
+
+
+#######################################################################################
+[testenv:yamllint]
+deps = {[testenv]deps}
+ -r{toxinidir}/requirements-test.txt
+ yamllint
+commands = yamllint .
+
+#######################################################################################
+[testenv:build]
+passenv=HTTP_PROXY HTTPS_PROXY NO_PROXY
+whitelist_externals =
+ charmcraft
+ sh
+commands =
+ charmcraft pack
+ sh -c 'ubuntu_version=20.04; \
+ architectures="amd64-aarch64-arm64"; \
+ charm_name=`cat metadata.yaml | grep -E "^name: " | cut -f 2 -d " "`; \
+ mv $charm_name"_ubuntu-"$ubuntu_version-$architectures.charm $charm_name.charm'
+
+#######################################################################################
+[flake8]
+ignore =
+ W291,
+ W293,
+ W503,
+ E123,
+ E125,
+ E226,
+ E241,
+exclude =
+ .git,
+ __pycache__,
+ .tox,
+max-line-length = 120
+show-source = True
+builtins = _
+max-complexity = 10
+import-order-style = google