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

fix for #36

parent 35e0e68c
Loading
Loading
Loading
Loading
Loading
+5
Changes for pom.xml: 5 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -113,6 +113,11 @@
			<version>13.0</version>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>
	
		<build>
+71
Changes for src/main/java/org/etsi/osl/tmf/ri639/model/Resource.java: 71 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -597,6 +597,77 @@ public class Resource extends BaseRootNamedEntity {
		this.usageState = usageState;
	}

	/**
	 * Classifies this resource's health from its ITU-T X.731 state attributes.
	 *
	 * <p>{@code resourceStatus} is deliberately not consulted: it is inventory/pool bookkeeping
	 * ({@code AVAILABLE} = free for reservation, {@code RESERVED} = held by someone) and carries no
	 * information about whether the resource is working. {@code usageState} is not consulted either —
	 * a healthy resource carrying no load is legitimately {@code IDLE}.
	 *
	 * <p>Evaluation order matters. {@code SHUTDOWN} outranks everything, because a torn-down resource
	 * is gone whatever its operational state last reported. A resource is only ever judged healthy
	 * when it <b>explicitly</b> declares {@code administrativeState=UNLOCKED}: an unset attribute
	 * means the producer has not adopted this contract, and such a resource must neither promote nor
	 * demote a service.
	 *
	 * @return the health verdict; never null
	 */
	public ResourceHealth deriveHealth() {
		if (administrativeState == ResourceAdministrativeStateType.SHUTDOWN) {
			return ResourceHealth.GONE;
		}
		if (administrativeState == ResourceAdministrativeStateType.LOCKED) {
			return ResourceHealth.HELD;
		}
		if (operationalState == null || administrativeState == null) {
			return ResourceHealth.PENDING;
		}
		return operationalState == ResourceOperationalStateType.ENABLE
				? ResourceHealth.UP
				: ResourceHealth.DOWN;
	}

	/**
	 * Sets the ITU-T X.731 state attributes so that {@link #deriveHealth()} reports the given verdict.
	 * The inverse of {@code deriveHealth}, and the one place that decides how a health verdict is
	 * spelled out in attributes — callers that want to say "this resource is up" should not have to
	 * remember which pair of enums means that.
	 *
	 * <p>{@code resourceStatus} is untouched: health and pool bookkeeping are independent.
	 *
	 * @param health the verdict to express; {@code PENDING} clears both attributes, which is how a
	 *               resource that has not reported yet is represented
	 */
	public void applyHealth(ResourceHealth health) {
		if (health == null) {
			return;
		}
		switch (health) {
		case UP:
			this.operationalState = ResourceOperationalStateType.ENABLE;
			this.administrativeState = ResourceAdministrativeStateType.UNLOCKED;
			break;
		case DOWN:
			this.operationalState = ResourceOperationalStateType.DISABLE;
			this.administrativeState = ResourceAdministrativeStateType.UNLOCKED;
			break;
		case HELD:
			this.operationalState = ResourceOperationalStateType.ENABLE;
			this.administrativeState = ResourceAdministrativeStateType.LOCKED;
			break;
		case GONE:
			this.operationalState = ResourceOperationalStateType.DISABLE;
			this.administrativeState = ResourceAdministrativeStateType.SHUTDOWN;
			break;
		default:
			// PENDING: nothing is known about this resource.
			this.operationalState = null;
			this.administrativeState = null;
			break;
		}
	}

	

	@Override
+39
Changes for src/main/java/org/etsi/osl/tmf/ri639/model/ResourceHealth.java: 39 added lines, 0 removed lines.
Original line number Diff line number Diff line
package org.etsi.osl.tmf.ri639.model;

/**
 * The health verdict of a single {@link Resource}, derived from its ITU-T X.731 state attributes.
 *
 * <p>This is deliberately <b>not</b> {@link ResourceStatusType}. {@code ResourceStatusType} is
 * inventory/pool bookkeeping — {@code AVAILABLE} means "free in a pool, available for reservation"
 * and {@code RESERVED} means "held by someone" — and says nothing about whether the resource is
 * working. Health is expressed by {@link ResourceOperationalStateType} (is it functioning?) and
 * {@link ResourceAdministrativeStateType} (is it permitted to be used?).
 *
 * <p>{@link ResourceUsageStateType} is <b>not</b> consulted: a resource that is deployed and
 * perfectly healthy but carrying no load is legitimately {@code IDLE}, and most controllers cannot
 * observe utilisation at all.
 *
 * @see Resource#deriveHealth()
 * @see org.etsi.osl.tmf.sim638.model.Service#findNextStateBasedOnResourceList(java.util.List)
 */
public enum ResourceHealth {

