Search in sources :

Example 21 with Registry

use of org.bf2.srs.fleetmanager.rest.publicapi.beans.Registry in project srs-fleet-manager by bf2fc6cc711aee1a0c2a.

the class CheckReadPermissionsInterceptor method intercept.

@AroundInvoke
public Object intercept(InvocationContext context) throws Exception {
    if (isResolvable(securityIdentity)) {
        final AccountInfo accountInfo = authService.extractAccountInfo();
        final Optional<RegistryData> registry = storage.getRegistryById(context.getParameters()[0].toString());
        if (userCanReadInstance(accountInfo, registry)) {
            return context.proceed();
        }
    } else {
        return context.proceed();
    }
    // TODO Refactor for readability
    log.info("Attempt to read registry instance without the proper permissions");
    throw new ForbiddenException();
}
Also used : ForbiddenException(javax.ws.rs.ForbiddenException) RegistryData(org.bf2.srs.fleetmanager.storage.sqlPanacheImpl.model.RegistryData) AccountInfo(org.bf2.srs.fleetmanager.spi.common.model.AccountInfo) AroundInvoke(javax.interceptor.AroundInvoke)

Example 22 with Registry

use of org.bf2.srs.fleetmanager.rest.publicapi.beans.Registry in project srs-fleet-manager by bf2fc6cc711aee1a0c2a.

the class FileQuotaPlansService method init.

@Override
public void init() throws IOException {
    log.debug("Using FileQuotaPlansService implementation of QuotaPlansService");
    if (plansConfigFile.isEmpty()) {
        throw new IllegalArgumentException("Error in static quota plans config: Property 'registry.quota.plans.config.file' is required.");
    }
    log.info("Loading registry quota plans config file from {}", plansConfigFile.get().getAbsolutePath());
    YAMLMapper mapper = SerDesObjectMapperProducer.getYAMLMapper();
    QuotaPlansConfigList quotaPlansConfigList = mapper.readValue(plansConfigFile.get(), QuotaPlansConfigList.class);
    List<QuotaPlan> staticQuotaPlans = quotaPlansConfigList.getPlans();
    Set<String> names = new HashSet<>();
    List<String> duplicatedNames = staticQuotaPlans.stream().map(d -> {
        Set<ConstraintViolation<QuotaPlan>> errors = validator.validate(d);
        if (!errors.isEmpty()) {
            throw new ConstraintViolationException(errors);
        }
        return d;
    }).filter(d -> !names.add(d.getName())).map(d -> d.getName()).collect(Collectors.toList());
    if (!duplicatedNames.isEmpty()) {
        throw new IllegalArgumentException("Error in static quota plans config, duplicated plan name: " + duplicatedNames.toString());
    }
    if (!names.contains(defaultQuotaPlan)) {
        throw new IllegalArgumentException("Error in static quota plans config, default plan does not exist in plans config, default plan name: " + defaultQuotaPlan);
    }
    for (QuotaPlan p : staticQuotaPlans) {
        tmClient.validateConfig(p.getResources());
        plans.put(p.getName(), p);
    }
    List<OrganizationAssignment> staticOrganizationAssignments = quotaPlansConfigList.getOrganizations();
    if (staticOrganizationAssignments == null)
        staticOrganizationAssignments = Collections.emptyList();
    for (OrganizationAssignment assignment : staticOrganizationAssignments) {
        if (!plans.containsKey(assignment.getPlan())) {
            throw new IllegalStateException("Could not find quota plan named '" + assignment.getPlan() + "' intended for organization ID '" + assignment.getOrgId() + "'");
        }
        organizationAssignments.put(assignment.getOrgId(), assignment);
    }
    if (quotaPlansConfigList.getReconcile() != null && quotaPlansConfigList.getReconcile()) {
        reconcile();
    }
}
Also used : TenantManagerService(org.bf2.srs.fleetmanager.spi.tenants.TenantManagerService) UpdateTenantRequest(org.bf2.srs.fleetmanager.spi.tenants.model.UpdateTenantRequest) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) HashSet(java.util.HashSet) Inject(javax.inject.Inject) TenantLimit(org.bf2.srs.fleetmanager.spi.tenants.model.TenantLimit) YAMLMapper(com.fasterxml.jackson.dataformat.yaml.YAMLMapper) ResourceStorage(org.bf2.srs.fleetmanager.storage.ResourceStorage) Map(java.util.Map) Objects.requireNonNull(java.util.Objects.requireNonNull) QuotaPlan(org.bf2.srs.fleetmanager.service.model.QuotaPlan) SerDesObjectMapperProducer(org.bf2.srs.fleetmanager.common.SerDesObjectMapperProducer) NoSuchElementException(java.util.NoSuchElementException) ConstraintViolation(javax.validation.ConstraintViolation) TenantManagerServiceException(org.bf2.srs.fleetmanager.spi.tenants.TenantManagerServiceException) QuotaPlansService(org.bf2.srs.fleetmanager.service.QuotaPlansService) QuotaPlansConfigList(org.bf2.srs.fleetmanager.service.model.QuotaPlansConfigList) Logger(org.slf4j.Logger) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) Validator(javax.validation.Validator) IOException(java.io.IOException) RegistryData(org.bf2.srs.fleetmanager.storage.sqlPanacheImpl.model.RegistryData) Collectors(java.util.stream.Collectors) File(java.io.File) OrganizationAssignment(org.bf2.srs.fleetmanager.service.model.OrganizationAssignment) List(java.util.List) ConstraintViolationException(javax.validation.ConstraintViolationException) IfBuildProfile(io.quarkus.arc.profile.IfBuildProfile) Optional(java.util.Optional) Utils(org.bf2.srs.fleetmanager.execution.impl.workers.Utils) TenantNotFoundServiceException(org.bf2.srs.fleetmanager.spi.tenants.TenantNotFoundServiceException) ApplicationScoped(javax.enterprise.context.ApplicationScoped) ConfigProperty(org.eclipse.microprofile.config.inject.ConfigProperty) Collections(java.util.Collections) HashSet(java.util.HashSet) Set(java.util.Set) YAMLMapper(com.fasterxml.jackson.dataformat.yaml.YAMLMapper) QuotaPlan(org.bf2.srs.fleetmanager.service.model.QuotaPlan) OrganizationAssignment(org.bf2.srs.fleetmanager.service.model.OrganizationAssignment) ConstraintViolationException(javax.validation.ConstraintViolationException) QuotaPlansConfigList(org.bf2.srs.fleetmanager.service.model.QuotaPlansConfigList) HashSet(java.util.HashSet)

