Commit e5af72ac authored by Christos Tranoris's avatar Christos Tranoris
Browse files

KubernetesCluster: accept the create HELD, report it UP 60 s later

In production the cluster is reported HELD in the reply, and a background
report marks it UP in the catalogue after
osl-controller.kubernetes-cluster.provisioning-seconds (default 60). A new
ExampleResourceSpec.onTeardown hook drops a pending report when the cluster is
deleted. Simulation is unchanged.
parent 9d633c83
Loading
Loading
Loading
Loading
Loading
+53
Changes for .changelog/20261022_2345_kubernetes-cluster-long-running-deployment.md: 53 added lines, 0 removed lines.
Original line number Diff line number Diff line
# KubernetesCluster: a long-running deployment, accepted HELD and reported UP later

**Date:** 2026-10-22
**Change type:** Linear.

## What
In production (not simulation), `KubernetesCluster.resourceLogic` now behaves like a real, slow
provisioner:
1. **It accepts the request at once.** The reply carries the cluster **HELD**
   (`ENABLE` + `LOCKED`, usage `IDLE`, `status.Health=Provisioning`), so OSOM gets its reply well
   inside its 20 s request timeout.
2. **After the provisioning time** (default 60 s), a background thread writes the cluster **UP** to the
   catalogue (`ENABLE` + `UNLOCKED`, usage `ACTIVE`, `status.Health=Healthy`,
   `status.infoMessage=Cluster ready: ...`). OSOM's `GCOrchestrationCheckDeploymentService` loop
   (every 15 s) folds that into the supporting service, which then goes ACTIVE.

Simulation is unchanged: the cluster is UP at once, and nothing is sent in the background.

## Details
- `ResourceSpecCatalogConfig` gives the cluster a catalogue reporter, which calls
  `CatalogClient.updateResourceById`. The client is looked up through `ObjectProvider` only when a
  report goes out, so the config test context still starts without one.
- New property `osl-controller.kubernetes-cluster.provisioning-seconds` (default `60`).
- The ready report is built from the request's own values, never from the spec's instance fields.
  The spec is a singleton.
- **One pending report per resource**, kept as a token:
  - a later request for the same resource supersedes the earlier report;
  - teardown drops it, through a new `ExampleResourceSpec.onTeardown(resourceId)` hook (no-op by
    default). `ResourceRepoService.deleteResource` calls the hook on every spec, because a delete does
    not reliably name a spec.

  So a late report can never bring a deleted cluster back.
- `resourceStatus` is not touched: it is pool bookkeeping.

## Tests
`KubernetesClusterTest` has 5 new tests:
- held at once, then UP;
- nothing reported before the provisioning time;
- teardown drops the report;
- a later request supersedes an earlier one;
- simulation reports nothing.

`ExampleResourceSpecTest` and `ResourceSpecRegistryTest` were updated to the new bean method signature.
`mvn test`: 124 tests, 0 failures.

## Limits
- **Day-2 updates follow the same path.** `updateResource` calls the same `resourceLogic`, so a day-2
  change to a cluster also goes HELD, then UP 60 s later. The service may show INACTIVE meanwhile.
- **The pending report lives only in memory.** If the controller restarts inside the window, the
  report is lost, and the cluster stays HELD (the service is never activated).
- **This relies on OSOM's GC fix.** OSOM leaves a resource that is already HELD to the
  check-deployment loop (OSOM `.changelog/20261022_2259_slow-generic-controller-is-not-a-failed-one.md`).
  Because the reply now comes back at once, it no longer hits the timeout path.
+5
Changes for .changelog/index.md: 5 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -2,6 +2,11 @@

