Search in sources :

Example 1 with TenantManagerConfig

use of org.bf2.srs.fleetmanager.spi.tenants.model.TenantManagerConfig in project srs-fleet-manager by bf2fc6cc711aee1a0c2a.

the class DeprovisionRegistryWorker method execute.

@Transactional
@Override
public void execute(Task aTask, WorkerContext ctl) throws RegistryStorageConflictException, RegistryNotFoundException, AccountManagementServiceException, TenantManagerServiceException {
    var task = (DeprovisionRegistryTask) aTask;
    var registryOptional = storage.getRegistryById(task.getRegistryId());
    if (registryOptional.isPresent()) {
        // FAILURE POINT 1
        var registry = registryOptional.get();
        RegistryDeploymentData registryDeployment = registry.getRegistryDeployment();
        // FAILURE POINT 2
        if (task.getRegistryTenantId() == null) {
            final var tenantId = registry.getId();
            TenantManagerConfig tenantManagerConfig = Utils.createTenantManagerConfig(registryDeployment);
            try {
                tms.deleteTenant(tenantManagerConfig, tenantId);
                log.debug("Tenant id='{}' delete request send.", tenantId);
            } catch (TenantNotFoundServiceException ex) {
                log.info("Tenant id='{}' does not exist (already deleted?).", tenantId);
            }
            task.setRegistryTenantId(tenantId);
        }
        /* Return AMS entitlement
             * FAILURE POINT 3
             * Recovery: We recover by setting the registry status to failed so we don't lose information
             *   and the process can be initiated again.
             * Reentrancy: If the registry was already returned, (i.e. failed in #3)
             *   we need to continue without raising an error, otherwise we will keep retrying.
             */
        if (!task.isAmsSuccess()) {
            final String subscriptionId = registry.getSubscriptionId();
            // TODO Workaround: Remove this once we have RHOSRTrial working.
            if (subscriptionId != null && RegistryInstanceTypeValueDto.of(registry.getInstanceType()) != RegistryInstanceTypeValueDto.EVAL) {
                try {
                    ams.deleteSubscription(subscriptionId);
                } catch (SubscriptionNotFoundServiceException ex) {
                    log.info("Subscription ID '{}' for tenant ID '{}' does not exist (already deleted?).", subscriptionId, task.getRegistryTenantId());
                }
            } else {
                log.debug("Deleting an eval instance {} without calling AMS.", registry.getId());
            }
            task.setAmsSuccess(true);
            log.debug("Subscription (id='{}') for Registry (id='{}') deleted.", subscriptionId, registry.getId());
        }
        /* Delete the registry from DB
             * FAILURE POINT 4
             * Recovery: We set the status to failed so it can be retried.
             * Reentrancy: This is the last step, so nothing to do.
             */
        storage.deleteRegistry(registry.getId());
    } else {
        log.warn("Registry id='{}' not found. Stopping.", task.getRegistryId());
        ctl.stop();
    }
}
Also used : DeprovisionRegistryTask(org.bf2.srs.fleetmanager.execution.impl.tasks.deprovision.DeprovisionRegistryTask) TenantNotFoundServiceException(org.bf2.srs.fleetmanager.spi.tenants.TenantNotFoundServiceException) SubscriptionNotFoundServiceException(org.bf2.srs.fleetmanager.spi.ams.SubscriptionNotFoundServiceException) RegistryDeploymentData(org.bf2.srs.fleetmanager.storage.sqlPanacheImpl.model.RegistryDeploymentData) TenantManagerConfig(org.bf2.srs.fleetmanager.spi.tenants.model.TenantManagerConfig) Transactional(javax.transaction.Transactional)

Example 2 with TenantManagerConfig

use of org.bf2.srs.fleetmanager.spi.tenants.model.TenantManagerConfig in project srs-fleet-manager by bf2fc6cc711aee1a0c2a.

the class ProvisionRegistryTenantWorker method execute.

