Search in sources :

Example 11 with Resource

use of bio.terra.buffer.common.Resource in project terra-resource-buffer by DataBiosphere.

the class FlightSchedulerTest method scheduleDeactivationFlights_smallerLimitPerExecute.

@Test
public void scheduleDeactivationFlights_smallerLimitPerExecute() throws Exception {
    // Pool1 size 5, need to deactivate the 4 READY resources.
    // Expect number of resourceDeactivationPerPoolLimit(3) flights are submitted at most.
    Pool pool = newPoolWithResourceCount(5, ImmutableMultiset.of(ResourceState.READY, ResourceState.READY, ResourceState.READY, ResourceState.READY, ResourceState.CREATING));
    bufferDao.deactivatePools(ImmutableList.of(pool.id()));
    List<Resource> resources = bufferDao.retrieveResourcesRandomly(pool.id(), ResourceState.READY, 4);
    PrimaryConfiguration primaryConfiguration = newPrimaryConfiguration();
    primaryConfiguration.setResourceDeletionPerPoolLimit(3);
    initializeScheduler(primaryConfiguration);
    TimeUnit.SECONDS.sleep(4);
    verify(flightManager, times(3)).submitDeletionFlight(resourceArgumentCaptor.capture(), eq(ResourceType.GOOGLE_PROJECT));
    assertThat(resources, (Matcher) Matchers.hasItems(resourceArgumentCaptor.getAllValues().toArray()));
    verify(flightManager, never()).submitCreationFlight(any(Pool.class));
}
Also used : Resource(bio.terra.buffer.common.Resource) PrimaryConfiguration(bio.terra.buffer.app.configuration.PrimaryConfiguration) Pool(bio.terra.buffer.common.Pool) BaseUnitTest(bio.terra.buffer.common.BaseUnitTest) Test(org.junit.jupiter.api.Test)

Example 12 with Resource

use of bio.terra.buffer.common.Resource in project terra-resource-buffer by DataBiosphere.

the class BufferDao method updateReadyResourceToDeleting.

/**
 * Updates resource in READY state to DELETING. Returns true if previous state is READY and we
 * successfully update its state.
 */
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.SERIALIZABLE)
public boolean updateReadyResourceToDeleting(ResourceId id) {
    Optional<Resource> resource = retrieveResource(id);
    if (resource.isEmpty() || !resource.get().state().equals(ResourceState.READY)) {
        logger.warn("We shouldn't mark non-READY resource {} to DELETING", resource);
        return false;
    } else {
        String sql = "UPDATE resource SET state = :state WHERE id = :id";
        MapSqlParameterSource params = new MapSqlParameterSource().addValue("state", ResourceState.DELETING.toString()).addValue("id", id.id());
        return jdbcTemplate.update(sql, params) == 1;
    }
}
Also used : MapSqlParameterSource(org.springframework.jdbc.core.namedparam.MapSqlParameterSource) Resource(bio.terra.buffer.common.Resource) Transactional(org.springframework.transaction.annotation.Transactional)

Example 13 with Resource

use of bio.terra.buffer.common.Resource in project terra-resource-buffer by DataBiosphere.

the class BufferDao method updateOneReadyResourceToHandedOut.

/**
 * Pick one READY resource and handed it out to client. The steps are:
 *
 * <ul>
 *   <li>Step 1: Checks if any resource uses this {@link RequestHandoutId}, if yes, return the
 *       resource.
 *   <li>Step 2: Randomly pick a READY entity from resource table
 *   <li>Step 3: Update this resource state to HANDED_OUT
 *   <li>Step 4: Return step 2's resource.
 * </ul>
 */
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.SERIALIZABLE)
public Optional<Resource> updateOneReadyResourceToHandedOut(PoolId poolId, RequestHandoutId requestHandoutId) {
    Optional<Resource> existingResource = retrieveResource(poolId, requestHandoutId);
    if (existingResource.isPresent()) {
        if (existingResource.get().state().equals(ResourceState.HANDED_OUT)) {
            logger.info("Resource {}, requestHandoutId {} already handed out. Handing out again...", existingResource.get().id(), requestHandoutId);
            return existingResource;
        } else {
            // resource.
            throw new InternalServerErrorException(String.format("Unexpected handed out resource state found in pool id: %s, requestHandoutId: %s", poolId, requestHandoutId));
        }
    } else {
        List<Resource> resources = retrieveResourcesRandomly(poolId, ResourceState.READY, 1);
        if (resources.size() == 0) {
            logger.warn("No resource is ready to use at this moment for pool: {}.", poolId);
            return Optional.empty();
        } else {
            Resource selectedResource = resources.get(0);
            String sql = "UPDATE resource " + "SET state = :state, request_handout_id = :request_handout_id, handout_time = :handout_time" + " WHERE id = :id AND state = :previous_state AND request_handout_id IS null";
            MapSqlParameterSource params = new MapSqlParameterSource().addValue("state", ResourceState.HANDED_OUT.toString()).addValue("previous_state", ResourceState.READY.toString()).addValue("request_handout_id", requestHandoutId.id()).addValue("handout_time", OffsetDateTime.now(ZoneOffset.UTC)).addValue("id", selectedResource.id().id());
            // Return the selectedResource if update successfully. Otherwise, return empty.
            return jdbcTemplate.update(sql, params) == 1 ? Optional.of(selectedResource) : Optional.empty();
        }
    }
}
Also used : MapSqlParameterSource(org.springframework.jdbc.core.namedparam.MapSqlParameterSource) Resource(bio.terra.buffer.common.Resource) InternalServerErrorException(bio.terra.common.exception.InternalServerErrorException) Transactional(org.springframework.transaction.annotation.Transactional)