  /** Functioning and permitted to be used: {@code operationalState=ENABLE, administrativeState=UNLOCKED}. */
  UP,

  /**
   * The resource has not told us where it stands yet — either state attribute is unset. Typically a
   * resource that is still being provisioned, or one written by a producer that predates the health
   * contract. A service must not be promoted on it, nor demoted because of it.
   */
  PENDING,

  /** Not functioning while still administratively in service: {@code operationalState=DISABLE}. */
  DOWN,

  /** Administratively barred from use: {@code administrativeState=LOCKED}. */
  HELD,

  /** Torn down: {@code administrativeState=SHUTDOWN}. The terminal verdict. */
  GONE
}
+55 −62
Changes for src/main/java/org/etsi/osl/tmf/sim638/model/Service.java: 55 added lines, 62 removed lines.
Original line number Diff line number Diff line
@@ -37,7 +37,7 @@ import org.etsi.osl.tmf.common.model.service.ServiceSpecificationRef;
import org.etsi.osl.tmf.common.model.service.ServiceStateType;
import org.etsi.osl.tmf.prm669.model.RelatedParty;
import org.etsi.osl.tmf.ri639.model.Resource;
import org.etsi.osl.tmf.ri639.model.ResourceStatusType;
import org.etsi.osl.tmf.ri639.model.ResourceHealth;
import org.springframework.validation.annotation.Validated;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.persistence.CascadeType;
@@ -786,82 +786,75 @@ public class Service extends BaseRootNamedEntity {
	}
	
	/**
	 * @param supportingResources
	 * @return
	 * Derives the state this service should move to, given the current condition of its supporting
	 * resources.
	 *
	 * <p>The verdict comes from each resource's {@link Resource#deriveHealth()} — the ITU-T X.731
	 * operational and administrative states — and <b>not</b> from {@code resourceStatus}, which is
	 * inventory/pool bookkeeping and says nothing about whether a resource is working. Producers
	 * declare their own resource's health; this method only folds those verdicts together.
	 *
	 * <p>The fold, in order:
	 * <ol>
	 * <li>{@code TERMINATED} is absorbing — a terminated service never comes back on its own.</li>
	 * <li>Nothing to judge (empty list) leaves the state untouched; a service is never promoted on
	 * the absence of evidence.</li>
	 * <li>Every resource {@code GONE} means the service has been torn down: {@code TERMINATED}.</li>
	 * <li>Any resource {@code GONE}, {@code DOWN} or {@code HELD} — a part of the service is missing,
	 * broken, or administratively barred: {@code INACTIVE}.</li>
	 * <li>Any resource {@code PENDING} — still coming up, or a producer that has not adopted the
	 * health contract. A live service is <b>not</b> demoted by that (a transient unknown must not
	 * knock out a running service); anything else is still on its way up: {@code RESERVED}.</li>
	 * <li>Otherwise every resource is {@code UP}: {@code ACTIVE}.</li>
	 * </ol>
	 *
	 * @param supportingResources the resources this service is built on; may be empty or null
	 * @return the state to move to, which may be the current one; never null
	 */
	public ServiceStateType findNextStateBasedOnResourceList(List<Resource> supportingResources) {

      if (this.getState().equals( ServiceStateType.TERMINATED  )) {
		@Valid
		ServiceStateType currentState = this.getState();

		if (ServiceStateType.TERMINATED.equals(currentState)) {
			return ServiceStateType.TERMINATED;
		}
		if (supportingResources == null || supportingResources.isEmpty()) {
			return currentState;
		}

      @Valid
      ServiceStateType nextState = this.getState() ;
      boolean allResourcesAvailable = true ;
      boolean allResourcesTerminated = true ;
      boolean existsSuspended=false;
      boolean existsStandby=false;
      boolean existsReserved=false;
      boolean existUnknown=false;
      boolean existAlarm=false;
		boolean allGone = true;
		boolean anyOutOfService = false;
		boolean anyPending = false;

		for (Resource res : supportingResources) {
			ResourceHealth health =
					res == null ? ResourceHealth.PENDING : res.deriveHealth();

          if ( res.getResourceStatus() != null ) {
            switch (res.getResourceStatus()) {
              case AVAILABLE: {
			allGone = allGone && health == ResourceHealth.GONE;

                break;
              }
              case STANDBY: {
                existsStandby = true;
                break;
              }
              case SUSPENDED: {
                existsSuspended = true;
                break;
              }
              case RESERVED: {
                existsReserved = true;
                break;
			if (health == ResourceHealth.GONE
					|| health == ResourceHealth.DOWN
					|| health == ResourceHealth.HELD) {
				anyOutOfService = true;
			} else if (health == ResourceHealth.PENDING) {
				anyPending = true;
			}
              case UNKNOWN: {
                existUnknown =true;
                break;
		}
              case ALARM: {
                existAlarm = true;
                break;
              }
              default:
                throw new IllegalArgumentException("Unexpected value: " + res.getResourceStatus());
            } 
          } else 
            existUnknown =true;

          allResourcesAvailable = allResourcesAvailable && res.getResourceStatus()!=null && res.getResourceStatus().equals(ResourceStatusType.AVAILABLE);
          allResourcesTerminated = allResourcesTerminated && res.getResourceStatus()!=null && res.getResourceStatus().equals(ResourceStatusType.SUSPENDED);

		if (allGone) {
			return ServiceStateType.TERMINATED;
		}
      
      if ( allResourcesAvailable ) {
        nextState = ServiceStateType.ACTIVE ; 
      } else if ( allResourcesTerminated ) {
        nextState = ServiceStateType.TERMINATED ; 
      } else if ( existAlarm ) {
        nextState = ServiceStateType.INACTIVE ; 
      } else if ( existsReserved || existsStandby) {
        nextState = ServiceStateType.RESERVED ; 
      } else if ( existsSuspended ) {
          //do nothing
      } else if ( existUnknown ) {
//        if (this.getState().equals( ServiceStateType.ACTIVE  )) { //helpful state for argoCD lifecycle
//          nextState = ServiceStateType.TERMINATED ;
//        }
		if (anyOutOfService) {
			return ServiceStateType.INACTIVE;
		}
      
      return nextState;      
      
		if (anyPending) {
			// A resource that has not reported yet must not demote a service that is already running.
			return ServiceStateType.ACTIVE.equals(currentState)
					? ServiceStateType.ACTIVE
					: ServiceStateType.RESERVED;
		}
		return ServiceStateType.ACTIVE;
	}


+200
Changes for src/test/java/org/etsi/osl/tmf/sim638/model/ServiceStateFromResourceHealthTest.java: 200 added lines, 0 removed lines.
Original line number Diff line number Diff line
package org.etsi.osl.tmf.sim638.model;

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.etsi.osl.tmf.common.model.service.ServiceStateType;
import org.etsi.osl.tmf.ri639.model.Resource;
import org.etsi.osl.tmf.ri639.model.ResourceAdministrativeStateType;
import org.etsi.osl.tmf.ri639.model.ResourceHealth;
import org.etsi.osl.tmf.ri639.model.ResourceOperationalStateType;
import org.etsi.osl.tmf.ri639.model.ResourceStatusType;
import org.junit.jupiter.api.Test;

/**
 * The service state fold over its supporting resources' health.
 *
 * <p>Every case here is expressed with the ITU-T X.731 attributes only; {@code resourceStatus} is
 * deliberately left at its default (or set to something contradictory) to prove it no longer takes
 * part in the derivation.
 */
public class ServiceStateFromResourceHealthTest {

  private static Resource resource(ResourceOperationalStateType op,
      ResourceAdministrativeStateType admin) {
    Resource r = new Resource();
    r.setOperationalState(op);
    r.setAdministrativeState(admin);
    return r;
  }

  private static Resource up() {
    return resource(ResourceOperationalStateType.ENABLE, ResourceAdministrativeStateType.UNLOCKED);
  }

  private static Resource down() {
    return resource(ResourceOperationalStateType.DISABLE, ResourceAdministrativeStateType.UNLOCKED);
  }

  private static Resource held() {
    return resource(ResourceOperationalStateType.ENABLE, ResourceAdministrativeStateType.LOCKED);
  }

  private static Resource gone() {
    return resource(ResourceOperationalStateType.DISABLE, ResourceAdministrativeStateType.SHUTDOWN);
  }

  /** A resource that has not declared its health yet — e.g. a row written before the upgrade. */
  private static Resource pending() {
    return resource(ResourceOperationalStateType.ENABLE, null);
  }

  private static Service service(ServiceStateType state) {
    Service s = new Service();
    s.setState(state);
    return s;
  }

  private static List<Resource> list(Resource... resources) {
    return new ArrayList<>(Arrays.asList(resources));
  }

  @Test
  public void terminatedIsAbsorbing() {
    Service s = service(ServiceStateType.TERMINATED);

    assertEquals(ServiceStateType.TERMINATED, s.findNextStateBasedOnResourceList(list(up(), up())));
  }

  @Test
  public void noResourcesLeavesTheStateUntouched() {
    Service s = service(ServiceStateType.RESERVED);

    assertEquals(ServiceStateType.RESERVED, s.findNextStateBasedOnResourceList(Collections.emptyList()));
    assertEquals(ServiceStateType.RESERVED, s.findNextStateBasedOnResourceList(null));
  }

  @Test
  public void allUpMakesTheServiceActive() {
    Service s = service(ServiceStateType.RESERVED);

    assertEquals(ServiceStateType.ACTIVE, s.findNextStateBasedOnResourceList(list(up(), up(), up())));
  }

  @Test
  public void allGoneTerminatesTheService() {
    Service s = service(ServiceStateType.ACTIVE);

    assertEquals(ServiceStateType.TERMINATED, s.findNextStateBasedOnResourceList(list(gone(), gone())));
  }

  @Test
  public void partialTeardownOnlyDeactivates() {
    Service s = service(ServiceStateType.ACTIVE);

    assertEquals(ServiceStateType.INACTIVE, s.findNextStateBasedOnResourceList(list(gone(), up())));
  }

  @Test
  public void aBrokenResourceDeactivatesTheService() {
    Service s = service(ServiceStateType.ACTIVE);

    assertEquals(ServiceStateType.INACTIVE, s.findNextStateBasedOnResourceList(list(up(), down())));
  }

  @Test
  public void anAdministrativelyLockedResourceDeactivatesTheService() {
    Service s = service(ServiceStateType.ACTIVE);

    assertEquals(ServiceStateType.INACTIVE, s.findNextStateBasedOnResourceList(list(up(), held())));
  }

  @Test
  public void outOfServiceOutranksPending() {
    Service s = service(ServiceStateType.ACTIVE);

    assertEquals(ServiceStateType.INACTIVE, s.findNextStateBasedOnResourceList(list(pending(), down())));
  }

  @Test
  public void pendingDoesNotDemoteALiveService() {
    Service s = service(ServiceStateType.ACTIVE);

    assertEquals(ServiceStateType.ACTIVE, s.findNextStateBasedOnResourceList(list(up(), pending())));
  }

  @Test
  public void pendingHoldsAServiceThatIsStillComingUp() {
    Service s = service(ServiceStateType.RESERVED);

    assertEquals(ServiceStateType.RESERVED, s.findNextStateBasedOnResourceList(list(up(), pending())));
  }

  @Test
  public void aResourceMissingBothStateAttributesIsPending() {
    Service s = service(ServiceStateType.RESERVED);
    Resource legacy = new Resource();

    assertEquals(ServiceStateType.RESERVED, s.findNextStateBasedOnResourceList(list(legacy)));
  }

  @Test
  public void aNullResourceEntryIsTreatedAsPending() {
    Service s = service(ServiceStateType.RESERVED);
    List<Resource> resources = list(up());
    resources.add(null);

    assertEquals(ServiceStateType.RESERVED, s.findNextStateBasedOnResourceList(resources));
  }

  @Test
  public void resourceStatusNoLongerTakesPart() {
    Service s = service(ServiceStateType.RESERVED);

    // A Chronos booking that is genuinely held: RESERVED in the pool, and perfectly healthy.
    Resource booked = up();
    booked.setResourceStatus(ResourceStatusType.RESERVED);

    assertEquals(ServiceStateType.ACTIVE, s.findNextStateBasedOnResourceList(list(booked)));

    // ...and the mirror image: free in the pool, but not working.
    Resource free = down();
    free.setResourceStatus(ResourceStatusType.AVAILABLE);

    assertEquals(ServiceStateType.INACTIVE,
        service(ServiceStateType.ACTIVE).findNextStateBasedOnResourceList(list(free)));
  }

  /**
   * {@code applyHealth} is the inverse of {@code deriveHealth}: every verdict a resource can report
   * must be expressible in attributes, or a caller that wants to say "this is up" cannot.
   */
  @Test
  void applyHealthRoundTripsThroughDeriveHealth() {
    for (ResourceHealth health : ResourceHealth.values()) {
      Resource r = new Resource();
      r.applyHealth(health);
      assertEquals(health, r.deriveHealth(), "round trip failed for " + health);
    }
  }

  /** A null verdict says nothing, so it must not silently wipe the attributes already set. */
  @Test
  void applyHealthOfNullLeavesTheResourceAlone() {
    Resource r = up();
    r.applyHealth(null);
    assertEquals(ResourceHealth.UP, r.deriveHealth());
  }

  /** Health and pool bookkeeping are independent: applying one must not disturb the other. */
  @Test
  void applyHealthLeavesTheInventoryStatusUntouched() {
    Resource r = new Resource();
    r.setResourceStatus(ResourceStatusType.RESERVED);
    r.applyHealth(ResourceHealth.UP);
    assertEquals(ResourceStatusType.RESERVED, r.getResourceStatus());
  }
}