@Transactional
@Override
public void execute(Task aTask, WorkerContext ctl) throws RegistryStorageConflictException, TenantManagerServiceException {
    // TODO Split along failure points?
    ProvisionRegistryTenantTask task = (ProvisionRegistryTenantTask) aTask;
    Optional<RegistryData> registryOptional = storage.getRegistryById(task.getRegistryId());
    // NOTE: Failure point 1
    if (registryOptional.isEmpty()) {
        ctl.retry();
    }
    RegistryData registry = registryOptional.get();
    RegistryDeploymentData registryDeployment = registry.getRegistryDeployment();
    // NOTE: Failure point 2
    if (registryDeployment == null) {
        // Either the schedule task didn't run yet, or we are in trouble
        ctl.retry();
    }
    String registryUrl = registryDeployment.getRegistryDeploymentUrl();
    // New approach: configure the deployment URL with a replacement like:  https://TENANT_ID.shrd.sr.openshift.com
    if (registryUrl.contains("TENANT_ID")) {
        registryUrl = registryUrl.replace("TENANT_ID", registry.getId());
    } else {
        // Old approach: configure the deployment URL without a replacement, and just add "/t/TENANT_ID" to the end of it.
        if (!registryUrl.endsWith("/")) {
            registryUrl += "/";
        }
        registryUrl += "t/" + registry.getId();
    }
    registry.setRegistryUrl(registryUrl);
    // Avoid accidentally creating orphan tenants
    if (task.getRegistryTenantId() == null) {
        CreateTenantRequest tenantRequest = CreateTenantRequest.builder().tenantId(registry.getId()).createdBy(registry.getOwner()).organizationId(registry.getOrgId()).resources(plansService.determineQuotaPlan(registry.getOrgId()).getResources()).build();
        TenantManagerConfig tenantManager = Utils.createTenantManagerConfig(registryDeployment);
        // NOTE: Failure point 4
        tmClient.createTenant(tenantManager, tenantRequest);
        task.setRegistryTenantId(registry.getId());
    }
    // Add expiration task if this is an eval instance
    if (isEvalInstance(registry.getInstanceType())) {
        var expiration = Instant.now().plus(Duration.ofSeconds(evalLifetimeSeconds));
        log.debug("Scheduling an expiration task for the eval instance {} to be executed at {}", registry, expiration);
        ctl.delay(() -> tasks.submit(EvalInstanceExpirationRegistryTask.builder().registryId(registry.getId()).schedule(TaskSchedule.builder().firstExecuteAt(expiration).build()).build()));
    }
    // NOTE: Failure point 5
    registry.setStatus(RegistryStatusValueDto.READY.value());
    storage.createOrUpdateRegistry(registry);
// TODO This task is (temporarily) not used. Enable when needed.
// Update status to available in the heartbeat task, which should run ASAP
// ctl.delay(() -> tasks.submit(RegistryHeartbeatTask.builder().registryId(registry.getId()).build()));
}
Also used : CreateTenantRequest(org.bf2.srs.fleetmanager.spi.tenants.model.CreateTenantRequest) ProvisionRegistryTenantTask(org.bf2.srs.fleetmanager.execution.impl.tasks.ProvisionRegistryTenantTask) RegistryDeploymentData(org.bf2.srs.fleetmanager.storage.sqlPanacheImpl.model.RegistryDeploymentData) RegistryData(org.bf2.srs.fleetmanager.storage.sqlPanacheImpl.model.RegistryData) TenantManagerConfig(org.bf2.srs.fleetmanager.spi.tenants.model.TenantManagerConfig) Transactional(javax.transaction.Transactional)

Example 3 with TenantManagerConfig

use of org.bf2.srs.fleetmanager.spi.tenants.model.TenantManagerConfig in project srs-fleet-manager by bf2fc6cc711aee1a0c2a.

the class MigrationService method runMigration.

public void runMigration() throws TenantManagerServiceException {
    if (deleteAll.isPresent() && deleteAll.get()) {
        log.warn("Removing all data first");
        TenantManagerConfig tm = TenantManagerConfig.builder().tenantManagerUrl("http://tenant-manager:8585").registryDeploymentUrl("https://service-registry-stage.apps.app-sre-stage-0.k3s7.p1.openshiftapps.com").build();
        for (Tenant t : tenantManagerClient.getAllTenants(tm)) {
            log.warn("Deleting tenant '{}'", t.getId());
            try {
                tenantManagerClient.deleteTenant(tm, t.getId());
            } catch (TenantNotFoundServiceException ex) {
                log.warn("Could not delete tenant '{}'. Tenant does not exist and may have been already deleted.", t.getId());
            }
        }
        CleanResult cleanResult = flyway.clean();
        log.info("Database clean result: " + "flywayVersion = '{}', " + "database = '{}', " + "schemasCleaned = '{}', " + "schemasDropped = '{}', " + "warnings = '{}'.", cleanResult.flywayVersion, cleanResult.database, cleanResult.schemasCleaned, cleanResult.schemasDropped, cleanResult.warnings);
    }
    MigrateResult migrateResult = flyway.migrate();
    log.info("Database migrate result: " + "flywayVersion = '{}', " + "database = '{}', " + "initialSchemaVersion = '{}', " + "targetSchemaVersion = '{}', " + "migrations = '{}', " + "warnings = '{}'.", migrateResult.flywayVersion, migrateResult.database, migrateResult.initialSchemaVersion, migrateResult.targetSchemaVersion, migrateResult.migrations, migrateResult.warnings);
}
Also used : TenantNotFoundServiceException(org.bf2.srs.fleetmanager.spi.tenants.TenantNotFoundServiceException) Tenant(org.bf2.srs.fleetmanager.spi.tenants.model.Tenant) MigrateResult(org.flywaydb.core.api.output.MigrateResult) TenantManagerConfig(org.bf2.srs.fleetmanager.spi.tenants.model.TenantManagerConfig) CleanResult(org.flywaydb.core.api.output.CleanResult)

Example 4 with TenantManagerConfig