| Doc | Description |
|---|---|
| [20261022_2345_kubernetes-cluster-long-running-deployment.md](20261022_2345_kubernetes-cluster-long-running-deployment.md) | `KubernetesCluster` in production accepts the create request at once with the cluster HELD, and a background report marks it UP in the catalogue 60 s later (`osl-controller.kubernetes-cluster.provisioning-seconds`). A new `onTeardown` hook drops a pending report when the cluster is deleted. Simulation is unchanged. 124 tests pass. |
| [20261016_0011_presentation-osl-template.md](20261016_0011_presentation-osl-template.md) | Restyled `docs/creating-an-openslice-controller.pptx` to the OpenSlice promo template (`osl.promo/overview/Template.pptx`): photos with the curved edge on title and section slides, the OpenSlice logo on every layout, Cambria and Calibri fonts, the OSL blue and amber palette, and cards with a soft shadow. Same 29 slides and notes, checked in PowerPoint. No code changed. |
| [20261015_2354_controller-guide-presentation.md](20261015_2354_controller-guide-presentation.md) | New `docs/creating-an-openslice-controller.pptx`: a 29-slide deck with speaker notes generated from the generic controller guide (overview, Part 1 adapting resources, Part 2 supporting simulation, appendices). Built with pptxgenjs and checked by rendering in PowerPoint. No code changed. |
| [20261015_2337_rename-example-generic-controller-doc.md](20261015_2337_rename-example-generic-controller-doc.md) | Renamed `docs/writing-an-openslice-controller.md` → `docs/the-example-generic-controller.md`, retitled "The Example Generic Controller", and updated its references in the README and the generic guide. Historical changelog entries keep the old name. |
| [20261015_2332_generic-controller-guide.md](20261015_2332_generic-controller-guide.md) | New `docs/creating-an-openslice-controller.md`: language-agnostic controller contract in two parts — (1) adapting the resources of a category (OSOM routing, queues/headers, RSpec registration, health reporting, replies) and (2) supporting simulation (`/PLANNING` queues, no side effects, planning callback, HELD → UP, estimates, `estimateOnly`, timeouts). Linked from the existing guide. No code changed. |
| [20261015_1605_fix-executable-jar.md](20261015_1605_fix-executable-jar.md) | Bind `spring-boot-maven-plugin` `repackage` in `pom.xml`. With no Spring Boot parent it never ran, so the image jar had no `Main-Class` ("no main manifest attribute" on osl-staging). 119 tests pass; the jar starts locally |
| [20261015_1530_restore-weakened-test-assertions.md](20261015_1530_restore-weakened-test-assertions.md) | Re-enable the X.731 header assertions in `ResourceRepoServiceHealthTest` (without `resourceStatus`), drop the vacuous `supersedesAnEarlierConditionVerdict`, re-pin KubernetesCluster's default `operationCostPerHour` and fix its stale javadoc. 119 tests pass. |
| [20261015_1500_dockerfile.md](20261015_1500_dockerfile.md) | Add a runtime-only `Dockerfile` (temurin 17 JRE, non-root) that packages the prebuilt jar, matching the CI `maven_build` → `docker_build` flow, plus a `.dockerignore`. |
+9
Changes for src/main/java/org/etsi/osl/example/gc/api/ExampleResourceSpec.java: 9 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -111,6 +111,15 @@ public abstract class ExampleResourceSpec extends DomainModelDefinition
    public abstract ResourceUpdate resourceLogic(ResourceUpdate resourceUpdate, String resourceId,
            boolean simulation);

    /**
     * A real resource is being torn down. Called on every spec, because a delete request does not
     * reliably name one. A spec that still has work in flight for this resource, such as a delayed
     * report, must drop it here, or that late report would bring the deleted resource back. The
     * default does nothing.
     */
    public void onTeardown(String resourceId) {
    }

    /**
     * Builds the catalog registration payload: the common skeleton plus this spec's own
     * characteristics. Final — a spec differentiates itself through {@link #defineCharacteristics} and
+126 −13
Changes for src/main/java/org/etsi/osl/example/gc/api/KubernetesCluster.java: 126 added lines, 13 removed lines.
Original line number Diff line number Diff line
package org.etsi.osl.example.gc.api;

import java.time.Duration;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;
import org.etsi.osl.tmf.common.model.EValueType;
import org.etsi.osl.tmf.rcm634.model.ResourceSpecificationCreate;
import org.etsi.osl.tmf.ri639.model.Characteristic;
import org.etsi.osl.tmf.ri639.model.ResourceAdministrativeStateType;
import org.etsi.osl.tmf.ri639.model.ResourceOperationalStateType;
import org.etsi.osl.tmf.ri639.model.ResourceStatusType;
import org.etsi.osl.tmf.ri639.model.Resource;
import org.etsi.osl.tmf.ri639.model.ResourceHealth;
import org.etsi.osl.tmf.ri639.model.ResourceUpdate;
import org.etsi.osl.tmf.ri639.model.ResourceUsageStateType;
import org.slf4j.Logger;
@@ -22,6 +28,12 @@ import org.slf4j.LoggerFactory;
 * with how many worker nodes it has. The model is a fixed control-plane part plus a per-node
 * increment, so a bigger cluster reports a proportionally bigger CREATION / OPERATION / TEARDOWN
 * estimate (see {@link #estimateProfile(ResourceUpdate)}).
 *
 * <p>It is also the example of a <b>long-running deployment</b>. In production (not simulation) the
 * request is accepted at once: the reply reports the cluster {@code HELD} (it exists, but is not usable
 * yet), and the provisioning time later a background report tells the catalogue it is {@code UP}.
 * OSOM's check-deployment loop follows that HELD &rarr; UP progression, so the supporting service goes
 * ACTIVE once the cluster is ready, and OSOM's request never times out waiting for it.
 */