Example 23 with Registry

use of org.bf2.srs.fleetmanager.rest.publicapi.beans.Registry 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 24 with Registry

use of org.bf2.srs.fleetmanager.rest.publicapi.beans.Registry in project srs-fleet-manager by bf2fc6cc711aee1a0c2a.

the class RegistryDeprovisioningIT method testDeprovisionRegistryBasic.

@Test
void testDeprovisionRegistryBasic() {
    FleetManagerApi.verifyApiIsSecured();
    var alice = new AccountInfo("testDeprovisionRegistry", "alice", false, 10L);
    var registry1 = new RegistryCreate();
    registry1.setName("registry1");
    var createdRegistry1 = FleetManagerApi.createRegistry(registry1, alice);
    assertNotEquals(RegistryStatusValue.failed, createdRegistry1.getStatus());
    Awaitility.await("registry1 available").atMost(30, SECONDS).pollInterval(5, SECONDS).until(() -> {
        var reg = FleetManagerApi.getRegistry(createdRegistry1.getId(), alice);
        return reg.getStatus().equals(RegistryStatusValue.ready);
    });
    Registry registry = FleetManagerApi.getRegistry(createdRegistry1.getId(), alice);
    TenantManagerClient tenantManager = Utils.createTenantManagerClient();
    var internalTenant = tenantManager.getTenant(registry.getId());
    assertEquals(TenantStatusValue.READY, internalTenant.getStatus());
    FleetManagerApi.deleteRegistry(createdRegistry1.getId(), alice);
    // We don't have to wait for the status to be RegistryStatusValueRest.deleting, since that happens almost immediately now.
    Awaitility.await("registry1 deleting initiated").atMost(5, SECONDS).pollInterval(1, SECONDS).until(() -> {
        var tenant1 = tenantManager.getTenant(registry.getId());
        return TenantStatusValue.TO_BE_DELETED.equals(tenant1.getStatus());
    });
    var req = new UpdateRegistryTenantRequest();
    req.setStatus(TenantStatusValue.DELETED);
    tenantManager.updateTenant(registry.getId(), req);
    Awaitility.await("registry1 deleted").atMost(5, SECONDS).pollInterval(1, SECONDS).until(() -> {
        try {
            FleetManagerApi.verifyRegistryNotExists(createdRegistry1.getId(), alice);
            return true;
        } catch (AssertionError ex) {
            return false;
        }
    });
}
Also used : TenantManagerClient(io.apicurio.multitenant.client.TenantManagerClient) Registry(org.bf2.srs.fleetmanager.rest.publicapi.beans.Registry) RegistryCreate(org.bf2.srs.fleetmanager.rest.publicapi.beans.RegistryCreate) AccountInfo(org.bf2.srs.fleetmanager.spi.common.model.AccountInfo) UpdateRegistryTenantRequest(io.apicurio.multitenant.api.datamodel.UpdateRegistryTenantRequest) Test(org.junit.jupiter.api.Test)

