Search in sources :

Example 1 with ComplianceStatus

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

the class CandlepinPoolManager method getBestPoolsForHost.

/**
 * Here we pick uncovered products from the guest where no virt-only
 * subscriptions exist, and have the host bind non-zero virt_limit
 * subscriptions in order to generate pools for the guest to bind later.
 *
 * @param guest whose products we want to provide
 * @param host to bind entitlements to
 * @param entitleDate
 * @param owner
 * @param serviceLevelOverride
 * @return PoolQuantity list to attempt to attach
 * @throws EntitlementRefusedException if unable to bind
 */
@Override
@SuppressWarnings("checkstyle:methodlength")
public List<PoolQuantity> getBestPoolsForHost(Consumer guest, Consumer host, Date entitleDate, String ownerId, String serviceLevelOverride, Collection<String> fromPools) throws EntitlementRefusedException {
    Map<String, ValidationResult> failedResults = new HashMap<>();
    log.debug("Looking up best pools for host: {}", host);
    boolean tempLevel = false;
    if (StringUtils.isEmpty(host.getServiceLevel())) {
        host.setServiceLevel(guest.getServiceLevel());
        tempLevel = true;
    }
    Date activePoolDate = entitleDate;
    if (entitleDate == null) {
        activePoolDate = new Date();
    }
    PoolFilterBuilder poolFilter = new PoolFilterBuilder();
    poolFilter.addIdFilters(fromPools);
    List<Pool> allOwnerPools = this.listAvailableEntitlementPools(host, null, ownerId, null, null, activePoolDate, false, poolFilter, null, false, false, null).getPageData();
    log.debug("Found {} total pools in org.", allOwnerPools.size());
    logPools(allOwnerPools);
    List<Pool> allOwnerPoolsForGuest = this.listAvailableEntitlementPools(guest, null, ownerId, null, null, activePoolDate, false, poolFilter, null, false, false, null).getPageData();
    log.debug("Found {} total pools already available for guest", allOwnerPoolsForGuest.size());
    logPools(allOwnerPoolsForGuest);
    for (Entitlement ent : host.getEntitlements()) {
        // filter out pools that are attached, there is no need to
        // complete partial stacks, as they are already granting
        // virtual pools
        log.debug("Removing pool host is already entitled to: {}", ent.getPool());
        allOwnerPools.remove(ent.getPool());
    }
    List<Pool> filteredPools = new LinkedList<>();
    ComplianceStatus guestCompliance = complianceRules.getStatus(guest, entitleDate, false);
    Set<String> tmpSet = new HashSet<>();
    // we only want to heal red products, not yellow
    tmpSet.addAll(guestCompliance.getNonCompliantProducts());
    log.debug("Guest's non-compliant products: {}", Util.collectionToString(tmpSet));
    /*Do not attempt to create subscriptions for products that
          already have virt_only pools available to the guest */
    Set<String> productsToRemove = getProductsToRemove(allOwnerPoolsForGuest, tmpSet);
    log.debug("Guest already will have virt-only pools to cover: {}", Util.collectionToString(productsToRemove));
    tmpSet.removeAll(productsToRemove);
    String[] productIds = tmpSet.toArray(new String[] {});
    if (log.isDebugEnabled()) {
        log.debug("Attempting host autobind for guest products: {}", Util.collectionToString(tmpSet));
    }
    // Bulk fetch our provided and derived provided product IDs so we're not hitting the DB
    // several times for this lookup.
    Map<String, Set<String>> providedProductIds = this.poolCurator.getProvidedProductIds(allOwnerPools);
    Map<String, Set<String>> derivedProvidedProductIds = this.poolCurator.getDerivedProvidedProductIds(allOwnerPools);
    for (Pool pool : allOwnerPools) {
        boolean providesProduct = false;
        // and we only need to check that it's non-zero
        if (pool.getProduct().hasAttribute(Product.Attributes.VIRT_LIMIT) && !pool.getProduct().getAttributeValue(Product.Attributes.VIRT_LIMIT).equals("0")) {
            Map<String, Set<String>> providedProductMap;
            String baseProductId;
            // Determine which set of provided products we should use...
            if (pool.getDerivedProduct() != null) {
                providedProductMap = derivedProvidedProductIds;
                baseProductId = pool.getDerivedProduct().getId();
            } else {
                providedProductMap = providedProductIds;
                baseProductId = pool.getProduct().getId();
            }
            // Add the base product to the list of derived provided products...
            Set<String> poolProvidedProductIds = providedProductMap.get(pool.getId());
            if (baseProductId != null) {
                if (poolProvidedProductIds != null) {
                    poolProvidedProductIds.add(baseProductId);
                } else {
                    poolProvidedProductIds = Collections.<String>singleton(baseProductId);
                }
            }
            // Check if the pool provides any of the specified products
            if (poolProvidedProductIds != null) {
                for (String productId : productIds) {
                    // provides anything for the guest, otherwise we use the parent.
                    if (poolProvidedProductIds.contains(productId)) {
                        log.debug("Found virt_limit pool providing product {}: {}", productId, pool);
                        providesProduct = true;
                        break;
                    }
                }
            }
        }
        if (providesProduct) {
            ValidationResult result = enforcer.preEntitlement(host, pool, 1, CallerType.BEST_POOLS);
            if (result.hasErrors() || result.hasWarnings()) {
                // Just keep the last one around, if we need it
                failedResults.put(pool.getId(), result);
                if (log.isDebugEnabled()) {
                    log.debug("Pool filtered from candidates due to failed rule(s): {}", pool);
                    log.debug("  warnings: {}", Util.collectionToString(result.getWarnings()));
                    log.debug("  errors: {}", Util.collectionToString(result.getErrors()));
                }
            } else {
                filteredPools.add(pool);
            }
        }
    }
    // Only throw refused exception if we actually hit the rules:
    if (filteredPools.size() == 0 && !failedResults.isEmpty()) {
        throw new EntitlementRefusedException(failedResults);
    }
    ComplianceStatus hostCompliance = complianceRules.getStatus(host, entitleDate, false);
    log.debug("Host pools being sent to rules: {}", filteredPools.size());
    logPools(filteredPools);
    List<PoolQuantity> enforced = autobindRules.selectBestPools(host, productIds, filteredPools, hostCompliance, serviceLevelOverride, poolCurator.retrieveServiceLevelsForOwner(ownerId, true), true);
    if (log.isDebugEnabled()) {
        log.debug("Host selectBestPools returned {} pools: ", enforced.size());
        for (PoolQuantity poolQuantity : enforced) {
            log.debug("  " + poolQuantity.getPool());
        }
    }
    if (tempLevel) {
        host.setServiceLevel("");
        // complianceRules.getStatus may have persisted the host with the temp service level,
        // so we need to be certain we undo that.
        consumerCurator.update(host);
    }
    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) ValidationResult(org.candlepin.policy.ValidationResult) Date(java.util.Date) LinkedList(java.util.LinkedList) PoolFilterBuilder(org.candlepin.model.PoolFilterBuilder) Pool(org.candlepin.model.Pool) Entitlement(org.candlepin.model.Entitlement) HashSet(java.util.HashSet)

