Search in sources :

Example 1 with AccountInfo

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

the class AccountManagementServiceImpl method createResource.

@Timed(value = Constants.AMS_CREATE_TIMER, description = Constants.AMS_TIMER_DESCRIPTION)
@Audited(extractResult = KEY_AMS_SUBSCRIPTION_ID)
// but AMS still performs the reservation.
@Override
public String createResource(AccountInfo accountInfo, ResourceType resourceType) throws TermsRequiredException, ResourceLimitReachedException, AccountManagementServiceException {
    try {
        boolean termsAccepted = false;
        String siteCode = amsProperties.termsSiteCode;
        List<String> eventCodes = amsProperties.termsEventCode;
        for (String eventCode : eventCodes) {
            final TermsReview termsReview = new TermsReview();
            termsReview.setAccountUsername(accountInfo.getAccountUsername());
            termsReview.setSiteCode(siteCode);
            termsReview.setEventCode(eventCode);
            // Check if the user has accepted the Terms & Conditions
            final ResponseTermsReview responseTermsReview = restClient.termsReview(termsReview);
            boolean accepted = !responseTermsReview.getTermsRequired();
            // Terms are accepted if *any* of the T&C checks come back as "accepted"
            termsAccepted = termsAccepted || accepted;
        }
        if (!termsAccepted) {
            throw new TermsRequiredException(accountInfo.getAccountUsername());
        }
        // TODO Workaround: Remove this once we have RHOSRTrial working.
        if (resourceType == ResourceType.REGISTRY_INSTANCE_EVAL) {
            log.debug("Creating an eval instance for '{}' in org '{}' without calling AMS.", accountInfo.getAccountUsername(), accountInfo.getOrganizationId());
            return null;
        }
        // Set the productId and resourceName based on if it's an Eval or Standard instance
        String productId = amsProperties.standardProductId;
        String resourceName = amsProperties.standardResourceName;
        if (resourceType == ResourceType.REGISTRY_INSTANCE_EVAL) {
            productId = amsProperties.evalProductId;
            resourceName = amsProperties.evalResourceName;
        }
        // Build a quota resource ID to pass to AMS
        final var quotaResource = ReservedResource.builder().resourceType(amsProperties.resourceType).byoc(false).resourceName(resourceName).billingModel("marketplace").availabilityZone("single").count(1).build();
        // Create the cluster authorization REST operation input
        final ClusterAuthorization clusterAuthorization = ClusterAuthorization.builder().accountUsername(accountInfo.getAccountUsername()).productId(productId).managed(true).byoc(false).cloudProviderId("aws").reserve(true).availabilityZone("single").clusterId(UUID.randomUUID().toString()).resources(Collections.singletonList(quotaResource)).build();
        // Consume quota from AMS via the AMS REST API
        final ClusterAuthorizationResponse clusterAuthorizationResponse = restClient.clusterAuthorization(clusterAuthorization);
        if (clusterAuthorizationResponse.getAllowed()) {
            return clusterAuthorizationResponse.getSubscription().getId();
        } else {
            // User not allowed to create resource
            throw new ResourceLimitReachedException();
        }
    } catch (AccountManagementSystemClientException ex) {
        ExceptionConvert.convert(ex);
        // Never returns
        return null;
    }
}
Also used : ResponseTermsReview(org.bf2.srs.fleetmanager.spi.ams.impl.model.response.ResponseTermsReview) TermsReview(org.bf2.srs.fleetmanager.spi.ams.impl.model.request.TermsReview) ClusterAuthorization(org.bf2.srs.fleetmanager.spi.ams.impl.model.request.ClusterAuthorization) ClusterAuthorizationResponse(org.bf2.srs.fleetmanager.spi.ams.impl.model.response.ClusterAuthorizationResponse) TermsRequiredException(org.bf2.srs.fleetmanager.spi.ams.TermsRequiredException) AccountManagementSystemClientException(org.bf2.srs.fleetmanager.spi.ams.impl.exception.AccountManagementSystemClientException) ResourceLimitReachedException(org.bf2.srs.fleetmanager.spi.ams.ResourceLimitReachedException) ResponseTermsReview(org.bf2.srs.fleetmanager.spi.ams.impl.model.response.ResponseTermsReview) Audited(org.bf2.srs.fleetmanager.common.operation.auditing.Audited) Timed(io.micrometer.core.annotation.Timed)

Example 2 with AccountInfo

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

the class AccountManagementServiceImpl method determineAllowedResourceType.

