Search in sources :

Example 1 with EventBuilder

use of org.candlepin.audit.EventBuilder in project candlepin by candlepin.

the class CandlepinPoolManager method updateFloatingPools.

/**
 * Update pools which have no subscription attached, if applicable.
 *
 * @param floatingPools
 * @return
 */
@Transactional
void updateFloatingPools(List<Pool> floatingPools, boolean lazy, Map<String, Product> changedProducts) {
    /*
         * Rules need to determine which pools have changed, but the Java must
         * send out the events. Create an event for each pool that could change,
         * even if we won't use them all.
         */
    Map<String, EventBuilder> poolEvents = new HashMap<>();
    for (Pool existing : floatingPools) {
        EventBuilder eventBuilder = eventFactory.getEventBuilder(Target.POOL, Type.MODIFIED).setEventData(existing);
        poolEvents.put(existing.getId(), eventBuilder);
    }
    // Hand off to rules to determine which pools need updating
    List<PoolUpdate> updatedPools = poolRules.updatePools(floatingPools, changedProducts);
    regenerateCertificatesByEntIds(processPoolUpdates(poolEvents, updatedPools), lazy);
}
Also used : EventBuilder(org.candlepin.audit.EventBuilder) HashMap(java.util.HashMap) Pool(org.candlepin.model.Pool) PoolUpdate(org.candlepin.policy.js.pool.PoolUpdate) Transactional(com.google.inject.persist.Transactional)

Example 2 with EventBuilder

use of org.candlepin.audit.EventBuilder in project candlepin by candlepin.

the class ConsumerResource method performConsumerUpdates.

