Search in sources :

Example 11 with Entitlement

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

the class Entitler method sendEvents.

public void sendEvents(List<Entitlement> entitlements) {
    if (entitlements != null) {
        for (Entitlement entitlement : entitlements) {
            Event event = evtFactory.entitlementCreated(entitlement);
            sink.queueEvent(event);
        }
    }
}
Also used : Event(org.candlepin.audit.Event) Entitlement(org.candlepin.model.Entitlement)

Example 12 with Entitlement

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

the class Entitler method bindByProducts.

/**
 * Force option is used to heal entire org
 *
 * @param data AutobindData encapsulating data required for an autobind request
 * @param force heal host even if it has autoheal disabled
 * @return List of Entitlements
 * @throws AutobindDisabledForOwnerException when an autobind attempt is made and the owner
 *         has it disabled.
 */
@Transactional
public List<Entitlement> bindByProducts(AutobindData data, boolean force) throws AutobindDisabledForOwnerException {
    Consumer consumer = data.getConsumer();
    Owner owner = data.getOwner();
    if (!consumer.isDev() && owner.isAutobindDisabled()) {
        log.info("Skipping auto-attach for consumer '{}'. Auto-attach is disabled for owner {}.", consumer, owner.getKey());
        throw new AutobindDisabledForOwnerException(i18n.tr("Auto-attach is disabled for owner \"{0}\".", owner.getKey()));
    }
    // entitlements based on the planned design of the subscriptions
    if (consumer.hasFact("virt.uuid") && !consumer.isDev()) {
        String guestUuid = consumer.getFact("virt.uuid");
        // Remove any expired unmapped guest entitlements
        revokeUnmappedGuestEntitlements(consumer);
        // Scoped to the consumer's organization.  Even in the event of sharing, a guest in one
        // organization should not be able to compel a heal in an another organization
        Consumer host = consumerCurator.getHost(consumer, consumer.getOwnerId());
        if (host != null && (force || host.isAutoheal())) {
            log.info("Attempting to heal host machine with UUID \"{}\" for guest with UUID \"{}\"", host.getUuid(), consumer.getUuid());
            if (!StringUtils.equals(host.getServiceLevel(), consumer.getServiceLevel())) {
                log.warn("Host with UUID \"{}\" has a service level \"{}\" that does not match" + " that of the guest with UUID \"{}\" and service level \"{}\"", host.getUuid(), host.getServiceLevel(), consumer.getUuid(), consumer.getServiceLevel());
            }
            try {
                List<Entitlement> hostEntitlements = poolManager.entitleByProductsForHost(consumer, host, data.getOnDate(), data.getPossiblePools());
                log.debug("Granted host {} entitlements", hostEntitlements.size());
                sendEvents(hostEntitlements);
            } catch (Exception e) {
                // log and continue, this should NEVER block
                log.debug("Healing failed for host UUID {} with message: {}", host.getUuid(), e.getMessage());
            }
            /* Consumer is stale at this point.  Note that we use find() instead of
                 * findByUuid() or getConsumer() since the latter two methods are secured
                 * to a specific host principal and bindByProducts can get called when
                 * a guest is switching hosts */
            consumer = consumerCurator.find(consumer.getId());
            data.setConsumer(consumer);
        }
    }
    if (consumer.isDev()) {
        if (config.getBoolean(ConfigProperties.STANDALONE) || !poolCurator.hasActiveEntitlementPools(consumer.getOwnerId(), null)) {
            throw new ForbiddenException(i18n.tr("Development units may only be used on hosted servers" + " and with orgs that have active subscriptions."));
        }
        // Look up the dev pool for this consumer, and if not found
        // create one. If a dev pool already exists, remove it and
        // create a new one.
        String sku = consumer.getFact("dev_sku");
        Pool devPool = poolCurator.findDevPool(consumer);
        if (devPool != null) {
            poolManager.deletePool(devPool);
        }
        devPool = poolManager.createPool(assembleDevPool(consumer, owner, sku));
        data.setPossiblePools(Arrays.asList(devPool.getId()));
        data.setProductIds(new String[] { sku });
    }
    // Attempt to create entitlements:
    try {
        // the pools are only used to bind the guest
        List<Entitlement> entitlements = poolManager.entitleByProducts(data);
        log.debug("Created entitlements: {}", entitlements);
        return entitlements;
    } catch (EntitlementRefusedException e) {
        // TODO: Could be multiple errors, but we'll just report the first one for now
        String productId = "Unknown Product";
        if (data.getProductIds().length > 0) {
            productId = data.getProductIds()[0];
        }
        throw new ForbiddenException(messageTranslator.productErrorToMessage(productId, e.getResults().values().iterator().next().getErrors().get(0)));
    }
}
Also used : Owner(org.candlepin.model.Owner) ForbiddenException(org.candlepin.common.exceptions.ForbiddenException) Consumer(org.candlepin.model.Consumer) EntitlementRefusedException(org.candlepin.policy.EntitlementRefusedException) Pool(org.candlepin.model.Pool) Entitlement(org.candlepin.model.Entitlement) BadRequestException(org.candlepin.common.exceptions.BadRequestException) ForbiddenException(org.candlepin.common.exceptions.ForbiddenException) EntitlementRefusedException(org.candlepin.policy.EntitlementRefusedException) Transactional(com.google.inject.persist.Transactional)