@Timed(value = Constants.AMS_DETERMINE_ALLOWED_INSTANCE_TIMER, description = Constants.AMS_TIMER_DESCRIPTION)
@Audited
@Timeout(FaultToleranceConstants.TIMEOUT_MS)
@RetryUnwrap
// 3 retries, 200ms jitter
@Retry(retryOn = { RetryWrapperException.class })
@RetryWrap
@Override
public ResourceType determineAllowedResourceType(AccountInfo accountInfo) throws AccountManagementServiceException {
    try {
        Organization organization = restClient.getOrganizationByExternalId(accountInfo.getOrganizationId());
        String orgId = organization.getId();
        // Check QuotaCostList for a RHOSR entry with "allowed" quota > 0.  If found, then
        // return "Standard" as the resource type to create.
        QuotaCostList quotaCostList = restClient.getQuotaCostList(orgId, true);
        if (quotaCostList.getSize() > 0) {
            for (QuotaCost quotaCost : quotaCostList.getItems()) {
                // We only care about QuotaCost with "allowed" > 0 and with at least one related resource.
                if (quotaCost.getAllowed() != null && quotaCost.getAllowed() > 0 && quotaCost.getRelated_resources() != null && !quotaCost.getRelated_resources().isEmpty() && isRhosrStandardQuota(quotaCost)) {
                    return ResourceType.REGISTRY_INSTANCE_STANDARD;
                }
            }
        }
        // Default to only allow eval.
        return ResourceType.REGISTRY_INSTANCE_EVAL;
    } catch (AccountManagementSystemClientException ex) {
        ExceptionConvert.convert(ex);
        // Never returns
        return null;
    }
}
Also used : Organization(org.bf2.srs.fleetmanager.spi.ams.impl.model.response.Organization) QuotaCostList(org.bf2.srs.fleetmanager.spi.ams.impl.model.response.QuotaCostList) QuotaCost(org.bf2.srs.fleetmanager.spi.ams.impl.model.response.QuotaCost) AccountManagementSystemClientException(org.bf2.srs.fleetmanager.spi.ams.impl.exception.AccountManagementSystemClientException) Audited(org.bf2.srs.fleetmanager.common.operation.auditing.Audited) Timed(io.micrometer.core.annotation.Timed) Timeout(org.eclipse.microprofile.faulttolerance.Timeout) Retry(org.eclipse.microprofile.faulttolerance.Retry) RetryUnwrap(org.bf2.srs.fleetmanager.common.operation.faulttolerance.RetryUnwrap) RetryWrap(org.bf2.srs.fleetmanager.common.operation.faulttolerance.RetryWrap)

Example 3 with AccountInfo

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

the class AuthService method extractAccountInfo.

public AccountInfo extractAccountInfo() {
    AccountInfo accountInfo = new AccountInfo(defaultOrg, OWNER_PLACEHOLDER, false, OWNER_ID_PLACEHOLDER);
    if (SecurityUtil.isResolvable(securityIdentity)) {
        if (isTokenResolvable()) {
            log.trace("Extracting account information from the authentication token");
            final String username = jwt.get().getName();
            final String organizationId = (String) jwt.get().claim(organizationIdClaimName).orElse(defaultOrg);
            final Long accountId = Long.parseLong((String) jwt.get().claim(accountIdClaim).orElse(defaultAccountId));
            boolean isOrgAdmin = false;
            final Optional<Object> isOrgAdminClaimValue = jwt.get().claim(isAdminClaim);
            if (isOrgAdminClaimValue.isPresent()) {
                isOrgAdmin = Boolean.valueOf(isOrgAdminClaimValue.get().toString());
            }
            return new AccountInfo(organizationId, username, isOrgAdmin, accountId);
        }
    }
    return accountInfo;
}
Also used : AccountInfo(org.bf2.srs.fleetmanager.spi.common.model.AccountInfo)

Example 4 with AccountInfo

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