Example 14 with Resource

use of bio.terra.buffer.common.Resource in project terra-resource-buffer by DataBiosphere.

the class FlightScheduler method scheduleDeletionFlights.

/**
 * Schedules up to {@code number} of resources deletion flight for a pool.
 */
private void scheduleDeletionFlights(Pool pool, int number) {
    if (number == 0) {
        return;
    }
    int flightsToScheduleCount = Math.min(primaryConfiguration.getResourceDeletionPerPoolLimit(), number);
    logger.info("Beginning resource deletion flights for pool: {}, target submission number: {} .", pool.id(), flightsToScheduleCount);
    // TODO: check pool expiration time before deleting projects
    List<Resource> resources = bufferDao.retrieveResourcesRandomly(pool.id(), ResourceState.READY, flightsToScheduleCount);
    int successSubmitNum = 0;
    for (Resource resource : resources) {
        boolean submissionSuccessful = flightManager.submitDeletionFlight(resource, pool.resourceType()).isPresent();
        if (submissionSuccessful) {
            ++successSubmitNum;
        }
    }
    logger.info("Successfully submitted {} number of resource deletion flights for pool: {} .", successSubmitNum, pool.id());
}
Also used : Resource(bio.terra.buffer.common.Resource)

Example 15 with Resource

use of bio.terra.buffer.common.Resource in project terra-resource-buffer by DataBiosphere.

the class CleanupScheduler method scheduleCleanup.

public void scheduleCleanup() {
    List<Resource> resources = bufferDao.retrieveResourceToCleanup(MESSAGE_TO_PUBLISH_PER_RUN);
    for (Resource resource : resources) {
        publish(resource.cloudResourceUid());
        bufferDao.insertCleanupRecord(resource.id());
    }
}
Also used : Resource(bio.terra.buffer.common.Resource)

Aggregations

Resource (bio.terra.buffer.common.Resource)25 Pool (bio.terra.buffer.common.Pool)18 Test (org.junit.jupiter.api.Test)18 BaseUnitTest (bio.terra.buffer.common.BaseUnitTest)11 BaseIntegrationTest (bio.terra.buffer.common.BaseIntegrationTest)7 IntegrationUtils.preparePool (bio.terra.buffer.integration.IntegrationUtils.preparePool)6 FlightManager (bio.terra.buffer.service.resource.FlightManager)6 StubSubmissionFlightFactory (bio.terra.buffer.integration.IntegrationUtils.StubSubmissionFlightFactory)5 PoolId (bio.terra.buffer.common.PoolId)3 ResourceId (bio.terra.buffer.common.ResourceId)3 Project (com.google.api.services.cloudresourcemanager.v3.model.Project)3 CloudResourceUid (bio.terra.buffer.generated.model.CloudResourceUid)2 GoogleProjectUid (bio.terra.buffer.generated.model.GoogleProjectUid)2 InternalServerErrorException (bio.terra.common.exception.InternalServerErrorException)2 MapSqlParameterSource (org.springframework.jdbc.core.namedparam.MapSqlParameterSource)2 Transactional (org.springframework.transaction.annotation.Transactional)2 PrimaryConfiguration (bio.terra.buffer.app.configuration.PrimaryConfiguration)1 RequestHandoutId (bio.terra.buffer.common.RequestHandoutId)1 NotFoundException (bio.terra.buffer.common.exception.NotFoundException)1 ResourceConfig (bio.terra.buffer.generated.model.ResourceConfig)1