Example 13 with Entitlement

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

the class EntitlementCertificateGenerator method regenerateCertificatesByEntitlementIds.

/**
 * Regenerates the certificates for the specified entitlements. This method is a utility method
 * which individually regenerates certificates for each entitlement in the provided collection.
 *
 * @param entitlementIds
 *  An iterable collection of entitlement IDs for which to regenerate certificates
 *
 * @param lazy
 *  Whether or not to generate the certificate immediately, or mark it dirty and allow it to be
 *  regenerated on-demand
 */
@Transactional
public void regenerateCertificatesByEntitlementIds(Iterable<String> entitlementIds, boolean lazy) {
    if (lazy) {
        this.entitlementCurator.markEntitlementsDirty(entitlementIds);
    } else {
        for (String entitlementId : entitlementIds) {
            Entitlement entitlement = entitlementCurator.find(entitlementId);
            if (entitlement == null) {
                // If it has been deleted, that's fine; one less to regenerate
                log.info("Unable to load entitlement for regeneration: {}", entitlementId);
                continue;
            }
            this.regenerateCertificatesOf(entitlement, false);
        }
    }
}
Also used : Entitlement(org.candlepin.model.Entitlement) Transactional(com.google.inject.persist.Transactional)

Example 14 with Entitlement

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

the class RevocationOp method execute.

@Transactional
public void execute(PoolManager poolManager) {
    Collection<Pool> overflowing = new ArrayList<>();
    for (Pool pool : pools) {
        if (pool.isOverflowing()) {
            overflowing.add(pool);
        }
    }
    if (overflowing.isEmpty()) {
        return;
    }
    overflowing = poolCurator.lockAndLoad(overflowing);
    for (Pool pool : overflowing) {
        poolNewConsumed.put(pool, pool.getConsumed());
        List<Pool> shared = poolCurator.listSharedPoolsOf(pool);
        if (!shared.isEmpty()) {
            sharedPools.put(pool, shared);
            // first determine shared pool counts where allotted units are not in use
            reduceSharedPools(pool);
        }
        // we then start revoking the existing entitlements
        determineExcessEntitlements(pool);
    }
    // revoke the entitlements amassed above
    poolManager.revokeEntitlements(new ArrayList<>(entitlementsToRevoke));
    // We have to wait until we get here so that share pool entitlements we want revoked are gone
    for (Entitlement entitlement : shareEntitlementsToAdjust.keySet()) {
        try {
            poolManager.adjustEntitlementQuantity(entitlement.getConsumer(), entitlement, shareEntitlementsToAdjust.get(entitlement).intValue());
        } catch (EntitlementRefusedException e) {
            // TODO: Could be multiple errors, but we'll just report the first one for now:
            throw new ForbiddenException(e.getResults().values().iterator().next().getErrors().get(0).toString());
        }
    }
}
Also used : ForbiddenException(org.candlepin.common.exceptions.ForbiddenException) EntitlementRefusedException(org.candlepin.policy.EntitlementRefusedException) ArrayList(java.util.ArrayList) Pool(org.candlepin.model.Pool) Entitlement(org.candlepin.model.Entitlement) Transactional(com.google.inject.persist.Transactional)

