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;
}
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];
}
});
}
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());
}
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);
}
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));
}
Aggregations