Major improvement in OSM charms
- Adapt all new operator charms to use the same pattern. They are all
using now this library that encapsulates the common logic for all
charms: https://github.com/davigar15/ops-lib-charmed-osm. That will be
eventually moved to gitlab, when it has a PyPI repository available
- Add unit tests to all charms
- Modify installer and bundles to point to the new charms
- Improve the build.sh script for building the charms
Change-Id: I0896ceb082d1b6a76b3560c07482a4135a220a3f
Signed-off-by: David Garcia <david.garcia@canonical.com>
diff --git a/installers/charm/mon/.gitignore b/installers/charm/mon/.gitignore
index 0be86d6..2885df2 100644
--- a/installers/charm/mon/.gitignore
+++ b/installers/charm/mon/.gitignore
@@ -1,4 +1,4 @@
-# Copyright 2020 Canonical Ltd.
+# 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
@@ -22,7 +22,9 @@
venv
.vscode
build
-mon.charm
+*.charm
.coverage
+coverage.xml
.stestr
cover
+release
\ No newline at end of file
diff --git a/installers/charm/mon/.jujuignore b/installers/charm/mon/.jujuignore
new file mode 100644
index 0000000..bf04eb4
--- /dev/null
+++ b/installers/charm/mon/.jujuignore
@@ -0,0 +1,28 @@
+# 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
+prometheus.charm
+.coverage
+.stestr
+cover
diff --git a/installers/charm/mon/.yamllint.yaml b/installers/charm/mon/.yamllint.yaml
index c20ac8d..d71fb69 100644
--- a/installers/charm/mon/.yamllint.yaml
+++ b/installers/charm/mon/.yamllint.yaml
@@ -1,4 +1,4 @@
-# Copyright 2020 Canonical Ltd.
+# 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
@@ -28,6 +28,7 @@
- ".yamllint"
ignore: |
.tox
+ cover/
build/
- mod/
- lib/
+ venv
+ release/
diff --git a/installers/charm/mon/config.yaml b/installers/charm/mon/config.yaml
index 9480ea7..93d77fe 100644
--- a/installers/charm/mon/config.yaml
+++ b/installers/charm/mon/config.yaml
@@ -60,3 +60,15 @@
type: string
description: "The VCA cacert."
default: ""
+ grafana_url:
+ description: Grafana URL
+ type: string
+ default: http://grafana:3000
+ grafana_user:
+ description: Grafana user
+ type: string
+ default: admin
+ grafana_password:
+ description: Grafana password
+ type: string
+ default: admin
diff --git a/installers/charm/mon/requirements-test.txt b/installers/charm/mon/requirements-test.txt
new file mode 100644
index 0000000..d7585f3
--- /dev/null
+++ b/installers/charm/mon/requirements-test.txt
@@ -0,0 +1,31 @@
+# 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
+##
+-r requirements.txt
+coverage
+stestr
+mock
+black
+yamllint
+flake8
+safety
+requests-mock
+asynctest
+nose2
\ No newline at end of file
diff --git a/installers/charm/mon/requirements.txt b/installers/charm/mon/requirements.txt
index a26601f..f10a199 100644
--- a/installers/charm/mon/requirements.txt
+++ b/installers/charm/mon/requirements.txt
@@ -1,4 +1,4 @@
-# Copyright 2020 Canonical Ltd.
+# 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
@@ -19,5 +19,4 @@
# osm-charmers@lists.launchpad.net
##
-ops
-git+https://github.com/juju-solutions/resource-oci-image/@c5778285d332edf3d9a538f9d0c06154b7ec1b0b#egg=oci-image
+git+https://github.com/davigar15/ops-lib-charmed-osm/@e7f26cd29b322e175a23cadbe4546b7f2bbf111c
\ No newline at end of file
diff --git a/installers/charm/mon/src/charm.py b/installers/charm/mon/src/charm.py
index f51213d..98c3297 100755
--- a/installers/charm/mon/src/charm.py
+++ b/installers/charm/mon/src/charm.py
@@ -1,5 +1,5 @@
#!/usr/bin/env python3
-# Copyright 2020 Canonical Ltd.
+# 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
@@ -20,254 +20,135 @@
# osm-charmers@lists.launchpad.net
##
+# pylint: disable=E0213
+
+
import logging
-from typing import Any, Dict, NoReturn
+from typing import NoReturn
-from ops.charm import CharmBase, CharmEvents
-from ops.framework import EventBase, EventSource, StoredState
from ops.main import main
-from ops.model import ActiveStatus, BlockedStatus, MaintenanceStatus
-from oci_image import OCIImageResource, OCIImageResourceError
-from pod_spec import make_pod_spec
+from opslib.osm.charm import CharmedOsmBase, RelationsMissing
-LOGGER = logging.getLogger(__name__)
+from opslib.osm.pod import (
+ ContainerV3Builder,
+ PodSpecV3Builder,
+)
-MON_PORT = 8000
+from opslib.osm.validator import (
+ ModelValidator,
+ validator,
+)
+
+from opslib.osm.interfaces.kafka import KafkaClient
+from opslib.osm.interfaces.mongo import MongoClient
+from opslib.osm.interfaces.prometheus import PrometheusClient
-class ConfigurePodEvent(EventBase):
- """Configure Pod event"""
+logger = logging.getLogger(__name__)
- pass
+PORT = 8000
-class MonEvents(CharmEvents):
- """MON Events"""
+class ConfigModel(ModelValidator):
+ vca_host: str
+ vca_user: str
+ vca_password: str
+ vca_cacert: str
+ database_commonkey: str
+ log_level: str
+ openstack_default_granularity: int
+ global_request_timeout: int
+ collector_interval: int
+ evaluator_interval: int
+ grafana_url: str
+ grafana_user: str
+ grafana_password: str
- configure_pod = EventSource(ConfigurePodEvent)
+ @validator("log_level")
+ def validate_log_level(cls, v):
+ if v not in {"INFO", "DEBUG"}:
+ raise ValueError("value must be INFO or DEBUG")
+ return v
-class MonCharm(CharmBase):
- """MON Charm."""
-
- state = StoredState()
- on = MonEvents()
-
+class MonCharm(CharmedOsmBase):
def __init__(self, *args) -> NoReturn:
- """MON Charm constructor."""
- super().__init__(*args)
+ super().__init__(*args, oci_image="image")
- # Internal state initialization
- self.state.set_default(pod_spec=None)
+ self.kafka_client = KafkaClient(self, "kafka")
+ self.framework.observe(self.on["kafka"].relation_changed, self.configure_pod)
+ self.framework.observe(self.on["kafka"].relation_broken, self.configure_pod)
- # Message bus data initialization
- self.state.set_default(message_host=None)
- self.state.set_default(message_port=None)
+ 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)
- # Database data initialization
- self.state.set_default(database_uri=None)
-
- # Prometheus data initialization
- self.state.set_default(prometheus_host=None)
- self.state.set_default(prometheus_port=None)
-
- self.port = MON_PORT
- self.image = OCIImageResource(self, "image")
-
- # Registering regular events
- self.framework.observe(self.on.start, self.configure_pod)
- self.framework.observe(self.on.config_changed, self.configure_pod)
- self.framework.observe(self.on.upgrade_charm, self.configure_pod)
-
- # Registering custom internal events
- self.framework.observe(self.on.configure_pod, self.configure_pod)
-
- # Registering required relation events
+ self.prometheus_client = PrometheusClient(self, "prometheus")
self.framework.observe(
- self.on.kafka_relation_changed, self._on_kafka_relation_changed
+ self.on["prometheus"].relation_changed, self.configure_pod
)
self.framework.observe(
- self.on.mongodb_relation_changed, self._on_mongodb_relation_changed
- )
- self.framework.observe(
- self.on.prometheus_relation_changed, self._on_prometheus_relation_changed
+ self.on["prometheus"].relation_broken, self.configure_pod
)
- # Registering required relation departed events
- self.framework.observe(
- self.on.kafka_relation_departed, self._on_kafka_relation_departed
- )
- self.framework.observe(
- self.on.mongodb_relation_departed, self._on_mongodb_relation_departed
- )
- self.framework.observe(
- self.on.prometheus_relation_departed, self._on_prometheus_relation_departed
+ def _check_missing_dependencies(self, config: ConfigModel):
+ missing_relations = []
+
+ if self.kafka_client.is_missing_data_in_unit():
+ missing_relations.append("kafka")
+ if self.mongodb_client.is_missing_data_in_unit():
+ missing_relations.append("mongodb")
+ if self.prometheus_client.is_missing_data_in_app():
+ missing_relations.append("prometheus")
+
+ if missing_relations:
+ raise RelationsMissing(missing_relations)
+
+ def build_pod_spec(self, image_info):
+ # Validate config
+ config = ConfigModel(**dict(self.config))
+ # Check relations
+ self._check_missing_dependencies(config)
+ # Create Builder for the PodSpec
+ pod_spec_builder = PodSpecV3Builder()
+ # Build Container
+ container_builder = ContainerV3Builder(self.app.name, image_info)
+ container_builder.add_port(name=self.app.name, port=PORT)
+ container_builder.add_envs(
+ {
+ # General configuration
+ "ALLOW_ANONYMOUS_LOGIN": "yes",
+ "OSMMON_OPENSTACK_DEFAULT_GRANULARITY": config.openstack_default_granularity,
+ "OSMMON_GLOBAL_REQUEST_TIMEOUT": config.global_request_timeout,
+ "OSMMON_GLOBAL_LOGLEVEL": config.log_level,
+ "OSMMON_COLLECTOR_INTERVAL": config.collector_interval,
+ "OSMMON_EVALUATOR_INTERVAL": config.evaluator_interval,
+ # Kafka configuration
+ "OSMMON_MESSAGE_DRIVER": "kafka",
+ "OSMMON_MESSAGE_HOST": self.kafka_client.host,
+ "OSMMON_MESSAGE_PORT": self.kafka_client.port,
+ # Database configuration
+ "OSMMON_DATABASE_DRIVER": "mongo",
+ "OSMMON_DATABASE_URI": self.mongodb_client.connection_string,
+ "OSMMON_DATABASE_COMMONKEY": config.database_commonkey,
+ # Prometheus configuration
+ "OSMMON_PROMETHEUS_URL": f"http://{self.prometheus_client.hostname}:{self.prometheus_client.port}",
+ # VCA configuration
+ "OSMMON_VCA_HOST": config.vca_host,
+ "OSMMON_VCA_USER": config.vca_user,
+ "OSMMON_VCA_SECRET": config.vca_password,
+ "OSMMON_VCA_CACERT": config.vca_cacert,
+ "OSMMON_GRAFANA_URL": config.grafana_url,
+ "OSMMON_GRAFANA_USER": config.grafana_user,
+ "OSMMON_GRAFANA_PASSWORD": config.grafana_password,
+ }
)
- def _on_kafka_relation_changed(self, event: EventBase) -> NoReturn:
- """Reads information about the kafka relation.
-
- Args:
- event (EventBase): Kafka relation event.
- """
- message_host = event.relation.data[event.unit].get("host")
- message_port = event.relation.data[event.unit].get("port")
-
- if (
- message_host
- and message_port
- and (
- self.state.message_host != message_host
- or self.state.message_port != message_port
- )
- ):
- self.state.message_host = message_host
- self.state.message_port = message_port
- self.on.configure_pod.emit()
-
- def _on_kafka_relation_departed(self, event: EventBase) -> NoReturn:
- """Clear kafka relation data.
-
- Args:
- event (EventBase): Kafka relation event.
- """
- self.state.message_host = None
- self.state.message_port = None
- self.on.configure_pod.emit()
-
- def _on_mongodb_relation_changed(self, event: EventBase) -> NoReturn:
- """Reads information about the DB relation.
-
- Args:
- event (EventBase): DB relation event.
- """
- database_uri = event.relation.data[event.unit].get("connection_string")
-
- if database_uri and self.state.database_uri != database_uri:
- self.state.database_uri = database_uri
- self.on.configure_pod.emit()
-
- def _on_mongodb_relation_departed(self, event: EventBase) -> NoReturn:
- """Clear mongodb relation data.
-
- Args:
- event (EventBase): DB relation event.
- """
- self.state.database_uri = None
- self.on.configure_pod.emit()
-
- def _on_prometheus_relation_changed(self, event: EventBase) -> NoReturn:
- """Reads information about the prometheus relation.
-
- Args:
- event (EventBase): Prometheus relation event.
- """
- prometheus_host = event.relation.data[event.unit].get("hostname")
- prometheus_port = event.relation.data[event.unit].get("port")
-
- if (
- prometheus_host
- and prometheus_port
- and (
- self.state.prometheus_host != prometheus_host
- or self.state.prometheus_port != prometheus_port
- )
- ):
- self.state.prometheus_host = prometheus_host
- self.state.prometheus_port = prometheus_port
- self.on.configure_pod.emit()
-
- def _on_prometheus_relation_departed(self, event: EventBase) -> NoReturn:
- """Clear prometheus relation data.
-
- Args:
- event (EventBase): Prometheus relation event.
- """
- self.state.prometheus_host = None
- self.state.prometheus_port = None
- self.on.configure_pod.emit()
-
- def _missing_relations(self) -> str:
- """Checks if there missing relations.
-
- Returns:
- str: string with missing relations
- """
- data_status = {
- "kafka": self.state.message_host,
- "mongodb": self.state.database_uri,
- "prometheus": self.state.prometheus_host,
- }
-
- missing_relations = [k for k, v in data_status.items() if not v]
-
- return ", ".join(missing_relations)
-
- @property
- def relation_state(self) -> Dict[str, Any]:
- """Collects relation state configuration for pod spec assembly.
-
- Returns:
- Dict[str, Any]: relation state information.
- """
- relation_state = {
- "message_host": self.state.message_host,
- "message_port": self.state.message_port,
- "database_uri": self.state.database_uri,
- "prometheus_host": self.state.prometheus_host,
- "prometheus_port": self.state.prometheus_port,
- }
-
- return relation_state
-
- def configure_pod(self, event: EventBase) -> NoReturn:
- """Assemble the pod spec and apply it, if possible.
-
- Args:
- event (EventBase): Hook or Relation event that started the
- function.
- """
- if missing := self._missing_relations():
- self.unit.status = BlockedStatus(
- "Waiting for {0} relation{1}".format(
- missing, "s" if "," in missing else ""
- )
- )
- return
-
- if not self.unit.is_leader():
- self.unit.status = ActiveStatus("ready")
- return
-
- self.unit.status = MaintenanceStatus("Assembling pod spec")
-
- # Fetch image information
- try:
- self.unit.status = MaintenanceStatus("Fetching image information")
- image_info = self.image.fetch()
- except OCIImageResourceError:
- self.unit.status = BlockedStatus("Error fetching image information")
- return
-
- try:
- pod_spec = make_pod_spec(
- image_info,
- self.model.config,
- self.relation_state,
- self.model.app.name,
- self.port,
- )
- except ValueError as exc:
- LOGGER.exception("Config/Relation data validation error")
- self.unit.status = BlockedStatus(str(exc))
- return
-
- if self.state.pod_spec != pod_spec:
- self.model.pod.set_spec(pod_spec)
- self.state.pod_spec = pod_spec
-
- self.unit.status = ActiveStatus("ready")
+ container = container_builder.build()
+ # Add container to pod spec
+ pod_spec_builder.add_container(container)
+ return pod_spec_builder.build()
if __name__ == "__main__":
diff --git a/installers/charm/mon/src/pod_spec.py b/installers/charm/mon/src/pod_spec.py
index 1c50565..dcadfc0 100644
--- a/installers/charm/mon/src/pod_spec.py
+++ b/installers/charm/mon/src/pod_spec.py
@@ -36,15 +36,18 @@
relation_data (Dict[str, Any]): relation data.
"""
config_validators = {
- "openstack_default_granularity": lambda value, _: isinstance(value, int)
- and value > 0,
+ "openstack_default_granularity": lambda value, _: (
+ isinstance(value, int) and value > 0
+ ),
"global_request_timeout": lambda value, _: isinstance(value, int) and value > 0,
- "log_level": lambda value, _: isinstance(value, str)
- and value in ("INFO", "DEBUG"),
+ "log_level": lambda value, _: (
+ isinstance(value, str) and value in ("INFO", "DEBUG")
+ ),
"collector_interval": lambda value, _: isinstance(value, int) and value > 0,
"evaluator_interval": lambda value, _: isinstance(value, int) and value > 0,
- "database_commonkey": lambda value, _: isinstance(value, str)
- and len(value) > 0,
+ "database_commonkey": lambda value, _: (
+ isinstance(value, str) and len(value) > 0
+ ),
"vca_host": lambda value, _: isinstance(value, str) and len(value) > 0,
"vca_user": lambda value, _: isinstance(value, str) and len(value) > 0,
"vca_password": lambda value, _: isinstance(value, str) and len(value) > 0,
@@ -53,8 +56,9 @@
relation_validators = {
"message_host": lambda value, _: isinstance(value, str) and len(value) > 0,
"message_port": lambda value, _: isinstance(value, int) and value > 0,
- "database_uri": lambda value, _: isinstance(value, str)
- and value.startswith("mongodb://"),
+ "database_uri": lambda value, _: (
+ isinstance(value, str) and value.startswith("mongodb://")
+ ),
"prometheus_host": lambda value, _: isinstance(value, str) and len(value) > 0,
"prometheus_port": lambda value, _: isinstance(value, int) and value > 0,
}
diff --git a/installers/charm/mon/tests/test_charm.py b/installers/charm/mon/tests/test_charm.py
index 010262f..6fcd6a6 100644
--- a/installers/charm/mon/tests/test_charm.py
+++ b/installers/charm/mon/tests/test_charm.py
@@ -1,5 +1,5 @@
#!/usr/bin/env python3
-# Copyright 2020 Canonical Ltd.
+# 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
@@ -20,102 +20,82 @@
# osm-charmers@lists.launchpad.net
##
+import sys
from typing import NoReturn
import unittest
-from ops.model import BlockedStatus
-
+from ops.model import ActiveStatus, BlockedStatus
from ops.testing import Harness
from charm import MonCharm
class TestCharm(unittest.TestCase):
- """MON Charm unit tests."""
+ """Prometheus Charm unit tests."""
def setUp(self) -> NoReturn:
"""Test setup"""
+ self.image_info = sys.modules["oci_image"].OCIImageResource().fetch()
self.harness = Harness(MonCharm)
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("kafka", self.harness.charm.unit.status.message)
- self.assertIn("mongodb", self.harness.charm.unit.status.message)
- self.assertIn("prometheus", self.harness.charm.unit.status.message)
- self.assertTrue(self.harness.charm.unit.status.message.endswith(" relations"))
-
- def test_on_start_with_relations(self) -> NoReturn:
- """Test deployment without keystone."""
- expected_result = {
- "version": 3,
- "containers": [
- {
- "name": "mon",
- "imageDetails": self.harness.charm.image.fetch(),
- "imagePullPolicy": "Always",
- "ports": [
- {
- "name": "mon",
- "containerPort": 8000,
- "protocol": "TCP",
- }
- ],
- "envConfig": {
- "ALLOW_ANONYMOUS_LOGIN": "yes",
- "OSMMON_OPENSTACK_DEFAULT_GRANULARITY": 300,
- "OSMMON_GLOBAL_REQUEST_TIMEOUT": 10,
- "OSMMON_GLOBAL_LOGLEVEL": "INFO",
- "OSMMON_COLLECTOR_INTERVAL": 30,
- "OSMMON_EVALUATOR_INTERVAL": 30,
- "OSMMON_MESSAGE_DRIVER": "kafka",
- "OSMMON_MESSAGE_HOST": "kafka",
- "OSMMON_MESSAGE_PORT": 9092,
- "OSMMON_DATABASE_DRIVER": "mongo",
- "OSMMON_DATABASE_URI": "mongodb://mongo:27017",
- "OSMMON_DATABASE_COMMONKEY": "osm",
- "OSMMON_PROMETHEUS_URL": "http://prometheus:9090",
- "OSMMON_VCA_HOST": "admin",
- "OSMMON_VCA_USER": "admin",
- "OSMMON_VCA_SECRET": "secret",
- "OSMMON_VCA_CACERT": "",
- },
- }
- ],
- "kubernetesResources": {"ingressResources": []},
+ self.config = {
+ "vca_host": "192.168.0.13",
+ "vca_user": "admin",
+ "vca_password": "admin",
+ "vca_cacert": "cacert",
+ "database_commonkey": "commonkey",
+ "log_level": "INFO",
+ "openstack_default_granularity": 10,
+ "global_request_timeout": 10,
+ "collector_interval": 30,
+ "evaluator_interval": 30,
}
+ self.harness.update_config(self.config)
- self.harness.charm.on.start.emit()
+ def test_config_changed_no_relations(
+ self,
+ ) -> NoReturn:
+ """Test ingress resources without HTTP."""
- # Check if kafka datastore is initialized
- self.assertIsNone(self.harness.charm.state.message_host)
- self.assertIsNone(self.harness.charm.state.message_port)
+ self.harness.charm.on.config_changed.emit()
- # Check if mongodb datastore is initialized
- self.assertIsNone(self.harness.charm.state.database_uri)
+ # Assertions
+ self.assertIsInstance(self.harness.charm.unit.status, BlockedStatus)
+ self.assertTrue(
+ all(
+ relation in self.harness.charm.unit.status.message
+ for relation in ["mongodb", "kafka", "prometheus"]
+ )
+ )
- # Check if prometheus datastore is initialized
- self.assertIsNone(self.harness.charm.state.prometheus_host)
- self.assertIsNone(self.harness.charm.state.prometheus_port)
+ 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()
- # Initializing the kafka relation
+ # Assertions
+ self.assertIsInstance(self.harness.charm.unit.status, ActiveStatus)
+
+ def test_with_relations(
+ self,
+ ) -> NoReturn:
+ "Test with relations (internal)"
+ self.initialize_kafka_relation()
+ self.initialize_mongo_relation()
+ self.initialize_prometheus_relation()
+ # Verifying status
+ self.assertNotIsInstance(self.harness.charm.unit.status, BlockedStatus)
+
+ def initialize_kafka_relation(self):
kafka_relation_id = self.harness.add_relation("kafka", "kafka")
self.harness.add_relation_unit(kafka_relation_id, "kafka/0")
self.harness.update_relation_data(
kafka_relation_id, "kafka/0", {"host": "kafka", "port": 9092}
)
- # Initializing the mongo relation
+ 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(
@@ -124,118 +104,227 @@
{"connection_string": "mongodb://mongo:27017"},
)
- # Initializing the prometheus relation
+ def initialize_prometheus_relation(self):
prometheus_relation_id = self.harness.add_relation("prometheus", "prometheus")
self.harness.add_relation_unit(prometheus_relation_id, "prometheus/0")
self.harness.update_relation_data(
prometheus_relation_id,
- "prometheus/0",
+ "prometheus",
{"hostname": "prometheus", "port": 9090},
)
- # Checking if kafka data is stored
- self.assertEqual(self.harness.charm.state.message_host, "kafka")
- self.assertEqual(self.harness.charm.state.message_port, 9092)
-
- # Checking if mongodb data is stored
- self.assertEqual(self.harness.charm.state.database_uri, "mongodb://mongo:27017")
-
- # Checking if prometheus data is stored
- self.assertEqual(self.harness.charm.state.prometheus_host, "prometheus")
- self.assertEqual(self.harness.charm.state.prometheus_port, 9090)
-
- # 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_on_kafka_unit_relation_changed(self) -> NoReturn:
- """Test to see if kafka relation is updated."""
- self.harness.charm.on.start.emit()
-
- self.assertIsNone(self.harness.charm.state.message_host)
- self.assertIsNone(self.harness.charm.state.message_port)
-
- relation_id = self.harness.add_relation("kafka", "kafka")
- self.harness.add_relation_unit(relation_id, "kafka/0")
- self.harness.update_relation_data(
- relation_id, "kafka/0", {"host": "kafka", "port": 9092}
- )
-
- self.assertEqual(self.harness.charm.state.message_host, "kafka")
- self.assertEqual(self.harness.charm.state.message_port, 9092)
-
- # 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.assertNotIn("kafka", self.harness.charm.unit.status.message)
- self.assertIn("mongodb", self.harness.charm.unit.status.message)
- self.assertIn("prometheus", self.harness.charm.unit.status.message)
- self.assertTrue(self.harness.charm.unit.status.message.endswith(" relations"))
-
- def test_on_mongodb_unit_relation_changed(self) -> NoReturn:
- """Test to see if mongodb relation is updated."""
- self.harness.charm.on.start.emit()
-
- self.assertIsNone(self.harness.charm.state.database_uri)
-
- 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:27017"}
- )
-
- self.assertEqual(self.harness.charm.state.database_uri, "mongodb://mongo:27017")
-
- # 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("kafka", self.harness.charm.unit.status.message)
- self.assertNotIn("mongodb", self.harness.charm.unit.status.message)
- self.assertIn("prometheus", self.harness.charm.unit.status.message)
- self.assertTrue(self.harness.charm.unit.status.message.endswith(" relations"))
-
- def test_on_prometheus_unit_relation_changed(self) -> NoReturn:
- """Test to see if prometheus relation is updated."""
- self.harness.charm.on.start.emit()
-
- self.assertIsNone(self.harness.charm.state.prometheus_host)
- self.assertIsNone(self.harness.charm.state.prometheus_port)
-
- relation_id = self.harness.add_relation("prometheus", "prometheus")
- self.harness.add_relation_unit(relation_id, "prometheus/0")
- self.harness.update_relation_data(
- relation_id, "prometheus/0", {"hostname": "prometheus", "port": 9090}
- )
-
- self.assertEqual(self.harness.charm.state.prometheus_host, "prometheus")
- self.assertEqual(self.harness.charm.state.prometheus_port, 9090)
-
- # 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("kafka", self.harness.charm.unit.status.message)
- self.assertIn("mongodb", self.harness.charm.unit.status.message)
- self.assertNotIn("prometheus", self.harness.charm.unit.status.message)
- self.assertTrue(self.harness.charm.unit.status.message.endswith(" relations"))
-
if __name__ == "__main__":
unittest.main()
+
+
+# class TestCharm(unittest.TestCase):
+# """MON Charm unit tests."""
+
+# def setUp(self) -> NoReturn:
+# """Test setup"""
+# self.harness = Harness(MonCharm)
+# 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("kafka", self.harness.charm.unit.status.message)
+# self.assertIn("mongodb", self.harness.charm.unit.status.message)
+# self.assertIn("prometheus", self.harness.charm.unit.status.message)
+# self.assertTrue(self.harness.charm.unit.status.message.endswith(" relations"))
+
+# def test_on_start_with_relations(self) -> NoReturn:
+# """Test deployment without keystone."""
+# expected_result = {
+# "version": 3,
+# "containers": [
+# {
+# "name": "mon",
+# "imageDetails": self.harness.charm.image.fetch(),
+# "imagePullPolicy": "Always",
+# "ports": [
+# {
+# "name": "mon",
+# "containerPort": 8000,
+# "protocol": "TCP",
+# }
+# ],
+# "envConfig": {
+# "ALLOW_ANONYMOUS_LOGIN": "yes",
+# "OSMMON_OPENSTACK_DEFAULT_GRANULARITY": 300,
+# "OSMMON_GLOBAL_REQUEST_TIMEOUT": 10,
+# "OSMMON_GLOBAL_LOGLEVEL": "INFO",
+# "OSMMON_COLLECTOR_INTERVAL": 30,
+# "OSMMON_EVALUATOR_INTERVAL": 30,
+# "OSMMON_MESSAGE_DRIVER": "kafka",
+# "OSMMON_MESSAGE_HOST": "kafka",
+# "OSMMON_MESSAGE_PORT": 9092,
+# "OSMMON_DATABASE_DRIVER": "mongo",
+# "OSMMON_DATABASE_URI": "mongodb://mongo:27017",
+# "OSMMON_DATABASE_COMMONKEY": "osm",
+# "OSMMON_PROMETHEUS_URL": "http://prometheus:9090",
+# "OSMMON_VCA_HOST": "admin",
+# "OSMMON_VCA_USER": "admin",
+# "OSMMON_VCA_SECRET": "secret",
+# "OSMMON_VCA_CACERT": "",
+# },
+# }
+# ],
+# "kubernetesResources": {"ingressResources": []},
+# }
+
+# self.harness.charm.on.start.emit()
+
+# # Check if kafka datastore is initialized
+# self.assertIsNone(self.harness.charm.state.message_host)
+# self.assertIsNone(self.harness.charm.state.message_port)
+
+# # Check if mongodb datastore is initialized
+# self.assertIsNone(self.harness.charm.state.database_uri)
+
+# # Check if prometheus datastore is initialized
+# self.assertIsNone(self.harness.charm.state.prometheus_host)
+# self.assertIsNone(self.harness.charm.state.prometheus_port)
+
+# # Initializing the kafka relation
+# kafka_relation_id = self.harness.add_relation("kafka", "kafka")
+# self.harness.add_relation_unit(kafka_relation_id, "kafka/0")
+# self.harness.update_relation_data(
+# kafka_relation_id, "kafka/0", {"host": "kafka", "port": 9092}
+# )
+
+# # Initializing the mongo relation
+# 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"},
+# )
+
+# # Initializing the prometheus relation
+# prometheus_relation_id = self.harness.add_relation("prometheus", "prometheus")
+# self.harness.add_relation_unit(prometheus_relation_id, "prometheus/0")
+# self.harness.update_relation_data(
+# prometheus_relation_id,
+# "prometheus",
+# {"hostname": "prometheus", "port": 9090},
+# )
+
+# # Checking if kafka data is stored
+# self.assertEqual(self.harness.charm.state.message_host, "kafka")
+# self.assertEqual(self.harness.charm.state.message_port, 9092)
+
+# # Checking if mongodb data is stored
+# self.assertEqual(self.harness.charm.state.database_uri, "mongodb://mongo:27017")
+
+# # Checking if prometheus data is stored
+# self.assertEqual(self.harness.charm.state.prometheus_host, "prometheus")
+# self.assertEqual(self.harness.charm.state.prometheus_port, 9090)
+
+# # 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_on_kafka_unit_relation_changed(self) -> NoReturn:
+# """Test to see if kafka relation is updated."""
+# self.harness.charm.on.start.emit()
+
+# self.assertIsNone(self.harness.charm.state.message_host)
+# self.assertIsNone(self.harness.charm.state.message_port)
+
+# relation_id = self.harness.add_relation("kafka", "kafka")
+# self.harness.add_relation_unit(relation_id, "kafka/0")
+# self.harness.update_relation_data(
+# relation_id, "kafka/0", {"host": "kafka", "port": 9092}
+# )
+
+# self.assertEqual(self.harness.charm.state.message_host, "kafka")
+# self.assertEqual(self.harness.charm.state.message_port, 9092)
+
+# # 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.assertNotIn("kafka", self.harness.charm.unit.status.message)
+# self.assertIn("mongodb", self.harness.charm.unit.status.message)
+# self.assertIn("prometheus", self.harness.charm.unit.status.message)
+# self.assertTrue(self.harness.charm.unit.status.message.endswith(" relations"))
+
+# def test_on_mongodb_unit_relation_changed(self) -> NoReturn:
+# """Test to see if mongodb relation is updated."""
+# self.harness.charm.on.start.emit()
+
+# self.assertIsNone(self.harness.charm.state.database_uri)
+
+# 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:27017"}
+# )
+
+# self.assertEqual(self.harness.charm.state.database_uri, "mongodb://mongo:27017")
+
+# # 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("kafka", self.harness.charm.unit.status.message)
+# self.assertNotIn("mongodb", self.harness.charm.unit.status.message)
+# self.assertIn("prometheus", self.harness.charm.unit.status.message)
+# self.assertTrue(self.harness.charm.unit.status.message.endswith(" relations"))
+
+# def test_on_prometheus_unit_relation_changed(self) -> NoReturn:
+# """Test to see if prometheus relation is updated."""
+# self.harness.charm.on.start.emit()
+
+# self.assertIsNone(self.harness.charm.state.prometheus_host)
+# self.assertIsNone(self.harness.charm.state.prometheus_port)
+
+# relation_id = self.harness.add_relation("prometheus", "prometheus")
+# self.harness.add_relation_unit(relation_id, "prometheus/0")
+# self.harness.update_relation_data(
+# relation_id, "prometheus", {"hostname": "prometheus", "port": 9090}
+# )
+
+# self.assertEqual(self.harness.charm.state.prometheus_host, "prometheus")
+# self.assertEqual(self.harness.charm.state.prometheus_port, 9090)
+
+# # 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("kafka", self.harness.charm.unit.status.message)
+# self.assertIn("mongodb", self.harness.charm.unit.status.message)
+# self.assertNotIn("prometheus", self.harness.charm.unit.status.message)
+# self.assertTrue(self.harness.charm.unit.status.message.endswith(" relations"))
+
+
+# if __name__ == "__main__":
+# unittest.main()
diff --git a/installers/charm/mon/tests/test_pod_spec.py b/installers/charm/mon/tests/test_pod_spec.py
index 777c18e..6f61916 100644
--- a/installers/charm/mon/tests/test_pod_spec.py
+++ b/installers/charm/mon/tests/test_pod_spec.py
@@ -199,7 +199,8 @@
"OSMMON_DATABASE_DRIVER": "mongo",
"OSMMON_DATABASE_URI": relation_state["database_uri"],
"OSMMON_DATABASE_COMMONKEY": config["database_commonkey"],
- "OSMMON_PROMETHEUS_URL": f"http://{relation_state['prometheus_host']}:{relation_state['prometheus_port']}",
+ "OSMMON_PROMETHEUS_URL":
+ f"http://{relation_state['prometheus_host']}:{relation_state['prometheus_port']}",
"OSMMON_VCA_HOST": config["vca_host"],
"OSMMON_VCA_USER": config["vca_user"],
"OSMMON_VCA_SECRET": config["vca_password"],
diff --git a/installers/charm/mon/tox.ini b/installers/charm/mon/tox.ini
index 7ddaf8d..1f9442e 100644
--- a/installers/charm/mon/tox.ini
+++ b/installers/charm/mon/tox.ini
@@ -1,4 +1,4 @@
-# Copyright 2020 Canonical Ltd.
+# 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
@@ -18,63 +18,98 @@
# To get in touch with the maintainers, please contact:
# osm-charmers@lists.launchpad.net
##
+#######################################################################################
[tox]
+envlist = flake8, cover, pylint, safety, yamllint
skipsdist = True
-envlist = unit, lint
-sitepackages = False
-skip_missing_interpreters = False
[testenv]
basepython = python3.8
setenv =
+ VIRTUAL_ENV={envdir}
PYTHONHASHSEED=0
PYTHONPATH = {toxinidir}/src
- CHARM_NAME = mon
+deps = -r{toxinidir}/requirements.txt
+#######################################################################################
+[testenv:cover]
+deps = {[testenv]deps}
+ -r{toxinidir}/requirements-test.txt
+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:safety]
+setenv =
+ LC_ALL=C.UTF-8
+ LANG=C.UTF-8
+deps = {[testenv]deps}
+ -r{toxinidir}/requirements-test.txt
+commands =
+ - safety check --full-report
+
+#######################################################################################
+[testenv:flake8]
+deps = flake8
+commands =
+ flake8 src/ tests/
+
+#######################################################################################
+[testenv:pylint]
+deps = {[testenv]deps}
+ -r{toxinidir}/requirements-test.txt
+ pylint
+commands =
+ pylint -E src
+
+#######################################################################################
+[testenv:black]
+deps = {[testenv]deps}
+ -r{toxinidir}/requirements-test.txt
+ black
+commands = black --check --diff . --exclude "build/|.tox/|mod/|lib/"
+
+#######################################################################################
+[testenv:yamllint]
+deps = {[testenv]deps}
+ -r{toxinidir}/requirements-test.txt
+ yamllint
+commands = yamllint .
+
+#######################################################################################
[testenv:build]
passenv=HTTP_PROXY HTTPS_PROXY NO_PROXY
+deps = {[testenv]deps}
+ -r{toxinidir}/requirements-test.txt
+ charmcraft
whitelist_externals =
charmcraft
- rm
- unzip
+ cp
commands =
- rm -rf release mon.charm
charmcraft build
- unzip mon.charm -d release
+ cp -r build release
-[testenv:unit]
-commands =
- coverage erase
- stestr run --slowest --test-path=./tests --top-dir=./
- coverage combine
- coverage html -d cover
- coverage xml -o cover/coverage.xml
- coverage report
-deps =
- coverage
- stestr
- mock
- ops
-setenv =
- {[testenv]setenv}
- PYTHON=coverage run
+#######################################################################################
+[flake8]
+ignore =
+ W291,
+ W293,
+ E123,
+ E125,
+ E226,
+ E241,
+exclude =
+ .git,
+ __pycache__,
+ .tox,
+max-line-length = 120
+show-source = True
+builtins = _
-[testenv:lint]
-deps =
- black
- yamllint
- flake8
-commands =
- black --check --diff . --exclude "build/|.tox/|mod/|lib/|release/"
- yamllint .
- flake8 . --max-line-length=100 --ignore="E501,W503,W504,F722" --exclude "build/ .tox/ mod/ lib/ release/"
-[coverage:run]
-branch = True
-concurrency = multiprocessing
-parallel = True
-source =
- .
-omit =
- .tox/*
- tests/*