// NOTE: This scenario should NEVER happen since listByConsumerAndDate should // never return dates before the specified date. This test exists to // test the guard clauses in the ComplianceRulesHelper in case it ever happened. @Test public void expiredEntitlementIsIgnoredWhenCalculatingCompliantUntilDate() { Consumer consumer = mockConsumer(new String[] {PRODUCT_1}); Date start = TestUtil.createDate(2005, 6, 12); Entitlement expired = mockEntitlement( consumer, "Provides Product 1 past Ent3", TestUtil.createDate(2005, 5, 20), TestUtil.createDate(2005, 6, 2), PRODUCT_1); Entitlement ent = mockEntitlement( consumer, "Provides Product 1 For Short Period", start, TestUtil.createDate(2005, 6, 22), PRODUCT_1); // Set up entitlements at specific dates. when(entCurator.listByConsumerAndDate(eq(consumer), eq(start))) .thenReturn(Arrays.asList(expired, ent)); when(entCurator.listByConsumerAndDate(eq(consumer), eq(addSecond(ent.getEndDate())))) .thenReturn(Arrays.asList(new Entitlement[0])); Date expectedDate = addSecond(ent.getEndDate()); ComplianceStatus status = compliance.getStatus(consumer, start); assertEquals(expectedDate, status.getCompliantUntil()); }
@Test public void testFutureSuggested() { consumer.setFact(SOCKET_FACT, "4"); pool.setStartDate(TestUtil.createDate(9000, 1, 1)); pool.setEndDate(TestUtil.createDate(9001, 1, 1)); Pool currentPool = TestUtil.createPool(owner, product); currentPool.setStartDate(TestUtil.createDate(2000, 1, 1)); currentPool.setEndDate(TestUtil.createDate(5000, 1, 1)); currentPool.getProduct().setAttribute("multi-entitlement", "yes"); currentPool.getProduct().setAttribute("stacking_id", "1"); pool.getProduct().setAttribute(SOCKET_ATTRIBUTE, "2"); currentPool.getProduct().setAttribute(SOCKET_ATTRIBUTE, "2"); Entitlement currentEntitlement = TestUtil.createEntitlement(owner, consumer, currentPool, null); currentEntitlement.setQuantity(2); Set<Entitlement> ents = new HashSet<Entitlement>(); ents.add(currentEntitlement); consumer.setEntitlements(ents); SuggestedQuantity suggested = quantityRules.getSuggestedQuantity(currentPool, consumer, TestUtil.createDate(2010, 6, 1)); assertEquals(new Long(0), suggested.getSuggested()); // Make sure current coverage does not affect the future suggested = quantityRules.getSuggestedQuantity(pool, consumer, TestUtil.createDate(9000, 6, 1)); assertEquals(new Long(2), suggested.getSuggested()); }
@Test(expected = ExportCreationException.class) public void doNotExportDirtyEntitlements() throws Exception { config.setProperty(ConfigProperties.SYNC_WORK_DIR, "/tmp/"); Consumer consumer = mock(Consumer.class); Entitlement ent = mock(Entitlement.class); Principal principal = mock(Principal.class); IdentityCertificate idcert = new IdentityCertificate(); List<Entitlement> entitlements = new ArrayList<Entitlement>(); entitlements.add(ent); when(pki.getSHA256WithRSAHash(any(InputStream.class))).thenReturn("signature".getBytes()); when(pprov.get()).thenReturn(principal); when(principal.getUsername()).thenReturn("testUser"); when(ec.listByConsumer(consumer)).thenReturn(entitlements); when(ent.getDirty()).thenReturn(true); idcert.setSerial(new CertificateSerial(10L, new Date())); idcert.setKey("euh0876puhapodifbvj094"); idcert.setCert("hpj-08ha-w4gpoknpon*)&^%#"); idcert.setCreated(new Date()); idcert.setUpdated(new Date()); when(consumer.getIdCert()).thenReturn(idcert); KeyPair keyPair = createKeyPair(); when(consumer.getKeyPair()).thenReturn(keyPair); when(pki.getPemEncoded(keyPair.getPrivateKey())).thenReturn("privateKey".getBytes()); when(pki.getPemEncoded(keyPair.getPublicKey())).thenReturn("publicKey".getBytes()); Exporter e = new Exporter( ctc, me, ce, cte, re, ece, ecsa, pe, psa, pce, ec, ee, pki, config, exportRules, pprov); e.getFullExport(consumer); }
@Test public void testPhysicalIgnoresFutureConsumed() { // Setup a future pool for the same product: Pool futurePool = TestUtil.createPool(owner, product); futurePool.setStartDate(TestUtil.createDate(2050, 1, 1)); futurePool.setEndDate(TestUtil.createDate(2060, 1, 1)); pool.getProduct().setAttribute("multi-entitlement", "yes"); pool.getProduct().setAttribute("stacking_id", "1"); pool.getProduct().setAttribute(SOCKET_ATTRIBUTE, "1"); futurePool.getProduct().setAttribute("multi-entitlement", "yes"); futurePool.getProduct().setAttribute("stacking_id", "1"); futurePool.getProduct().setAttribute(SOCKET_ATTRIBUTE, "1"); consumer.setFact(SOCKET_FACT, "4"); // Green in future but we have nothing now: Entitlement e = createValidEntitlement(futurePool); e.setQuantity(4); Set<Entitlement> ents = new HashSet<Entitlement>(); ents.add(e); consumer.setEntitlements(ents); SuggestedQuantity suggested = quantityRules.getSuggestedQuantity(pool, consumer, new Date()); assertEquals(new Long(4), suggested.getSuggested()); }
@Test public void testLazyRegenerate() { Entitlement e = new Entitlement(); manager.regenerateCertificatesOf(e, false, true); assertTrue(e.getDirty()); verifyZeroInteractions(entCertAdapterMock); }
@Test public void testStackOnlyStacksWithSameStackingId() { consumer.setFact(IS_VIRT, "false"); consumer.setFact(SOCKET_FACT, "8"); pool.getProduct().setAttribute(SOCKET_ATTRIBUTE, "2"); pool.setQuantity(10L); Product product1 = TestUtil.createProduct(); Pool pool1 = TestUtil.createPool(owner, product1); Entitlement e = TestUtil.createEntitlement(owner, consumer, pool1, new EntitlementCertificate()); Set<Entitlement> entSet = new HashSet<Entitlement>(); entSet.add(e); pool1.setEntitlements(entSet); pool1.getProduct().setAttribute("multi-entitlement", "yes"); pool1.getProduct().setAttribute("stacking_id", "2"); pool1.getProduct().setAttribute(SOCKET_ATTRIBUTE, "2"); pool1.setQuantity(10L); // Consume 2 subscriptions with another stacking ID Entitlement toAdd = pool1.getEntitlements().iterator().next(); toAdd.setQuantity(2); consumer.addEntitlement(toAdd); // Ensure the 2 attached entitlements do not cause the suggested quantity to change SuggestedQuantity suggested = quantityRules.getSuggestedQuantity(pool, consumer, new Date()); assertEquals(new Long(4), suggested.getSuggested()); }
@Test public void listProvidingNoResults() { Entitlement ent = setupListProvidingEntitlement(); Set<Entitlement> results = entitlementCurator.listProviding( consumer, "nosuchproductid", ent.getStartDate(), ent.getEndDate()); assertEquals(0, results.size()); }
private List<Pool> createPoolsWithSourceEntitlement(Entitlement e, Product p) { List<Pool> pools = new LinkedList<Pool>(); Pool pool1 = TestUtil.createPool(e.getOwner(), p); pools.add(pool1); Pool pool2 = TestUtil.createPool(e.getOwner(), p); pools.add(pool2); return pools; }
@Test public void listModifyingProvided() { Entitlement ent = setupListModifyingEntitlement(); List<Entitlement> results = entitlementCurator.listModifying( consumer, providedProduct1.getId(), ent.getStartDate(), ent.getEndDate()); assertEquals(1, results.size()); }
@Test public void listProvidingNoOverlap() { Entitlement ent = setupListProvidingEntitlement(); Set<Entitlement> results = entitlementCurator.listProviding( consumer, ent.getPool().getProductId(), pastDate, pastDate); assertEquals(0, results.size()); }
@Test public void listModifyingNoResults() { Entitlement ent = setupListModifyingEntitlement(); List<Entitlement> results = entitlementCurator.listModifying( consumer, "notarealproduct", ent.getStartDate(), ent.getEndDate()); assertEquals(0, results.size()); }
@Test public void listProvidingStartDateOverlap() { Entitlement ent = setupListProvidingEntitlement(); Set<Entitlement> results = entitlementCurator.listProviding( consumer, ent.getPool().getProductId(), overlappingDate, futureDate); assertEquals(1, results.size()); }
@Test public void testLazyRegenerateForConsumer() { Entitlement e = new Entitlement(); Consumer c = new Consumer(); c.addEntitlement(e); manager.regenerateEntitlementCertificates(c, true); assertTrue(e.getDirty()); verifyZeroInteractions(entCertAdapterMock); }
private Set<Product> getDerivedProductsForDistributor(Subscription sub, Entitlement ent) { Set<Product> derivedProducts = new HashSet<Product>(); boolean derived = ent.getPool().hasAttribute("pool_derived"); if (!derived && ent.getConsumer().getType().isManifest() && sub.getDerivedProduct() != null) { derivedProducts.add(sub.getDerivedProduct()); derivedProducts.addAll(sub.getDerivedProvidedProducts()); } return derivedProducts; }
@Test public void listProvidingProvidedProduct() { Entitlement ent = setupListProvidingEntitlement(); // Test a successful query: Set<Entitlement> results = entitlementCurator.listProviding( consumer, providedProduct1.getId(), ent.getStartDate(), ent.getEndDate()); assertEquals(1, results.size()); }
@Test public void testRefreshPoolsRemovesExpiredSubscriptionsAlongWithItsPoolsAndEnts() { PreUnbindHelper preHelper = mock(PreUnbindHelper.class); Date expiredStart = TestUtil.createDate(2004, 5, 5); Date expiredDate = TestUtil.createDate(2005, 5, 5); List<Subscription> subscriptions = Util.newList(); Subscription sub = TestUtil.createSubscription(getOwner(), TestUtil.createProduct()); sub.setStartDate(expiredStart); sub.setEndDate(expiredDate); sub.setId("123"); subscriptions.add(sub); when(mockSubAdapter.getSubscriptions(any(Owner.class))).thenReturn(subscriptions); List<Pool> pools = Util.newList(); Pool p = TestUtil.createPool(sub.getOwner(), sub.getProduct()); p.setSubscriptionId(sub.getId()); p.setStartDate(expiredStart); p.setEndDate(expiredDate); p.setConsumed(1L); pools.add(p); when(mockPoolCurator.lockAndLoad(any(Pool.class))).thenReturn(p); when(mockPoolCurator.listAvailableEntitlementPools( any(Consumer.class), any(Owner.class), anyString(), any(Date.class), anyBoolean(), anyBoolean())) .thenReturn(pools); List<Entitlement> poolEntitlements = Util.newList(); Entitlement ent = TestUtil.createEntitlement(); ent.setPool(p); ent.setQuantity(1); poolEntitlements.add(ent); when(mockPoolCurator.entitlementsIn(eq(p))).thenReturn(poolEntitlements); ValidationResult result = new ValidationResult(); when(preHelper.getResult()).thenReturn(result); this.manager.getRefresher().add(sub.getOwner()).run(); verify(mockSubAdapter).deleteSubscription(eq(sub)); verify(mockPoolCurator).delete(eq(p)); // Verify the entitlement was removed. verify(entCertAdapterMock).revokeEntitlementCertificates(eq(ent)); verify(entitlementCurator).delete(eq(ent)); }
private void postBindVirtLimit( PoolHelper postHelper, Entitlement entitlement, Pool pool, Consumer c, Map<String, String> attributes) { log.debug("Running virt_limit post-bind."); if (!c.isManifest() && (config.standalone() || attributes.containsKey("host_limited"))) { String productId = pool.getProductId(); String virtLimit = attributes.get("virt_limit"); if ("unlimited".equals(virtLimit)) { postHelper.createHostRestrictedPool(productId, pool, "unlimited"); } else { int virtQuantity = Integer.parseInt(virtLimit) * entitlement.getQuantity(); if (virtQuantity > 0) { postHelper.createHostRestrictedPool(productId, pool, String.valueOf(virtQuantity)); } } } else { if (!config.standalone() && c.isManifest()) { String virtLimit = attributes.get("virt_limit"); if (!"unlimited".equals(virtLimit)) { // if the bonus pool is not unlimited, then the bonus pool // quantity // needs to be adjusted based on the virt limit int virtQuantity = Integer.parseInt(virtLimit) * entitlement.getQuantity(); if (virtQuantity > 0) { List<Pool> pools = postHelper.lookupBySubscriptionId(pool.getSubscriptionId()); for (int idex = 0; idex < pools.size(); idex++) { Pool derivedPool = pools.get(idex); if (derivedPool.getAttributeValue("pool_derived") != null) { derivedPool = postHelper.updatePoolQuantity(derivedPool, -1 * virtQuantity); } } } } else { // if the bonus pool is unlimited, then the quantity needs // to go to 0 // when the physical pool is exhausted completely by export. // A quantity of 0 will block future binds, whereas -1 does // not. if (pool.getQuantity().equals(pool.getExported())) { // getting all pools matching the sub id. Filtering out // the 'parent'. List<Pool> pools = postHelper.lookupBySubscriptionId(pool.getSubscriptionId()); for (int idex = 0; idex < pools.size(); idex++) { Pool derivedPool = pools.get(idex); if (derivedPool.getAttributeValue("pool_derived") != null) { derivedPool = postHelper.setPoolQuantity(derivedPool, 0); } } } } } } }
@Test public void entIsNotCompliantWhenSocketsAreNotCovered() { Consumer c = mock(Consumer.class); when(c.hasFact("cpu.cpu_socket(s)")).thenReturn(true); when(c.getFact("cpu.cpu_socket(s)")).thenReturn("8"); Entitlement ent = mockEntitlement(c, PRODUCT_1); ent.getPool().setProductAttribute("sockets", "4", PRODUCT_1); assertFalse(compliance.isEntitlementCompliant(c, ent)); }
protected void runPostUnbind(PoolHelper postHelper, Entitlement entitlement) { Pool pool = entitlement.getPool(); Consumer c = entitlement.getConsumer(); Map<String, String> attributes = postHelper.getFlattenedAttributes(pool); if (attributes.containsKey("virt_limit")) { postUnbindVirtLimit(postHelper, entitlement, pool, c, attributes); } }
/** * @param ent * @param useContentPrefix * @return * @throws IOException */ private String getContentPrefix(Entitlement ent, boolean useContentPrefix) throws IOException { String contentPrefix = null; if (useContentPrefix) { contentPrefix = ent.getOwner().getContentPrefix(); Environment env = ent.getConsumer().getEnvironment(); if (contentPrefix != null && !contentPrefix.equals("")) { if (env != null) { contentPrefix = contentPrefix.replaceAll("\\$env", env.getName()); } contentPrefix = this.cleanUpPrefix(contentPrefix); } } return contentPrefix; }
@Test public void testUnmappedGuestRevocation() throws Exception { Owner owner1 = new Owner("o1"); Owner owner2 = new Owner("o2"); Product product1 = TestUtil.createProduct(); Product product2 = TestUtil.createProduct(); Pool p1 = TestUtil.createPool(owner1, product1); Pool p2 = TestUtil.createPool(owner2, product2); p1.addAttribute(new PoolAttribute("unmapped_guests_only", "true")); p2.addAttribute(new PoolAttribute("unmapped_guests_only", "true")); Date thirtySixHoursAgo = new Date(new Date().getTime() - 36L * 60L * 60L * 1000L); Date twelveHoursAgo = new Date(new Date().getTime() - 12L * 60L * 60L * 1000L); Consumer c; c = TestUtil.createConsumer(owner1); c.setCreated(twelveHoursAgo); Entitlement e1 = TestUtil.createEntitlement(owner1, c, p1, null); e1.setEndDateOverride(new Date(new Date().getTime() + 1L * 60L * 60L * 1000L)); Set<Entitlement> entitlementSet1 = new HashSet<Entitlement>(); entitlementSet1.add(e1); p1.setEntitlements(entitlementSet1); c = TestUtil.createConsumer(owner2); c.setCreated(twelveHoursAgo); Entitlement e2 = TestUtil.createEntitlement(owner2, c, p2, null); e2.setEndDateOverride(thirtySixHoursAgo); Set<Entitlement> entitlementSet2 = new HashSet<Entitlement>(); entitlementSet2.add(e2); p2.setEntitlements(entitlementSet2); CandlepinQuery cqmock = mock(CandlepinQuery.class); when(cqmock.iterator()).thenReturn(Arrays.asList(e1, e2).iterator()); when(entitlementCurator.findByPoolAttribute(eq("unmapped_guests_only"), eq("true"))) .thenReturn(cqmock); int total = entitler.revokeUnmappedGuestEntitlements(); assertEquals(1, total); verify(pm).revokeEntitlement(e1); }
@Test public void testPhysicalAccountsForCurrentlyConsumed() { consumer.setFact(SOCKET_FACT, "4"); pool.getProduct().setAttribute(SOCKET_ATTRIBUTE, "1"); Entitlement e = createValidEntitlement(pool); e.setQuantity(2); Set<Entitlement> ents = new HashSet<Entitlement>(); ents.add(e); consumer.setEntitlements(ents); SuggestedQuantity suggested = quantityRules.getSuggestedQuantity(pool, consumer, new Date()); assertEquals(new Long(2), suggested.getSuggested()); }
/** * @param ent * @return */ private Map<String, EnvironmentContent> getPromotedContent(Entitlement ent) { // Build a set of all content IDs promoted to the consumer's environment so // we can determine if anything needs to be skipped: Map<String, EnvironmentContent> promotedContent = new HashMap<String, EnvironmentContent>(); if (ent.getConsumer().getEnvironment() != null) { log.debug( "Consumer has environment, checking for promoted content in: " + ent.getConsumer().getEnvironment()); for (EnvironmentContent envContent : ent.getConsumer().getEnvironment().getEnvironmentContent()) { log.debug(" promoted content: " + envContent.getContentId()); promotedContent.put(envContent.getContentId(), envContent); } } return promotedContent; }
private Entitlement createValidEntitlement(Pool p) { Entitlement e = TestUtil.createEntitlement(owner, consumer, p, null); Calendar cal = Calendar.getInstance(); cal.setTime(new Date()); cal.add(Calendar.DATE, 1); Date dayFromNow = cal.getTime(); cal.add(Calendar.DATE, -2); Date dayAgo = cal.getTime(); e.setCreated(dayAgo); p.setEndDate(dayFromNow); return e; }
private Pool createPoolWithEntitlements() { Pool newPool = TestUtil.createPool(o, product); Entitlement e1 = new Entitlement( newPool, TestUtil.createConsumer(o), newPool.getStartDate(), newPool.getEndDate(), 1); e1.setId("1"); Entitlement e2 = new Entitlement( newPool, TestUtil.createConsumer(o), newPool.getStartDate(), newPool.getEndDate(), 1); e2.setId("2"); newPool.getEntitlements().add(e1); newPool.getEntitlements().add(e2); return newPool; }
@Test public void testCalculatedValueIsZeroWhenNegativeIsCalculated() { consumer.setFact(IS_VIRT, ""); consumer.setFact(SOCKET_FACT, "4"); pool.getProduct().setAttribute(SOCKET_ATTRIBUTE, "2"); Entitlement e = createValidEntitlement(pool); e.setQuantity(1000); Set<Entitlement> ents = new HashSet<Entitlement>(); ents.add(e); consumer.setEntitlements(ents); SuggestedQuantity suggested = quantityRules.getSuggestedQuantity(pool, consumer, new Date()); assertEquals(new Long(0), suggested.getSuggested()); }
private Entitlement mockStackedEntitlement( Consumer consumer, String stackId, String productId, String... providedProductIds) { Entitlement e = mockEntitlement(consumer, productId, providedProductIds); Random gen = new Random(); int id = gen.nextInt(Integer.MAX_VALUE); e.setId(String.valueOf(id)); Pool p = e.getPool(); // Setup the attributes for stacking: p.addProductAttribute(new ProductPoolAttribute("stacking_id", stackId, productId)); p.addProductAttribute(new ProductPoolAttribute("sockets", "2", productId)); return e; }
private void exportProducts(File baseDir, Consumer consumer) throws IOException { File productDir = new File(baseDir.getCanonicalPath(), "products"); productDir.mkdir(); Map<String, Product> products = new HashMap<String, Product>(); for (Entitlement entitlement : consumer.getEntitlements()) { for (ProvidedProduct providedProduct : entitlement.getPool().getProvidedProducts()) { // Don't want to call the adapter if not needed, it can be expensive. if (!products.containsKey(providedProduct.getProductId())) { products.put( providedProduct.getProductId(), productAdapter.getProductById(providedProduct.getProductId())); } } // Don't forget the 'main' product! String productId = entitlement.getPool().getProductId(); if (!products.containsKey(productId)) { products.put(productId, productAdapter.getProductById(productId)); } } for (Product product : products.values()) { String path = productDir.getCanonicalPath(); String productId = product.getId(); File file = new File(path, productId + ".json"); FileWriter writer = new FileWriter(file); productExporter.export(mapper, writer, product); writer.close(); // Real products have a numeric id. if (StringUtils.isNumeric(product.getId())) { ProductCertificate cert = productAdapter.getProductCertificate(product); // XXX: not all product adapters implement getProductCertificate, // so just skip over this if we get null back // 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(); } } } }
protected void runPostEntitlement(PoolHelper postHelper, Entitlement entitlement) { Pool pool = entitlement.getPool(); Consumer c = entitlement.getConsumer(); Map<String, String> attributes = postHelper.getFlattenedAttributes(pool); // Perform pool management based on the attributes of the pool: // TODO: should really be cleaned up, this used to be post rules but // because // it actually manages pools we pulled back to engine. Needs re-org. if (attributes.containsKey("user_license")) { postBindUserLicense(postHelper, pool, c, attributes); } if (attributes.containsKey("virt_limit")) { postBindVirtLimit(postHelper, entitlement, pool, c, attributes); } }
private Pool entitlementPoolWithMembersAndExpiration( Owner theOwner, Product product, final int currentMembers, final int maxMembers, Date expiry) { Pool p = createPoolAndSub(theOwner, product, Long.valueOf(maxMembers), new Date(), expiry); for (int i = 0; i < currentMembers; i++) { Consumer c = createConsumer(theOwner); Entitlement e = createEntitlement(theOwner, c, p, null); e.setQuantity(1); entitlementCurator.create(e); p.getEntitlements().add(e); poolCurator.merge(p); } poolCurator.refresh(p); return p; }