Search in sources :

Example 1 with PoolQuantity

use of org.candlepin.model.PoolQuantity in project candlepin by candlepin.

the class HandleCertificatesOp method preProcess.

/**
 * create certificates without associating the entitlements and certs with each other.
 * also, dont persist the certs.
 * @param context
 */
@Override
public boolean preProcess(BindContext context) {
    if (!context.getConsumerType().isType(ConsumerTypeEnum.SHARE)) {
        List<String> poolIds = new LinkedList<>();
        Map<String, Product> products = new HashMap<>();
        Map<String, PoolQuantity> poolQuantities = context.getPoolQuantities();
        for (PoolQuantity poolQuantity : poolQuantities.values()) {
            Pool pool = poolQuantity.getPool();
            products.put(pool.getId(), pool.getProduct());
            poolIds.add(pool.getId());
        }
        certs = ecGenerator.generateEntitlementCertificates(context.getConsumer(), products, poolQuantities, context.getEntitlementMap(), false);
        modifyingEnts = this.eCurator.getDependentEntitlementIdsForPools(context.getConsumer(), poolIds);
    }
    return true;
}
Also used : PoolQuantity(org.candlepin.model.PoolQuantity) HashMap(java.util.HashMap) Product(org.candlepin.model.Product) Pool(org.candlepin.model.Pool) LinkedList(java.util.LinkedList)

Example 2 with PoolQuantity

use of org.candlepin.model.PoolQuantity in project candlepin by candlepin.

the class PostBindBonusPoolsOp method execute.

@Override
public boolean execute(BindContext context) {
    Consumer consumer = context.getLockedConsumer();
    Map<String, Entitlement> entitlements = context.getEntitlementMap();
    Map<String, PoolQuantity> poolQuantities = context.getPoolQuantities();
    poolManager.handlePostEntitlement(poolManager, consumer, context.getOwner(), entitlements, poolQuantities);
    // we might have changed the bonus pool quantities, lets revoke ents if needed.
    poolManager.checkBonusPoolQuantities(consumer.getOwnerId(), entitlements);
    return true;
}
Also used : PoolQuantity(org.candlepin.model.PoolQuantity) Consumer(org.candlepin.model.Consumer) Entitlement(org.candlepin.model.Entitlement)

Example 3 with PoolQuantity

use of org.candlepin.model.PoolQuantity in project candlepin by candlepin.

the class CandlepinPoolManager method entitleByProductsImpl.

/**
 * Performs the work of the entitleByProducts method in its own transaction to help unlock
 * pools which can no longer be bound.
 * <p></p>
 * This method should not be called directly, and is only declared protected to allow the
 * @Transactional annotation to function.
 *
 * @param data
 *  The autobind data to use for entitling a consumer
 *
 * @return
 *  a list of entitlements created as for this autobind operation
 */
@Transactional
protected List<Entitlement> entitleByProductsImpl(AutobindData data) throws EntitlementRefusedException {
    Consumer consumer = data.getConsumer();
    String[] productIds = data.getProductIds();
    Collection<String> fromPools = data.getPossiblePools();
    Date entitleDate = data.getOnDate();
    String ownerId = consumer.getOwnerId();
    List<PoolQuantity> bestPools = new ArrayList<>();
    // fromPools will be empty if the dev pool was already created.
    if (consumer != null && consumer.isDev() && !fromPools.isEmpty()) {
        String poolId = fromPools.iterator().next();
        PoolQuantity pq = new PoolQuantity(poolCurator.find(poolId), 1);
        bestPools.add(pq);
    } else {
        bestPools = getBestPools(consumer, productIds, entitleDate, ownerId, null, fromPools);
    }
    if (bestPools == null) {
        return null;
    }
    return entitleByPools(consumer, convertToMap(bestPools));
}
Also used : PoolQuantity(org.candlepin.model.PoolQuantity) Consumer(org.candlepin.model.Consumer) ArrayList(java.util.ArrayList) Date(java.util.Date) Transactional(com.google.inject.persist.Transactional)

Example 4 with PoolQuantity

use of org.candlepin.model.PoolQuantity 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 5 with PoolQuantity

use of org.candlepin.model.PoolQuantity in project candlepin by candlepin.

the class CandlepinPoolManager method entitleByProductsForHost.

/**
 * Request an entitlement by product for a host system in
 * a host-guest relationship.  Allows getBestPoolsForHost
 * to choose products to bind.
 *
 * @param guest consumer requesting to have host entitled
 * @param host host consumer to entitle
 * @param entitleDate specific date to entitle by.
 * @return Entitlement
 * @throws EntitlementRefusedException if entitlement is refused
 */
// 
// NOTE: after calling this method both entitlement pool and consumer
// parameters will most certainly be stale. beware!
@Override
@Transactional
public List<Entitlement> entitleByProductsForHost(Consumer guest, Consumer host, Date entitleDate, Collection<String> possiblePools) throws EntitlementRefusedException {
    host = consumerCurator.lockAndLoad(host);
    List<Entitlement> entitlements = new LinkedList<>();
    if (!host.getOwnerId().equals(guest.getOwnerId())) {
        log.debug("Host {} and guest {} have different owners", host.getUuid(), guest.getUuid());
        return entitlements;
    }
    // Use the current date if one wasn't provided:
    if (entitleDate == null) {
        entitleDate = new Date();
    }
    List<PoolQuantity> bestPools = getBestPoolsForHost(guest, host, entitleDate, host.getOwnerId(), null, possiblePools);
    if (bestPools == null) {
        log.info("No entitlements for host: {}", host.getUuid());
        return null;
    }
    // now make the entitlements
    return entitleByPools(host, convertToMap(bestPools));
}
Also used : PoolQuantity(org.candlepin.model.PoolQuantity) Entitlement(org.candlepin.model.Entitlement) LinkedList(java.util.LinkedList) Date(java.util.Date) Transactional(com.google.inject.persist.Transactional)

Aggregations

PoolQuantity (org.candlepin.model.PoolQuantity)75 Pool (org.candlepin.model.Pool)65 Test (org.junit.Test)52 Entitlement (org.candlepin.model.Entitlement)34 LinkedList (java.util.LinkedList)30 Product (org.candlepin.model.Product)28 HashMap (java.util.HashMap)27 ArrayList (java.util.ArrayList)21 Consumer (org.candlepin.model.Consumer)12 List (java.util.List)11 ConsumerType (org.candlepin.model.ConsumerType)11 Matchers.anyString (org.mockito.Matchers.anyString)11 Date (java.util.Date)8 Set (java.util.Set)8 HashSet (java.util.HashSet)7 EntitlementRefusedException (org.candlepin.policy.EntitlementRefusedException)7 ValidationResult (org.candlepin.policy.ValidationResult)7 Subscription (org.candlepin.model.dto.Subscription)6 Matchers.anyLong (org.mockito.Matchers.anyLong)6 PoolFilterBuilder (org.candlepin.model.PoolFilterBuilder)5