use of org.bf2.srs.fleetmanager.spi.tenants.model.TenantManagerConfig in project srs-fleet-manager by bf2fc6cc711aee1a0c2a.

the class RestClientTenantManagerServiceImpl method createTenant.

@Timed(value = Constants.TENANT_MANAGER_CREATE_TENANT_TIMER, description = Constants.TENANT_MANAGER_DESCRIPTION)
@Audited
// 3 retries, 200ms jitter
@Retry(retryOn = { TenantManagerServiceException.class })
@Override
public Tenant createTenant(TenantManagerConfig tm, CreateTenantRequest tenantRequest) throws TenantManagerServiceException {
    try {
        var client = getClient(tm);
        NewRegistryTenantRequest req = new NewRegistryTenantRequest();
        req.setOrganizationId(tenantRequest.getOrganizationId());
        req.setTenantId(tenantRequest.getTenantId());
        req.setCreatedBy(tenantRequest.getCreatedBy());
        req.setResources(Optional.ofNullable(tenantRequest.getResources()).stream().flatMap(Collection::stream).map(r -> {
            TenantResource tr = new TenantResource();
            tr.setType(ResourceType.fromValue(r.getType()));
            tr.setLimit(r.getLimit());
            return tr;
        }).collect(Collectors.toList()));
        RegistryTenant tenant = client.createTenant(req);
        return convert(tenant);
    } catch (TenantManagerClientException ex) {
        throw ExceptionConvert.convert(ex);
    }
}
Also used : TenantResource(io.apicurio.multitenant.api.datamodel.TenantResource) RegistryTenant(io.apicurio.multitenant.api.datamodel.RegistryTenant) TenantManagerClientException(io.apicurio.multitenant.client.exception.TenantManagerClientException) NewRegistryTenantRequest(io.apicurio.multitenant.api.datamodel.NewRegistryTenantRequest) Audited(org.bf2.srs.fleetmanager.common.operation.auditing.Audited) Timed(io.micrometer.core.annotation.Timed) Retry(org.eclipse.microprofile.faulttolerance.Retry)

Example 5 with TenantManagerConfig

use of org.bf2.srs.fleetmanager.spi.tenants.model.TenantManagerConfig in project srs-fleet-manager by bf2fc6cc711aee1a0c2a.

the class MockTenantManagerService method createTenant.

@Timed(value = Constants.TENANT_MANAGER_CREATE_TENANT_TIMER, description = Constants.TENANT_MANAGER_DESCRIPTION)
@Audited
@Override
public Tenant createTenant(TenantManagerConfig tm, CreateTenantRequest req) {
    requireNonNull(tm);
    requireNonNull(req);
    Tenant tenant = Tenant.builder().id(req.getTenantId()).build();
    init(tm);
    testData.get(tm).put(tenant.getId(), tenant);
    return tenant;
}
Also used : Tenant(org.bf2.srs.fleetmanager.spi.tenants.model.Tenant) Audited(org.bf2.srs.fleetmanager.common.operation.auditing.Audited) Timed(io.micrometer.core.annotation.Timed)

Aggregations

TenantManagerConfig (org.bf2.srs.fleetmanager.spi.tenants.model.TenantManagerConfig)3 Timed (io.micrometer.core.annotation.Timed)2 Transactional (javax.transaction.Transactional)2 Audited (org.bf2.srs.fleetmanager.common.operation.auditing.Audited)2 TenantNotFoundServiceException (org.bf2.srs.fleetmanager.spi.tenants.TenantNotFoundServiceException)2 Tenant (org.bf2.srs.fleetmanager.spi.tenants.model.Tenant)2 RegistryDeploymentData (org.bf2.srs.fleetmanager.storage.sqlPanacheImpl.model.RegistryDeploymentData)2 NewRegistryTenantRequest (io.apicurio.multitenant.api.datamodel.NewRegistryTenantRequest)1 RegistryTenant (io.apicurio.multitenant.api.datamodel.RegistryTenant)1 TenantResource (io.apicurio.multitenant.api.datamodel.TenantResource)1 TenantManagerClientException (io.apicurio.multitenant.client.exception.TenantManagerClientException)1 ProvisionRegistryTenantTask (org.bf2.srs.fleetmanager.execution.impl.tasks.ProvisionRegistryTenantTask)1 DeprovisionRegistryTask (org.bf2.srs.fleetmanager.execution.impl.tasks.deprovision.DeprovisionRegistryTask)1 SubscriptionNotFoundServiceException (org.bf2.srs.fleetmanager.spi.ams.SubscriptionNotFoundServiceException)1 CreateTenantRequest (org.bf2.srs.fleetmanager.spi.tenants.model.CreateTenantRequest)1 RegistryData (org.bf2.srs.fleetmanager.storage.sqlPanacheImpl.model.RegistryData)1 Retry (org.eclipse.microprofile.faulttolerance.Retry)1 CleanResult (org.flywaydb.core.api.output.CleanResult)1 MigrateResult (org.flywaydb.core.api.output.MigrateResult)1