Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 57 additions & 22 deletions sunbeam-python/sunbeam/core/steps.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,43 @@
LOG = logging.getLogger(__name__)


def _get_lb_service(
kube: "l_client.Client", service_name: str, find_lb: bool = True
) -> "core_v1.Service":
"""Look up a service by name, optionally preferring its LoadBalancer service.

With find_lb, ``<service_name>-lb`` is tried first and ``service_name`` is
the fallback. Callers pass the base service name (e.g. ``traefik``).

:raises ApiError: the last 404 if no candidate exists, or any non-404 error.
"""
candidates = [f"{service_name}-lb", service_name] if find_lb else [service_name]

for candidate in candidates[:-1]:
try:
return kube.get(core_v1.Service, candidate)
except l_exceptions.ApiError as e:
if e.status.code != 404:
raise
LOG.debug("Service %r not found, trying next candidate", candidate)
return kube.get(core_v1.Service, candidates[-1])


def _ignored_services_result(services: list[str], skipped: int) -> Result:
"""Result of a LoadBalancer patch run that skipped some services.

SKIPPED when every service was skipped under ignore_errors, matching
is_skip(), so the plan does not report a step that patched nothing as
completed. COMPLETED otherwise.
"""
if services and skipped == len(services):
return Result(
ResultType.SKIPPED,
"No LoadBalancer service found, skipping as ignore_errors is set",
)
return Result(ResultType.COMPLETED)


class DeployMachineApplicationStep(BaseStep):
"""Base class to deploy machine application using Terraform cloud."""

Expand Down Expand Up @@ -440,15 +477,7 @@ def _get_service(
self, service_name: str, find_lb: bool = True
) -> "core_v1.Service":
"""Look up a service by name, optionally looking for a LoadBalancer service."""
search_service = service_name
if find_lb:
search_service += "-lb"
try:
return self.kube.get(core_v1.Service, search_service)
except l_exceptions.ApiError as e:
if e.status.code == 404 and search_service.endswith("-lb"):
return self._get_service(service_name, find_lb=False)
raise e
return _get_lb_service(self.kube, service_name, find_lb=find_lb)