Example 15 with Entitlement

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

the class RevocationOp method determineExcessEntitlements.

/**
 * In the second part, the list of entitlements is compiled from the main pool plus the shared pools
 * It is sorted in the order of LIFO. Entitlements are put in the revoke list until the count is
 * acceptable for the main pool. Any entitlements that came from a shared pool are also reflected in
 * the adjustment for the source entitlement for that shared pool.
 *
 * @param pool
 */
private void determineExcessEntitlements(Pool pool) {
    List<Pool> pools = new ArrayList<>();
    pools.add(pool);
    if (sharedPools.get(pool) != null) {
        pools.addAll(sharedPools.get(pool));
    }
    List<Entitlement> entitlements = this.poolCurator.retrieveOrderedEntitlementsOf(pools);
    long newConsumed = poolNewConsumed.get(pool);
    long existing = pool.getQuantity();
    for (Entitlement ent : entitlements) {
        if (newConsumed > existing) {
            ConsumerType ctype = this.consumerTypeCurator.getConsumerType(ent.getConsumer());
            if (!ctype.isType(ConsumerTypeEnum.SHARE)) {
                if (ent.getPool().isCreatedByShare()) {
                    Entitlement source = ent.getPool().getSourceEntitlement();
                    // the source entitlement may have already been adjusted in the shared pool reduction
                    if (shareEntitlementsToAdjust.get(source) == null) {
                        addEntitlementToAdjust(source, source.getQuantity());
                    }
                    addEntitlementToAdjust(source, shareEntitlementsToAdjust.get(source) - ent.getQuantity());
                    if (shareEntitlementsToAdjust.get(source) == 0) {
                        shareEntitlementsToAdjust.remove(source);
                        addEntitlmentToRevoke(source);
                    }
                }
                addEntitlementToRevoke(ent);
                newConsumed -= ent.getQuantity();
            }
        }
    }
    poolNewConsumed.put(pool, newConsumed);
}
Also used : ArrayList(java.util.ArrayList) Pool(org.candlepin.model.Pool) Entitlement(org.candlepin.model.Entitlement) ConsumerType(org.candlepin.model.ConsumerType)

Aggregations

Entitlement (org.candlepin.model.Entitlement)301 Test (org.junit.Test)201 Consumer (org.candlepin.model.Consumer)164 Pool (org.candlepin.model.Pool)125 LinkedList (java.util.LinkedList)84 Product (org.candlepin.model.Product)68 Date (java.util.Date)62 ArrayList (java.util.ArrayList)61 HashSet (java.util.HashSet)59 HashMap (java.util.HashMap)55 Owner (org.candlepin.model.Owner)44 PoolQuantity (org.candlepin.model.PoolQuantity)35 ConsumerType (org.candlepin.model.ConsumerType)34 List (java.util.List)30 ConsumerInstalledProduct (org.candlepin.model.ConsumerInstalledProduct)24 Matchers.anyString (org.mockito.Matchers.anyString)17 Set (java.util.Set)16 Subscription (org.candlepin.model.dto.Subscription)16 ApiOperation (io.swagger.annotations.ApiOperation)15 ApiResponses (io.swagger.annotations.ApiResponses)15