public class KubernetesCluster extends ExampleResourceSpec {

@@ -30,6 +42,9 @@ public class KubernetesCluster extends ExampleResourceSpec {
    public static final String RESOURCE_NAME = "KubernetesCluster";
    public static final String RESOURCE_DESCRIPTION = "A Kubernetes cluster";

    /** How long a real cluster takes to come up after its request was accepted. */
    public static final Duration DEFAULT_PROVISIONING_TIME = Duration.ofSeconds(60);

    /**
     * The node count the fixed {@link #estimateProfile()} sizes against, and the characteristic default.
     * Shared so the two cannot drift apart.
@@ -44,8 +59,40 @@ public class KubernetesCluster extends ExampleResourceSpec {
    private String nodeCount = String.valueOf(DEFAULT_NODE_COUNT);
    private String nodeFlavor = "m1.large";

    /** Writes a partial update of a resource to the catalogue: (resourceId, update). */
    private final BiConsumer<String, ResourceUpdate> catalogReporter;

    private final Duration provisioningTime;

    /**
     * One token per resource whose "ready" report is still to come. A report goes out only if its own
     * token is still here: a later request for the same resource replaces it, and a teardown removes
     * it, so a late report can neither overwrite a newer one nor bring a deleted cluster back.
     */
    private final Map<String, Object> pendingReady = new ConcurrentHashMap<>();

    /** Daemon scheduler for the delayed "ready" report (no lifecycle management needed). */
    private final ScheduledExecutorService provisioningScheduler =
            Executors.newSingleThreadScheduledExecutor(r -> {
                Thread t = new Thread(r, "gc-k8s-provisioning");
                t.setDaemon(true);
                return t;
            });

    /** A cluster with no catalogue to report readiness to; enough for estimates and simulation. */
    public KubernetesCluster(String version, String category) {
        this(version, category, null, DEFAULT_PROVISIONING_TIME);
    }

    /**
     * @param catalogReporter where the delayed "ready" report goes; when null the report is only logged
     * @param provisioningTime how long after the request the cluster reports itself UP
     */
    public KubernetesCluster(String version, String category,
            BiConsumer<String, ResourceUpdate> catalogReporter, Duration provisioningTime) {
        super(RESOURCE_NAME, version, RESOURCE_DESCRIPTION, category);
        this.catalogReporter = catalogReporter;
        this.provisioningTime = provisioningTime;
    }

    @Override
@@ -119,6 +166,15 @@ public class KubernetesCluster extends ExampleResourceSpec {
        return DEFAULT_NODE_COUNT;
    }

    /**
     * In simulation the cluster is reported ready at once. In production the request is accepted with
     * the cluster {@code HELD}, and the ready ({@code UP}) report follows from a background thread once
     * the provisioning time has passed.
     *
     * <p>The ready report is built here, from this request's values, and not from the instance fields:
     * the spec is a singleton, so by the time the report goes out the fields may hold another request's
     * values.
     */
    @Override
    public ResourceUpdate resourceLogic(ResourceUpdate resourceUpdate, String resourceId, boolean simulation) {

@@ -134,21 +190,78 @@ public class KubernetesCluster extends ExampleResourceSpec {
            }
        }

        infoMessage = "Cluster ready: k8s " + k8sVersion + ", " + nodeCount + " x " + nodeFlavor + " nodes";
        healthStatus = "Healthy";
        logger.info(infoMessage);
        String cluster = "k8s " + k8sVersion + ", " + nodeCount + " x " + nodeFlavor + " nodes";
        resourceUpdate.addResourceCharacteristicItemShort("status.UUID", UUID.randomUUID().toString(), EValueType.TEXT.getValue());
        resourceUpdate.addResourceCharacteristicItemShort("status.apiServer", "https://k8s-" + idDerived(resourceId, 100) + ".example.org:6443", EValueType.TEXT.getValue());

        if (simulation) {
            return markReady(resourceUpdate, cluster);
        }

        // Accepted, but not usable yet: HELD. The ready report follows once the cluster is up.
        infoMessage = "Provisioning cluster: " + cluster + " (ready in about "
                + provisioningTime.toSeconds() + " s)";
        healthStatus = "Provisioning";
        logger.info(infoMessage);
        resourceUpdate.addResourceCharacteristicItemShort("status.infoMessage", infoMessage, EValueType.TEXT.getValue());
        resourceUpdate.addResourceCharacteristicItemShort("status.Health", healthStatus, EValueType.TEXT.getValue());
        resourceUpdate.addResourceCharacteristicItemShort("status.UUID", UUID.randomUUID().toString(), EValueType.TEXT.getValue());
        resourceUpdate.addResourceCharacteristicItemShort("status.apiServer", "https://k8s-" + idDerived(resourceId, 100) + ".example.org:6443", EValueType.TEXT.getValue());
        applyHealth(resourceUpdate, ResourceHealth.HELD);
        resourceUpdate.setUsageState(ResourceUsageStateType.IDLE);

        // Deployed and in service: declare AVAILABLE (never over an allocation) + ENABLE/UNLOCKED/ACTIVE.
        //resourceUpdate.declareResourceStatus(ResourceStatusType.AVAILABLE);
        resourceUpdate.setOperationalState(ResourceOperationalStateType.ENABLE);
        resourceUpdate.setAdministrativeState(ResourceAdministrativeStateType.UNLOCKED);
        resourceUpdate.setUsageState(ResourceUsageStateType.ACTIVE);
        scheduleReady(resourceId, markReady(new ResourceUpdate(), cluster));
        return resourceUpdate;
    }

