Skip to content

Commit

Permalink
Post rebase fixup
Browse files Browse the repository at this point in the history
  • Loading branch information
addyess committed Apr 25, 2024
1 parent 11c9b70 commit 9f1d8f7
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 75 deletions.
31 changes: 2 additions & 29 deletions charms/worker/k8s/src/charm.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,6 @@
UserFacingDatastoreConfig,
)
from charms.kubernetes_libs.v0.etcd import EtcdReactiveRequires
from charms.interface_kube_dns import KubeDnsRequires
from charms.node_base import LabelMaker
from charms.reconciler import Reconciler
from cos_integration import COSIntegration
Expand Down Expand Up @@ -384,11 +383,10 @@ def _enable_functionalities(self):
"""Enable necessary components for the Kubernetes cluster."""
status.add(ops.MaintenanceStatus("Updating K8s features"))
log.info("Enabling K8s features")
dns_config = DNSConfig(enabled=True)
dns_config = self._get_dns_config()
network_config = NetworkConfig(enabled=True)
user_cluster_config = UserFacingClusterConfig(dns=dns_config, network=network_config)
update_request = UpdateClusterConfigRequest(config=user_cluster_config)

self.api_manager.update_cluster_config(update_request)

@on_error(
Expand Down Expand Up @@ -421,32 +419,7 @@ def _ensure_cluster_config(self):

self.api_manager.update_cluster_config(update_request)

def _configure_components(self):
"""Enable necessary components for the Kubernetes cluster."""
dns_settings = self._dns_charm_integrated()
status.add(ops.MaintenanceStatus(f"Configuring DNS"))

if dns_settings:
self.api_manager.configure_component("dns", False)
self.api_manager.configure_dns(dns_settings.get("dns_domain"), dns_settings.get("dns_ip"))
else:
self.api_manager.configure_component("dns", True)

status.add(ops.MaintenanceStatus("Enabling Network"))
self.api_manager.configure_component("network", True)

def _dns_charm_integrated(self) -> Optional[dict]:
"""Check if the DNS charm is integrated."""
status.add(ops.MaintenanceStatus("Configuring DNS and Network"))

dns_config = self._get_dns_config()
network_config = NetworkConfig(enabled=True)

user_cluster_config = UserFacingClusterConfig(dns=dns_config, network=network_config)
update_request = UpdateClusterConfigRequest(config=user_cluster_config)
self.api_manager.update_cluster_config(update_request)

def _get_dns_config(self) -> Optional[dict]:
def _get_dns_config(self) -> DNSConfig:
"""Get DNS config either for the enabled built-in dns or an integrated charm.
Returns:
Expand Down
25 changes: 9 additions & 16 deletions tests/integration/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -277,16 +277,13 @@ async def grafana_agent(kubernetes_cluster: Model):


@pytest_asyncio.fixture(scope="module")
async def cluster_kubeconfig(ops_test: OpsTest, kubernetes_cluster: juju.model.Model):
"""
Fixture to pull the kubeconfig out of the kubernetes cluster
"""
async def cluster_kubeconfig(ops_test: OpsTest, kubernetes_cluster: Model):
"""Fixture to pull the kubeconfig out of the kubernetes cluster."""
k8s = kubernetes_cluster.applications["k8s"].units[0]
action = await k8s.run("k8s config")
result = await action.wait()
assert result.results["return-code"] == 0, "Failed to get kubeconfig with kubectl"
action = await k8s.run_action("get-kubeconfig")
action = await action.wait()
kubeconfig_path = ops_test.tmp_path / "kubeconfig"
kubeconfig_path.write_text(result.results["stdout"])
kubeconfig_path.write_text(action.results["kubeconfig"])
yield kubeconfig_path


Expand All @@ -296,8 +293,6 @@ async def coredns_model(ops_test: OpsTest, cluster_kubeconfig: Path):
This fixture deploys Coredns on the specified
Kubernetes (k8s) model for testing purposes.
"""
log.info("Deploying Coredns ")

coredns_alias = "coredns-model"

config = type.__call__(Configuration)
Expand All @@ -308,6 +303,7 @@ async def coredns_model(ops_test: OpsTest, cluster_kubeconfig: Path):
k8s_model = await ops_test.track_model(
coredns_alias, cloud_name=k8s_cloud, keep=ops_test.ModelKeep.NEVER
)
log.info("Deploying Coredns ")
await k8s_model.deploy("coredns", trust=True)
await k8s_model.wait_for_idle(apps=["coredns"], status="active")
yield k8s_model
Expand All @@ -317,10 +313,8 @@ async def coredns_model(ops_test: OpsTest, cluster_kubeconfig: Path):


@pytest_asyncio.fixture(scope="module")
async def integrate_coredns(ops_test: OpsTest, coredns_model: juju.model.Model, kubernetes_cluster: juju.model.Model):
"""
This function offers Coredns in the specified Kubernetes (k8s) model.
"""
async def integrate_coredns(coredns_model: Model, kubernetes_cluster: Model):
"""This function offers Coredns in the specified Kubernetes (k8s) model."""
log.info("Offering Coredns...")
await coredns_model.create_offer("coredns:dns-provider")
await coredns_model.block_until(lambda: "coredns" in coredns_model.application_offers)
Expand All @@ -334,14 +328,13 @@ async def integrate_coredns(ops_test: OpsTest, coredns_model: juju.model.Model,

offer_url = f"{model_owner}/{coredns_model.name}.coredns"
saas = await kubernetes_cluster.consume(offer_url)

log.info("Coredns consumed...")

log.info("Relating Coredns...")
await kubernetes_cluster.integrate("k8s:dns-provider", "coredns")
assert "coredns" in kubernetes_cluster.remote_applications

yield
yield coredns_model

# Now let's clean up
await kubernetes_cluster.applications["k8s"].destroy_relation("k8s:dns-provider", "coredns")
Expand Down
34 changes: 4 additions & 30 deletions tests/integration/test_k8s.py
Original file line number Diff line number Diff line change
Expand Up @@ -177,50 +177,24 @@ async def test_prometheus(traefik_address: str, cos_model: model.Model):
await prometheus.check_metrics(query)


async def test_fixtures(kubernetes_cluster: model.Model, integrate_coredns: model.Model):
"""Test the coredns integration."""
log.info("Testing coredns integration...")


async def test_coredns_integration(kubernetes_cluster: model.Model, integrate_coredns: model.Model):
"""Test the coredns integration."""
k8s = kubernetes_cluster.applications["k8s"]
k8s_unit = k8s.units[0]

coredns = coredns_model.applications["coredns"]
coredns_unit = coredns.units[0]
log.info("Coredns: %s", coredns)
log.info("coredns offers %s", coredns.application_offers)
log.info("K8s: %s", k8s_unit)

dns_relation = k8s_unit.get_relation("dns-provider")
log.info("DNS relation: %s", dns_relation)

#TODO make sure this works
# Check if the DNS relation is set, and the domain is set to cluster.local
assert dns_relation, "No DNS relation found"
assert dns_relation.data["domain"] == "cluster.local", "Domain not set to cluster.local"

@pytest.mark.skip(reason="Test skipped until cluster configs are propagated properly")
async def test_dns(kubernetes_cluster: model.Model, integrate_coredns: model.Model):
@pytest.mark.usefixtures("integrate_coredns")
async def test_dns(kubernetes_cluster: model.Model):
"""
This function performs a DNS test on the specified Kubernetes (k8s) unit in the cluster model.
The test is performed by running a pod in the k8s unit and
checking if it can resolve the domain name
(See: https://charmhub.io/microk8s/docs/how-to-advanced-dns).
"""
# TODO: Validate the DNS test works once cluster configs are propagated properly
log.info("Running DNS test...")
k8s = kubernetes_cluster.applications["k8s"]
# Do we need to switch models?
exec_cmd = "k8s kubectl run --rm -it --image alpine \
--restart=Never test-dns -- nslookup canonical.com"
action = await k8s.units[0].run(exec_cmd)
result = await action.wait()
log.info("DNS test result: %s", result)
log.info("DNS test result: %s", result.results)
assert result.results["return-code"] == 0, "DNS Test failed."

output = json.loads(result.results["stdout"])
output = result.results["stdout"]
assert "canonical.com" in output, "Canonical.com not found in DNS result."

Check failure

Code scanning / CodeQL

Incomplete URL substring sanitization High test

The string
canonical.com
may be at an arbitrary position in the sanitized URL.
# TODO: test this output, https://charmhub.io/microk8s/docs/how-to-advanced-dns
log.info("DNS test passed.")

0 comments on commit 9f1d8f7

Please sign in to comment.