def is_skip(self, context: StepContext) -> Result:
"""Determines if the step should be skipped or not.
Expand Down Expand Up @@ -551,10 +580,20 @@ def is_skip(self, context: StepContext) -> Result:

def run(self, context: StepContext) -> Result:
"""Patch LoadBalancer services annotations with LB IP."""
for service_name in self.services():
services = self.services()
skipped = 0
for service_name in services:
try:
service = self._get_service(service_name, find_lb=True)
except l_exceptions.ApiError as e:
if self.ignore_errors and e.status.code == 404:
LOG.debug(
"Service %r of type LoadBalancer not found, "
"skipping as ignore_errors is set",
service_name,
)
skipped += 1
continue
return Result(ResultType.FAILED, str(e))
if not service.metadata:
return Result(
Expand Down Expand Up @@ -637,7 +676,7 @@ def run(self, context: StepContext) -> Result:
service_annotations[self.lb_ip_annotation],
)

return Result(ResultType.COMPLETED)
return _ignored_services_result(services, skipped)


class PatchLoadBalancerServicesIPPoolStep(BaseStep, abc.ABC):
Expand Down Expand Up @@ -699,15 +738,7 @@ def _get_service(
self, service_name: str, find_lb: bool = True
) -> "core_v1.Service":
"""Look up a service by name, optionally looking for a LoadBalancer service."""
search_service = service_name
if find_lb:
search_service += "-lb"
try:
return self.kube.get(core_v1.Service, search_service)
except l_exceptions.ApiError as e:
if e.status.code == 404 and search_service.endswith("-lb"):
return self._get_service(service_name, find_lb=False)
raise e
return _get_lb_service(self.kube, service_name, find_lb=find_lb)

def check_lb_pool_exists_in_annotations(
self, service_annotations: dict, lb_pool: str
Expand Down Expand Up @@ -783,7 +814,9 @@ def is_skip(self, context: StepContext) -> Result:

def run(self, context: StepContext) -> Result: # noqa: C901
"""Patch LoadBalancer services annotations with LB IP pool."""
for service_name in self.services():
services = self.services()
skipped = 0
for service_name in services:
try:
service = self._get_service(service_name, find_lb=True)
except l_exceptions.ApiError as e:
Expand All @@ -793,6 +826,7 @@ def run(self, context: StepContext) -> Result: # noqa: C901
"skipping as ignore_errors is set"
)
LOG.debug(message)
skipped += 1
continue
return Result(ResultType.FAILED, str(e))

Expand All @@ -806,6 +840,7 @@ def run(self, context: StepContext) -> Result: # noqa: C901
"skipping as ignore_errors is set"
)
LOG.debug(message)
skipped += 1
continue

if not service.metadata:
Expand Down Expand Up @@ -870,7 +905,7 @@ def run(self, context: StepContext) -> Result: # noqa: C901
except ValueError as e:
return Result(ResultType.FAILED, str(e))

return Result(ResultType.COMPLETED)
return _ignored_services_result(services, skipped)


class CreateLoadBalancerIPPoolsStep(BaseStep, abc.ABC):
Expand Down
7 changes: 4 additions & 3 deletions sunbeam-python/sunbeam/features/instance_recovery/consul.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,8 @@
CONSUL_CLIENT_TFPLAN = "consul-client-plan"
CONSUL_CLIENT_CONFIG_KEY = "TerraformVarsFeatureConsulPlanConsulClient"
PRINCIPAL_APP = "openstack-hypervisor"
CONSUL_STORAGE_LB_SERVICE = "consul-storage-lb"
# Base service name; PatchLoadBalancerServices* steps look up "<name>-lb" first.
CONSUL_STORAGE_SERVICE = "consul-storage"


class ConsulServerNetworks(enum.Enum):
Expand Down Expand Up @@ -496,7 +497,7 @@ def set_tfvars_on_enable(
class PatchConsulStorageLoadBalancerIPStep(PatchLoadBalancerServicesIPStep):
def services(self) -> list[str]:
"""List of services to patch."""
return [CONSUL_STORAGE_LB_SERVICE]
return [CONSUL_STORAGE_SERVICE]

def model(self) -> str:
"""Name of the model to use."""
Expand All @@ -506,7 +507,7 @@ def model(self) -> str:
class PatchConsulStorageLoadBalancerIPPoolStep(PatchLoadBalancerServicesIPPoolStep):
def services(self) -> list[str]:
"""List of services to patch."""
return [CONSUL_STORAGE_LB_SERVICE]
return [CONSUL_STORAGE_SERVICE]

def model(self) -> str:
"""Name of the model to use."""
Expand Down
179 changes: 179 additions & 0 deletions sunbeam-python/tests/unit/sunbeam/core/test_steps.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,25 @@
# SPDX-FileCopyrightText: 2023 - Canonical Ltd
# SPDX-License-Identifier: Apache-2.0

import json
from unittest.mock import Mock, patch

import httpx
import pytest
import tenacity
from lightkube.core.exceptions import ApiError
from lightkube.models import core_v1, meta_v1
from lightkube.resources.core_v1 import Service

from sunbeam.core.common import ResultType, Role
from sunbeam.core.juju import ApplicationNotFoundException
from sunbeam.core.k8s import K8SHelper
from sunbeam.core.steps import (
DeployMachineApplicationStep,
PatchLoadBalancerServicesIPPoolStep,
PatchLoadBalancerServicesIPStep,
RemoveMachineUnitsStep,
_get_lb_service,
)
from sunbeam.core.terraform import TerraformException, TerraformStateLockedException

Expand Down Expand Up @@ -275,3 +284,173 @@ def test_run_timeout(self, cclient, jhelper, read_config, step_context):
jhelper.wait_application_ready.assert_called_once()
assert result.result_type == ResultType.FAILED
assert result.message == "timed out"


def _api_error(code: int) -> ApiError:
return ApiError(
Mock(),
httpx.Response(
status_code=code,
content=json.dumps({"code": code, "reason": "test"}),
),
)


def _lb_service(name: str, ip: str | None = None) -> Service:
return Service(
metadata=meta_v1.ObjectMeta(name=name, annotations={}),
spec=core_v1.ServiceSpec(type="LoadBalancer"),
status=core_v1.ServiceStatus(
loadBalancer=core_v1.LoadBalancerStatus(
ingress=[core_v1.LoadBalancerIngress(ip=ip)] if ip else None
)
),
)


def _requested_names(kube: Mock) -> list[str]:
return [c.args[1] for c in kube.get.call_args_list]


class TestGetLbService:
def test_prefers_lb_service(self):
kube = Mock()
kube.get.return_value = _lb_service("bind-lb")

assert _get_lb_service(kube, "bind").metadata.name == "bind-lb"
assert _requested_names(kube) == ["bind-lb"]

def test_falls_back_to_base_service(self):
kube = Mock()
kube.get.side_effect = [_api_error(404), _lb_service("bind")]

assert _get_lb_service(kube, "bind").metadata.name == "bind"
assert _requested_names(kube) == ["bind-lb", "bind"]

def test_find_lb_false_looks_up_name_only(self):
kube = Mock()
kube.get.side_effect = _api_error(404)

with pytest.raises(ApiError):
_get_lb_service(kube, "bind", find_lb=False)
assert _requested_names(kube) == ["bind"]

def test_missing_service_raises_404(self):
kube = Mock()
kube.get.side_effect = _api_error(404)

with pytest.raises(ApiError) as exc_info:
_get_lb_service(kube, "consul-storage")
assert exc_info.value.status.code == 404
assert _requested_names(kube) == ["consul-storage-lb", "consul-storage"]

@pytest.mark.parametrize(
"find_lb, expected_lookups",
[
(True, ["consul-storage-lb-lb", "consul-storage-lb"]),
(False, ["consul-storage-lb"]),
],
)
def test_missing_name_ending_in_lb_does_not_recurse(
self, find_lb, expected_lookups
):
"""LP#2168498: a missing '<x>-lb' service used to recurse forever."""
kube = Mock()
kube.get.side_effect = _api_error(404)