@Transactional
public boolean performConsumerUpdates(ConsumerDTO updated, Consumer toUpdate, GuestMigration guestMigration, boolean isIdCert) {
    log.debug("Updating consumer: {}", toUpdate.getUuid());
    // We need a representation of the consumer before making any modifications.
    // If nothing changes we won't send.  The new entity needs to be correct though,
    // so we should get a Jsonstring now, and finish it off if we're going to send
    EventBuilder eventBuilder = eventFactory.getEventBuilder(Target.CONSUMER, Type.MODIFIED).setEventData(toUpdate);
    // version changed on non-checked in consumer, or list of capabilities
    // changed on checked in consumer
    boolean changesMade = updateCapabilities(toUpdate, updated);
    changesMade = checkForFactsUpdate(toUpdate, updated) || changesMade;
    changesMade = checkForInstalledProductsUpdate(toUpdate, updated) || changesMade;
    changesMade = checkForHypervisorIdUpdate(toUpdate, updated) || changesMade;
    changesMade = guestMigration.isMigrationPending() || changesMade;
    if (updated.getContentTags() != null && !updated.getContentTags().equals(toUpdate.getContentTags())) {
        log.info("   Updating content tags.");
        toUpdate.setContentTags(updated.getContentTags());
        changesMade = true;
    }
    // Allow optional setting of the autoheal attribute:
    if (updated.getAutoheal() != null && !updated.getAutoheal().equals(toUpdate.isAutoheal())) {
        log.info("   Updating consumer autoheal setting.");
        toUpdate.setAutoheal(updated.getAutoheal());
        changesMade = true;
    }
    if (updated.getReleaseVersion() != null && !updated.getReleaseVersion().equals(toUpdate.getReleaseVer() == null ? null : toUpdate.getReleaseVer().getReleaseVer())) {
        log.info("   Updating consumer releaseVer setting.");
        toUpdate.setReleaseVer(new Release(updated.getReleaseVersion()));
        changesMade = true;
    }
    // Allow optional setting of the service level attribute:
    String level = updated.getServiceLevel();
    if (level != null && !level.equals(toUpdate.getServiceLevel())) {
        log.info("   Updating consumer service level setting.");
        consumerBindUtil.validateServiceLevel(toUpdate.getOwnerId(), level);
        toUpdate.setServiceLevel(level);
        changesMade = true;
    }
    String environmentId = updated.getEnvironment() == null ? null : updated.getEnvironment().getId();
    if (environmentId != null && (toUpdate.getEnvironmentId() == null || !toUpdate.getEnvironmentId().equals(environmentId))) {
        Environment e = environmentCurator.find(environmentId);
        if (e == null) {
            throw new NotFoundException(i18n.tr("Environment with ID \"{0}\" could not be found.", environmentId));
        }
        log.info("Updating environment to: {}", environmentId);
        toUpdate.setEnvironment(e);
        // lazily regenerate certs, so the client can still work
        poolManager.regenerateCertificatesOf(toUpdate, true);
        changesMade = true;
    }
    // it should remain the same
    if (updated.getName() != null && !toUpdate.getName().equals(updated.getName())) {
        checkConsumerName(updated);
        log.info("Updating consumer name: {} -> {}", toUpdate.getName(), updated.getName());
        toUpdate.setName(updated.getName());
        changesMade = true;
        // get the new name into the id cert if we are using the cert
        if (isIdCert) {
            IdentityCertificate ic = generateIdCert(toUpdate, true);
            toUpdate.setIdCert(ic);
        }
    }
    ConsumerType ctype = this.consumerTypeCurator.getConsumerType(toUpdate);
    if (updated.getContentAccessMode() != null && !updated.getContentAccessMode().equals(toUpdate.getContentAccessMode()) && ctype.isManifest()) {
        Owner toUpdateOwner = ownerCurator.findOwnerById(toUpdate.getOwnerId());
        if (!toUpdateOwner.isAllowedContentAccessMode(updated.getContentAccessMode())) {
            throw new BadRequestException(i18n.tr("The consumer cannot use the supplied content access mode."));
        }
        toUpdate.setContentAccessMode(updated.getContentAccessMode());
        changesMade = true;
    }
    if (!StringUtils.isEmpty(updated.getContentAccessMode()) && !ctype.isManifest()) {
        throw new BadRequestException(i18n.tr("The consumer cannot be assigned a content access mode."));
    }
    if (updated.getLastCheckin() != null) {
        log.info("Updating to specific last checkin time: {}", updated.getLastCheckin());
        toUpdate.setLastCheckin(updated.getLastCheckin());
        changesMade = true;
    }
    if (changesMade) {
        log.debug("Consumer {} updated.", toUpdate.getUuid());
        // Set the updated date here b/c @PreUpdate will not get fired
        // since only the facts table will receive the update.
        toUpdate.setUpdated(new Date());
        // this should update compliance on toUpdate, but not call the curator
        complianceRules.getStatus(toUpdate, null, false, false);
        Event event = eventBuilder.setEventData(toUpdate).buildEvent();
        sink.queueEvent(event);
    }
    return changesMade;
}
Also used : Owner(org.candlepin.model.Owner) EventBuilder(org.candlepin.audit.EventBuilder) Environment(org.candlepin.model.Environment) NotFoundException(org.candlepin.common.exceptions.NotFoundException) BadRequestException(org.candlepin.common.exceptions.BadRequestException) Event(org.candlepin.audit.Event) ConsumerType(org.candlepin.model.ConsumerType) Release(org.candlepin.model.Release) Date(java.util.Date) IdentityCertificate(org.candlepin.model.IdentityCertificate) Transactional(com.google.inject.persist.Transactional)

Example 3 with EventBuilder

use of org.candlepin.audit.EventBuilder in project candlepin by candlepin.

the class CandlepinPoolManager method processPoolUpdates.