the class CheckDeletePermissionsInterceptor 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 (userCanDeleteInstance(accountInfo, registry)) {
            return context.proceed();
        }
    } else {
        return context.proceed();
    }
    log.info("Attempt to delete 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 5 with AccountInfo

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

the class QuotaPlanIT method testQuotaPlan.

@Test
void testQuotaPlan() throws Exception {
    var alice = new AccountInfo("alice", "alice", false, 1L);
    var registry1 = new RegistryCreate();
    registry1.setName("registry-basic");
    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);
    });
    var bob = new AccountInfo("bob", "bob", false, 2L);
    var registry2 = new RegistryCreate();
    registry2.setName("registry-premium");
    var registry2Result = FleetManagerApi.createRegistry(registry2, bob);
    assertNotEquals(RegistryStatusValue.failed, registry2Result.getStatus());
    Awaitility.await("registry available").atMost(30, TimeUnit.SECONDS).pollInterval(5, TimeUnit.SECONDS).until(() -> {
        var reg = FleetManagerApi.getRegistry(registry2Result.getId(), bob);
        return reg.getStatus().equals(RegistryStatusValue.ready);
    });
    TenantManagerClient tenantManager = Utils.createTenantManagerClient();
    // basic
    var tenant = tenantManager.getTenant(registry1Result.getId());
    var resources = tenant.getResources();
    Long l = null;
    for (var r : resources) {
        if (r.getType() == ResourceType.MAX_TOTAL_SCHEMAS_COUNT) {
            l = r.getLimit();
        }
    }
    assertNotNull(l);
    assertEquals(10, l);
    // premium
    tenant = tenantManager.getTenant(registry2Result.getId());
    resources = tenant.getResources();
    l = null;
    for (var r : resources) {
        if (r.getType() == ResourceType.MAX_TOTAL_SCHEMAS_COUNT) {
            l = r.getLimit();
        }
    }
    assertNotNull(l);
    assertEquals(100, l);
    // Update the limit value and recheck after forced reconciliation
    for (var r : resources) {
        if (r.getType() == ResourceType.MAX_TOTAL_SCHEMAS_COUNT) {
            r.setLimit(-1L);
        }
    }
    var ur = new UpdateRegistryTenantRequest();
    ur.setResources(resources);
    tenantManager.updateTenant(registry2Result.getId(), ur);
    // Check updated
    tenant = tenantManager.getTenant(registry2Result.getId());
    resources = tenant.getResources();
    l = null;
    for (var r : resources) {
        if (r.getType() == ResourceType.MAX_TOTAL_SCHEMAS_COUNT) {
            l = r.getLimit();
        }
    }
    assertNotNull(l);
    assertEquals(-1, l);
    // Restart fleet manager(s) so the quota plan is reconciled
    TestInfraManager.getInstance().restartFleetManager();
    tenant = tenantManager.getTenant(registry2Result.getId());
    resources = tenant.getResources();
    l = null;
    for (var r : resources) {
        if (r.getType() == ResourceType.MAX_TOTAL_SCHEMAS_COUNT) {
            l = r.getLimit();
        }
    }
    assertNotNull(l);
    assertEquals(100, l);
    // Delete
    FleetManagerApi.deleteRegistry(registry1Result.getId(), alice);
    FleetManagerApi.deleteRegistry(registry2Result.getId(), bob);
}
Also used : TenantManagerClient(io.apicurio.multitenant.client.TenantManagerClient) 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)

Aggregations

AccountInfo (org.bf2.srs.fleetmanager.spi.common.model.AccountInfo)9 RegistryData (org.bf2.srs.fleetmanager.storage.sqlPanacheImpl.model.RegistryData)4 TenantManagerClient (io.apicurio.multitenant.client.TenantManagerClient)3 Audited (org.bf2.srs.fleetmanager.common.operation.auditing.Audited)3 RegistryCreate (org.bf2.srs.fleetmanager.rest.publicapi.beans.RegistryCreate)3 Test (org.junit.jupiter.api.Test)3 UpdateRegistryTenantRequest (io.apicurio.multitenant.api.datamodel.UpdateRegistryTenantRequest)2 Timed (io.micrometer.core.annotation.Timed)2 AroundInvoke (javax.interceptor.AroundInvoke)2 ForbiddenException (javax.ws.rs.ForbiddenException)2 Registry (org.bf2.srs.fleetmanager.rest.publicapi.beans.Registry)2 AccountManagementSystemClientException (org.bf2.srs.fleetmanager.spi.ams.impl.exception.AccountManagementSystemClientException)2 TenantResource (io.apicurio.multitenant.api.datamodel.TenantResource)1 ArrayList (java.util.ArrayList)1 ActivateRequestContext (javax.enterprise.context.control.ActivateRequestContext)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 HttpServletResponse (javax.servlet.http.HttpServletResponse)1 ValidationException (javax.validation.ValidationException)1 Pair (org.apache.commons.lang3.tuple.Pair)1 RetryUnwrap (org.bf2.srs.fleetmanager.common.operation.faulttolerance.RetryUnwrap)1