Example 25 with Registry

use of org.bf2.srs.fleetmanager.rest.publicapi.beans.Registry in project srs-fleet-manager by bf2fc6cc711aee1a0c2a.

the class RegistryProvisioningIT method testProvisionRegistry.

@Test
void testProvisionRegistry() {
    FleetManagerApi.verifyApiIsSecured();
    var alice = new AccountInfo("testProvisionRegistry", "alice", false, 10L);
    // verify static deployments config file feature
    var deployment = new RegistryDeploymentCreateRest();
    deployment.setName("test-deployment");
    deployment.setTenantManagerUrl(infra.getTenantManagerUri());
    deployment.setRegistryDeploymentUrl("http://registry-test");
    FleetManagerApi.verifyCreateDeploymentNotAllowed(deployment, alice);
    var registry1 = new RegistryCreate();
    registry1.setName("test-registry-1");
    var registry1Result = FleetManagerApi.createRegistry(registry1, alice);
    assertNotEquals(RegistryStatusValue.failed, registry1Result.getStatus());
    Awaitility.await("registry available").atMost(30, TimeUnit.SECONDS).pollInterval(5, TimeUnit.SECONDS).until(() -> {
        var reg = FleetManagerApi.getRegistry(registry1Result.getId(), alice);
        return reg.getStatus().equals(RegistryStatusValue.ready);
    });
    Registry registry = FleetManagerApi.getRegistry(registry1Result.getId(), alice);
    TenantManagerClient tenantManager = Utils.createTenantManagerClient();
    var internalTenant = tenantManager.getTenant(registry.getId());
    var resources = internalTenant.getResources();
    TenantResource maxTotalSchemas = null;
    for (var r : resources) {
        if (r.getType() == ResourceType.MAX_TOTAL_SCHEMAS_COUNT) {
            maxTotalSchemas = r;
        }
    }
    assertNotNull(maxTotalSchemas);
    assertEquals(10, maxTotalSchemas.getLimit());
    // TODO e2e test check limits are applied
    // Delete
    FleetManagerApi.deleteRegistry(registry1Result.getId(), alice);
}
Also used : TenantManagerClient(io.apicurio.multitenant.client.TenantManagerClient) RegistryDeploymentCreateRest(org.bf2.srs.fleetmanager.rest.privateapi.beans.RegistryDeploymentCreateRest) TenantResource(io.apicurio.multitenant.api.datamodel.TenantResource) Registry(org.bf2.srs.fleetmanager.rest.publicapi.beans.Registry) RegistryCreate(org.bf2.srs.fleetmanager.rest.publicapi.beans.RegistryCreate) AccountInfo(org.bf2.srs.fleetmanager.spi.common.model.AccountInfo) Test(org.junit.jupiter.api.Test)

Aggregations

RegistryData (org.bf2.srs.fleetmanager.storage.sqlPanacheImpl.model.RegistryData)13 Transactional (javax.transaction.Transactional)8 Test (org.junit.jupiter.api.Test)7 AccountInfo (org.bf2.srs.fleetmanager.spi.common.model.AccountInfo)6 TenantNotFoundServiceException (org.bf2.srs.fleetmanager.spi.tenants.TenantNotFoundServiceException)5 RegistryDeploymentData (org.bf2.srs.fleetmanager.storage.sqlPanacheImpl.model.RegistryDeploymentData)5 Secret (io.fabric8.kubernetes.api.model.Secret)4 MeterRegistry (io.micrometer.core.instrument.MeterRegistry)4 ManagedConnector (org.bf2.cos.fleetshard.api.ManagedConnector)4 TenantManagerClient (io.apicurio.multitenant.client.TenantManagerClient)3 IOException (java.io.IOException)3 HashMap (java.util.HashMap)3 List (java.util.List)3 Optional (java.util.Optional)3 ApplicationScoped (javax.enterprise.context.ApplicationScoped)3 Inject (javax.inject.Inject)3 ConnectorDeployment (org.bf2.cos.fleet.manager.model.ConnectorDeployment)3 FleetShardSyncConfig (org.bf2.cos.fleetshard.sync.FleetShardSyncConfig)3 FleetManagerClient (org.bf2.cos.fleetshard.sync.client.FleetManagerClient)3 FleetShardClient (org.bf2.cos.fleetshard.sync.client.FleetShardClient)3