protected Set<String> processPoolUpdates(Map<String, EventBuilder> poolEvents, List<PoolUpdate> updatedPools) {
    boolean flush = false;
    Set<String> existingPoolIds = new HashSet<>();
    Set<Pool> poolsToDelete = new HashSet<>();
    Set<Pool> poolsToRegenEnts = new HashSet<>();
    Set<String> entitlementsToRegen = new HashSet<>();
    // Get our list of pool IDs so we can check which of them still exist in the DB...
    for (PoolUpdate update : updatedPools) {
        if (update != null && update.getPool() != null && update.getPool().getId() != null) {
            existingPoolIds.add(update.getPool().getId());
        }
    }
    existingPoolIds = this.poolCurator.getExistingPoolIdsByIds(existingPoolIds);
    // Process pool updates...
    for (PoolUpdate updatedPool : updatedPools) {
        Pool existingPool = updatedPool.getPool();
        log.info("Pool changed: {}", updatedPool.toString());
        if (existingPool == null || !existingPoolIds.contains(existingPool.getId())) {
            log.info("Pool has already been deleted from the database.");
            continue;
        }
        // Delete pools the rules signal needed to be cleaned up:
        if (existingPool.isMarkedForDelete()) {
            log.warn("Deleting pool as requested by rules: {}", existingPool.getId());
            poolsToDelete.add(existingPool);
            continue;
        }
        // save changes for the pool. We'll flush these changes later.
        this.poolCurator.merge(existingPool);
        flush = true;
        // the quantity has not yet been expressed on the pool itself
        if (updatedPool.getQuantityChanged()) {
            RevocationOp revPlan = new RevocationOp(this.poolCurator, this.consumerTypeCurator, Collections.singletonList(existingPool));
            revPlan.execute(this);
        }
        // dates changed. regenerate all entitlement certificates
        if (updatedPool.getDatesChanged() || updatedPool.getProductsChanged() || updatedPool.getBrandingChanged()) {
            poolsToRegenEnts.add(existingPool);
        }
        // Build event for this update...
        EventBuilder builder = poolEvents.get(existingPool.getId());
        if (builder != null) {
            Event event = builder.setEventData(existingPool).buildEvent();
            sink.queueEvent(event);
        } else {
            log.warn("Pool updated without an event builder: {}", existingPool);
        }
    }
    // Flush our merged changes
    if (flush) {
        this.poolCurator.flush();
    }
    // Fetch entitlement IDs for updated pools...
    if (poolsToRegenEnts.size() > 0) {
        entitlementsToRegen.addAll(this.poolCurator.retrieveOrderedEntitlementIdsOf(poolsToRegenEnts));
    }
    // Delete pools marked for deletion
    if (poolsToDelete.size() > 0) {
        this.deletePools(poolsToDelete);
    }
    // Return entitlement IDs in need regeneration
    return entitlementsToRegen;
}
Also used : EventBuilder(org.candlepin.audit.EventBuilder) Event(org.candlepin.audit.Event) Pool(org.candlepin.model.Pool) PoolUpdate(org.candlepin.policy.js.pool.PoolUpdate) HashSet(java.util.HashSet)

Example 4 with EventBuilder

use of org.candlepin.audit.EventBuilder in project candlepin by candlepin.

the class CandlepinPoolManager method updatePoolsForMasterPool.

/**
 * Update pool for master pool.
 *
 * @param existingPools the existing pools
 * @param pool the master pool
 * @param originalQuantity the pool's original quantity before multiplier was applied
 * @param updateStackDerived whether or not to attempt to update stack
 *        derived pools
 */
Set<String> updatePoolsForMasterPool(List<Pool> existingPools, Pool pool, Long originalQuantity, boolean updateStackDerived, Map<String, Product> changedProducts) {
    /*
         * Rules need to determine which pools have changed, but the Java must
         * send out the events. Create an event for each pool that could change,
         * even if we won't use them all.
         */
    if (CollectionUtils.isEmpty(existingPools)) {
        return new HashSet<>(0);
    }
    log.debug("Updating {} pools for existing master pool: {}", existingPools.size(), pool);
    Map<String, EventBuilder> poolEvents = new HashMap<>();
    for (Pool existing : existingPools) {
        EventBuilder eventBuilder = eventFactory.getEventBuilder(Target.POOL, Type.MODIFIED).setEventData(existing);
        poolEvents.put(existing.getId(), eventBuilder);
    }
    // Hand off to rules to determine which pools need updating:
    List<PoolUpdate> updatedPools = poolRules.updatePools(pool, existingPools, originalQuantity, changedProducts);
    String virtLimit = pool.getProduct().getAttributeValue(Product.Attributes.VIRT_LIMIT);
    boolean createsSubPools = !StringUtils.isBlank(virtLimit) && !"0".equals(virtLimit);
    // Update subpools if necessary
    if (updateStackDerived && !updatedPools.isEmpty() && createsSubPools && pool.isStacked()) {
        // Get all pools for the master pool owner derived from the pool's
        // stack id, because we cannot look it up by subscriptionId
        List<Pool> subPools = getOwnerSubPoolsForStackId(pool.getOwner(), pool.getStackId());
        for (Pool subPool : subPools) {
            PoolUpdate update = updatePoolFromStack(subPool, changedProducts);
            if (update.changed()) {
                updatedPools.add(update);
                EventBuilder eventBuilder = eventFactory.getEventBuilder(Target.POOL, Type.MODIFIED).setEventData(subPool);
                poolEvents.put(subPool.getId(), eventBuilder);
            }
        }
    }
    return processPoolUpdates(poolEvents, updatedPools);
}
Also used : EventBuilder(org.candlepin.audit.EventBuilder) HashMap(java.util.HashMap) Pool(org.candlepin.model.Pool) PoolUpdate(org.candlepin.policy.js.pool.PoolUpdate) HashSet(java.util.HashSet)