with pytest.raises(ApiError) as exc_info:
_get_lb_service(kube, "consul-storage-lb", find_lb=find_lb)
assert exc_info.value.status.code == 404
assert _requested_names(kube) == expected_lookups

def test_non_404_error_raises_immediately(self):
kube = Mock()
kube.get.side_effect = _api_error(500)

with pytest.raises(ApiError) as exc_info:
_get_lb_service(kube, "bind")
assert exc_info.value.status.code == 500
assert _requested_names(kube) == ["bind-lb"]


class _IPStep(PatchLoadBalancerServicesIPStep):
def services(self) -> list[str]:
return ["consul-storage"]

def model(self) -> str:
return "openstack"


class _IPPoolStep(PatchLoadBalancerServicesIPPoolStep):
def services(self) -> list[str]:
return ["consul-storage"]

def model(self) -> str:
return "openstack"


@pytest.fixture()
def missing_kube():
kube = Mock()
kube.get.side_effect = _api_error(404)
return kube


class TestPatchLoadBalancerServicesMissingService:
@pytest.mark.parametrize("step_cls", [_IPStep, _IPPoolStep])
def test_run_ignore_errors_skips_missing(
self, step_cls, missing_kube, step_context
):
step = step_cls(Mock(), "storage-pool", ignore_errors=True)
step.kube = missing_kube

# Nothing was patched: report SKIPPED, like is_skip() does.
assert step.run(step_context).result_type == ResultType.SKIPPED
missing_kube.apply.assert_not_called()
missing_kube.patch.assert_not_called()

@pytest.mark.parametrize("step_cls", [_IPStep, _IPPoolStep])
def test_run_ignore_errors_completes_if_any_service_found(
self, step_cls, step_context
):
"""Only an all-skipped run is SKIPPED; one found service completes."""
present = _lb_service("traefik-lb", ip="10.0.0.1")
present.metadata.annotations = {
K8SHelper.get_loadbalancer_ip_annotation(): "10.0.0.1",
K8SHelper.get_loadbalancer_address_pool_annotation(): "storage-pool",
K8SHelper.get_loadbalancer_allocated_pool_annotation(): "storage-pool",
}

def _get(_resource, name):
if name == "traefik-lb":
return present
raise _api_error(404)

kube = Mock()
kube.get.side_effect = _get
step = step_cls(Mock(), "storage-pool", ignore_errors=True)
step.services = lambda: ["consul-storage", "traefik"]
step.kube = kube

assert step.run(step_context).result_type == ResultType.COMPLETED

@pytest.mark.parametrize("step_cls", [_IPStep, _IPPoolStep])
def test_run_without_ignore_errors_fails(
self, step_cls, missing_kube, step_context
):
step = step_cls(Mock(), "storage-pool", ignore_errors=False)
step.kube = missing_kube

assert step.run(step_context).result_type == ResultType.FAILED
missing_kube.apply.assert_not_called()
missing_kube.patch.assert_not_called()

@patch("sunbeam.core.steps.l_client.Client")
@patch("sunbeam.core.steps.l_kubeconfig.KubeConfig.from_dict")
def test_ip_step_is_skip_ignore_errors_skips_missing(
self, _from_dict, mock_client, read_config, missing_kube, step_context
):
mock_client.return_value = missing_kube
step = _IPStep(Mock(), pool_name=None, ignore_errors=True)

assert step.is_skip(step_context).result_type == ResultType.SKIPPED
Loading