Search in sources :

Example 1 with Pool

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

the class Exporter method exportProducts.

private void exportProducts(File baseDir, Consumer consumer) throws IOException {
    File productDir = new File(baseDir.getCanonicalPath(), "products");
    productDir.mkdir();
    Map<String, Product> products = new HashMap<>();
    for (Entitlement entitlement : consumer.getEntitlements()) {
        Pool pool = entitlement.getPool();
        for (Product providedProduct : productCurator.getPoolProvidedProductsCached(pool)) {
            products.put(providedProduct.getId(), providedProduct);
        }
        // Don't forget the 'main' product!
        Product product = pool.getProduct();
        products.put(product.getId(), product);
        // Also need to check for sub products
        Product derivedProduct = pool.getDerivedProduct();
        if (derivedProduct != null) {
            products.put(derivedProduct.getId(), derivedProduct);
        }
        for (Product derivedProvidedProduct : productCurator.getPoolDerivedProvidedProductsCached(pool)) {
            products.put(derivedProvidedProduct.getId(), derivedProvidedProduct);
        }
    }
    for (Product product : products.values()) {
        // Clear the owner and UUID so they can be re-generated/assigned on import
        // product.setUuid(null);
        // product.setOwner(null);
        String path = productDir.getCanonicalPath();
        String productId = product.getId();
        File file = new File(path, productId + ".json");
        FileWriter writer = null;
        try {
            writer = new FileWriter(file);
            productExporter.export(mapper, writer, product);
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
        // Real products have a numeric id.
        if (StringUtils.isNumeric(product.getId())) {
            Owner owner = ownerCurator.findOwnerById(consumer.getOwnerId());
            ProductCertificate cert = productAdapter.getProductCertificate(owner, product.getId());
            // XXX: need to decide if the cert should always be in the export, or never.
            if (cert != null) {
                file = new File(productDir.getCanonicalPath(), product.getId() + ".pem");
                writer = new FileWriter(file);
                productCertExporter.export(writer, cert);
                writer.close();
            }
        }
    }
}
Also used : Owner(org.candlepin.model.Owner) HashMap(java.util.HashMap) FileWriter(java.io.FileWriter) ProductCertificate(org.candlepin.model.ProductCertificate) Product(org.candlepin.model.Product) Pool(org.candlepin.model.Pool) Entitlement(org.candlepin.model.Entitlement) File(java.io.File)

Example 2 with Pool

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

the class DefaultContentAccessCertServiceAdapter method createContentAccessDataPayload.

private byte[] createContentAccessDataPayload(Owner owner, Environment environment) throws IOException {
    // fake a product dto as a container for the org content
    Set<Product> containerSet = new HashSet<>();
    CandlepinQuery<Content> ownerContent = ownerContentCurator.getContentByOwner(owner);
    Set<String> entitledProductIds = new HashSet<>();
    List<org.candlepin.model.dto.Product> productModels = new ArrayList<>();
    Map<String, EnvironmentContent> promotedContent = getPromotedContent(environment);
    String contentPrefix = getContentPrefix(owner, environment);
    Product container = new Product();
    Entitlement emptyEnt = new Entitlement();
    Pool emptyPool = new Pool();
    Product skuProduct = new Product();
    Consumer emptyConsumer = new Consumer();
    containerSet.add(container);
    container.setId("content_access");
    container.setName(" Content Access");
    for (Content c : ownerContent) {
        container.addContent(c, false);
    }
    emptyConsumer.setEnvironment(environment);
    emptyEnt.setPool(emptyPool);
    emptyEnt.setConsumer(emptyConsumer);
    emptyPool.setProduct(skuProduct);
    emptyPool.setStartDate(new Date());
    emptyPool.setEndDate(new Date());
    skuProduct.setName("Content Access");
    skuProduct.setId("content_access");
    entitledProductIds.add("content-access");
    org.candlepin.model.dto.Product productModel = v3extensionUtil.mapProduct(container, skuProduct, contentPrefix, promotedContent, emptyConsumer, emptyPool, entitledProductIds);
    productModels.add(productModel);
    return v3extensionUtil.createEntitlementDataPayload(productModels, emptyConsumer, emptyPool, null);
}
Also used : ArrayList(java.util.ArrayList) Product(org.candlepin.model.Product) EnvironmentContent(org.candlepin.model.EnvironmentContent) Date(java.util.Date) Consumer(org.candlepin.model.Consumer) Content(org.candlepin.model.Content) EnvironmentContent(org.candlepin.model.EnvironmentContent) Pool(org.candlepin.model.Pool) Entitlement(org.candlepin.model.Entitlement) HashSet(java.util.HashSet)

Example 3 with Pool

use of org.candlepin.model.Pool 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 4 with Pool

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

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

the class CandlepinPoolManager method refreshPoolsWithRegeneration.

/*
     * We need to update/regen entitlements in the same transaction we update pools
     * so we don't miss anything
     */
@Transactional
@SuppressWarnings("checkstyle:methodlength")
@Traceable
void refreshPoolsWithRegeneration(SubscriptionServiceAdapter subAdapter, @TraceableParam("owner") Owner owner, boolean lazy) {
    Date now = new Date();
    owner = this.resolveOwner(owner);
    log.info("Refreshing pools for owner: {}", owner);
    Map<String, Subscription> subscriptionMap = new HashMap<>();
    Map<String, ProductData> productMap = new HashMap<>();
    Map<String, ContentData> contentMap = new HashMap<>();
    // Resolve all our subscriptions, products and content to ensure we don't have bad or
    // duplicate inbound data
    log.debug("Fetching subscriptions from adapter...");
    List<Subscription> subscriptions = subAdapter.getSubscriptions(owner);
    log.debug("Done. Processing subscriptions...");
    for (Subscription subscription : subscriptions) {
        if (subscription == null) {
            continue;
        }
        if (subscription.getId() == null) {
            log.error("subscription does not contain a mappable ID: {}", subscription);
            throw new IllegalStateException("subscription does not contain a mappable ID: " + subscription);
        }
        Subscription existingSub = subscriptionMap.get(subscription.getId());
        if (existingSub != null && !existingSub.equals(subscription)) {
            log.warn("Multiple versions of the same subscription received during refresh; " + "discarding duplicate: {} => {}, {}", subscription.getId(), existingSub, subscription);
            continue;
        }
        subscriptionMap.put(subscription.getId(), subscription);
        List<ProductData> products = new LinkedList<>();
        products.add(subscription.getProduct());
        products.add(subscription.getDerivedProduct());
        products.addAll(subscription.getProvidedProducts());
        products.addAll(subscription.getDerivedProvidedProducts());
        for (ProductData product : products) {
            if (product == null) {
                // forward.
                continue;
            }
            if (product.getId() == null) {
                log.error("product does not contain a mappable Red Hat ID: {}", product);
                throw new IllegalStateException("product does not contain a mappable Red Hat ID: " + product);
            }
            // Product is coming from an upstream source; lock it so only upstream can make
            // further changes to it.
            product.setLocked(true);
            ProductData existingProduct = productMap.get(product.getId());
            if (existingProduct != null && !existingProduct.equals(product)) {
                log.warn("Multiple versions of the same product received during refresh; " + "discarding duplicate: {} => {}, {}", product.getId(), existingProduct, product);
            } else {
                productMap.put(product.getId(), product);
                Collection<ProductContentData> pcdCollection = product.getProductContent();
                if (pcdCollection != null) {
                    for (ProductContentData pcd : pcdCollection) {
                        if (pcd == null) {
                            log.error("product contains a null product-content mapping: {}", product);
                            throw new IllegalStateException("product contains a null product-content mapping: " + product);
                        }
                        ContentData content = pcd.getContent();
                        // population validation for us.
                        if (content == null || content.getId() == null) {
                            log.error("product contains a null or incomplete product-content mapping: {}", product);
                            throw new IllegalStateException("product contains a null or incomplete " + "product-content mapping: " + product);
                        }
                        // We need to lock the incoming content here, but doing so will affect
                        // the equality comparison for products. We'll correct them later.
                        ContentData existingContent = contentMap.get(content.getId());
                        if (existingContent != null && !existingContent.equals(content)) {
                            log.warn("Multiple versions of the same content received during refresh; " + "discarding duplicate: {} => {}, {}", content.getId(), existingContent, content);
                        } else {
                            contentMap.put(content.getId(), content);
                        }
                    }
                }
            }
        }
    }
    // Persist content changes
    log.debug("Importing {} content...", contentMap.size());
    // TODO: Find a more efficient way of doing this, preferably within this method
    for (ContentData cdata : contentMap.values()) {
        cdata.setLocked(true);
    }
    Map<String, Content> importedContent = this.contentManager.importContent(owner, contentMap, productMap.keySet()).getImportedEntities();
    log.debug("Importing {} product(s)...", productMap.size());
    ImportResult<Product> importResult = this.productManager.importProducts(owner, productMap, importedContent);
    Map<String, Product> importedProducts = importResult.getImportedEntities();
    Map<String, Product> updatedProducts = importResult.getUpdatedEntities();
    log.debug("Refreshing {} pool(s)...", subscriptionMap.size());
    Iterator<Map.Entry<String, Subscription>> subsIterator = subscriptionMap.entrySet().iterator();
    while (subsIterator.hasNext()) {
        Map.Entry<String, Subscription> entry = subsIterator.next();
        Subscription sub = entry.getValue();
        if (now.after(sub.getEndDate())) {
            log.info("Skipping expired subscription: {}", sub);
            subsIterator.remove();
            continue;
        }
        log.debug("Processing subscription: {}", sub);
        Pool pool = this.convertToMasterPoolImpl(sub, owner, importedProducts);
        this.refreshPoolsForMasterPool(pool, false, lazy, updatedProducts);
    }
    // delete pools whose subscription disappeared:
    log.debug("Deleting pools for absent subscriptions...");
    List<Pool> poolsToDelete = new ArrayList<>();
    for (Pool pool : poolCurator.getPoolsFromBadSubs(owner, subscriptionMap.keySet())) {
        if (this.isManaged(pool)) {
            poolsToDelete.add(pool);
        }
    }
    deletePools(poolsToDelete);
    // TODO: break this call into smaller pieces. There may be lots of floating pools
    log.debug("Updating floating pools...");
    List<Pool> floatingPools = poolCurator.getOwnersFloatingPools(owner);
    updateFloatingPools(floatingPools, lazy, updatedProducts);
    log.info("Refresh pools for owner: {} completed in: {}ms", owner.getKey(), System.currentTimeMillis() - now.getTime());
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Product(org.candlepin.model.Product) Entry(java.util.Map.Entry) ProductContentData(org.candlepin.model.dto.ProductContentData) ContentData(org.candlepin.model.dto.ContentData) Pool(org.candlepin.model.Pool) SourceSubscription(org.candlepin.model.SourceSubscription) Subscription(org.candlepin.model.dto.Subscription) ProductContentData(org.candlepin.model.dto.ProductContentData) ProductData(org.candlepin.model.dto.ProductData) Date(java.util.Date) LinkedList(java.util.LinkedList) Content(org.candlepin.model.Content) Map(java.util.Map) HashMap(java.util.HashMap) Traceable(org.candlepin.util.Traceable) Transactional(com.google.inject.persist.Transactional)

Aggregations

Pool (org.candlepin.model.Pool)508 Test (org.junit.Test)358 Product (org.candlepin.model.Product)217 Entitlement (org.candlepin.model.Entitlement)125 Consumer (org.candlepin.model.Consumer)115 ValidationResult (org.candlepin.policy.ValidationResult)111 ArrayList (java.util.ArrayList)100 LinkedList (java.util.LinkedList)100 Owner (org.candlepin.model.Owner)80 HashSet (java.util.HashSet)76 HashMap (java.util.HashMap)67 PoolQuantity (org.candlepin.model.PoolQuantity)66 Date (java.util.Date)65 ConsumerInstalledProduct (org.candlepin.model.ConsumerInstalledProduct)62 Subscription (org.candlepin.model.dto.Subscription)60 List (java.util.List)48 ConsumerType (org.candlepin.model.ConsumerType)48 SourceSubscription (org.candlepin.model.SourceSubscription)47 ActivationKey (org.candlepin.model.activationkeys.ActivationKey)38 Matchers.anyString (org.mockito.Matchers.anyString)30