Search in sources :

Example 16 with ComplianceStatus

use of org.candlepin.policy.js.compliance.ComplianceStatus in project candlepin by candlepin.

the class ConsumerResourceTest method testGetComplianceStatusList.

@Test
public void testGetComplianceStatusList() {
    Owner owner = this.createOwner();
    Consumer c = this.createConsumer(owner);
    Consumer c2 = this.createConsumer(owner);
    List<Consumer> consumers = new ArrayList<>();
    consumers.add(c);
    consumers.add(c2);
    CandlepinQuery cqmock = mock(CandlepinQuery.class);
    when(cqmock.list()).thenReturn(consumers);
    when(cqmock.iterator()).thenReturn(consumers.iterator());
    List<String> uuids = new ArrayList<>();
    uuids.add(c.getUuid());
    uuids.add(c2.getUuid());
    when(mockConsumerCurator.findByUuids(eq(uuids))).thenReturn(cqmock);
    ComplianceStatus status = new ComplianceStatus();
    when(mockComplianceRules.getStatus(any(Consumer.class), any(Date.class))).thenReturn(status);
    ConsumerResource cr = new ConsumerResource(mockConsumerCurator, mockConsumerTypeCurator, null, null, null, null, null, null, i18n, null, null, null, null, null, null, null, null, null, null, mockComplianceRules, null, null, null, this.config, null, null, null, consumerBindUtil, null, null, this.factValidator, null, consumerEnricher, migrationProvider, translator);
    Map<String, ComplianceStatus> results = cr.getComplianceStatusList(uuids);
    assertEquals(2, results.size());
    assertTrue(results.containsKey(c.getUuid()));
    assertTrue(results.containsKey(c2.getUuid()));
}
Also used : Owner(org.candlepin.model.Owner) Consumer(org.candlepin.model.Consumer) ComplianceStatus(org.candlepin.policy.js.compliance.ComplianceStatus) ArrayList(java.util.ArrayList) CandlepinQuery(org.candlepin.model.CandlepinQuery) Matchers.anyString(org.mockito.Matchers.anyString) Date(java.util.Date) Test(org.junit.Test)

Example 17 with ComplianceStatus

use of org.candlepin.policy.js.compliance.ComplianceStatus in project candlepin by candlepin.

the class AutobindRulesTest method createEnforcer.

@Before
public void createEnforcer() throws Exception {
    MockitoAnnotations.initMocks(this);
    when(config.getInt(eq(ConfigProperties.PRODUCT_CACHE_MAX))).thenReturn(100);
    InputStream is = this.getClass().getResourceAsStream(RulesCurator.DEFAULT_RULES_FILE);
    Rules rules = new Rules(Util.readFile(is));
    when(rulesCurator.getRules()).thenReturn(rules);
    when(rulesCurator.getUpdated()).thenReturn(TestDateUtil.date(2010, 1, 1));
    when(cacheProvider.get()).thenReturn(cache);
    JsRunner jsRules = new JsRunnerProvider(rulesCurator, cacheProvider).get();
    translator = new StandardTranslator(consumerTypeCurator, environmentCurator, mockOwnerCurator);
    autobindRules = new AutobindRules(jsRules, mockProductCurator, consumerTypeCurator, mockOwnerCurator, new RulesObjectMapper(new ProductCachedSerializationModule(mockProductCurator)), translator);
    owner = new Owner();
    owner.setId(TestUtil.randomString());
    when(mockOwnerCurator.findOwnerById(eq(owner.getId()))).thenReturn(owner);
    ConsumerType ctype = new ConsumerType(ConsumerTypeEnum.SYSTEM);
    ctype.setId("test-ctype");
    consumer = new Consumer("test consumer", "test user", owner, ctype);
    when(consumerTypeCurator.find(eq(ctype.getId()))).thenReturn(ctype);
    when(consumerTypeCurator.lookupByLabel(eq(ctype.getLabel()))).thenReturn(ctype);
    when(consumerTypeCurator.getConsumerType(eq(consumer))).thenReturn(ctype);
    compliance = new ComplianceStatus();
    activeGuestAttrs = new HashMap<>();
    activeGuestAttrs.put("virtWhoType", "libvirt");
    activeGuestAttrs.put("active", "1");
}
Also used : Owner(org.candlepin.model.Owner) AutobindRules(org.candlepin.policy.js.autobind.AutobindRules) ComplianceStatus(org.candlepin.policy.js.compliance.ComplianceStatus) InputStream(java.io.InputStream) RulesObjectMapper(org.candlepin.policy.js.RulesObjectMapper) JsRunner(org.candlepin.policy.js.JsRunner) Rules(org.candlepin.model.Rules) AutobindRules(org.candlepin.policy.js.autobind.AutobindRules) StandardTranslator(org.candlepin.dto.StandardTranslator) ProductCachedSerializationModule(org.candlepin.jackson.ProductCachedSerializationModule) Consumer(org.candlepin.model.Consumer) JsRunnerProvider(org.candlepin.policy.js.JsRunnerProvider) ConsumerType(org.candlepin.model.ConsumerType) Before(org.junit.Before)

