Search in sources :

Example 1 with Audited

use of org.bf2.srs.fleetmanager.common.operation.auditing.Audited 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 Audited

use of org.bf2.srs.fleetmanager.common.operation.auditing.Audited 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 Audited

use of org.bf2.srs.fleetmanager.common.operation.auditing.Audited 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 4 with Audited

use of org.bf2.srs.fleetmanager.common.operation.auditing.Audited 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)

Example 5 with Audited

use of org.bf2.srs.fleetmanager.common.operation.auditing.Audited in project srs-fleet-manager by bf2fc6cc711aee1a0c2a.

the class AuditingInterceptor method intercept.

@AroundInvoke
public Object intercept(InvocationContext context) throws Exception {
    Audited annotation = context.getMethod().getAnnotation(Audited.class);
    if (annotation.extractParameters().length % 2 != 0)
        throw new IllegalStateException("Field @Audited.extractParameters on method '" + context.getMethod().getName() + "' must contain an even number of elements.");
    var event = new AuditingEvent();
    if (securityIdentity != null && !securityIdentity.isAnonymous()) {
        event.addData(KEY_PRINCIPAL_ID, securityIdentity.getPrincipal().getName());
    }
    // Event ID
    var eventId = annotation.eventId();
    if (eventId.isBlank()) {
        eventId = EVENT_ID_METHOD_CALL_PREFIX + context.getMethod().getName();
    }
    event.setEventId(eventId);
    event.addData(KEY_CLASS, context.getTarget().getClass().getCanonicalName());
    // Event Description
    var eventDescription = annotation.eventDescription();
    if (!eventDescription.isBlank()) {
        event.setEventDescription(eventDescription);
    }
    // Parameter extraction via annotation
    var annotationParams = annotation.extractParameters();
    if (annotationParams.length > 0) {
        for (int i = 0; i <= annotationParams.length - 2; i += 2) {
            var key = annotationParams[i + 1];
            var value = context.getParameters()[Integer.parseInt(annotationParams[i])];
            event.addData(key, value);
        }
    }
    // Parameter extraction via extractors
    for (Object param : context.getParameters()) {
        if (param != null) {
            var extractor = PARAMETER_EXTRACTORS.get(param.getClass());
            if (extractor != null) {
                extractor.accept(param, event);
            }
        }
    }
    try {
        var result = context.proceed();
        event.setSuccessful(true);
        if (result != null) {
            // Return value extraction via annotation
            if (!annotation.extractResult().isBlank()) {
                var key = annotation.extractResult();
                event.addData(key, result);
            }
            // Return value extraction via extractors
            var extractor = PARAMETER_EXTRACTORS.get(result.getClass());
            if (extractor != null) {
                extractor.accept(result, event);
            }
        }
        return result;
    } catch (Exception ex) {
        event.setSuccessful(false);
        var message = ex.getClass().getCanonicalName() + (ex.getMessage() != null ? ": " + ex.getMessage() : "");
        event.addData(KEY_ERROR_MESSAGE, shorten(message, 120));
        throw ex;
    } finally {
        auditing.recordEvent(event);
    }
}
Also used : Audited(org.bf2.srs.fleetmanager.common.operation.auditing.Audited) AuditingEvent(org.bf2.srs.fleetmanager.operation.auditing.AuditingEvent) AroundInvoke(javax.interceptor.AroundInvoke)

Aggregations

Audited (org.bf2.srs.fleetmanager.common.operation.auditing.Audited)7 Timed (io.micrometer.core.annotation.Timed)4 AccountManagementSystemClientException (org.bf2.srs.fleetmanager.spi.ams.impl.exception.AccountManagementSystemClientException)2 Retry (org.eclipse.microprofile.faulttolerance.Retry)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 AroundInvoke (javax.interceptor.AroundInvoke)1 CheckDeletePermissions (org.bf2.srs.fleetmanager.auth.interceptor.CheckDeletePermissions)1 RetryUnwrap (org.bf2.srs.fleetmanager.common.operation.faulttolerance.RetryUnwrap)1 RetryWrap (org.bf2.srs.fleetmanager.common.operation.faulttolerance.RetryWrap)1 AuditingEvent (org.bf2.srs.fleetmanager.operation.auditing.AuditingEvent)1 RegistryInstanceTypeValueDto (org.bf2.srs.fleetmanager.rest.service.model.RegistryInstanceTypeValueDto)1 ResourceLimitReachedException (org.bf2.srs.fleetmanager.spi.ams.ResourceLimitReachedException)1 TermsRequiredException (org.bf2.srs.fleetmanager.spi.ams.TermsRequiredException)1 ClusterAuthorization (org.bf2.srs.fleetmanager.spi.ams.impl.model.request.ClusterAuthorization)1 TermsReview (org.bf2.srs.fleetmanager.spi.ams.impl.model.request.TermsReview)1 ClusterAuthorizationResponse (org.bf2.srs.fleetmanager.spi.ams.impl.model.response.ClusterAuthorizationResponse)1 Organization (org.bf2.srs.fleetmanager.spi.ams.impl.model.response.Organization)1