Example 2 with ComplianceStatus

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

the class PoolManagerTest method init.

@Before
public void init() throws Exception {
    MockitoAnnotations.initMocks(this);
    i18n = I18nFactory.getI18n(getClass(), Locale.US, I18nFactory.FALLBACK);
    owner = TestUtil.createOwner("key", "displayname");
    product = TestUtil.createProduct();
    pool = TestUtil.createPool(owner, product);
    when(mockOwnerCurator.lookupByKey(eq(owner.getKey()))).thenReturn(owner);
    when(mockConfig.getInt(eq(ConfigProperties.PRODUCT_CACHE_MAX))).thenReturn(100);
    when(eventFactory.getEventBuilder(any(Target.class), any(Type.class))).thenReturn(eventBuilder);
    when(eventBuilder.setEventData(any(Eventful.class))).thenReturn(eventBuilder);
    this.principal = TestUtil.createOwnerPrincipal(owner);
    this.manager = spy(new CandlepinPoolManager(mockPoolCurator, mockEventSink, eventFactory, mockConfig, enforcerMock, poolRulesMock, entitlementCurator, consumerCuratorMock, consumerTypeCuratorMock, certCuratorMock, mockECGenerator, complianceRules, autobindRules, activationKeyRules, mockProductCurator, mockProductManager, mockContentManager, mockOwnerContentCurator, mockOwnerCurator, mockOwnerProductCurator, mockOwnerManager, pinsetterKernel, i18n, mockBindChainFactory));
    setupBindChain();
    Map<String, EntitlementCertificate> entCerts = new HashMap<>();
    entCerts.put(pool.getId(), new EntitlementCertificate());
    when(mockECGenerator.generateEntitlementCertificates(any(Consumer.class), any(Map.class), any(Map.class), any(Map.class), eq(false))).thenReturn(entCerts);
    dummyComplianceStatus = new ComplianceStatus(new Date());
    when(complianceRules.getStatus(any(Consumer.class), any(Date.class))).thenReturn(dummyComplianceStatus);
    when(consumerCuratorMock.lockAndLoad(any(Consumer.class))).thenAnswer(new Answer<Consumer>() {

        @Override
        public Consumer answer(InvocationOnMock invocation) throws Throwable {
            Object[] args = invocation.getArguments();
            return (Consumer) args[0];
        }
    });
}
Also used : EntitlementCertificate(org.candlepin.model.EntitlementCertificate) HashMap(java.util.HashMap) ComplianceStatus(org.candlepin.policy.js.compliance.ComplianceStatus) Matchers.anyString(org.mockito.Matchers.anyString) Eventful(org.candlepin.model.Eventful) Date(java.util.Date) Target(org.candlepin.audit.Event.Target) Type(org.candlepin.audit.Event.Type) CallerType(org.candlepin.policy.js.entitlement.Enforcer.CallerType) ConsumerType(org.candlepin.model.ConsumerType) PoolType(org.candlepin.model.Pool.PoolType) Consumer(org.candlepin.model.Consumer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Map(java.util.Map) Matchers.anyMap(org.mockito.Matchers.anyMap) HashMap(java.util.HashMap) Before(org.junit.Before)

Example 3 with ComplianceStatus

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

the class EventFactoryTest method testComplianceCreatedSetsEventData.

@Test
public void testComplianceCreatedSetsEventData() {
    Consumer consumer = mock(Consumer.class);
    ComplianceStatus status = mock(ComplianceStatus.class);
    when(consumer.getName()).thenReturn("consumer-name");
    when(consumer.getOwnerId()).thenReturn("owner-id");
    when(consumer.getUuid()).thenReturn("48b09f4e-f18c-4765-9c41-9aed6f122739");
    when(status.getStatus()).thenReturn("invalid");
    ComplianceReason reason1 = new ComplianceReason();
    reason1.setKey(ComplianceReason.ReasonKeys.SOCKETS);
    reason1.setMessage("Only supports 2 of 12 sockets.");
    reason1.setAttributes(ImmutableMap.of(ComplianceReason.Attributes.MARKETING_NAME, "Awesome OS"));
    ComplianceReason reason2 = new ComplianceReason();
    reason2.setKey(ComplianceReason.ReasonKeys.ARCHITECTURE);
    reason2.setMessage("Supports architecture ppc64 but the system is x86_64.");
    reason2.setAttributes(ImmutableMap.of(ComplianceReason.Attributes.MARKETING_NAME, "Awesome Middleware"));
    when(status.getReasons()).thenReturn(ImmutableSet.of(reason1, reason2));
    String expectedEventData = "{\"reasons\":[" + "{\"productName\":\"Awesome OS\"," + "\"message\":\"Only supports 2 of 12 sockets.\"}," + "{\"productName\":\"Awesome Middleware\"," + "\"message\":\"Supports architecture ppc64 but the system is x86_64.\"}]," + "\"status\":\"invalid\"}";
    Event event = eventFactory.complianceCreated(consumer, status);
    assertEquals(expectedEventData, event.getEventData());
}
Also used : Consumer(org.candlepin.model.Consumer) ComplianceStatus(org.candlepin.policy.js.compliance.ComplianceStatus) ComplianceReason(org.candlepin.policy.js.compliance.ComplianceReason) Test(org.junit.Test)

Example 4 with ComplianceStatus

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

the class ConsumerResourceUpdateTest method init.

@Before
public void init() throws Exception {
    Configuration config = new CandlepinCommonTestConfig();
    this.i18n = I18nFactory.getI18n(getClass(), Locale.US, I18nFactory.FALLBACK);
    testMigration = new GuestMigration(consumerCurator);
    migrationProvider = Providers.of(testMigration);
    this.translator = new StandardTranslator(this.consumerTypeCurator, this.environmentCurator, this.ownerCurator);
    this.resource = new ConsumerResource(this.consumerCurator, this.consumerTypeCurator, null, this.subscriptionService, this.ownerService, null, this.idCertService, null, this.i18n, this.sink, this.eventFactory, null, null, this.userService, poolManager, null, null, this.activationKeyCurator, this.entitler, this.complianceRules, this.deletedConsumerCurator, this.environmentCurator, null, config, null, null, null, this.consumerBindUtil, null, null, new FactValidator(config, this.i18n), null, consumerEnricher, migrationProvider, this.translator);
    when(complianceRules.getStatus(any(Consumer.class), any(Date.class), any(Boolean.class), any(Boolean.class))).thenReturn(new ComplianceStatus(new Date()));
    when(idCertService.regenerateIdentityCert(any(Consumer.class))).thenReturn(new IdentityCertificate());
    when(consumerEventBuilder.setEventData(any(Consumer.class))).thenReturn(consumerEventBuilder);
    when(eventFactory.getEventBuilder(any(Target.class), any(Type.class))).thenReturn(consumerEventBuilder);
}
Also used : FactValidator(org.candlepin.util.FactValidator) Configuration(org.candlepin.common.config.Configuration) ComplianceStatus(org.candlepin.policy.js.compliance.ComplianceStatus) StandardTranslator(org.candlepin.dto.StandardTranslator) Date(java.util.Date) GuestMigration(org.candlepin.resource.util.GuestMigration) Target(org.candlepin.audit.Event.Target) Type(org.candlepin.audit.Event.Type) ConsumerType(org.candlepin.model.ConsumerType) Consumer(org.candlepin.model.Consumer) CandlepinCommonTestConfig(org.candlepin.config.CandlepinCommonTestConfig) Mockito.anyBoolean(org.mockito.Mockito.anyBoolean) IdentityCertificate(org.candlepin.model.IdentityCertificate) Before(org.junit.Before)

Example 5 with ComplianceStatus

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

the class ComplianceStatusHasherTest method ensureDifferentHashWhenConsumerFactsChange.

@Test
public void ensureDifferentHashWhenConsumerFactsChange() {
    Consumer consumer = createConsumer(owner);
    ComplianceStatus testStatus = createInitialStatus(consumer);
    assertEquals(initialHash, generateHash(testStatus, consumer));
    Map<String, String> initialConsumerFacts = consumer.getFacts();
    String firstFactKey = initialConsumerFacts.keySet().iterator().next();
    // Same facts, new map.
    consumer.setFacts(new HashMap<>(initialConsumerFacts));
    assertEquals(initialHash, generateHash(testStatus, consumer));
    // Facts cleared
    consumer.getFacts().clear();
    assertNotEquals(initialHash, generateHash(testStatus, consumer));
    // Fact added
    consumer.setFacts(new HashMap<>(initialConsumerFacts));
    assertEquals(initialHash, generateHash(testStatus, consumer));
    consumer.setFact("another", "fact");
    assertNotEquals(initialHash, generateHash(testStatus, consumer));
    // Fact removed
    consumer.setFacts(new HashMap<>(initialConsumerFacts));
    assertEquals(initialHash, generateHash(testStatus, consumer));
    consumer.getFacts().remove(firstFactKey);
    assertNotEquals(initialHash, generateHash(testStatus, consumer));
    // Fact changed
    consumer.setFacts(new HashMap<>(initialConsumerFacts));
    assertEquals(initialHash, generateHash(testStatus, consumer));
    consumer.setFact(firstFactKey, "Different Value");
    assertNotEquals(initialHash, generateHash(testStatus, consumer));
}
Also used : Consumer(org.candlepin.model.Consumer) ComplianceStatus(org.candlepin.policy.js.compliance.ComplianceStatus) 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