Example 5 with EventBuilder

use of org.candlepin.audit.EventBuilder in project candlepin by candlepin.

the class EventCuratorTest method testSecondarySorting.

@Test
public void testSecondarySorting() {
    ConsumerType consumerType = this.consumerTypeCurator.create(new ConsumerType("system"));
    Consumer newConsumer = new Consumer("consumername", "user", owner, consumerType);
    newConsumer = consumerCurator.create(newConsumer);
    setupPrincipal(owner, Access.ALL);
    // Force all events to have exact same timestamp:
    Date forcedDate = new Date();
    EventBuilder builder = eventFactory.getEventBuilder(Event.Target.RULES, Event.Type.DELETED);
    Event rulesDeletedEvent = builder.setEventData(new Rules()).buildEvent();
    rulesDeletedEvent.setTimestamp(forcedDate);
    builder = eventFactory.getEventBuilder(Event.Target.CONSUMER, Event.Type.CREATED);
    Event consumerCreatedEvent = builder.setEventData(newConsumer).buildEvent();
    consumerCreatedEvent.setTimestamp(forcedDate);
    builder = eventFactory.getEventBuilder(Event.Target.CONSUMER, Event.Type.MODIFIED);
    Event consumerModifiedEvent = builder.setEventData(newConsumer).buildEvent();
    consumerModifiedEvent.setTimestamp(forcedDate);
    eventCurator.create(rulesDeletedEvent);
    eventCurator.create(consumerCreatedEvent);
    eventCurator.create(consumerModifiedEvent);
    List<Event> mostRecent = eventCurator.listMostRecent(3).list();
    assertEquals(3, mostRecent.size());
    // We should see this sorted by timestamp (all the same), then entity, then type:
    assertEquals(consumerCreatedEvent.getId(), mostRecent.get(0).getId());
    assertEquals(consumerModifiedEvent.getId(), mostRecent.get(1).getId());
    assertEquals(rulesDeletedEvent.getId(), mostRecent.get(2).getId());
}
Also used : EventBuilder(org.candlepin.audit.EventBuilder) Event(org.candlepin.audit.Event) Date(java.util.Date) Test(org.junit.Test)

Aggregations

EventBuilder (org.candlepin.audit.EventBuilder)8 HashMap (java.util.HashMap)4 HashSet (java.util.HashSet)4 Event (org.candlepin.audit.Event)4 Pool (org.candlepin.model.Pool)4 PoolUpdate (org.candlepin.policy.js.pool.PoolUpdate)4 Transactional (com.google.inject.persist.Transactional)2 Date (java.util.Date)2 IdentityCertificate (org.candlepin.model.IdentityCertificate)2 Test (org.junit.Test)2 ArrayList (java.util.ArrayList)1 LinkedList (java.util.LinkedList)1 BadRequestException (org.candlepin.common.exceptions.BadRequestException)1 NotFoundException (org.candlepin.common.exceptions.NotFoundException)1 ConsumerType (org.candlepin.model.ConsumerType)1 Environment (org.candlepin.model.Environment)1 Owner (org.candlepin.model.Owner)1 Product (org.candlepin.model.Product)1 ProductShare (org.candlepin.model.ProductShare)1 Release (org.candlepin.model.Release)1