Example 18 with ComplianceStatus

use of org.candlepin.policy.js.compliance.ComplianceStatus in project candlepin by candlepin.

the class ConsumerResource method getComplianceStatus.

@ApiOperation(notes = "Retireves the Compliance Status of a Consumer.", value = "getComplianceStatus")
@ApiResponses({ @ApiResponse(code = 404, message = "") })
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("{consumer_uuid}/compliance")
@Transactional
public ComplianceStatus getComplianceStatus(@PathParam("consumer_uuid") @Verify(Consumer.class) String uuid, @ApiParam("Date to get compliance information for, default is now.") @QueryParam("on_date") String onDate) {
    Consumer consumer = consumerCurator.verifyAndLookupConsumer(uuid);
    ConsumerType ctype = this.consumerTypeCurator.getConsumerType(consumer);
    Date date = ResourceDateParser.parseDateString(onDate);
    if (ctype.isType(ConsumerTypeEnum.SHARE)) {
        logShareConsumerRequestWarning("fetch compliance", consumer);
        return new ComplianceStatus(date);
    }
    return this.complianceRules.getStatus(consumer, date);
}
Also used : DeletedConsumer(org.candlepin.model.DeletedConsumer) Consumer(org.candlepin.model.Consumer) ComplianceStatus(org.candlepin.policy.js.compliance.ComplianceStatus) ConsumerType(org.candlepin.model.ConsumerType) Date(java.util.Date) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses) Transactional(com.google.inject.persist.Transactional)

Example 19 with ComplianceStatus

use of org.candlepin.policy.js.compliance.ComplianceStatus in project candlepin by candlepin.

the class CandlepinPoolManager method getBestPools.

@Override
public List<PoolQuantity> getBestPools(Consumer consumer, String[] productIds, Date entitleDate, String ownerId, String serviceLevelOverride, Collection<String> fromPools) throws EntitlementRefusedException {
    Map<String, ValidationResult> failedResults = new HashMap<>();
    Date activePoolDate = entitleDate;
    if (entitleDate == null) {
        activePoolDate = new Date();
    }
    PoolFilterBuilder poolFilter = new PoolFilterBuilder();
    poolFilter.addIdFilters(fromPools);
    List<Pool> allOwnerPools = this.listAvailableEntitlementPools(consumer, null, ownerId, null, null, activePoolDate, false, poolFilter, null, false, false, null).getPageData();
    List<Pool> filteredPools = new LinkedList<>();
    // We have to check compliance status here so we can replace an empty
    // array of product IDs with the array the consumer actually needs. (i.e. during
    // a healing request)
    ComplianceStatus compliance = complianceRules.getStatus(consumer, entitleDate, false);
    if (productIds == null || productIds.length == 0) {
        log.debug("No products specified for bind, checking compliance to see what is needed.");
        Set<String> tmpSet = new HashSet<>();
        tmpSet.addAll(compliance.getNonCompliantProducts());
        tmpSet.addAll(compliance.getPartiallyCompliantProducts().keySet());
        productIds = tmpSet.toArray(new String[] {});
    }
    if (log.isDebugEnabled()) {
        log.debug("Attempting for products on date: {}", entitleDate);
        for (String productId : productIds) {
            log.debug("  {}", productId);
        }
    }
    // Bulk fetch our provided product IDs so we're not hitting the DB several times
    // for this lookup.
    Map<String, Set<String>> providedProductIds = this.poolCurator.getProvidedProductIds(allOwnerPools);
    for (Pool pool : allOwnerPools) {
        boolean providesProduct = false;
        // We want to complete partial stacks if possible, even if they do not provide any products
        Product poolProduct = pool.getProduct();
        String stackingId = poolProduct.getAttributeValue(Product.Attributes.STACKING_ID);
        if (stackingId != null && compliance.getPartialStacks().containsKey(stackingId)) {
            providesProduct = true;
        } else {
            Set<String> poolProvidedProductIds = providedProductIds.get(pool.getId());
            String poolProductId = pool.getProduct() != null ? pool.getProduct().getId() : null;
            if (poolProductId != null) {
                // Add the base product to our list of "provided" products
                if (poolProvidedProductIds != null) {
                    poolProvidedProductIds.add(poolProductId);
                } else {
                    poolProvidedProductIds = Collections.singleton(poolProductId);
                }
            }
            if (poolProvidedProductIds != null) {
                for (String productId : productIds) {
                    if (poolProvidedProductIds.contains(productId)) {
                        providesProduct = true;
                        break;
                    }
                }
            }
        }
        if (providesProduct) {
            ValidationResult result = enforcer.preEntitlement(consumer, pool, 1, CallerType.BEST_POOLS);
            if (result.hasErrors() || result.hasWarnings()) {
                failedResults.put(pool.getId(), result);
                log.debug("Pool filtered from candidates due to rules failure: {}", pool.getId());
            } else {
                filteredPools.add(pool);
            }
        }
    }
    // Only throw refused exception if we actually hit the rules:
    if (filteredPools.size() == 0 && !failedResults.isEmpty()) {
        throw new EntitlementRefusedException(failedResults);
    }
    List<PoolQuantity> enforced = autobindRules.selectBestPools(consumer, productIds, filteredPools, compliance, serviceLevelOverride, poolCurator.retrieveServiceLevelsForOwner(ownerId, true), false);
    // Sort the resulting pools to avoid deadlocks
    Collections.sort(enforced);
    return enforced;
}
Also used : PoolQuantity(org.candlepin.model.PoolQuantity) Set(java.util.Set) HashSet(java.util.HashSet) HashMap(java.util.HashMap) ComplianceStatus(org.candlepin.policy.js.compliance.ComplianceStatus) EntitlementRefusedException(org.candlepin.policy.EntitlementRefusedException) Product(org.candlepin.model.Product) ValidationResult(org.candlepin.policy.ValidationResult) Date(java.util.Date) LinkedList(java.util.LinkedList) PoolFilterBuilder(org.candlepin.model.PoolFilterBuilder) Pool(org.candlepin.model.Pool) HashSet(java.util.HashSet)

