use of rhsm.data.EntitlementCert in project rhsm-qe by RedHatQE.
the class DataCenterTests method testAvailabilityOfDerivedProductSubpools.
// Test methods ***********************************************************************
@// update=true, // uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-19987", "RHEL7-33089" }, level = DefTypes.Level.COMPONENT, component = "subscription-manager", testtype = @TestType(testtype = DefTypes.TestTypes.FUNCTIONAL, subtype1 = DefTypes.Subtypes.RELIABILITY, subtype2 = DefTypes.Subtypes.EMPTY), posneg = PosNeg.POSITIVE, importance = DefTypes.Importance.HIGH, automation = DefTypes.Automation.AUTOMATED, tags = "Tier1")
@Test(description = "given an available data center pool, consume it and assert that a pool for the derivedProduct is generated and available only to its guests", groups = { "Tier1Tests", "VerifyAvailabilityOfDerivedProductSubpools_Test" }, dataProvider = "getAvailableDataCenterSubscriptionPoolsData", enabled = true)
public // @ImplementsNitrateTest(caseId=)
void testAvailabilityOfDerivedProductSubpools(Object bugzilla, /*Boolean systemIsGuest, Integer systemSockets,*/
SubscriptionPool pool) throws NumberFormatException, JSONException, Exception {
String expectedTemporaryPoolIndicator = " (Temporary)";
// make sure we are unsubscribed from all subscriptions
// clienttasks.unsubscribe(true, (BigInteger)null, null, null, null);
// unsubscribe this way to ensure the newest serial is removed first
clienttasks.unsubscribeFromTheCurrentlyConsumedSerialsCollectively();
// get some attributes from the subscription pool
String poolDerivedProductId = (String) CandlepinTasks.getPoolValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId, "derivedProductId");
String poolDerivedProductName = (String) CandlepinTasks.getPoolValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId, "derivedProductName");
String poolDerivedProductArch = (String) CandlepinTasks.getPoolDerivedProductAttributeValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId, "arch");
// Note: the arch attribute can be a comma separated list of values
List<String> poolDerivedProductArches = new ArrayList<String>(Arrays.asList(poolDerivedProductArch.trim().split(" *, *")));
List<String> poolDerivedProvidedProductIds = CandlepinTasks.getPoolDerivedProvidedProductIds(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId);
String poolVirtLimit = CandlepinTasks.getPoolProductAttributeValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId, "virt_limit");
List<String> poolProvidedProductIds = CandlepinTasks.getPoolProvidedProductIds(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId);
// TEMPORARY WORKAROUND FOR BUG
if (sm_serverType.equals(CandlepinType.hosted)) {
// Bug 1214001 - after stage refresh, Virtual Data Center SKUs no longer have a host_limited pool productAttributes
String bugId = "1214001";
boolean invokeWorkaroundWhileBugIsOpen = true;
try {
if (invokeWorkaroundWhileBugIsOpen && BzChecker.getInstance().isBugOpen(bugId)) {
log.fine("Invoking workaround for " + BzChecker.getInstance().getBugState(bugId).toString() + " Bugzilla " + bugId + ". (https://bugzilla.redhat.com/show_bug.cgi?id=" + bugId + ")");
SubscriptionManagerCLITestScript.addInvokedWorkaround(bugId);
} else {
invokeWorkaroundWhileBugIsOpen = false;
}
} catch (BugzillaAPIException be) {
/* ignore exception */
} catch (RuntimeException re) {
/* ignore exception */
}
if (invokeWorkaroundWhileBugIsOpen) {
throw new SkipException("Skipping this Virtual Data Center test against SKU '" + pool.productId + "' while bug '" + bugId + "' is open.");
}
}
// TEMPORARY WORKAROUND FOR BUG
if (sm_serverType.equals(CandlepinType.hosted)) {
// Bug 1261193 - Datacenter subscriptions in stage candlepin-0.9.51.5-1 should create Temporary pools for their derived products
String bugId = "1261193";
boolean invokeWorkaroundWhileBugIsOpen = true;
try {
if (invokeWorkaroundWhileBugIsOpen && BzChecker.getInstance().isBugOpen(bugId)) {
log.fine("Invoking workaround for " + BzChecker.getInstance().getBugState(bugId).toString() + " Bugzilla " + bugId + ". (https://bugzilla.redhat.com/show_bug.cgi?id=" + bugId + ")");
SubscriptionManagerCLITestScript.addInvokedWorkaround(bugId);
} else {
invokeWorkaroundWhileBugIsOpen = false;
}
} catch (BugzillaAPIException be) {
/* ignore exception */
} catch (RuntimeException re) {
/* ignore exception */
}
if (invokeWorkaroundWhileBugIsOpen) {
throw new SkipException("Skipping this Virtual Data Center test against SKU '" + pool.productId + "' while bug '" + bugId + "' is open.");
}
}
// END OF WORKAROUND
// assert that this virtual data center SKU is host_limited
Assert.assertTrue(CandlepinTasks.isPoolProductHostLimited(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId), "As a functional requirement for Virtual Data Center SKUs, asserting that the pool's productAttributes contains host_limited=true so that a subscription pool for derivedProductId '" + poolDerivedProductId + "' is available ONLY to mapped virtual guests.");
// assert that the derivedProductId is different from the host pool's productId
Assert.assertTrue(!pool.productId.equals(poolDerivedProductId), "The host pool's data center subscription product Id '" + pool.productId + "' should be different than its derived pool's product Id '" + poolDerivedProductId + "'.");
// NOT NECESSARILY TRUE // assert that the derivedProductName is different from the host pool's subscription name
// NOT NECESSARILY TRUE Assert.assertNotSame(pool.subscriptionName, poolDerivedProductName, "The host pool's data center subscription name '"+pool.subscriptionName+"' should be different than its derived pool's product name '"+poolDerivedProductName+"'.");
// instrument the system facts to behave as a physical host
factsMap.put("virt.is_guest", String.valueOf(false));
clienttasks.createFactsFileWithOverridingValues(factsMap);
// update facts
clienttasks.facts(null, true, null, null, null, null);
// reset a few fake guest ids for this host consumer
String systemUuid = clienttasks.getCurrentConsumerId();
// [root@jsefler-5 ~]# curl -k -u testuser1:password --request PUT --data '{"guestIds":["e6f55b91-aae1-44d6-f0db-c8f25ec73ef5","abcd"]}' --header 'accept:application/json' --header 'content-type: application/json' https://jsefler-f14-candlepin.usersys.redhat.com:8443/candlepin/consumers/d2ee0c6e-a57d-4e37-8be3-228a44ca2739
JSONObject jsonConsumer = CandlepinTasks.setGuestIdsForConsumer(sm_clientUsername, sm_clientPassword, sm_serverUrl, systemUuid, Arrays.asList(new String[] { "abc", "def" }));
// assert that only Physical pools are available for consumption for this data center sku
for (SubscriptionPool subscriptionPool : SubscriptionPool.findAllInstancesWithMatchingFieldFromList("productId", pool.productId, clienttasks.getCurrentlyAllAvailableSubscriptionPools())) {
Assert.assertEquals(subscriptionPool.machineType, "Physical", "Only physical pools to '" + pool.productId + "' should be available to a physical host system.");
}
// subscribe the host to the data center pool
File hostEntitlementFile = clienttasks.subscribeToSubscriptionPool(pool, /*sm_serverAdminUsername*/
sm_clientUsername, /*sm_serverAdminPassword*/
sm_clientPassword, sm_serverUrl);
EntitlementCert hostEntitlementCert = clienttasks.getEntitlementCertFromEntitlementCertFile(hostEntitlementFile);
client.runCommandAndWait("rct cat-cert " + hostEntitlementFile);
// the following general asserts are not true against a production datacenter SKU...
if (false) {
// Subscription Name: Red Hat Enterprise Linux for Virtual Datacenters, Premium
// Provides: Red Hat Enterprise Linux Atomic Host
// SKU: RH00001
// Contract: 10472273
// Pool ID: 8a99f98146b4fa9d0146b5d3c0005253
// Available: 98
// Suggested: 1
// Service Level: Premium
// Service Type: L1-L3
// Subscription Type: Stackable
// Ends: 12/30/2014
// System Type: Physical
// in general the data center pool will not provide any engineering products
Assert.assertTrue(poolProvidedProductIds.isEmpty(), "In general, a data center product subscription will not provide any engineering products (productId= '" + pool.productId + "'). Asserting the providedProducts from the subscription is empty...");
Assert.assertTrue(hostEntitlementCert.productNamespaces.isEmpty(), "In general, a data center product subscription will not provide any engineering products (productId= '" + pool.productId + "'). Asserting the productNamespaces from the granted entitlement are empty...");
// in general the data center pool will not provide any content
Assert.assertTrue(hostEntitlementCert.contentNamespaces.isEmpty(), "In general, a data center product subscription will not provide any content sets (productId= '" + pool.productId + "').");
}
// assert that the derivedProductId is NOT available to the Physical host system
List<SubscriptionPool> availablePoolsForDerivedProductId = SubscriptionPool.findAllInstancesWithMatchingFieldFromList("productId", poolDerivedProductId, clienttasks.getCurrentlyAllAvailableSubscriptionPools());
Assert.assertTrue(availablePoolsForDerivedProductId.isEmpty(), "A subpool for the derivedProductId '" + poolDerivedProductId + "' should NOT be available to the host after (or before) it consumes the data center product subscription.");
// now we can assert that a host_limited subpool was generated from consumption of this physical pool and is only available to guests of this physical system
// first, let's flip the virt.is_guest to true and assert that the virtual guest subpool is not (yet) available since the virtUuid is not on the host consumer's list of guestIds
factsMap.put("virt.is_guest", String.valueOf(true));
clienttasks.createFactsFileWithOverridingValues(factsMap);
// update facts
clienttasks.facts(null, true, null, null, null, null);
availablePoolsForDerivedProductId = SubscriptionPool.findAllInstancesWithMatchingFieldFromList("productId", poolDerivedProductId, clienttasks.getCurrentlyAllAvailableSubscriptionPools());
if (SubscriptionManagerTasks.isVersion(servertasks.statusVersion, "<", "0.9.45-1")) {
// this assertion was valid prior to introduction of Temporary pools for unmapped guests
Assert.assertTrue(availablePoolsForDerivedProductId.isEmpty(), "A subpool for the derivedProductId '" + poolDerivedProductId + "' should NOT be available to a guest system when its virt_uuid is not on the host's list of guestIds.");
} else {
// this assertion is valid after the introduction of Temporary pools for unmapped guests
Assert.assertTrue(!availablePoolsForDerivedProductId.isEmpty(), "Starting with candlepin version 0.9.45-1, a temporary subpool for the derivedProductId '" + poolDerivedProductId + "' should NOW be available to a guest system when its virt_uuid is not on the host's list of guestIds.");
if (SubscriptionManagerTasks.isVersion(servertasks.statusVersion, ">=", "0.9.47-1")) {
// commit dfd7e68ae83642f77c80590439353a0d66fe2961 // Bug 1201520 - [RFE] Usability suggestions to better identify a temporary (aka 24 hour) entitlement
for (SubscriptionPool subscriptionPool : availablePoolsForDerivedProductId) {
Assert.assertTrue(subscriptionPool.subscriptionType.endsWith(expectedTemporaryPoolIndicator), "Starting with candlepin version 0.9.47-1, a temporary subpool (indicated by subscription type ending in '" + expectedTemporaryPoolIndicator + "') for the derivedProductId '" + poolDerivedProductId + "' should NOW be available to a guest system when its virt_uuid is not on the host's list of guestIds: " + subscriptionPool);
}
}
}
// now fake this consumer's facts and guestIds to make it think it is a guest of itself (a trick for testing)
factsMap.put("virt.uuid", systemUuid);
clienttasks.createFactsFileWithOverridingValues(factsMap);
// update facts
clienttasks.facts(null, true, null, null, null, null);
// [root@jsefler-5 ~]# curl -k -u testuser1:password --request PUT --data '{"guestIds":["e6f55b91-aae1-44d6-f0db-c8f25ec73ef5","abcd"]}' --header 'accept:application/json' --header 'content-type: application/json' https://jsefler-f14-candlepin.usersys.redhat.com:8443/candlepin/consumers/d2ee0c6e-a57d-4e37-8be3-228a44ca2739
jsonConsumer = CandlepinTasks.setGuestIdsForConsumer(sm_clientUsername, sm_clientPassword, sm_serverUrl, systemUuid, Arrays.asList(new String[] { "abc", systemUuid, "def" }));
// now the host_limited subpool to the derivedProductId for this virtual system should be available
availablePoolsForDerivedProductId = SubscriptionPool.findAllInstancesWithMatchingFieldFromList("productId", poolDerivedProductId, clienttasks.getCurrentlyAllAvailableSubscriptionPools());
Assert.assertTrue(!availablePoolsForDerivedProductId.isEmpty(), "Host_limited subpool from data center product id '" + pool.productId + "' to derived product id '" + poolDerivedProductId + "' is available to its guest.");
Assert.assertEquals(availablePoolsForDerivedProductId.size(), 1, "Only one host_limited subpool to derived product id '" + poolDerivedProductId + "' is available to its guest.");
SubscriptionPool derivedPool = availablePoolsForDerivedProductId.get(0);
Assert.assertTrue(!derivedPool.subscriptionType.endsWith(expectedTemporaryPoolIndicator), "The host_limited subpool to derived product id '" + poolDerivedProductId + "' available to its guest should NOT indicate that the subscription type '" + derivedPool.subscriptionType + "' is temporary.");
Assert.assertEquals(derivedPool.subscriptionName, poolDerivedProductName, "Subscription name for the derived product id '" + poolDerivedProductId + "'.");
Assert.assertEquals(derivedPool.quantity.toLowerCase(), poolVirtLimit, "The quantity of entitlements from the host_limited subpool to derived product subscription '" + poolDerivedProductName + "' should be the same as the host data center subscription's virt_limit '" + poolVirtLimit + "'.");
// now subscribe to the derived subpool and we'll assert the entitlement values come from the derived product and not the originating data center subscription
// subscribe the guest to the derived product subscription
File derivedEntitlementFile = clienttasks.subscribeToSubscriptionPool(derivedPool, /*sm_serverAdminUsername*/
sm_clientUsername, /*sm_serverAdminPassword*/
sm_clientPassword, sm_serverUrl);
EntitlementCert derivedEntitlementCert = clienttasks.getEntitlementCertFromEntitlementCertFile(derivedEntitlementFile);
client.runCommandAndWait("rct cat-cert " + derivedEntitlementFile);
// assert all of the derived provided products are included in the entitlement
List<String> actualDerivedProvidedProductIds = new ArrayList<String>();
for (ProductNamespace productNamespace : derivedEntitlementCert.productNamespaces) {
actualDerivedProvidedProductIds.add(productNamespace.id);
}
Assert.assertTrue(actualDerivedProvidedProductIds.containsAll(poolDerivedProvidedProductIds) && poolDerivedProvidedProductIds.containsAll(actualDerivedProvidedProductIds), "The actual product ids " + actualDerivedProvidedProductIds + " provided by an entitlement cert from the derived subpool '" + derivedPool.subscriptionName + "' match the expected derivedProvidedProducts " + poolDerivedProvidedProductIds + " from the data center subscription '" + pool.subscriptionName + "'.");
// assert the derivedProductAttributes are reflected in the entitlement cert granted from the derived subpool
// Order: Order:
// Name: Awesome OS Server Basic (data center) Name: Awesome OS Server Basic (dc-virt)
// Number: order-8675309 Number: order-8675309
// SKU: awesomeos-server-basic-dc SKU: awesomeos-server-basic-vdc
// Contract: 18 Contract: 18
// Account: 12331131231 Account: 12331131231
// Service Level: None Service Level: Full-Service
// Service Type: Self-Support Service Type: Drive-Through
// Quantity: 5 Quantity: 5
// Quantity Used: 1 Quantity Used: 1
// Socket Limit: 4 Socket Limit: 2
// RAM Limit: RAM Limit: 2
// Core Limit: Core Limit: 4
// Virt Limit: Virt Limit:
// Virt Only: False Virt Only: True
// Subscription: Subscription:
// Stacking ID: Stacking ID:
// Warning Period: 30 Warning Period: 0
// Provides Management: False Provides Management: False
// Name: Awesome OS Server Basic (data center) Name: Awesome OS Server Basic (dc-virt)
Assert.assertEquals(hostEntitlementCert.orderNamespace.productName, pool.subscriptionName, "hostEntitlementCert.orderNamespace.productName should match the data center pool's subscription name");
Assert.assertEquals(derivedEntitlementCert.orderNamespace.productName, poolDerivedProductName, "derivedEntitlementCert.orderNamespace.productName should match the derivedProductName");
// Number: order-8675309 Number: order-8675309
Assert.assertEquals(derivedEntitlementCert.orderNamespace.orderNumber, hostEntitlementCert.orderNamespace.orderNumber, "Order Number from the derived entitlement should match the host entitlement");
// SKU: awesomeos-server-basic-dc SKU: awesomeos-server-basic-vdc
Assert.assertEquals(hostEntitlementCert.orderNamespace.productId, pool.productId, "hostEntitlementCert.orderNamespace.productId should match the data center pool's productId");
Assert.assertEquals(derivedEntitlementCert.orderNamespace.productId, poolDerivedProductId, "derivedEntitlementCert.orderNamespace.productId should match the derivedProductId");
// Contract: 18 Contract: 18
Assert.assertEquals(derivedEntitlementCert.orderNamespace.contractNumber, hostEntitlementCert.orderNamespace.contractNumber, "Contract Number from the derived entitlement should match the host entitlement");
// Account: 12331131231 Account: 12331131231
Assert.assertEquals(derivedEntitlementCert.orderNamespace.accountNumber, hostEntitlementCert.orderNamespace.accountNumber, "Account Number from the derived entitlement should match the host entitlement");
// Service Level: None Service Level: Full-Service
Assert.assertEquals(hostEntitlementCert.orderNamespace.supportLevel, pool.serviceLevel, "hostEntitlementCert.orderNamespace.supportLevel should match the data center pool's serviceLevel");
Assert.assertEquals(derivedEntitlementCert.orderNamespace.supportLevel, CandlepinTasks.getPoolDerivedProductAttributeValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId, "support_level"), "derivedEntitlementCert.orderNamespace.supportLevel should match the derivedProductAttribute support_level");
// Service Type: Self-Support Service Type: Drive-Through
Assert.assertEquals(hostEntitlementCert.orderNamespace.supportType, pool.serviceType, "hostEntitlementCert.orderNamespace.supportType should match the data center pool's serviceType");
Assert.assertEquals(derivedEntitlementCert.orderNamespace.supportType, CandlepinTasks.getPoolDerivedProductAttributeValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId, "support_type"), "derivedEntitlementCert.orderNamespace.supportType should match the derivedProductAttribute support_type");
// Quantity: 5 Quantity: 5
JSONObject jsonPool = new JSONObject(CandlepinTasks.getResourceUsingRESTfulAPI(sm_clientUsername, sm_clientPassword, sm_serverUrl, "/pools/" + pool.poolId));
Assert.assertEquals(hostEntitlementCert.orderNamespace.quantity, String.valueOf(jsonPool.getInt("quantity")), "hostEntitlementCert.orderNamespace.quantity should match the data center subscription pool's total quantity");
// TEMPORARY WORKAROUND FOR BUG
String bugId = "983193";
boolean invokeWorkaroundWhileBugIsOpen = true;
try {
if (invokeWorkaroundWhileBugIsOpen && BzChecker.getInstance().isBugOpen(bugId)) {
log.fine("Invoking workaround for " + BzChecker.getInstance().getBugState(bugId).toString() + " Bugzilla " + bugId + ". (https://bugzilla.redhat.com/show_bug.cgi?id=" + bugId + ")");
SubscriptionManagerCLITestScript.addInvokedWorkaround(bugId);
} else {
invokeWorkaroundWhileBugIsOpen = false;
}
} catch (BugzillaAPIException be) {
/* ignore exception */
} catch (RuntimeException re) {
/* ignore exception */
}
if (invokeWorkaroundWhileBugIsOpen) {
log.warning("Skipping the assertion of quantity while bug '" + bugId + "' is open.");
} else {
// END OF WORKAROUND
if (// Bug 1011961 - rct cat-cert should display "Unlimited" for Quantity instead of "-1"; subscription-manager commit 7554c869608a0276151993d34fee4ddb54185f7a
clienttasks.isPackageVersion("subscription-manager", "<", "1.10.3-1") && derivedEntitlementCert.orderNamespace.quantity.equals("-1")) // Bug 1011961 - rct cat-cert should display "Unlimited" for Quantity instead of "-1"; subscription-manager commit 7554c869608a0276151993d34fee4ddb54185f7a
{
log.warning("The rct cat-cert tool encountered a Quantity of -1 which is fixed in subscription-manager-1.10.3-1. Skipping assertion.");
} else
Assert.assertEquals(derivedEntitlementCert.orderNamespace.quantity, derivedPool.quantity, "derivedEntitlementCert.orderNamespace.quantity should match the derivedPool's quantity");
}
// Quantity Used: 1 Quantity Used: 1
// TODO for derivedEntitlementCert only
// Socket Limit: 4 Socket Limit: 2
Assert.assertEquals(hostEntitlementCert.orderNamespace.socketLimit, CandlepinTasks.getPoolProductAttributeValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId, "sockets"), "hostEntitlementCert.orderNamespace.socketLimit should match the data center pool's productAttribute sockets");
Assert.assertEquals(derivedEntitlementCert.orderNamespace.socketLimit, CandlepinTasks.getPoolDerivedProductAttributeValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId, "sockets"), "derivedEntitlementCert.orderNamespace.socketLimit should match the derivedProductAttribute sockets");
// RAM Limit: RAM Limit: 2
Assert.assertEquals(hostEntitlementCert.orderNamespace.ramLimit, CandlepinTasks.getPoolProductAttributeValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId, "ram"), "hostEntitlementCert.orderNamespace.ramLimit should match the data center pool's productAttribute ram");
Assert.assertEquals(derivedEntitlementCert.orderNamespace.ramLimit, CandlepinTasks.getPoolDerivedProductAttributeValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId, "ram"), "derivedEntitlementCert.orderNamespace.ramLimit should match the derivedProductAttribute ram");
// Core Limit: Core Limit: 4
Assert.assertEquals(hostEntitlementCert.orderNamespace.coreLimit, CandlepinTasks.getPoolProductAttributeValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId, "cores"), "hostEntitlementCert.orderNamespace.coreLimit should match the data center pool's productAttribute cores");
Assert.assertEquals(derivedEntitlementCert.orderNamespace.coreLimit, CandlepinTasks.getPoolDerivedProductAttributeValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId, "cores"), "derivedEntitlementCert.orderNamespace.coreLimit should match the derivedProductAttribute cores");
// Virt Limit: Virt Limit:
// TODO ignoring for now based on https://bugzilla.redhat.com/show_bug.cgi?id=983193#c2
// Virt Only: False Virt Only: True
String virtOnly = CandlepinTasks.getPoolProductAttributeValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId, "virt_only");
Assert.assertEquals(hostEntitlementCert.orderNamespace.virtOnly, virtOnly == null ? Boolean.valueOf(false) : Boolean.valueOf(virtOnly), "hostEntitlementCert.orderNamespace.virtOnly should match the data center pool's productAttribute virt_only");
// CandlepinTasks.getPoolDerivedProductAttributeValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId, "virt_only");
virtOnly = String.valueOf(true);
/* the derived pool virt_only should ALWAYS be true */
Assert.assertEquals(derivedEntitlementCert.orderNamespace.virtOnly, virtOnly == null ? Boolean.valueOf(false) : Boolean.valueOf(virtOnly), "derivedEntitlementCert.orderNamespace.virtOnly should match the derivedProductAttribute virt_only");
// Subscription: Subscription:
Assert.assertEquals(derivedEntitlementCert.orderNamespace.subscriptionNumber, hostEntitlementCert.orderNamespace.subscriptionNumber, "Subscription from the derived entitlement should match the host entitlement");
// Stacking ID: Stacking ID:
Assert.assertEquals(hostEntitlementCert.orderNamespace.stackingId, CandlepinTasks.getPoolProductAttributeValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId, "stacking_id"), "hostEntitlementCert.orderNamespace.stackingId should match the data center pool's productAttribute stacking_id");
Assert.assertEquals(derivedEntitlementCert.orderNamespace.stackingId, CandlepinTasks.getPoolDerivedProductAttributeValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId, "stacking_id"), "derivedEntitlementCert.orderNamespace.stackingId should match the derivedProductAttribute stacking_id");
// Warning Period: 30 Warning Period: 0
String warningPeriod = CandlepinTasks.getPoolProductAttributeValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId, "warning_period");
Assert.assertEquals(hostEntitlementCert.orderNamespace.warningPeriod, warningPeriod == null ? "0" : warningPeriod, "hostEntitlementCert.orderNamespace.warningPeriod should match the data center pool's productAttribute warning_period");
warningPeriod = CandlepinTasks.getPoolDerivedProductAttributeValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId, "warning_period");
Assert.assertEquals(derivedEntitlementCert.orderNamespace.warningPeriod, warningPeriod == null ? "0" : warningPeriod, "derivedEntitlementCert.orderNamespace.warningPeriod should match the derivedProductAttribute warning_period");
// Provides Management: False Provides Management: False
String providesManagement = CandlepinTasks.getPoolProductAttributeValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId, "management_enabled");
Assert.assertEquals(hostEntitlementCert.orderNamespace.providesManagement, providesManagement == null ? Boolean.valueOf(false) : Boolean.valueOf(providesManagement), "hostEntitlementCert.orderNamespace.providesManagement should match the data center pool's productAttribute management_enabled");
providesManagement = CandlepinTasks.getPoolDerivedProductAttributeValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId, "management_enabled");
Assert.assertEquals(derivedEntitlementCert.orderNamespace.providesManagement, providesManagement == null ? Boolean.valueOf(false) : Boolean.valueOf(providesManagement), "derivedEntitlementCert.orderNamespace.providesManagement should match the derivedProductAttribute management_enabled");
// for the sake of cleanup and to avoid this candlepin errors, let's unsubscribe from derivedEntitlementCert and then hostEntitlementCert
// ssh root@jsefler-6server.usersys.redhat.com subscription-manager unregister
// Stdout: Runtime Error No row with the given identifier exists: [org.candlepin.model.ProvidedProduct#8a90869341e61f7c0141e84e9ade3efd] at org.hibernate.UnresolvableObjectException.throwIfNull:65
// Stderr:
// ExitCode: 255
//
// ssh root@jsefler-6server.usersys.redhat.com subscription-manager unsubscribe --all
// Stdout:
// Stderr: Runtime Error No row with the given identifier exists: [org.candlepin.model.DerivedProvidedProduct#8a90869341e61f7c0141e84f2b9a3f0e] at org.hibernate.UnresolvableObjectException.throwIfNull:65
// ExitCode: 255
clienttasks.unsubscribeFromSerialNumber(derivedEntitlementCert.serialNumber);
clienttasks.unsubscribeFromSerialNumber(hostEntitlementCert.serialNumber);
}
use of rhsm.data.EntitlementCert in project rhsm-qe by RedHatQE.
the class DevSKUTests method testDevSku.
// Test methods ***********************************************************************
@// update=true, // uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-25335", "RHEL7-52092" }, level = DefTypes.Level.COMPONENT, component = "subscription-manager", testtype = @TestType(testtype = DefTypes.TestTypes.FUNCTIONAL, subtype1 = DefTypes.Subtypes.RELIABILITY, subtype2 = DefTypes.Subtypes.EMPTY), posneg = PosNeg.POSITIVE, importance = DefTypes.Importance.HIGH, automation = DefTypes.Automation.AUTOMATED, tags = "Tier1")
@Test(description = "given an available SKU, configure the system with custom facts dev_sku=SKU, register the system with auto-attach and verify several requirements of the attached entitlement", groups = { "Tier1Tests" }, dataProvider = "getDevSkuData", enabled = true)
public // @ImplementsNitrateTest(caseId=)
void testDevSku(Object bugzilla, String devSku, String devPlatform) throws JSONException, Exception {
// get the JSON product representation of the devSku
String resourcePath = "/products/" + devSku;
String ownerKey = sm_clientOrg;
if (sm_clientOrg == null)
ownerKey = clienttasks.getCurrentlyRegisteredOwnerKey();
if (SubscriptionManagerTasks.isVersion(servertasks.statusVersion, ">=", "2.0.0"))
resourcePath = "/owners/" + ownerKey + resourcePath;
JSONObject jsonDevSkuProduct = new JSONObject(CandlepinTasks.getResourceUsingRESTfulAPI(sm_clientUsername, sm_clientPassword, sm_serverUrl, resourcePath));
if (jsonDevSkuProduct.has("displayMessage")) {
// indicative that: // Product with ID 'dev-mkt-product' could not be found.
}
// instrument the system facts to behave as a vagrant image
Map<String, String> factsMap = new HashMap<String, String>();
factsMap.put("dev_sku", devSku);
factsMap.put("dev_platform", devPlatform);
clienttasks.createFactsFileWithOverridingValues(factsMap);
// mark the rhsm.log file
String logMarker = System.currentTimeMillis() + " Testing VerifyDevSku_Test...";
RemoteFileTasks.markFile(client, clienttasks.rhsmLogFile, logMarker);
// register with auto subscribe and force (to unregister anyone that is already registered)
SSHCommandResult registerResult = clienttasks.register(sm_clientUsername, sm_clientPassword, sm_clientOrg, null, null, null, null, true, null, null, (String) null, null, null, null, true, null, null, null, null, null);
// get the tail of the marked rhsm.log file
String logTail = RemoteFileTasks.getTailFromMarkedFile(client, clienttasks.rhsmLogFile, logMarker, null).trim();
// assert when /etc/candlepin/candlepin.conf candlepin.standalone = true (FYI: candlepin.standalone=false is synonymous with a hosted candlepin deployment)
// 2016-01-05 17:02:34,527 [DEBUG] subscription-manager:20144 @connection.py:530 - Making request: POST /candlepin/consumers/21800967-1d20-43a9-9bf3-07c5c7d41f61/entitlements
// 2016-01-05 17:02:34,802 [DEBUG] subscription-manager:20144 @connection.py:562 - Response: status=403, requestUuid=b88c0d1c-0816-4097-89d5-114020d86af1
// 2016-01-05 17:02:34,804 [WARNING] subscription-manager:20144 @managercli.py:201 - Error during auto-attach.
// 2016-01-05 17:02:34,805 [ERROR] subscription-manager:20144 @managercli.py:202 - Development units may only be used on hosted servers and with orgs that have active subscriptions.
// Traceback (most recent call last):
// File "/usr/share/rhsm/subscription_manager/managercli.py", line 197, in autosubscribe
// ents = cp.bind(consumer_uuid) # new style
// File "/usr/lib64/python2.6/site-packages/rhsm/connection.py", line 1148, in bind
// return self.conn.request_post(method)
// File "/usr/lib64/python2.6/site-packages/rhsm/connection.py", line 657, in request_post
// return self._request("POST", method, params)
// File "/usr/lib64/python2.6/site-packages/rhsm/connection.py", line 571, in _request
// self.validateResponse(result, request_type, handler)
// File "/usr/lib64/python2.6/site-packages/rhsm/connection.py", line 621, in validateResponse
// raise RestlibException(response['status'], error_msg, response.get('headers'))
// RestlibException: Development units may only be used on hosted servers and with orgs that have active subscriptions.
String expectedStdError = "Development units may only be used on hosted servers and with orgs that have active subscriptions.";
String expectedLogError = "RestlibException: " + expectedStdError;
if (servertasks.statusStandalone) {
Assert.assertEquals(registerResult.getStderr().trim(), expectedStdError, "When attempting to autosubscribe a consumer with a dev_sku fact against a candlepin.standalone=true server, stderr reports '" + expectedStdError + "'.");
// TEMPORARY WORKAROUND
boolean invokeWorkaroundWhileBugIsOpen = true;
// Bug 1493299 - exception handling for a negative dev_sku test is no longer being logged to rhsm.log
String bugId = "1493299";
try {
if (invokeWorkaroundWhileBugIsOpen && BzChecker.getInstance().isBugOpen(bugId)) {
log.fine("Invoking workaround for " + BzChecker.getInstance().getBugState(bugId).toString() + " Bugzilla " + bugId + ". (https://bugzilla.redhat.com/show_bug.cgi?id=" + bugId + ")");
SubscriptionManagerCLITestScript.addInvokedWorkaround(bugId);
} else {
invokeWorkaroundWhileBugIsOpen = false;
}
} catch (BugzillaAPIException be) {
/* ignore exception */
} catch (RuntimeException re) {
/* ignore exception */
}
if (invokeWorkaroundWhileBugIsOpen) {
throw new SkipException("Detected that candlepin status standalone=true. DevSku support is only applicable when /etc/candlepin/candlepin candlepin.standalone=false (typical of a hosted candlepin server), but skipped assertion that an rhsm.log error is thrown while bug '" + bugId + "' is open.");
} else
// END OF WORKAROUND
Assert.assertTrue(logTail.contains(expectedLogError), "When attempting to autosubscribe a consumer with a dev_sku fact against a candlepin.standalone=true server, an rhsm.log error is thrown stating '" + expectedLogError + "'.");
throw new SkipException("Detected that candlepin status standalone=true. DevSku support is only applicable when /etc/candlepin/candlepin candlepin.standalone=false (typical of a hosted candlepin server).");
} else {
Assert.assertTrue(!registerResult.getStderr().trim().contains(expectedStdError), "When attempting to autosubscribe a consumer with a dev_sku fact against a candlepin.standalone=false server, stderr does NOT report '" + expectedStdError + "'.");
Assert.assertTrue(!logTail.contains(expectedLogError), "When attempting to autosubscribe a consumer with a dev_sku fact against a candlepin.standalone=false server, an rhsm.log error is NOT thrown stating '" + expectedLogError + "'.");
}
// RestlibException: SKU product not available to this development unit: 'dev-mkt-product'
if (jsonDevSkuProduct.has("displayMessage")) {
expectedStdError = String.format("SKU product not available to this development unit: '%s'", devSku);
if (SubscriptionManagerTasks.isVersion(servertasks.statusVersion, ">=", "2.3.1-1")) {
// commit 0d5fefcfa8c1c2485921d2dee6633879b1e06931 Correct incorrect punctuation in user messages
expectedStdError = String.format("SKU product not available to this development unit: \"%s\"", devSku);
}
expectedLogError = "RestlibException: " + expectedStdError;
Assert.assertEquals(registerResult.getStderr().trim(), expectedStdError, "When attempting to autosubscribe a consumer with an unknown dev_sku fact against a candlepin.standalone=false server, stderr reports '" + expectedStdError + "'.");
// TEMPORARY WORKAROUND
boolean invokeWorkaroundWhileBugIsOpen = true;
// Bug 1493299 - exception handling for a negative dev_sku test is no longer being logged to rhsm.log
String bugId = "1493299";
try {
if (invokeWorkaroundWhileBugIsOpen && BzChecker.getInstance().isBugOpen(bugId)) {
log.fine("Invoking workaround for " + BzChecker.getInstance().getBugState(bugId).toString() + " Bugzilla " + bugId + ". (https://bugzilla.redhat.com/show_bug.cgi?id=" + bugId + ")");
SubscriptionManagerCLITestScript.addInvokedWorkaround(bugId);
} else {
invokeWorkaroundWhileBugIsOpen = false;
}
} catch (BugzillaAPIException be) {
/* ignore exception */
} catch (RuntimeException re) {
/* ignore exception */
}
if (invokeWorkaroundWhileBugIsOpen) {
throw new SkipException("Detected that dev_sku '" + devSku + "' was unknown, but skipped verification that a graceful error was logged to rhsm.log while bug '" + bugId + "' is open.");
} else
// END OF WORKAROUND
Assert.assertTrue(logTail.contains(expectedLogError), "When attempting to autosubscribe a consumer with an unknown dev_sku fact against a candlepin.standalone=false server, an rhsm.log error is thrown stating '" + expectedLogError + "'.");
throw new SkipException("Detected that dev_sku '" + devSku + "' was unknown. Verified that a graceful error was logged to rhsm.log.");
}
// assert only one entitlement was granted
List<EntitlementCert> entitlementCerts = clienttasks.getCurrentEntitlementCerts();
Assert.assertEquals(entitlementCerts.size(), 1, "After registering (with autosubscribe) a system with dev_sku fact '" + devSku + "', only one entitlement should be granted.");
EntitlementCert devSkuEntitlement = entitlementCerts.get(0);
ProductSubscription devSkuProductSubscription = clienttasks.getCurrentlyConsumedProductSubscriptions().get(0);
// assert that all of the known installed products are provided by the consumed entitlement
List<InstalledProduct> installedProducts = clienttasks.getCurrentlyInstalledProducts();
List<ProductCert> productCerts = clienttasks.getCurrentProductCerts();
Set installedProductIds = new HashSet<String>();
for (InstalledProduct installedProduct : installedProducts) {
// ignore installed products that are unknown to the candlepin product layer
resourcePath = "/products/" + installedProduct.productId;
if (SubscriptionManagerTasks.isVersion(servertasks.statusVersion, ">=", "2.0.0"))
resourcePath = "/owners/" + ownerKey + resourcePath;
JSONObject jsonProduct = new JSONObject(CandlepinTasks.getResourceUsingRESTfulAPI(sm_clientUsername, sm_clientPassword, sm_serverUrl, resourcePath));
if (jsonProduct.has("displayMessage")) {
// indicative that: // Product with ID '69' could not be found.
String expectedDisplayMessage = String.format("Product with UUID '%s' could not be found.", installedProduct.productId);
if (SubscriptionManagerTasks.isVersion(servertasks.statusVersion, ">=", "2.0.0")) {
expectedDisplayMessage = String.format("Product with ID '%s' could not be found.", installedProduct.productId);
}
if (SubscriptionManagerTasks.isVersion(servertasks.statusVersion, ">=", "2.3.1-1")) {
// commit 0d5fefcfa8c1c2485921d2dee6633879b1e06931 Correct incorrect punctuation in user messages
expectedDisplayMessage = String.format("Product with ID \"%s\" could not be found.", installedProduct.productId);
}
Assert.assertEquals(jsonProduct.getString("displayMessage"), expectedDisplayMessage);
log.info("Installed Product ID '" + installedProduct.productId + "' (" + installedProduct.productName + ") was not recognized by our candlepin server. Therefore this product will not be entitled by the devSku.");
} else {
installedProductIds.add(installedProduct.productId);
}
}
Set<String> entitledProductIds = new HashSet<String>();
for (ProductNamespace productNamespace : devSkuEntitlement.productNamespaces) entitledProductIds.add(productNamespace.id);
Assert.assertTrue(entitledProductIds.containsAll(installedProductIds) && entitledProductIds.size() == installedProductIds.size(), "All (and only) of the currently installed products known by the candlepin product layer are entitled by the devSku entitlement. (Actual entitled product ids " + entitledProductIds + ")");
// assert that all of the entitled product names are shown in the provides list of the consumed devSku product subscription
for (ProductNamespace productNamespace : devSkuEntitlement.productNamespaces) {
Assert.assertTrue(devSkuProductSubscription.provides.contains(productNamespace.name), "The consumed devSku Product Subscriptions provides installed product name '" + productNamespace.name + "'.");
}
// assert that all of the provided product content sets that match this system's arch and installed product tags are available in yum repos
List<String> yumRepos = clienttasks.getYumRepolist("all");
for (ContentNamespace contentNamespace : devSkuEntitlement.contentNamespaces) {
if (contentNamespace.type.equals("yum") && clienttasks.areAllRequiredTagsInContentNamespaceProvidedByProductCerts(contentNamespace, productCerts) && clienttasks.isArchCoveredByArchesInContentNamespace(clienttasks.arch, contentNamespace)) {
Assert.assertTrue(yumRepos.contains(contentNamespace.label), "Found entitled yum repo '" + contentNamespace.label + "' (" + contentNamespace.name + ") (which matches this system arch and installed product tags) among yum repolist all.");
} else {
Assert.assertTrue(!yumRepos.contains(contentNamespace.label), "Did NOT find entitled yum repo '" + contentNamespace.label + "' (" + contentNamespace.name + ") (which does not match this system arch and installed product tags) among yum repolist all.");
}
}
// assert that the entitled service_level defaults to "Self-Service" when not explicitly set by the dev_sku product
String devSkuServiceLevel = CandlepinTasks.getResourceAttributeValue(jsonDevSkuProduct, "support_level");
if (devSkuServiceLevel == null) {
String defaultServiceLevel = "Self-Service";
Assert.assertEquals(devSkuEntitlement.orderNamespace.supportLevel, defaultServiceLevel, "When no support_level attribute exists on the devSku product, the entitlement's order service level defaults to '" + defaultServiceLevel + "'.");
Assert.assertEquals(devSkuProductSubscription.serviceLevel, defaultServiceLevel, "When no support_level attribute exists on the devSku product, the entitled consumed product subscription service level defaults to '" + defaultServiceLevel + "'.");
} else {
Assert.assertEquals(devSkuEntitlement.orderNamespace.supportLevel, devSkuServiceLevel, "When a support_level attribute was set on the devSku product, the entitlement's order service level matches '" + devSkuServiceLevel + "'.");
Assert.assertEquals(devSkuProductSubscription.serviceLevel, devSkuServiceLevel, "When a support_level attribute was set on the devSku product, the consumed product subscription service level matches '" + devSkuServiceLevel + "'.");
}
// assert that the entitled expires_after defaults to 90 days after the registered consumer data when not explicitly set by the dev_sku product
ConsumerCert consumerCert = clienttasks.getCurrentConsumerCert();
Calendar expectedEndDate = Calendar.getInstance();
expectedEndDate.setTimeInMillis(consumerCert.validityNotBefore.getTimeInMillis());
if (SubscriptionManagerTasks.isVersion(servertasks.statusVersion, ">=", "2.0.30-1")) {
// commit 9302c8f57f37dd5ec3c4020770ac1675a87d99ba 1419576: Pre-date certs to ease clock skew issues
expectedEndDate.add(Calendar.HOUR, Integer.valueOf(1));
log.info("Due to Candlepin RFE Bug 1419576, we need to increment the expected expires_after by one hour to account for pre-dating the consumer identity's validityNotBefore date by one hour.");
}
String devSkuExpiresAfter = CandlepinTasks.getResourceAttributeValue(jsonDevSkuProduct, "expires_after");
if (devSkuExpiresAfter == null) {
// days
String defaultExpiresAfter = "90";
// TEMPORARY WORKAROUND
boolean invokeWorkaroundWhileBugIsOpen = true;
// Bug 1297863 - to account for daylight savings events, dev_sku (CDK) entitlements should add Calendar.DATE units of expires_after to establish the subscription end date
String bugId = "1297863";
try {
if (invokeWorkaroundWhileBugIsOpen && BzChecker.getInstance().isBugOpen(bugId)) {
log.fine("Invoking workaround for " + BzChecker.getInstance().getBugState(bugId).toString() + " Bugzilla " + bugId + ". (https://bugzilla.redhat.com/show_bug.cgi?id=" + bugId + ")");
SubscriptionManagerCLITestScript.addInvokedWorkaround(bugId);
} else {
invokeWorkaroundWhileBugIsOpen = false;
}
} catch (BugzillaAPIException be) {
/* ignore exception */
} catch (RuntimeException re) {
/* ignore exception */
}
if (invokeWorkaroundWhileBugIsOpen && clienttasks.redhatReleaseX.equals("6") && clienttasks.isPackageVersion("subscription-manager", ">=", "1.15")) {
// NOTE: This will be an hour off when the duration crosses the "Fall" back or "Spring" forward daylight saving dates.
expectedEndDate.add(Calendar.HOUR, Integer.valueOf(defaultExpiresAfter) * 24);
} else
// END OF WORKAROUND
expectedEndDate.add(Calendar.DATE, Integer.valueOf(defaultExpiresAfter));
// /*debugTesting*/expectedEndDate.add(Calendar.SECOND, 20); // to force an expected failure
// Assert.assertEquals(ConsumerCert.formatDateString(devSkuEntitlement.validityNotAfter), ConsumerCert.formatDateString(expectedEndDate), "When no expires_after attribute exists on the devSku product, the entitlement's validityNotAfter date defaults to '"+defaultExpiresAfter+"' days after the date the consumer was registered ("+ConsumerCert.formatDateString(consumerCert.validityNotBefore)+").");
// java.lang.AssertionError: When no expires_after attribute exists on the devSku product, the entitlement's validityNotAfter date defaults to '90' days after the date the consumer was registered (Jul 6 2016 12:19:18 EDT). expected:<Oct 4 2016 12:19:18 EDT> but was:<Oct 4 2016 12:19:17 EDT>
// allow for a few seconds of tolerance
Calendar expectedEndDateUpperTolerance = (Calendar) expectedEndDate.clone();
expectedEndDateUpperTolerance.add(Calendar.SECOND, +5);
Calendar expectedEndDateLowerTolerance = (Calendar) expectedEndDate.clone();
expectedEndDateLowerTolerance.add(Calendar.SECOND, -5);
Assert.assertTrue(devSkuEntitlement.validityNotAfter.before(expectedEndDateUpperTolerance) && devSkuEntitlement.validityNotAfter.after(expectedEndDateLowerTolerance), "When no expires_after attribute exists on the devSku product, the entitlement's validityNotAfter date defaults to '" + defaultExpiresAfter + "' days after the date the consumer was registered (" + ConsumerCert.formatDateString(consumerCert.validityNotBefore) + "). devSkuEntitlement.validityNotAfter expected: <" + ConsumerCert.formatDateString(expectedEndDate) + "> (withn a few seconds of tolerance of) actual: <" + ConsumerCert.formatDateString(devSkuEntitlement.validityNotAfter) + ">");
} else {
// TEMPORARY WORKAROUND
boolean invokeWorkaroundWhileBugIsOpen = true;
// Bug 1297863 - to account for daylight savings events, dev_sku (CDK) entitlements should add Calendar.DATE units of expires_after to establish the subscription end date
String bugId = "1297863";
try {
if (invokeWorkaroundWhileBugIsOpen && BzChecker.getInstance().isBugOpen(bugId)) {
log.fine("Invoking workaround for " + BzChecker.getInstance().getBugState(bugId).toString() + " Bugzilla " + bugId + ". (https://bugzilla.redhat.com/show_bug.cgi?id=" + bugId + ")");
SubscriptionManagerCLITestScript.addInvokedWorkaround(bugId);
} else {
invokeWorkaroundWhileBugIsOpen = false;
}
} catch (BugzillaAPIException be) {
/* ignore exception */
} catch (RuntimeException re) {
/* ignore exception */
}
if (invokeWorkaroundWhileBugIsOpen && clienttasks.redhatReleaseX.equals("6") && clienttasks.isPackageVersion("subscription-manager", ">=", "1.15")) {
// NOTE: This will be an hour off when the duration crosses the "Fall" back or "Spring" forward daylight saving dates.
expectedEndDate.add(Calendar.HOUR, Integer.valueOf(devSkuExpiresAfter) * 24);
} else
// END OF WORKAROUND
expectedEndDate.add(Calendar.DATE, Integer.valueOf(devSkuExpiresAfter));
// /*debugTesting*/expectedEndDate.add(Calendar.SECOND, 20); // to force an expected failure
// Assert.assertEquals(ConsumerCert.formatDateString(devSkuEntitlement.validityNotAfter), ConsumerCert.formatDateString(expectedEndDate), "When an expires_after attribute exists on the devSku product, the entitlement's validityNotAfter is '"+devSkuExpiresAfter+"' days after the date the consumer was registered ("+ConsumerCert.formatDateString(consumerCert.validityNotBefore)+").");
// java.lang.AssertionError: When an expires_after attribute exists on the devSku product, the entitlement's validityNotAfter is '75' days after the date the consumer was registered (Jul 3 2016 21:43:03 EDT). expected:<Sep 16 2016 21:43:03 EDT> but was:<Sep 16 2016 21:43:02 EDT>
// allow for a few seconds of tolerance
Calendar expectedEndDateUpperTolerance = (Calendar) expectedEndDate.clone();
expectedEndDateUpperTolerance.add(Calendar.SECOND, +5);
Calendar expectedEndDateLowerTolerance = (Calendar) expectedEndDate.clone();
expectedEndDateLowerTolerance.add(Calendar.SECOND, -5);
Assert.assertTrue(devSkuEntitlement.validityNotAfter.before(expectedEndDateUpperTolerance) && devSkuEntitlement.validityNotAfter.after(expectedEndDateLowerTolerance), "When an expires_after attribute exists on the devSku product, the entitlement's validityNotAfter is '" + devSkuExpiresAfter + "' days after the date the consumer was registered (" + ConsumerCert.formatDateString(consumerCert.validityNotBefore) + "). devSkuEntitlement.validityNotAfter expected: <" + ConsumerCert.formatDateString(expectedEndDate) + "> (withn a few seconds of tolerance of) actual: <" + ConsumerCert.formatDateString(devSkuEntitlement.validityNotAfter) + ">");
}
// assert that the pool consumed exists with quantity 1
resourcePath = "/pools/" + devSkuProductSubscription.poolId;
JSONObject jsonDevSkuPool = new JSONObject(CandlepinTasks.getResourceUsingRESTfulAPI(sm_clientUsername, sm_clientPassword, sm_serverUrl, resourcePath));
Assert.assertEquals(jsonDevSkuPool.getInt("quantity"), 1, "The quantity on pool '" + devSkuProductSubscription.poolId + "' generated for devSku product '" + devSku + "'.");
// assert that the pool consumed requires_consumer UUID that is currently registered
// "4a49b1a7-c616-42dd-b96d-62233a4c82b9"
String devSkuRequiresConsumer = CandlepinTasks.getPoolAttributeValue(jsonDevSkuPool, "requires_consumer");
Assert.assertEquals(devSkuRequiresConsumer, consumerCert.consumerid, "The requires_consumer attribute on pool '" + devSkuProductSubscription.poolId + "' generated for devSku product '" + devSku + "'.");
// assert that the pool generated has attribute dev_pool: true
// "true" or "false"
String devSkuDevPool = CandlepinTasks.getPoolAttributeValue(jsonDevSkuPool, "dev_pool");
Assert.assertEquals(Boolean.valueOf(devSkuDevPool), Boolean.TRUE, "The dev_pool attribute on pool '" + devSkuProductSubscription.poolId + "' generated for devSku product '" + devSku + "'.");
}
use of rhsm.data.EntitlementCert in project rhsm-qe by RedHatQE.
the class DockerTests method testContainerConfigurationsAreSetAfterAutoHealingAndUnsubscribing.
@// update=true, // uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-26766", "RHEL7-51755" }, level = DefTypes.Level.COMPONENT, component = "subscription-manager", testtype = @TestType(testtype = DefTypes.TestTypes.FUNCTIONAL, subtype1 = DefTypes.Subtypes.RELIABILITY, subtype2 = DefTypes.Subtypes.EMPTY), posneg = PosNeg.POSITIVE, importance = DefTypes.Importance.HIGH, automation = DefTypes.Automation.AUTOMATED, tags = "Tier1")
@Test(description = "Verify that entitlements providing containerimage content are copied to relevant directories when attached via auto-heal (as governed by the subscription-manager-plugin-container package)", groups = { "Tier1Tests", "blockedByBug-1165692", "blockedByBug-1344500", "blockedByBug-1343139" }, enabled = true)
public // @ImplementsNitrateTest(caseId=)
void testContainerConfigurationsAreSetAfterAutoHealingAndUnsubscribing() {
// get the list of registry_hostnames from /etc/rhsm/pluginconf.d/container_content.ContainerContentPlugin.conf
String registry_hostnames = clienttasks.getConfFileParameter(containerContentPluginFile.getPath(), "registry_hostnames");
List<String> registryHostnames = Arrays.asList(registry_hostnames.split(" *, *"));
// rhsm-test.redhat.com does NOT appear to come from a redhat.com CDN
if (!registryHostnames.contains("rhsm-test.redhat.com"))
clienttasks.updateConfFileParameter(containerContentPluginFile.getPath(), "registry_hostnames", registry_hostnames + "," + "rhsm-test.redhat.com");
// cdn.rhsm-test.redhat.com DOES appear to come from a redhat.com CDN because it matches regex ^cdn\.(?:.*\.)?redhat\.com$
if (!registryHostnames.contains("cdn.rhsm-test.redhat.com"))
clienttasks.updateConfFileParameter(containerContentPluginFile.getPath(), "registry_hostnames", registry_hostnames + "," + "cdn.rhsm-test.redhat.com");
registry_hostnames = clienttasks.getConfFileParameter(containerContentPluginFile.getPath(), "registry_hostnames");
registryHostnames = Arrays.asList(registry_hostnames.split(" *, *"));
// make sure we are Enforcing selinux
RemoteFileTasks.runCommandAndAssert(client, "setenforce 1", Integer.valueOf(0));
RemoteFileTasks.runCommandAndAssert(client, "getenforce", Integer.valueOf(0), "Enforcing", null);
// register the host, auto-heal, and get the granted entitlements
clienttasks.register(sm_clientUsername, sm_clientPassword, sm_clientOrg, null, null, null, null, false, null, null, (String) null, null, null, null, true, null, null, null, null, null);
clienttasks.autoheal(null, true, null, null, null, null, null);
clienttasks.restart_rhsmcertd(null, null, true);
List<EntitlementCert> entitlementCerts = clienttasks.getCurrentEntitlementCerts();
// verify that the entitlements which provide containerimage content are copied to registry_hostnames...
if (!verifyEntitlementsProvidingContainerImageContentAreCopiedToRegistryHostnames(entitlementCerts, registryHostnames))
throw new SkipException("None of the auto-attached subscriptions for this system provide content of type \"containerimage\".");
// individually unsubscribe from entitlements and assert the entitlement bearing a containerimage is also removed from registry_hostnames
for (EntitlementCert entitlementCert : entitlementCerts) {
List<ContentNamespace> containerImageContentNamespaces = ContentNamespace.findAllInstancesWithCaseInsensitiveMatchingFieldFromList("type", "containerimage", entitlementCert.contentNamespaces);
BigInteger serialNumber = clienttasks.getSerialNumberFromEntitlementCertFile(entitlementCert.file);
clienttasks.unsubscribeFromSerialNumber(serialNumber);
if (!containerImageContentNamespaces.isEmpty()) {
// after unsubscribing, assert that the entitlementCert was removed from the directory of registry_hostnames
for (String registryHostname : registryHostnames) {
File certFile = getRegistryHostnameCertFileFromEntitlementCert(registryHostname, entitlementCert);
File keyFile = getRegistryHostnameCertKeyFileFromEntitlementCert(registryHostname, entitlementCert);
Assert.assertTrue(!RemoteFileTasks.testExists(client, certFile.getPath()), "Entitlement cert '" + entitlementCert.orderNamespace.productName + "' providing a 'containerimage' (case insensitive) was removed from '" + certFile.getPath() + "' after unsubscribing.");
Assert.assertTrue(!RemoteFileTasks.testExists(client, keyFile.getPath()), "Corresponding entitlement key providing a 'containerimage' (case insensitive) was removed from '" + keyFile.getPath() + "' after unsubscribing.");
}
}
}
}
use of rhsm.data.EntitlementCert in project rhsm-qe by RedHatQE.
the class DockerTests method testAllHostEntitlementsAreSharedWithRunningDockerImage.
@// update=true, // uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL7-60185" }, level = DefTypes.Level.COMPONENT, component = "subscription-manager", testtype = @TestType(testtype = DefTypes.TestTypes.FUNCTIONAL, subtype1 = DefTypes.Subtypes.RELIABILITY, subtype2 = DefTypes.Subtypes.EMPTY), posneg = PosNeg.POSITIVE, importance = DefTypes.Importance.HIGH, automation = DefTypes.Automation.AUTOMATED, tags = "Tier1")
@Test(description = "verify a running container has access to all the entitlement certs from the host", groups = { "Tier1Tests", "blockedByBug-1353433" }, dependsOnMethods = { "testYumRepolistOnRunningDockerImageConsumedFromHostEntitlements" }, dataProvider = "getDockerImageData", enabled = true)
public // @ImplementsNitrateTest(caseId=)
void testAllHostEntitlementsAreSharedWithRunningDockerImage(Object bugzilla, String dockerImage) {
// Note: the secret sauce for sharing host files to a running container are these two soft links from the container to the host...
// [root@hp-sl2x170zg6-01 ~]# docker run --rm docker-registry.usersys.redhat.com/brew/rhel7:latest ls -l /etc/pki/entitlement-host
// lrwxrwxrwx. 1 root root 32 Jul 27 2015 /etc/pki/entitlement-host -> /run/secrets/etc-pki-entitlement
// [root@hp-sl2x170zg6-01 ~]# docker run --rm docker-registry.usersys.redhat.com/brew/rhel7:latest ls -l /etc/rhsm-host
// lrwxrwxrwx. 1 root root 17 Jul 27 2015 /etc/rhsm-host -> /run/secrets/rhsm
//
//
// [root@hp-sl2x170zg6-01 ~]# docker run --rm docker-registry.usersys.redhat.com/brew/rhel7:latest ls -R /run/secrets/
// /run/secrets/:
// etc-pki-entitlement
// rhel7.repo
// rhsm
//
// /run/secrets/etc-pki-entitlement:
// 6528422180188702523-key.pem
// 6528422180188702523.pem
//
// /run/secrets/rhsm:
// ca
// logging.conf
// pluginconf.d
// rhsm.conf
//
// /run/secrets/rhsm/ca:
// redhat-entitlement-authority.pem
// redhat-uep.pem
//
// /run/secrets/rhsm/pluginconf.d:
// container_content.ContainerContentPlugin.conf
// ostree_content.OstreeContentPlugin.conf
/* replacing this block with a new register to avoid RateLimitExceededException: Access rate limit exceeded
// make sure we are already registered (from VerifyYumRepolistOnRunningDockerImageConsumedFromHostEntitlements_Test)
Assert.assertNotNull(clienttasks.getCurrentConsumerCert(),"This test assumes a consumer has already been registered on '"+clienttasks.hostname+"'.");
// make sure we are auto-subscribed to a minimal number of entitlements
clienttasks.unsubscribe_(true, (BigInteger)null, null, null, null, null, null);
clienttasks.subscribe(true, null, (String)null, (String)null, null, null, null, null, null, null, null, null, null);
*/
clienttasks.register(sm_clientUsername, sm_clientPassword, sm_clientOrg, null, null, null, null, true, null, null, (String) null, null, null, null, true, false, null, null, null, null);
// get the current entitlements on the host
// [root@hp-sl2x170zg6-01 ~]# ls /etc/pki/entitlement | sort
// 162581295513405082-key.pem
// 162581295513405082.pem
String entitlementDir = clienttasks.getConfFileParameter(clienttasks.rhsmConfFile, "entitlementCertDir");
SSHCommandResult entitlementCertListingResult = client.runCommandAndWait("ls " + entitlementDir + " | sort");
// and get the EntitlementCerts
List<EntitlementCert> entitlementCerts = clienttasks.getCurrentEntitlementCerts();
// get the current entitlements in the container
// [root@hp-sl2x170zg6-01 ~]# docker run --rm docker-registry.usersys.redhat.com/brew/rhel7:latest ls /etc/pki/entitlement-host | sort
// 162581295513405082-key.pem
// 162581295513405082.pem
SSHCommandResult entitlementHostCertListingResult = client.runCommandAndWait("docker run --rm " + dockerImage + " ls " + entitlementHostDir + " | sort");
// and get the EntitlementCerts
clienttasks.sshCommandRunner.runCommandAndWaitWithoutLogging("docker run --rm " + dockerImage + " find " + entitlementHostDir.replaceAll("/$", "") + "/" + " -regex \"/.+/[0-9]+.pem\" -exec rct cat-cert {} \\;");
String certificates = clienttasks.sshCommandRunner.getStdout();
List<EntitlementCert> entitlementHostCerts = EntitlementCert.parse(certificates);
// Test 1A: assert the listed filenames match
Assert.assertEquals(entitlementHostCertListingResult.getStdout().trim(), entitlementCertListingResult.getStdout().trim(), "The entitlement cert files accessible in directory '" + entitlementHostDir + "' within a running container match the entitlment cert files found in the host's directory '" + entitlementDir + "'.");
// Test 1B: assert entitlementHostCerts are equivalent to entitlementCerts
for (EntitlementCert entitlementCert : entitlementCerts) {
EntitlementCert entitlementHostCert = EntitlementCert.findFirstInstanceWithMatchingFieldFromList("serialString", entitlementCert.serialString, entitlementHostCerts);
Assert.assertNotNull(entitlementHostCert, "Found entitlement serial '" + entitlementCert.serialNumber + "' from running container that matches entitlement serial from the host.");
Assert.assertEquals(entitlementHostCert.productNamespaces.size(), entitlementCert.productNamespaces.size(), "Entitlement serial '" + entitlementCert.serialNumber + "' from running container has the same number of productNamespaces as the host's entitlement.");
Assert.assertEquals(entitlementHostCert.contentNamespaces.size(), entitlementCert.contentNamespaces.size(), "Entitlement serial '" + entitlementCert.serialNumber + "' from running container has the same number of contentNamespaces as the host's entitlement.");
// TODO: could add more precise equivalence to EntitlementCert comparison (implement a .equals method within EntitlementCert)
}
// now let's attach more entitlements on the host and make sure they are also available in the container.
clienttasks.subscribeToTheCurrentlyAllAvailableSubscriptionPoolsCollectively();
// get the current entitlements on the host
entitlementCertListingResult = client.runCommandAndWait("ls " + entitlementDir + " | sort");
// get the current entitlements in the container
entitlementHostCertListingResult = client.runCommandAndWait("docker run --rm " + dockerImage + " ls " + entitlementHostDir + " | sort");
// Test 2: assert the listed filenames match (after more entitlements have been attached to the host)
Assert.assertEquals(entitlementHostCertListingResult.getStdout().trim(), entitlementCertListingResult.getStdout().trim(), "The entitlement cert files accessible in directory '" + entitlementHostDir + "' within a running container match the entitlment cert files found in the host's directory '" + entitlementDir + "'.");
}
use of rhsm.data.EntitlementCert in project rhsm-qe by RedHatQE.
the class SubscriptionManagerTasks method getCurrentEntitlementCerts.
public List<EntitlementCert> getCurrentEntitlementCerts() {
if (false) {
// effectively commented out
// STRANGELY THIS ALGORITHM OCCASIONALY TAKES MORE THAN 30 MIN (sshCommandRunner emergencyTimeout > 18000000lMS); LET'S TRY A LESS AGRESSIVE ALGORITHM
// 2018-02-22 15:22:57.940 FINE: ssh root@bkr-hv03-guest12.dsal.lab.eng.bos.redhat.com find /etc/pki/entitlement -regex "/.+/[0-9]+.pem" -exec rct cat-cert {} \;
// 2018-02-22 15:52:58.081 SEVERE: Test Failed: testReposListPreservesSimultaneousEnablementOfRedhatRepos
// java.lang.RuntimeException: net.schmizz.sshj.connection.ConnectionException: Timeout expired
// at com.redhat.qe.tools.SSHCommandRunner.run(SSHCommandRunner.java:177)
// at com.redhat.qe.tools.SSHCommandRunner.runCommand(SSHCommandRunner.java:317)
// at com.redhat.qe.tools.SSHCommandRunner.runCommandAndWait(SSHCommandRunner.java:354)
// at com.redhat.qe.tools.SSHCommandRunner.runCommandAndWaitWithoutLogging(SSHCommandRunner.java:337)
// at rhsm.cli.tasks.SubscriptionManagerTasks.getCurrentEntitlementCerts(SubscriptionManagerTasks.java:2305)
sshCommandRunner.runCommandAndWaitWithoutLogging("find " + entitlementCertDir + " -regex \"/.+/[0-9]+.pem\" -exec rct cat-cert {} \\;");
String certificates = sshCommandRunner.getStdout();
return EntitlementCert.parse(certificates);
}
List<EntitlementCert> entitlementCerts = new ArrayList<EntitlementCert>();
for (File serialPemFile : getCurrentEntitlementCertFiles()) {
entitlementCerts.add(getEntitlementCertFromEntitlementCertFile(serialPemFile));
}
return entitlementCerts;
}
Aggregations