    /** The cluster is torn down, so a ready report still to come must not bring it back. */
    @Override
    public void onTeardown(String resourceId) {
        if (resourceId != null && pendingReady.remove(resourceId) != null) {
            logger.info("Cluster " + resourceId + " was torn down while provisioning; its ready report is dropped");
        }
    }

    /** Fills in the status characteristics and the X.731 attributes of a cluster in service. */
    private ResourceUpdate markReady(ResourceUpdate ru, String cluster) {
        infoMessage = "Cluster ready: " + cluster;
        healthStatus = "Healthy";
        ru.addResourceCharacteristicItemShort("status.infoMessage", "Cluster ready: " + cluster, EValueType.TEXT.getValue());
        ru.addResourceCharacteristicItemShort("status.Health", "Healthy", EValueType.TEXT.getValue());

        // Deployed and in service: UP (ENABLE/UNLOCKED) + ACTIVE. resourceStatus is left alone: it is
        // pool bookkeeping, and an allocation someone else made is not ours to end.
        applyHealth(ru, ResourceHealth.UP);
        ru.setUsageState(ResourceUsageStateType.ACTIVE);
        return ru;
    }

    private void scheduleReady(String resourceId, ResourceUpdate ready) {
        Object token = new Object();
        pendingReady.put(resourceId, token);
        provisioningScheduler.schedule(() -> reportReady(resourceId, token, ready),
                provisioningTime.toMillis(), TimeUnit.MILLISECONDS);
    }

    private void reportReady(String resourceId, Object token, ResourceUpdate ready) {
        if (!pendingReady.remove(resourceId, token)) {
            return; // superseded by a later request, or torn down in the meantime
        }
        if (catalogReporter == null) {
            logger.warn("Cluster " + resourceId + " is ready, but there is no catalogue to report it to");
            return;
        }
        try {
            logger.info("Cluster " + resourceId + " is ready; reporting it UP");
            catalogReporter.accept(resourceId, ready);
        } catch (Exception e) {
            logger.error("Failed to report cluster " + resourceId + " ready: " + e);
        }
    }

    /** Spelled out by {@link Resource#applyHealth}, so the one place that decides which enum pair means a verdict decides it here too. */
    private static void applyHealth(ResourceUpdate ru, ResourceHealth health) {
        Resource spelled = new Resource();
        spelled.applyHealth(health);
        ru.setOperationalState(spelled.getOperationalState());
        ru.setAdministrativeState(spelled.getAdministrativeState());
    }
}
+3
Changes for src/main/java/org/etsi/osl/example/gc/api/ResourceRepoService.java: 3 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -425,6 +425,9 @@ public class ResourceRepoService {
    
    String resourceid = resourceIdFromHeaders(headers); //the resource to update back

    // A spec may still have a delayed report in flight for this resource (KubernetesCluster's "ready").
    resourceSpecRegistry.all().forEach(spec -> spec.onTeardown(resourceid));

    ResourceUpdate resourceUpdate = r;
    // The resource is gone. resourceStatus=UNKNOWN says nothing about health, and PENDING health
    // would leave the supporting service hanging — administrativeState=SHUTDOWN is what the service
Loading