Example 20 with ComplianceStatus

use of org.candlepin.policy.js.compliance.ComplianceStatus in project candlepin by candlepin.

the class ConsumerResourceTest method testIdCertDoesNotRegenerate.

@Test
public void testIdCertDoesNotRegenerate() throws Exception {
    SubscriptionServiceAdapter ssa = Mockito.mock(SubscriptionServiceAdapter.class);
    ComplianceRules rules = Mockito.mock(ComplianceRules.class);
    Consumer consumer = createConsumer(createOwner());
    ComplianceStatus status = new ComplianceStatus();
    when(rules.getStatus(any(Consumer.class), any(Date.class), anyBoolean())).thenReturn(status);
    consumer.setIdCert(createIdCert(TestUtil.createDate(2025, 6, 9)));
    BigInteger origserial = consumer.getIdCert().getSerial().getSerial();
    ConsumerResource cr = new ConsumerResource(mockConsumerCurator, mockConsumerTypeCurator, null, ssa, this.mockOwnerServiceAdapter, null, null, null, null, null, null, null, null, null, null, null, mockOwnerCurator, null, null, rules, null, null, null, this.config, null, null, null, consumerBindUtil, null, null, this.factValidator, null, consumerEnricher, migrationProvider, translator);
    ConsumerDTO c = cr.getConsumer(consumer.getUuid());
    assertEquals(origserial, c.getIdCert().getSerial().getSerial());
}
Also used : Consumer(org.candlepin.model.Consumer) ComplianceStatus(org.candlepin.policy.js.compliance.ComplianceStatus) ConsumerDTO(org.candlepin.dto.api.v1.ConsumerDTO) BigInteger(java.math.BigInteger) ComplianceRules(org.candlepin.policy.js.compliance.ComplianceRules) SubscriptionServiceAdapter(org.candlepin.service.SubscriptionServiceAdapter) Date(java.util.Date) Test(org.junit.Test)

Aggregations

ComplianceStatus (org.candlepin.policy.js.compliance.ComplianceStatus)32 Consumer (org.candlepin.model.Consumer)26 Test (org.junit.Test)21 Date (java.util.Date)13 Entitlement (org.candlepin.model.Entitlement)8 HashSet (java.util.HashSet)7 ConsumerType (org.candlepin.model.ConsumerType)7 HashMap (java.util.HashMap)6 Owner (org.candlepin.model.Owner)5 Product (org.candlepin.model.Product)5 Before (org.junit.Before)5 StandardTranslator (org.candlepin.dto.StandardTranslator)4 ConsumerInstalledProduct (org.candlepin.model.ConsumerInstalledProduct)4 Pool (org.candlepin.model.Pool)4 ComplianceReason (org.candlepin.policy.js.compliance.ComplianceReason)4 InputStream (java.io.InputStream)3 LinkedList (java.util.LinkedList)3 Set (java.util.Set)3 Target (org.candlepin.audit.Event.Target)3 Type (org.candlepin.audit.Event.Type)3