use of rhsm.data.ProductSubscription in project rhsm-qe by RedHatQE.
the class MigrationTests method testRhnMigrateClassicToRhsm.
// rhn-migrate-classic-to-rhsm 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-20111", "RHEL7-51115" }, 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 = "Register system using RHN Classic and then Execute migration tool rhn-migrate-classic-to-rhsm with options after adding RHN Channels", groups = { "Tier1Tests", "RhnMigrateClassicToRhsm_Test", "blockedByBug-966745", "blockedByBug-840169", "blockedbyBug-878986", "blockedByBug-1052297", "blockedByBug-1111258", "blockedByBug-1512948", "blockedByBug-1516832" }, dependsOnMethods = {}, dataProvider = "RhnMigrateClassicToRhsmData", enabled = true)
public // @ImplementsNitrateTest(caseId=130764,130762) // TODO some expected yum repo assertions are not yet automated
void testRhnMigrateClassicToRhsm(Object bugzilla, String rhnreg_ksUsername, String rhnreg_ksPassword, String rhnHostname, List<String> rhnChannelsToAdd, String options, String rhnUsername, String rhnPassword, String rhsmUsername, String rhsmPassword, String rhsmOrg, Integer serviceLevelIndex, String serviceLevelExpected) throws JSONException {
if (sm_rhnHostname.equals(""))
throw new SkipException("This test requires access to RHN Classic or Satellite 5.");
if (Integer.valueOf(clienttasks.redhatReleaseX) >= 7 && clienttasks.arch.equals("ppc64le"))
throw new SkipException("Use of rhn-migrate-classic-to-rhsm is not necessary on RHEL '" + client1tasks.redhatReleaseX + "' arch '" + clienttasks.arch + "' since this product was not released on RHN Classic.");
if (Integer.valueOf(clienttasks.redhatReleaseX) >= 7 && clienttasks.arch.equals("aarch64"))
throw new SkipException("Use of rhn-migrate-classic-to-rhsm is not necessary on RHEL '" + client1tasks.redhatReleaseX + "' arch '" + clienttasks.arch + "' since this product was not released on RHN Classic.");
if (false) {
// TODO maybe this should go after the unregister and removeAll commands
// make sure our serverUrl is configured to it's original good value
restoreOriginallyConfiguredServerUrl();
// make sure we are NOT registered to RHSM
clienttasks.unregister(null, null, null, null);
// deleting the currently installed product certs
clienttasks.removeAllCerts(false, false, true);
clienttasks.removeAllFacts();
} else {
// TODO: 8/12/2013 Attempting the following logic in response to above TODO
// make sure we are NOT registered to RHSM (and system is clean from prior test) ignoring errors like:
// ssh root@cloud-qe-9.idm.lab.bos.redhat.com subscription-manager unregister
// Stdout: Runtime Error Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [org.candlepin.model.Pool#8a99f9823fc4919b013fc49408a302b7] at org.hibernate.persister.entity.AbstractEntityPersister.check:1,782
// Stderr:
// ExitCode: 255
clienttasks.unregister_(null, null, null, null);
clienttasks.removeAllCerts(true, true, true);
clienttasks.removeAllFacts();
restoreOriginallyConfiguredServerUrl();
}
// randomly remove a benign rhn classic package (just to add a little unnecessary fun)
if (randomGenerator.nextBoolean() && clienttasks.isPackageInstalled("osad"))
clienttasks.yumRemovePackage("osad");
if (randomGenerator.nextBoolean() && clienttasks.isPackageInstalled("openscap"))
clienttasks.yumRemovePackage("openscap");
// register to RHN Classic
String rhnSystemId = clienttasks.registerToRhnClassic(rhnreg_ksUsername, rhnreg_ksPassword, rhnHostname);
Assert.assertTrue(clienttasks.isRhnSystemIdRegistered(rhnreg_ksUsername, rhnreg_ksPassword, rhnHostname, rhnSystemId), "Confirmed that rhn systemId '" + rhnSystemId + "' is currently registered.");
// subscribe to more RHN Classic channels
if (rhnChannelsToAdd.size() > 0)
addRhnClassicChannels(rhnreg_ksUsername, rhnreg_ksPassword, rhnChannelsToAdd);
// get a list of the consumed RHN Classic channels
List<String> rhnChannelsConsumed = clienttasks.getCurrentRhnClassicChannels();
if (rhnChannelsToAdd.size() > 0)
Assert.assertTrue(rhnChannelsConsumed.containsAll(rhnChannelsToAdd), "All of the RHN Classic channels added appear to be consumed.");
// get a map of the productid.js file before we attempt migration
Map<String, List<String>> productIdRepoMapBeforeMigration = clienttasks.getProductIdToReposMap();
// get the product cert filenames that we should expect rhn-migrate-classic-to-rhsm to copy (or use the ones supplied to the @Test)
Set<String> expectedMigrationProductCertFilenames = getExpectedMappedProductCertFilenamesCorrespondingToChannels(rhnChannelsConsumed);
// screw up the currently configured [server]hostname:port/prefix when the command line options specify a new URL
if (options.contains("--serverurl") || options.contains("--destination-url")) {
log.info("Configuring a bad server hostname:port/prefix to test that the specified --serverurl can override it...");
List<String[]> listOfSectionNameValues = new ArrayList<String[]>();
if (doesStringContainMatches(options, "(--serverurl|--destination-url)=(https://)?[\\w\\.-]+")) {
// hostname
listOfSectionNameValues.add(new String[] { "server", "hostname", "bad-hostname.com" });
}
if (doesStringContainMatches(options, "(--serverurl|--destination-url)=(https://)?[\\w\\.-]+:\\d+")) {
// port
listOfSectionNameValues.add(new String[] { "server", "port", "000" });
}
if (doesStringContainMatches(options, "(--serverurl|--destination-url)=(https://)?[\\w\\.-]+(:\\d+)?/\\w+")) {
// prefix
listOfSectionNameValues.add(new String[] { "server", "prefix", "/bad-prefix" });
}
clienttasks.config(null, null, true, listOfSectionNameValues);
}
// execute rhn-migrate-classic-to-rhsm with options
SSHCommandResult sshCommandResult = executeRhnMigrateClassicToRhsm(options, rhnUsername, rhnPassword, rhsmUsername, rhsmPassword, rhsmOrg, null, serviceLevelIndex);
// assert valid usage
if (sshCommandResult.getStdout().contains("Usage: rhn-migrate-classic-to-rhsms")) {
Assert.fail("Detected a usage error.");
}
// get a map of the productid.js file after we attempt migration
Map<String, List<String>> productIdRepoMapAfterMigration = clienttasks.getProductIdToReposMap();
// assert the exit code
checkForKnownBug881952(sshCommandResult);
checkForKnownBug1130637(sshCommandResult);
String expectedMsg;
if (!getProductCertFilenamesContainingNonUniqueProductIds(expectedMigrationProductCertFilenames).isEmpty()) {
log.warning("The RHN Classic channels currently consumed map to multiple product certs that share the same product ID " + getProductCertFilenamesContainingNonUniqueProductIds(expectedMigrationProductCertFilenames) + ". We must abort in this case. Therefore, the " + rhnMigrateTool + " command should have exited with code 1.");
// TEMPORARY WORKAROUND FOR BUG
// Bug 1006985 - rhn-migrate-classic-to-rhsm should abort when it encounters RHN channels that map to different products certs that share the same productId
String bugId = "1006985";
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("The remainder of this test is blocked by bug " + bugId + ". There is no workaround.");
}
// END OF WORKAROUND
// +-----------------------------------------------------+
// Unable to continue migration!
// +-----------------------------------------------------+
// You are subscribed to channels that have conflicting product certificates.
// The following channels map to product ID 69:
// rhel-x86_64-rhev-agent-6-server
// rhel-x86_64-rhev-agent-6-server-beta
// rhel-x86_64-rhev-agent-6-server-beta-debuginfo
// rhel-x86_64-rhev-agent-6-server-debuginfo
// rhel-x86_64-server-6
// rhel-x86_64-server-6-cf-tools-1
// rhel-x86_64-server-6-cf-tools-1-beta
// rhel-x86_64-server-6-cf-tools-1-beta-debuginfo
// rhel-x86_64-server-6-cf-tools-1-debuginfo
// Reduce the number of channels per product ID to 1 and run migration again.
// To remove a channel, use 'rhn-channel --remove --channel=<conflicting_channel>'.
// TODO Improve the expectedMsg to better assert the list of conflicting channels
expectedMsg = "Unable to continue migration!";
Assert.assertTrue(sshCommandResult.getStdout().contains(expectedMsg), "Stdout from call to '" + rhnMigrateTool + " " + options + "' contains message: " + expectedMsg);
Assert.assertEquals(sshCommandResult.getExitCode(), new Integer(1), "ExitCode from call to '" + rhnMigrateTool + " " + options + "' when currently consumed RHN Classic channels map to multiple productCerts sharing the same productId.");
Assert.assertTrue(clienttasks.isRhnSystemRegistered(), "This system is still registered using RHN Classic when currently consumed RHN Classic channels map to multiple productCerts sharing the same productId.");
// assert that no product certs have been copied yet
// OLD Assert.assertEquals(clienttasks.getCurrentlyInstalledProducts().size(), 0, "No productCerts have been migrated when "+rhnMigrateTool+" aborts because the currently consumed RHN Classic channels map to multiple productCerts sharing the same productId.");
Assert.assertEquals(clienttasks.getProductCerts(clienttasks.productCertDir).size(), 0, "No productCerts have been migrated when " + rhnMigrateTool + " aborts because the currently consumed RHN Classic channels map to multiple productCerts sharing the same productId.");
// assert that we are not yet registered to RHSM
Assert.assertNull(clienttasks.getCurrentConsumerCert(), "We should NOT be registered to RHSM when " + rhnMigrateTool + " aborts because the currently consumed RHN Classic channels map to multiple productCerts sharing the same productId.");
// assert that we are still registered to RHN
Assert.assertTrue(clienttasks.isRhnSystemIdRegistered(rhnreg_ksUsername, rhnreg_ksPassword, rhnHostname, rhnSystemId), "Confirmed that rhn systemId '" + rhnSystemId + "' is still registered since our migration attempt aborts because the currently consumed RHN Classic channels map to multiple productCerts sharing the same productId.");
// assert that the rhnplugin is still enabled
Assert.assertEquals(clienttasks.getConfFileParameter(clienttasks.yumPluginConfFileForRhn, "enabled"), "1", "The enabled yum plugin configuration for RHN.");
// assert that productid.js is unchanged
Assert.assertTrue(productIdRepoMapBeforeMigration.keySet().containsAll(productIdRepoMapAfterMigration.keySet()) && productIdRepoMapAfterMigration.keySet().containsAll(productIdRepoMapBeforeMigration.keySet()), "The '" + clienttasks.productIdJsonFile + "' productIds remain unchanged when " + rhnMigrateTool + " aborts because the currently consumed RHN Classic channels map to multiple productCerts sharing the same productId.");
for (String productId : productIdRepoMapBeforeMigration.keySet()) {
Assert.assertTrue(productIdRepoMapBeforeMigration.get(productId).containsAll(productIdRepoMapAfterMigration.get(productId)) && productIdRepoMapAfterMigration.get(productId).containsAll(productIdRepoMapBeforeMigration.get(productId)), "The '" + clienttasks.productIdJsonFile + "' productIds repos for '" + productId + "' remain unchanged when " + rhnMigrateTool + " aborts because the currently consumed RHN Classic channels map to multiple productCerts sharing the same productId.");
}
return;
} else if (!areAllChannelsMapped(rhnChannelsConsumed) && !options.contains("-f")) /*--force*/
{
// when not all of the rhnChannelsConsumed have been mapped to a productCert and no --force has been specified.
log.warning("Not all of the channels are mapped to a product cert. Therefore, the " + rhnMigrateTool + " command should have exited with code 1.");
expectedMsg = "Use --force to ignore these channels and continue the migration.";
Assert.assertTrue(sshCommandResult.getStdout().contains(expectedMsg), "Stdout from call to '" + rhnMigrateTool + " " + options + "' contains message: " + expectedMsg);
Assert.assertEquals(sshCommandResult.getExitCode(), new Integer(1), "ExitCode from call to '" + rhnMigrateTool + " " + options + "' when any of the channels are not mapped to a productCert.");
Assert.assertTrue(clienttasks.isRhnSystemRegistered(), "This system is still registered using RHN Classic when rhn-migrate-classic-to-rhsm requires --force to continue.");
// assert that no product certs have been copied yet
Assert.assertEquals(clienttasks.getCurrentlyInstalledProducts().size(), 0, "No productCerts have been migrated when " + rhnMigrateTool + " requires --force to continue.");
// assert that we are not yet registered to RHSM
Assert.assertNull(clienttasks.getCurrentConsumerCert(), "We should NOT be registered to RHSM when " + rhnMigrateTool + " requires --force to continue.");
// assert that we are still registered to RHN
Assert.assertTrue(clienttasks.isRhnSystemIdRegistered(rhnreg_ksUsername, rhnreg_ksPassword, rhnHostname, rhnSystemId), "Confirmed that rhn systemId '" + rhnSystemId + "' is still registered since our migration attempt requires --force to continue.");
// assert that the rhnplugin is still enabled
Assert.assertEquals(clienttasks.getConfFileParameter(clienttasks.yumPluginConfFileForRhn, "enabled"), "1", "The enabled yum plugin configuration for RHN.");
// assert that productid.js is unchanged
Assert.assertTrue(productIdRepoMapBeforeMigration.keySet().containsAll(productIdRepoMapAfterMigration.keySet()) && productIdRepoMapAfterMigration.keySet().containsAll(productIdRepoMapBeforeMigration.keySet()), "The '" + clienttasks.productIdJsonFile + "' productIds remain unchanged when " + rhnMigrateTool + " requires --force to continue.");
for (String productId : productIdRepoMapBeforeMigration.keySet()) {
Assert.assertTrue(productIdRepoMapBeforeMigration.get(productId).containsAll(productIdRepoMapAfterMigration.get(productId)) && productIdRepoMapAfterMigration.get(productId).containsAll(productIdRepoMapBeforeMigration.get(productId)), "The '" + clienttasks.productIdJsonFile + "' productIds repos for '" + productId + "' remain unchanged when " + rhnMigrateTool + " requires --force to continue.");
}
return;
} else if (rhnChannelsConsumed.isEmpty()) {
log.warning("Modifying expected results when the current RHN Classically registered system is not consuming any RHN channels.");
String expectedStdout = "Problem encountered getting the list of subscribed channels. Exiting.";
// changed by commit c0f8052ec2b5b7b5c736eb626e381aef0e5327e5
if (clienttasks.isPackageVersion("subscription-manager-migration", ">=", "1.13.1"))
expectedStdout = "Problem encountered getting the list of subscribed channels. See /var/log/rhsm/rhsm.log for more details.";
Assert.assertTrue(sshCommandResult.getStdout().trim().endsWith(expectedStdout), "The expected stdout result from call to '" + rhnMigrateTool + "' when no RHN Classic channels are being consumed: " + expectedStdout);
// Assert.assertEquals(sshCommandResult.getExitCode(), new Integer(1), "The expected exit code from call to '"+rhnMigrateTool+"' when no RHN Classic channels are being consumed."); // the exitCode can be altered by the expect script rhn-migrate-classic-to-rhsm.tcl when the final arg slaIndex is non-null; therefore don't bother asserting exitCode; asserting stdout is sufficient
Assert.assertTrue(clienttasks.isRhnSystemIdRegistered(rhnreg_ksUsername, rhnreg_ksPassword, rhnHostname, rhnSystemId), "Confirmed that rhn systemId '" + rhnSystemId + "' is still registered after '" + rhnMigrateTool + "' exits due to: " + expectedStdout);
// assert that productid.js is unchanged
Assert.assertTrue(productIdRepoMapBeforeMigration.keySet().containsAll(productIdRepoMapAfterMigration.keySet()) && productIdRepoMapAfterMigration.keySet().containsAll(productIdRepoMapBeforeMigration.keySet()), "The '" + clienttasks.productIdJsonFile + "' productIds remain unchanged when " + rhnMigrateTool + " exits due to: " + expectedStdout);
for (String productId : productIdRepoMapBeforeMigration.keySet()) {
Assert.assertTrue(productIdRepoMapBeforeMigration.get(productId).containsAll(productIdRepoMapAfterMigration.get(productId)) && productIdRepoMapAfterMigration.get(productId).containsAll(productIdRepoMapBeforeMigration.get(productId)), "The '" + clienttasks.productIdJsonFile + "' productIds repos for '" + productId + "' remain unchanged when " + rhnMigrateTool + " exits due to: " + expectedStdout);
}
return;
}
Assert.assertEquals(sshCommandResult.getExitCode(), new Integer(0), "ExitCode from call to '" + rhnMigrateTool + " " + options + "' when all of the channels are mapped.");
// assert product certificates are copied
expectedMsg = String.format("Product certificates copied successfully to %s !", clienttasks.productCertDir);
expectedMsg = String.format("Product certificates copied successfully to %s", clienttasks.productCertDir);
// Bug 852107 - String Update: rhn-migrate-classic-to-rhsm output
expectedMsg = String.format("Product certificates installed successfully to %s.", clienttasks.productCertDir);
Assert.assertTrue(sshCommandResult.getStdout().contains(expectedMsg), "Stdout from call to '" + rhnMigrateTool + " " + options + "' contains message: " + expectedMsg);
// assert that the expected product certs mapped from the consumed RHN Classic channels are now installed
// OLD List<ProductCert> migratedProductCerts = clienttasks.getCurrentProductCerts();
// OLD Assert.assertEquals(clienttasks.getCurrentlyInstalledProducts().size(), expectedMigrationProductCertFilenames.size(), "The number of productCerts installed after running "+rhnMigrateTool+" with "+options+". (If this fails, one of these migration certs may have clobbered the other "+expectedMigrationProductCertFilenames+")");
List<ProductCert> migratedProductCerts = clienttasks.getProductCerts(clienttasks.productCertDir);
Assert.assertEquals(migratedProductCerts.size(), expectedMigrationProductCertFilenames.size(), "The number of productCerts in '" + clienttasks.productCertDir + "' after running " + rhnMigrateTool + " with options '" + options + "'. (If this fails, one of these migration certs may have clobbered the other " + expectedMigrationProductCertFilenames + ")");
for (String expectedMigrationProductCertFilename : expectedMigrationProductCertFilenames) {
ProductCert expectedMigrationProductCert = clienttasks.getProductCertFromProductCertFile(new File(baseProductsDir + "/" + expectedMigrationProductCertFilename));
Assert.assertTrue(migratedProductCerts.contains(expectedMigrationProductCert), "The newly migrated product certs in '" + clienttasks.productCertDir + "' includes the expected migration productCert: " + expectedMigrationProductCert);
}
// assert the expected migration.* facts are set
// [root@ibm-x3620m3-01 ~]# subscription-manager facts --list | grep migration
Map<String, String> factMap = clienttasks.getFacts();
if (clienttasks.isPackageVersion("subscription-manager-migration", ">=", "1.13")) {
// migration.classic_system_id: 1000021964
// migration.migrated_from: https://sat-56-server.usersys.redhat.com/XMLRPC
// migration.migration_date: 2015-02-07T18:42:18.744943
// migration.classic_system_id: 1033298347
// migration.migrated_from: https://xmlrpc.rhn.code.stage.redhat.com/XMLRPC
// migration.migration_date: 2015-02-24T19:52:14.685785
String expectedMigrationFromFact = rhnHostname + "/XMLRPC";
if (!expectedMigrationFromFact.startsWith("http"))
expectedMigrationFromFact = "https://xmlrpc." + expectedMigrationFromFact;
Assert.assertEquals(factMap.get(migrationFromFact), expectedMigrationFromFact, "The migration fact '" + migrationFromFact + "' should be set after running " + rhnMigrateTool + " with " + options + ".");
} else {
// migration.classic_system_id: 1023061526
// migration.migrated_from: rhn_hosted_classic
// migration.migration_date: 2012-07-13T18:51:44.254543
Assert.assertEquals(factMap.get(migrationFromFact), "rhn_hosted_classic", "The migration fact '" + migrationFromFact + "' should be set after running " + rhnMigrateTool + " with " + options + ".");
}
Assert.assertEquals(factMap.get(migrationSystemIdFact), rhnSystemId, "The migration fact '" + migrationSystemIdFact + "' should be set after running " + rhnMigrateTool + " with " + options + ".");
Assert.assertNotNull(factMap.get(migrationDateFact), "The migration fact '" + migrationDateFact + "' should be set after running " + rhnMigrateTool + " with " + options + ".");
// tolerance in seconds to assert that the migration_date facts was set within the last few seconds
int tol = 300;
Calendar migrationDate;
/* 10-23-2015 DELETEME AFTER PROVING THAT migrationDateFactWithGMTOffsetTimeZone WORKS
// if (client.runCommandAndWait("date +%Z").getStdout().trim().endsWith("DT")) { // are we currently on daylight summer/savings time?
// // determined on Mar 9, 2015 (day after Daylight Summer/Savings Time starts), when date +%Z returns EDT, passing passing null for timeZone will correctly pass the migrationDateFact assertion (Note: passing "EDT" will actually screw it up)
// migrationDate = parseDateStringUsingDatePattern(factMap.get(migrationDateFact), "yyyy-MM-dd'T'HH:mm:ss", null); // NOTE: The .SSS milliseconds was dropped from the date pattern because it was getting confused as seconds from the six digit value in migration.migration_date: 2012-08-08T11:11:15.818782
// } else {
// migrationDate = parseDateStringUsingDatePattern(factMap.get(migrationDateFact), "yyyy-MM-dd'T'HH:mm:ss", client.runCommandAndWait("date +%Z").getStdout().trim()); // NOTE: The .SSS milliseconds was dropped from the date pattern because it was getting confused as seconds from the six digit value in migration.migration_date: 2012-08-08T11:11:15.818782
// }
*/
// the time zone is absent from the value of the migration.migration_date fact (arguably an RFE bug), let's append the GMTOffsetTimeZone of the client
// [root@ibm-hs22-04 ~]# subscription-manager facts | grep migration_date
// migration.migration_date: 2015-10-24T00:01:54.040880
// [root@ibm-hs22-04 ~]# date -d "2015-10-24T00:01:54.040880" -Iseconds
// 2015-10-24T00:01:54+0200
// [root@ibm-hs22-04 ~]# date +%Z
// CEST
String migrationDateFactWithGMTOffsetTimeZone = client.runCommandAndWait("date -d \"" + factMap.get(migrationDateFact) + "\" -Iseconds").getStdout().trim();
String systemTimeZone = client.runCommandAndWait("date +%Z").getStdout().trim();
String systemTimeZoneHHMM = client.runCommandAndWait("date +%:z").getStdout().trim();
migrationDate = parseDateStringUsingDatePattern(migrationDateFactWithGMTOffsetTimeZone, "yyyy-MM-dd'T'HH:mm:ssZ", systemTimeZone);
// seconds since 1970-01-01 00:00:00 UTC (will be the same value no matter what TimeZone the system is in
long systemTimeInSeconds = Long.valueOf(client.runCommandAndWait("date +%s").getStdout().trim());
long migratTimeInSeconds = migrationDate.getTimeInMillis() / 1000;
// workaround on RHEL5 and RHEL6 for coreutils bug
if (Integer.valueOf(clienttasks.redhatReleaseX) < 7) {
// bump up the time in seconds by taking 7 hours and subtracting the time zone HH:MM offset) TODO: determine if this formula works during daylight savings time.
migratTimeInSeconds += 7 * /*hours*/
60 * 60 - (Integer.parseInt(systemTimeZoneHHMM.split(":")[0]) * /*hours*/
60 * 60 + Integer.parseInt(systemTimeZoneHHMM.split(":")[1]) * /*minutes*/
60);
}
Assert.assertTrue(systemTimeInSeconds - tol < migratTimeInSeconds && migratTimeInSeconds < systemTimeInSeconds + tol, "The migration date fact '" + factMap.get(migrationDateFact) + "' was set within the last '" + tol + "' seconds (local system time). Actual diff='" + String.valueOf(systemTimeInSeconds - migratTimeInSeconds) + "' seconds.");
// assert we are no longer registered to RHN Classic
// Two possible results can occur when the rhn-migrate-classic-to-rhsm script attempts to unregister from RHN Classic. We need to tolerate both cases...
String successfulUnregisterMsg = "System successfully unregistered from RHN Classic.";
if (clienttasks.isPackageVersion("subscription-manager-migration", ">=", "1.13"))
successfulUnregisterMsg = "System successfully unregistered from legacy server.";
String unsuccessfulUnregisterMsg = "Did not receive a completed unregistration message from RHN Classic for system " + rhnSystemId + "." + "\n" + "Please investigate on the Customer Portal at https://access.redhat.com.";
if (sshCommandResult.getStdout().contains(successfulUnregisterMsg)) {
// Case 1: number of subscribed channels is low and all communication completes in a timely fashion. Here is a snippet from stdout:
// Preparing to unregister system from RHN Classic ...
// System successfully unregistered from RHN Classic.
Assert.assertTrue(sshCommandResult.getStdout().contains(successfulUnregisterMsg), "Stdout from call to '" + rhnMigrateTool + " " + options + "' contains message: " + successfulUnregisterMsg);
Assert.assertTrue(!sshCommandResult.getStdout().contains(unsuccessfulUnregisterMsg), "Stdout from call to '" + rhnMigrateTool + " " + options + "' does NOT contain message: " + unsuccessfulUnregisterMsg);
Assert.assertTrue(!clienttasks.isRhnSystemRegistered(), "This system is NOT registered using RHN Classic. Therefore this system will no longer communicate with RHN Classic.");
Assert.assertTrue(!clienttasks.isRhnSystemIdRegistered(rhnreg_ksUsername, rhnreg_ksPassword, rhnHostname, rhnSystemId), "Confirmed that rhn systemId '" + rhnSystemId + "' is no longer registered on the RHN Classic server.");
} else {
// Case 2: number of subscribed channels is high and communication fails in a timely fashion (see bug 881952). Here is a snippet from stdout:
// Preparing to unregister system from RHN Classic ...
// Did not receive a completed unregistration message from RHN Classic for system 1023722557.
// Please investigate on the Customer Portal at https://access.redhat.com.
log.warning("Did not detect expected message '" + successfulUnregisterMsg + "' from " + rhnMigrateTool + " stdout. Nevertheless, the tool should inform us and continue the migration process.");
Assert.assertTrue(sshCommandResult.getStdout().contains(unsuccessfulUnregisterMsg), "Stdout from call to '" + rhnMigrateTool + " " + options + "' contains message: " + unsuccessfulUnregisterMsg);
Assert.assertTrue(!clienttasks.isRhnSystemRegistered(), "This system is NOT registered using RHN Classic. Therefore this system will no longer communicate with RHN Classic.");
if (!clienttasks.isRhnSystemIdRegistered(rhnreg_ksUsername, rhnreg_ksPassword, rhnHostname, rhnSystemId)) {
Assert.assertFalse(false, "Confirmed that rhn systemId '" + rhnSystemId + "' is no longer registered on the RHN Classic server.");
} else {
log.warning("The RHN Classic server believes that this system is still registered. SystemId '" + rhnSystemId + "' should be manually deleted on the Customer Portal.");
}
}
// assert that the legacy services have been stopped (introduced by RFE Bug 1185914
// Product certificates installed successfully to /etc/pki/product.
//
// Preparing to unregister system from legacy server...
// System successfully unregistered from legacy server.
// Stopping and disabling legacy services...
// osad: unrecognized service
// osad: unrecognized service
// TEMPORARY WORKAROUND FOR BUG
// Bug 1390341 - rhn-migrate-classic-to-rhsm is failing to stop and disable services
String bugId1 = "1390341";
// Bug 1432231 - rhn-migrate-classic-to-rhsm is failing to stop and disable services
String bugId2 = "1432231";
boolean invokeWorkaroundWhileBug1IsOpen = true;
boolean invokeWorkaroundWhileBug2IsOpen = true;
try {
if (BzChecker.getInstance().isBugOpen(bugId1)) {
log.fine("Invoking workaround for " + BzChecker.getInstance().getBugState(bugId1).toString() + " Bugzilla " + bugId1 + ". (https://bugzilla.redhat.com/show_bug.cgi?id=" + bugId1 + ")");
SubscriptionManagerCLITestScript.addInvokedWorkaround(bugId1);
} else {
invokeWorkaroundWhileBug1IsOpen = false;
}
} catch (BugzillaAPIException be) {
/* ignore exception */
} catch (RuntimeException re) {
/* ignore exception */
}
try {
if (BzChecker.getInstance().isBugOpen(bugId2)) {
log.fine("Invoking workaround for " + BzChecker.getInstance().getBugState(bugId2).toString() + " Bugzilla " + bugId2 + ". (https://bugzilla.redhat.com/show_bug.cgi?id=" + bugId2 + ")");
SubscriptionManagerCLITestScript.addInvokedWorkaround(bugId2);
} else {
invokeWorkaroundWhileBug2IsOpen = false;
}
} catch (BugzillaAPIException be) {
/* ignore exception */
} catch (RuntimeException re) {
/* ignore exception */
}
if (invokeWorkaroundWhileBug1IsOpen || invokeWorkaroundWhileBug2IsOpen) {
log.warning("Skipping assertion of stopped and disabled services while bug '" + bugId1 + "' OR '" + bugId2 + "' is open.");
;
} else // END OF WORKAROUND
if (clienttasks.isPackageVersion("subscription-manager-migration", ">=", "1.18.2-1")) {
String stoppingServicesMsg = "Stopping and disabling legacy services...";
Assert.assertTrue(sshCommandResult.getStdout().contains(stoppingServicesMsg), "Stdout from call to '" + rhnMigrateTool + " " + options + "' contains message: " + stoppingServicesMsg);
// taken from https://bugzilla.redhat.com/show_bug.cgi?id=1185914#c0
if (clienttasks.isPackageInstalled("osad")) {
if (Integer.valueOf(clienttasks.redhatReleaseX) >= 7) {
// [root@jsefler-rhel7 ~]# systemctl is-enabled osad.service
// osad.service is not a native service, redirecting to /sbin/chkconfig.
// Executing /sbin/chkconfig osad --level=5
// disabled
// [root@jsefler-rhel7 ~]# echo $?
// 1
SSHCommandResult sshSystemctlIsEnabledCommandResult = client.runCommandAndWait("systemctl is-enabled osad.service");
Assert.assertEquals(sshSystemctlIsEnabledCommandResult.getStdout().trim(), "disabled", "Expected stdout for systemctl is-enabled osad.service");
Assert.assertEquals(sshSystemctlIsEnabledCommandResult.getExitCode(), Integer.valueOf(1), "Expected exitCode for systemctl is-enabled osad.service");
// [root@jsefler-rhel7 ~]# systemctl is-active osad.service
// unknown
// [root@jsefler-rhel7 ~]# echo $?
// 3
SSHCommandResult sshSystemctlIsActiveCommandResult = client.runCommandAndWait("systemctl is-active osad.service");
Assert.assertEquals(sshSystemctlIsActiveCommandResult.getStdout().trim(), "unknown", "Expected stdout for systemctl is-active osad.service");
Assert.assertEquals(sshSystemctlIsActiveCommandResult.getExitCode(), Integer.valueOf(3), "Expected exitCode for systemctl is-active osad.service");
} else {
// [root@jsefler-rhel6 ~]# service osad status
// osad is stopped
// [root@jsefler-rhel6 ~]# echo $?
// 3
SSHCommandResult sshServiceCommandResult = client.runCommandAndWait("service osad status");
Assert.assertEquals(sshServiceCommandResult.getExitCode(), Integer.valueOf(3), "Expected exitCode for service osad status");
Assert.assertEquals(sshServiceCommandResult.getStdout().trim(), "osad is stopped", "Expected stdout for service osad status");
// [root@jsefler-rhel6 ~]# chkconfig --list osad
// osad 0:off 1:off 2:off 3:off 4:off 5:off 6:off
SSHCommandResult sshChkconfigCommandResult = client.runCommandAndWait("chkconfig --list osad");
Assert.assertEquals(sshChkconfigCommandResult.getExitCode(), Integer.valueOf(0), "Expected exitCode for chkconfig --list osad");
String sshChkconfigRegex = "osad\\s+0:off\\s+1:off\\s+2:off\\s+3:off\\s+4:off\\s+5:off\\s+6:off";
Assert.assertTrue(sshChkconfigCommandResult.getStdout().trim().matches(sshChkconfigRegex), "Expected stdout for chkconfig --list osad to match regex '" + sshChkconfigRegex + "'.");
}
}
if (clienttasks.isPackageInstalled("rhnsd")) {
if (Integer.valueOf(clienttasks.redhatReleaseX) >= 7) {
// [root@jsefler-rhel7 ~]# systemctl is-enabled rhnsd.service
// rhnsd.service is not a native service, redirecting to /sbin/chkconfig.
// Executing /sbin/chkconfig rhnsd --level=5
// disabled
// [root@jsefler-rhel7 ~]# echo $?
// 1
SSHCommandResult sshSystemctlIsEnabledCommandResult = client.runCommandAndWait("systemctl is-enabled rhnsd.service");
Assert.assertEquals(sshSystemctlIsEnabledCommandResult.getStdout().trim(), "disabled", "Expected stdout for systemctl is-enabled rhnsd.service");
Assert.assertEquals(sshSystemctlIsEnabledCommandResult.getExitCode(), Integer.valueOf(1), "Expected exitCode for systemctl is-enabled rhnsd.service");
// [root@jsefler-rhel7 ~]# chkconfig --list rhnsd
//
// Note: This output shows SysV services only and does not include native
// systemd services. SysV configuration data might be overridden by native
// systemd configuration.
//
// If you want to list systemd services use 'systemctl list-unit-files'.
// To see services enabled on particular target use
// 'systemctl list-dependencies [target]'.
//
// rhnsd 0:off 1:off 2:off 3:off 4:off 5:off 6:off
SSHCommandResult sshChkconfigCommandResult = client.runCommandAndWait("chkconfig --list rhnsd");
Assert.assertEquals(sshChkconfigCommandResult.getExitCode(), Integer.valueOf(0), "Expected exitCode for chkconfig --list rhnsd");
String sshChkconfigRegex = "rhnsd\\s+0:off\\s+1:off\\s+2:off\\s+3:off\\s+4:off\\s+5:off\\s+6:off";
Assert.assertTrue(sshChkconfigCommandResult.getStdout().trim().matches(sshChkconfigRegex), "Expected stdout for chkconfig --list rhnsd to match regex '" + sshChkconfigRegex + "'.");
// [root@jsefler-rhel7 ~]# systemctl is-active rhnsd.service
// unknown
// [root@jsefler-rhel7 ~]# echo $?
// 3
SSHCommandResult sshSystemctlIsActiveCommandResult = client.runCommandAndWait("systemctl is-active rhnsd.service");
Assert.assertEquals(sshSystemctlIsActiveCommandResult.getStdout().trim(), "unknown", "Expected stdout for systemctl is-active rhnsd.service");
Assert.assertEquals(sshSystemctlIsActiveCommandResult.getExitCode(), Integer.valueOf(3), "Expected exitCode for systemctl is-active rhnsd.service");
} else {
// [root@jsefler-rhel6 ~]# service rhnsd status
// [root@jsefler-rhel6 ~]# echo $?
// 6
SSHCommandResult sshServiceCommandResult = client.runCommandAndWait("service rhnsd status");
Assert.assertEquals(sshServiceCommandResult.getExitCode(), Integer.valueOf(6), "Expected exitCode for service rhnsd status - because /etc/init.d/rhnsd is programmed to exit 6 when there is no systemid file");
Assert.assertEquals(sshServiceCommandResult.getStdout().trim(), "", "Expected stdout for service rhnsd status");
// [root@jsefler-rhel6 ~]# chkconfig --list rhnsd
// rhnsd 0:off 1:off 2:off 3:off 4:off 5:off 6:off
SSHCommandResult sshChkconfigCommandResult = client.runCommandAndWait("chkconfig --list rhnsd");
Assert.assertEquals(sshChkconfigCommandResult.getExitCode(), Integer.valueOf(0), "Expected exitCode for chkconfig --list rhnsd");
String sshChkconfigRegex = "rhnsd\\s+0:off\\s+1:off\\s+2:off\\s+3:off\\s+4:off\\s+5:off\\s+6:off";
Assert.assertTrue(sshChkconfigCommandResult.getStdout().trim().matches(sshChkconfigRegex), "Expected stdout for chkconfig --list rhnsd to match regex '" + sshChkconfigRegex + "'.");
}
}
// assert that no FAILED nor Usage errors occurred
// Bug 1390341 - rhn-migrate-classic-to-rhsm is failing to stop and disable services
Assert.assertTrue(!sshCommandResult.getStdout().contains("FAILED"), "Should not encounter a FAILED message when Stopping and disabling legacy services");
// Bug 1390341 - rhn-migrate-classic-to-rhsm is failing to stop and disable services
Assert.assertTrue(!sshCommandResult.getStdout().contains("Usage"), "Should not encounter a Usage error when Stopping and disabling legacy services");
}
String removingPackagesMsg = "Removing legacy packages...";
if (options.contains("--remove-rhn-packages")) {
Assert.assertTrue(sshCommandResult.getStdout().contains(removingPackagesMsg), "Stdout from call to '" + rhnMigrateTool + " " + options + "' contains message: " + removingPackagesMsg);
} else {
Assert.assertTrue(!sshCommandResult.getStdout().contains(removingPackagesMsg), "Stdout from call to '" + rhnMigrateTool + " " + options + "' does not contain message: " + removingPackagesMsg);
}
// assert that when --serverurl is specified, its hostname:port/prefix are preserved into rhsm.conf
if (options.contains("--serverurl") || options.contains("--destination-url")) {
// comparing to original configuration values because these are the ones I am using in the dataProvider
Assert.assertEquals(clienttasks.getConfFileParameter(clienttasks.rhsmConfFile, "server", "hostname"), originalServerHostname, "The value of the [server]hostname newly configured in " + clienttasks.rhsmConfFile + " was extracted from the --serverurl option specified in rhn-migrated-classic-to-rhsm options '" + options + "'.");
Assert.assertEquals(clienttasks.getConfFileParameter(clienttasks.rhsmConfFile, "server", "port"), originalServerPort, "The value of the [server]port newly configured in " + clienttasks.rhsmConfFile + " was extracted from the --serverurl option specified in rhn-migrated-classic-to-rhsm options '" + options + "'.");
Assert.assertEquals(clienttasks.getConfFileParameter(clienttasks.rhsmConfFile, "server", "prefix"), originalServerPrefix, "The value of the [server]prefix newly configured in " + clienttasks.rhsmConfFile + " was extracted from the --serverurl option specified in rhn-migrated-classic-to-rhsm options '" + options + "'.");
}
// assert that we are newly registered using rhsm
clienttasks.identity(null, null, null, null, null, null, null, null);
Assert.assertNotNull(clienttasks.getCurrentConsumerId(), "The existance of a consumer cert indicates that the system is currently registered using RHSM.");
expectedMsg = String.format("System '%s' successfully registered to Red Hat Subscription Management.", clienttasks.hostname);
// changed by commit fad3de89
if (clienttasks.isPackageVersion("subscription-manager-migration", ">=", "1.13.1"))
expectedMsg = String.format("System '%s' successfully registered.", clienttasks.hostname);
// TEMPORARY WORKAROUND FOR BUG
// Bug 1451003 - subscription-manager identity reports redundant UUID info in the name field
String bugId = "1451003";
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 assertion that Stdout from call to '" + rhnMigrateTool + " " + options + "' contains message: " + expectedMsg);
} else
// END OF WORKAROUND
Assert.assertTrue(sshCommandResult.getStdout().contains(expectedMsg), "Stdout from call to '" + rhnMigrateTool + " " + options + "' contains message: " + expectedMsg);
// assert the the expected service level was set as a preference on the registered consumer
if (serviceLevelExpected != null) {
String serviceLevel = clienttasks.getCurrentServiceLevel();
Assert.assertTrue(serviceLevelExpected.equalsIgnoreCase(serviceLevel), "Regardless of case, the serviceLevel requested during migration (or possibly the org's defaultServiceLevel) was set as the system's service level preference (serviceLevelExpected='" + serviceLevelExpected + "').");
}
// assert that when --no-auto is specified, no entitlements were granted during the rhsm registration
String autosubscribeAttemptedMsg = "Attempting to auto-subscribe to appropriate subscriptions ...";
// changed by bug 876294
autosubscribeAttemptedMsg = "Attempting to auto-attach to appropriate subscriptions ...";
// changed by subscription-manager commit 1fba5696
autosubscribeAttemptedMsg = "Attempting to auto-attach to appropriate subscriptions...";
// commit fad3de89779f2217e788b3564ef5dca7f85914fb removed the "Attempting to auto-attach to appropriate subscriptions..." feedback
if (clienttasks.isPackageVersion("subscription-manager-migration", ">=", "1.13.1"))
autosubscribeAttemptedMsg = "Installed Product Current Status:";
String autosubscribeFailedMsg = "Unable to auto-subscribe. Do your existing subscriptions match the products installed on this system?";
// changed by bug 876294
autosubscribeFailedMsg = "Unable to auto-attach. Do your existing subscriptions match the products installed on this system?";
// commit fad3de89779f2217e788b3564ef5dca7f85914fb // matches functionality from bug 864195
if (clienttasks.isPackageVersion("subscription-manager-migration", ">=", "1.13.1"))
autosubscribeFailedMsg = "Unable to find available subscriptions for all your installed products.";
// OLD if (options.contains("-n")) { // -n, --no-auto Do not autosubscribe when registering with subscription-manager
if (options.contains("-n") && !options.contains("--activation-key")) {
// -n, --no-auto Do not autosubscribe when registering with subscription-manager
// assert that autosubscribe was NOT attempted
Assert.assertTrue(!sshCommandResult.getStdout().contains(autosubscribeAttemptedMsg), "Stdout from call to '" + rhnMigrateTool + " " + options + "' does NOT contain message: " + autosubscribeAttemptedMsg);
Assert.assertTrue(!sshCommandResult.getStdout().contains(autosubscribeFailedMsg), "Stdout from call to '" + rhnMigrateTool + " " + options + "' does NOT contain message: " + autosubscribeFailedMsg);
// assert that we are NOT registered using rhsm
/* THIS ASSERTION IS WRONG! DON'T DO IT! BUG 849644
clienttasks.identity_(null, null, null, null, null, null, null);
Assert.assertNull(clienttasks.getCurrentConsumerCert(),"We should NOT be registered to RHSM after a call to "+rhnMigrateTool+" with options "+options+".");
*/
// assert that we are NOT consuming any entitlements
Assert.assertTrue(clienttasks.getCurrentlyConsumedProductSubscriptions().isEmpty(), "We should NOT be consuming any RHSM entitlements after call to " + rhnMigrateTool + " with options (" + options + ") that indicate no autosubscribe.");
// OLD } else {
}
if (!options.contains("-n") && !options.contains("--activation-key")) {
// assert that autosubscribe was attempted
Assert.assertTrue(sshCommandResult.getStdout().contains(autosubscribeAttemptedMsg), "Stdout from call to '" + rhnMigrateTool + " " + options + "' contains message: " + autosubscribeAttemptedMsg);
// assert that the migrated productCert corresponding to the base channel has been autosubscribed by checking the status on the installedProduct
// FIXME This assertion is wrong when there are no available subscriptions that provide for the migrated product certs' providesTags; however since we register as qa@redhat.com, I think we have access to all base rhel subscriptions
// FIXME if a service-level is provided that is not available, then this product may NOT be subscribed
/* DECIDED NOT TO FIXME SINCE THIS ASSERTION IS THE JOB OF DEDICATED AUTOSUBSCRIBE TESTS IN SubscribeTests.java
InstalledProduct installedProduct = clienttasks.getInstalledProductCorrespondingToProductCert(clienttasks.getProductCertFromProductCertFile(new File(clienttasks.productCertDir+"/"+getPemFileNameFromProductCertFilename(channelsToProductCertFilenamesMap.get(rhnBaseChannel)))));
Assert.assertEquals(installedProduct.status, "Subscribed","The migrated product cert corresponding to the RHN Classic base channel '"+rhnBaseChannel+"' was autosubscribed: "+installedProduct);
*/
// assert that autosubscribe feedback was a success (or not)
List<ProductSubscription> consumedProductSubscriptions = clienttasks.getCurrentlyConsumedProductSubscriptions();
if (consumedProductSubscriptions.isEmpty()) {
Assert.assertTrue(sshCommandResult.getStdout().contains(autosubscribeFailedMsg), "Assuming the base RHN channel has been migrated, but no entitlements have been granted, stdout from call to '" + rhnMigrateTool + " " + options + "' contains message: " + autosubscribeFailedMsg);
}
/*else { // 06/15/2015: This else block is wrong since an RHN Channel could have been successfully migrated, but there is no subscription available to cover it. Replacing it with a call to get the compliance status
Assert.assertTrue(!sshCommandResult.getStdout().contains(autosubscribeFailedMsg), "When autosubscribe is successful and entitlements have been granted, stdout from call to '"+rhnMigrateTool+" "+options+"' does NOT contain message: "+autosubscribeFailedMsg);
} */
if (clienttasks.isPackageVersion("subscription-manager", ">=", "1.13.8-1")) {
// post commit 7957b8df95c575e6e8713c2f1a0f8f754e32aed3 bug 1119688
SSHCommandResult statusResult = clienttasks.status(null, null, null, null, null);
if (statusResult.getStdout().contains("Overall Status: Invalid")) {
Assert.assertTrue(sshCommandResult.getStdout().contains(autosubscribeFailedMsg), "Since the subscription-manager overall status appears Invalid, the most likely reason is because at least one of the migrated products could not be auto-subscribed. Therefore stdout from call to '" + rhnMigrateTool + " " + options + "' contains message: " + autosubscribeFailedMsg);
} else {
// Note: "Overall Status: Insufficient" is possible and likely when the auto-subscribed subscription pool is Temporary
Assert.assertTrue(!sshCommandResult.getStdout().contains(autosubscribeFailedMsg), "Since the subscription-manager overall status does not appear Invalid (overall status of Current or Insufficient are likely), all of the migrated products should have been auto-subscribed. Therefore stdout from call to '" + rhnMigrateTool + " " + options + "' does NOT contain message: " + autosubscribeFailedMsg);
}
}
// assert that when no --servicelevel is specified, then no service level preference will be set on the registered consumer
if (!options.contains("-s ") && !options.contains("--servicelevel") && !options.contains("--service-level") && (serviceLevelExpected == null || serviceLevelExpected.isEmpty())) {
// assert no service level preference was set
Assert.assertEquals(clienttasks.getCurrentServiceLevel(), "", "No servicelevel preference should be set on the consumer when no service level was requested.");
}
// assert the service levels consumed from autosubscribe match the requested serviceLevel
if (serviceLevelExpected != null && !serviceLevelExpected.isEmpty()) {
// when a valid servicelevel was either specified or chosen
expectedMsg = String.format("Service level set to: %s", serviceLevelExpected);
Assert.assertTrue(sshCommandResult.getStdout().toUpperCase().contains(expectedMsg.toUpperCase()), "Regardless of service level case, the stdout from call to '" + rhnMigrateTool + " " + options + "' contains message: " + expectedMsg);
for (ProductSubscription productSubscription : consumedProductSubscriptions) {
Assert.assertNotNull(productSubscription.serviceLevel, "When migrating from RHN Classic with a specified service level '" + serviceLevelExpected + "', this auto consumed product subscription's service level should not be null: " + productSubscription);
if (sm_exemptServiceLevelsInUpperCase.contains(productSubscription.serviceLevel.toUpperCase())) {
log.info("Exempt service levels: " + sm_exemptServiceLevelsInUpperCase);
Assert.assertTrue(sm_exemptServiceLevelsInUpperCase.contains(productSubscription.serviceLevel.toUpperCase()), "This auto consumed product subscription's service level is among the exempt service levels: " + productSubscription);
} else {
Assert.assertTrue(productSubscription.serviceLevel.equalsIgnoreCase(serviceLevelExpected), "When migrating from RHN Classic with a specified service level '" + serviceLevelExpected + "', this auto consumed product subscription's service level should match: " + productSubscription);
}
}
}
}
if (options.contains("--activation-key")) {
// assert that autosubscribe was NOT attempted
// Assert.assertTrue(!sshCommandResult.getStdout().contains(autosubscribeAttemptedMsg), "Stdout from call to '"+rhnMigrateTool+" "+options+"' does NOT contain message: "+autosubscribeAttemptedMsg); // not a fair assertion since autosubscribeAttemptedMsg was set to "Installed Product Current Status:"
// Assert.assertTrue(!sshCommandResult.getStdout().contains(autosubscribeFailedMsg), "Stdout from call to '"+rhnMigrateTool+" "+options+"' does NOT contain message: "+autosubscribeFailedMsg); // also not a fair assertion since autosubscribeFailedMsg was set to "Unable to find available subscriptions for all your installed products."
Assert.assertTrue(!sshCommandResult.getStdout().toLowerCase().contains("auto-attach"), "Stdout from an attempt to migrate with options (" + options + ") which include an activation key should make no reference to 'auto-attach'");
Assert.assertTrue(!sshCommandResult.getStdout().toLowerCase().contains("auto-subscribe"), "Stdout from an attempt to migrate with options (" + options + ") which include an activation key should make no reference to 'auto-subscribe'");
// assert that we are consuming entitlements, TODO but this is really dependent on the activation key
Assert.assertTrue(!clienttasks.getCurrentlyConsumedProductSubscriptions().isEmpty(), "We should be consuming some entitlements after a call to " + rhnMigrateTool + " with options (" + options + "). This assumes the activation key contained one or more pools.");
// TODO When an activation key is used, all of the consumed subscriptions should have come from the activation key.
// It would be best to make these assertion in the test that calls this function.
}
// assert that the rhnplugin has been disabled
Assert.assertEquals(clienttasks.getConfFileParameter(clienttasks.yumPluginConfFileForRhn, "enabled"), "0", "The enabled yum plugin configuration for RHN.");
// assert that productid.js is updated with productid mappings for all of the rhnChannelsConsumed; coverage for Bug 972883 - rhn-migrate-classic-to-rhsm tool neglects to populate /var/lib/rhsm/productid.js
client.runCommandAndWait("cat " + clienttasks.productIdJsonFile);
for (String rhnChannelConsumed : rhnChannelsConsumed) {
if (channelsToProductCertFilenamesMap.containsKey(rhnChannelConsumed)) {
String productId = MigrationDataTests.getProductIdFromProductCertFilename(channelsToProductCertFilenamesMap.get(rhnChannelConsumed));
// special case (see RhnMigrateClassicToRhsm_Rhel5ClientDesktopVersusWorkstation_Test)
if (clienttasks.releasever.equals("5Client")) {
String productIdForDesktop = "68";
String productIdForWorkstation = "71";
if (productId.equals(productIdForDesktop)) {
log.info("Encountered a special case for migration of a 5Client system from RHN Classic to RHSM...");
log.info("Red Hat Enterprise Linux Desktop (productId=68) corresponds to the base RHN Channel (rhel-ARCH-client-5) for a 5Client system where ARCH=i386,x86_64.");
log.info("Red Hat Enterprise Linux Workstation (productId=71) corresponds to child RHN Channel (rhel-ARCH-client-workstation-5) for a 5Client system where ARCH=i386,x86_64.");
log.info("After migrating from RHN Classic to RHSM, these two product certs should not be installed at the same time; Workstation should prevail.");
if (productIdRepoMapAfterMigration.containsKey(productIdForWorkstation)) {
Assert.assertTrue(!productIdRepoMapAfterMigration.containsKey(productId), "The '" + clienttasks.productIdJsonFile + "' database should NOT contain an entry for productId '" + productId + "' which was migrated for consumption of Classic RHN Channel '" + rhnChannelConsumed + "' when Workstation channels for product '" + productIdForWorkstation + "' have also been migrated (Workstation wins).");
continue;
}
}
}
if (productId.equalsIgnoreCase("none")) {
Assert.assertTrue(!productIdRepoMapAfterMigration.containsKey(productId), "The '" + clienttasks.productIdJsonFile + "' database does NOT contain an entry for productId '" + productId + "' after migration while consuming Classic RHN Channel '" + rhnChannelConsumed + "'.");
} else {
Assert.assertTrue(productIdRepoMapAfterMigration.containsKey(productId), "The '" + clienttasks.productIdJsonFile + "' database contains an entry for productId '" + productId + "' which was migrated for consumption of Classic RHN Channel '" + rhnChannelConsumed + "'.");
Assert.assertTrue(productIdRepoMapAfterMigration.get(productId).contains(rhnChannelConsumed), "The '" + clienttasks.productIdJsonFile + "' database entry for productId '" + productId + "' contains Classic RHN Channel/Repo '" + rhnChannelConsumed + "'.");
}
}
}
}
use of rhsm.data.ProductSubscription in project rhsm-qe by RedHatQE.
the class ContentTests method testRedHatRepoFileDoesNotContainExcessiveBlankLines_DEPRECATED.
@Test(description = "verify redhat.repo file does not contain an excessive (more than two) number of successive blank lines", groups = { "Tier2Tests", "blockedByBug-737145" }, // Disabling... this test takes too long to execute. VerifyRedHatRepoFileIsPurgedOfBlankLinesByYumPlugin_Test effectively provides the same test coverage.
enabled = false)
@Deprecated
public // @ImplementsNitrateTest(caseId=)
void testRedHatRepoFileDoesNotContainExcessiveBlankLines_DEPRECATED() {
// successive blank lines in redhat.repo must not exceed N
// (\n\s*){4,}
int N = 2;
// (\n\s*){4,}
String regex = "(\\n\\s*){" + (N + 2) + ",}";
String redhatRepoFileContents = "";
// check for excessive blank lines after a new register
clienttasks.register(sm_clientUsername, sm_clientPassword, sm_clientOrg, null, null, null, null, null, null, null, (String) null, null, null, null, true, null, null, null, null, null);
// --disableplugin=rhnplugin helps avoid: up2date_client.up2dateErrors.AbuseError
client.runCommandAndWait("yum -q repolist --disableplugin=rhnplugin");
redhatRepoFileContents = client.runCommandAndWait("cat " + clienttasks.redhatRepoFile).getStdout();
Assert.assertContainsNoMatch(redhatRepoFileContents, regex, null, "At most '" + N + "' successive blank are acceptable inside " + clienttasks.redhatRepoFile);
// check for excessive blank lines after subscribing to each pool
for (SubscriptionPool pool : clienttasks.getCurrentlyAvailableSubscriptionPools()) {
clienttasks.subscribe_(null, null, pool.poolId, null, null, null, null, null, null, null, null, null, null);
// --disableplugin=rhnplugin helps avoid: up2date_client.up2dateErrors.AbuseError
client.runCommandAndWait("yum -q repolist --disableplugin=rhnplugin");
}
redhatRepoFileContents = client.runCommandAndWait("cat " + clienttasks.redhatRepoFile).getStdout();
Assert.assertContainsNoMatch(redhatRepoFileContents, regex, null, "At most '" + N + "' successive blank are acceptable inside " + clienttasks.redhatRepoFile);
// check for excessive blank lines after unsubscribing from each serial
List<BigInteger> serialNumbers = new ArrayList<BigInteger>();
for (ProductSubscription productSubscription : clienttasks.getCurrentlyConsumedProductSubscriptions()) {
// save some time by avoiding redundant unsubscribes
if (serialNumbers.contains(productSubscription.serialNumber))
continue;
clienttasks.unsubscribe_(null, productSubscription.serialNumber, null, null, null, null, null);
serialNumbers.add(productSubscription.serialNumber);
// --disableplugin=rhnplugin helps avoid: up2date_client.up2dateErrors.AbuseError
client.runCommandAndWait("yum -q repolist --disableplugin=rhnplugin");
}
redhatRepoFileContents = client.runCommandAndWait("cat " + clienttasks.redhatRepoFile).getStdout();
Assert.assertContainsNoMatch(redhatRepoFileContents, regex, null, "At most '" + N + "' successive blank are acceptable inside " + clienttasks.redhatRepoFile);
// assert the comment heading is present
// Assert.assertContainsMatch(redhatRepoFileContents,"^# Red Hat Repositories$",null,"Comment heading \"Red Hat Repositories\" was found inside "+clienttasks.redhatRepoFile);
Assert.assertContainsMatch(redhatRepoFileContents, "^# Certificate-Based Repositories$", null, "Comment heading \"Certificate-Based Repositories\" was found inside " + clienttasks.redhatRepoFile);
Assert.assertContainsMatch(redhatRepoFileContents, "^# Managed by \\(rhsm\\) subscription-manager$", null, "Comment heading \"Managed by (rhsm) subscription-manager\" was found inside " + clienttasks.redhatRepoFile);
}
use of rhsm.data.ProductSubscription in project rhsm-qe by RedHatQE.
the class DevSKUTests method testRedundantAutosubscribesForDevSkuEntitlementWillReissueNewEntitlement.
@// update=true, // uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-22313", "RHEL7-51859" }, 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 = "configure the system with custom facts for a dev_sku, register the system with auto-subscribe and verify that an attempt to redundantly autosubscribed will re-issue a replacement entitlement (remove the old and attach a new).", groups = { "Tier1Tests", "blockedByBug-1292877" }, enabled = true)
public // @ImplementsNitrateTest(caseId=)
void testRedundantAutosubscribesForDevSkuEntitlementWillReissueNewEntitlement() throws JSONException, Exception {
// get a valid dev_sku to test with
List<Object> l = getRandomValidDevSkuData();
String devSku = (String) l.get(1);
String devPlatform = (String) l.get(2);
// 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);
// register with autosubscribe and force (to unregister anyone that is already registered)
SSHCommandResult result = 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);
if (servertasks.statusStandalone) {
Assert.assertEquals(result.getStderr().trim(), "Development units may only be used on hosted servers and with orgs that have active subscriptions.", "Expected stderr when /etc/candlepin/candlepin candlepin.standalone=true (typical of Satellite deployment).");
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).");
}
// are we fully compliant? complianceStatus=="valid"
String complianceStatus;
// complianceStatus = clienttasks.getFactValue("system.entitlements_valid");
complianceStatus = CandlepinTasks.getConsumerComplianceStatus(sm_clientUsername, sm_clientPassword, sm_serverUrl, clienttasks.getCurrentConsumerId());
// get the autosubscribed productSubscription
List<ProductSubscription> productSubscriptions = clienttasks.getCurrentlyConsumedProductSubscriptions();
Assert.assertEquals(productSubscriptions.size(), 1, "After registering (with autosubscribe) a system with dev_sku fact '" + devSku + "', only one product subscription should be consumed.");
ProductSubscription devSkuProductSubscription1 = productSubscriptions.get(0);
// re-autosubscribe
clienttasks.subscribe(true, null, null, null, (String) null, null, null, null, null, null, null, null, null);
// get the re-autosubscribed entitlement
productSubscriptions = clienttasks.getCurrentlyConsumedProductSubscriptions();
Assert.assertEquals(productSubscriptions.size(), 1, "After re-autosubscribing a system with dev_sku fact '" + devSku + "', only one product subscription should be consumed.");
ProductSubscription devSkuProductSubscription2 = productSubscriptions.get(0);
// assert the re-autosubscribes product subscriptions match (except for pool id and serial since the pool must go when a new autosubscribe is required)
Assert.assertEquals(ProductSubscription.formatDateString(devSkuProductSubscription2.endDate), ProductSubscription.formatDateString(devSkuProductSubscription1.endDate), "A dev_sku enabled system that has been re-autosubscribed is granted another product subscription with the same end date.");
Assert.assertEquals(devSkuProductSubscription2.serviceLevel, devSkuProductSubscription1.serviceLevel, "A dev_sku enabled system that has been re-autosubscribed is granted another product subscription with the same service level.");
Assert.assertEquals(devSkuProductSubscription2.quantityUsed, devSkuProductSubscription1.quantityUsed, "A dev_sku enabled system that has been re-autosubscribed is granted another product subscription with the quantity used.");
Assert.assertTrue(devSkuProductSubscription2.provides.containsAll(devSkuProductSubscription1.provides) && devSkuProductSubscription1.provides.containsAll(devSkuProductSubscription2.provides), "A dev_sku enabled system that has been re-autosubscribed is granted another product subscription that provides the same products." + " devSkuProductSubscription1.provides=" + devSkuProductSubscription1.provides + " devSkuProductSubscription2.provides=" + devSkuProductSubscription2.provides);
if (complianceStatus.equalsIgnoreCase("valid")) {
Assert.assertTrue(devSkuProductSubscription2.poolId.equals(devSkuProductSubscription1.poolId), "When system is already compliant, a dev_sku enabled system that has been re-autosubscribed will not be granted another product subscription from a different pool id (should not be needed since system is already green).");
Assert.assertTrue(devSkuProductSubscription2.serialNumber.equals(devSkuProductSubscription1.serialNumber), "When system is already compliant, a dev_sku enabled system that has been re-autosubscribed will not be granted another product subscription with a different serial (should not be needed since system is already green).");
} else {
Assert.assertTrue(!devSkuProductSubscription2.poolId.equals(devSkuProductSubscription1.poolId), "When system is not already compliant, dev_sku enabled system that has been re-autosubscribed is granted another product subscription from a different pool id.");
Assert.assertTrue(!devSkuProductSubscription2.serialNumber.equals(devSkuProductSubscription1.serialNumber), "When system is not already compliant, a dev_sku enabled system that has been re-autosubscribed is granted another product subscription with a different serial.");
}
}
use of rhsm.data.ProductSubscription in project rhsm-qe by RedHatQE.
the class ListTests method testRemoveSubscriptionContainingUTF8Character.
@// update=true // uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-37706", "RHEL7-51354" }, 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 = "Tier2")
@Test(description = "subscription-manager: subcription manager remove a consumed subscription containing UTF-8 character(s)", groups = { "Tier2Tests", "SubscriptionContainingUTF8CharacterTests", "blockedByBug-889204" }, dependsOnMethods = { "testCatCertContainingUTF8Character" }, priority = 140, enabled = true)
public // @ImplementsNitrateTest(caseId=)
void testRemoveSubscriptionContainingUTF8Character() {
// SURPRISED THAT THIS DID NOT WORK List AND THE FOLLOWING DOES <ProductSubscription> consumedProductSubscriptions = ProductSubscription.parse(clienttasks.runCommandWithLang(null, clienttasks.command+" list --consumed").getStdout());
List<ProductSubscription> consumedProductSubscriptions = ProductSubscription.parse(client.runCommandAndWait(clienttasks.command + " list --consumed").getStdout());
ProductSubscription consumedProductSubscription = ProductSubscription.findFirstInstanceWithCaseInsensitiveMatchingFieldFromList("productId", productIdForSubscriptionContainingUTF8Character, consumedProductSubscriptions);
Assert.assertNotNull(consumedProductSubscription, "Found subscription product '" + productIdForSubscriptionContainingUTF8Character + "' from the list of consumed subscriptions whose name contains a UTF8 character.");
Assert.assertEquals(consumedProductSubscription.productName, subscriptionNameForSubscriptionContainingUTF8Character, "asserting the consumed subscription name.");
clienttasks.unsubscribeFromSerialNumber(consumedProductSubscription.serialNumber);
}
use of rhsm.data.ProductSubscription in project rhsm-qe by RedHatQE.
the class ListTests method testListConsumedWithServicelevel.
@// update=true // uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-27116", "RHEL7-51336" }, 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 = "Tier2")
@Test(description = "subscription-manager: subcription manager list consumed should filter by servicelevel when this option is passed.", groups = { "Tier2Tests", "blockedByBug-800933", "blockedByBug-800999" }, dataProvider = "getConsumedWithServicelevelData", enabled = true)
public // @ImplementsNitrateTest(caseId=)
void testListConsumedWithServicelevel(Object bugzilla, String servicelevel) throws Exception {
SSHCommandResult listResult;
List<ProductSubscription> expectedProductSubscriptions, filteredProductSubscriptions;
// list consumed (without service level)
listResult = clienttasks.list_(false, false, true, null, null, null, null, null, null, null, null, null, null, null);
List<ProductSubscription> allConsumedProductSubscriptions = clienttasks.getCurrentlyConsumedProductSubscriptions();
// determine the subset of expected pools with a matching servicelevel
// CASE SENSITIVE expectedProductSubscriptions = ProductSubscription.findAllInstancesWithMatchingFieldFromList("serviceLevel", servicelevel, allConsumedProductSubscriptions);
expectedProductSubscriptions = ProductSubscription.findAllInstancesWithCaseInsensitiveMatchingFieldFromList("serviceLevel", servicelevel, allConsumedProductSubscriptions);
// list consumed filtered by servicelevel
listResult = clienttasks.list_(false, false, true, null, servicelevel, null, null, null, null, null, null, null, null, null);
Assert.assertEquals(listResult.getExitCode(), Integer.valueOf(0), "The exit code from the list --consumed --servicelevel command indicates a success.");
// assert results
filteredProductSubscriptions = ProductSubscription.parse(listResult.getStdout());
Assert.assertTrue(filteredProductSubscriptions.containsAll(expectedProductSubscriptions), "The actual list of --consumed --servicelevel=\"" + servicelevel + "\" ProductSubscriptions contains all of the expected ProductSubscriptions (the expected list contains only consumptions with ServiceLevel=\"" + servicelevel + "\")");
Assert.assertTrue(expectedProductSubscriptions.containsAll(filteredProductSubscriptions), "The expected list of ProductSubscriptions contains all of the actual ProductSubscriptions returned by list --consumed --servicelevel=\"" + servicelevel + "\".");
String expectedStdout = "No consumed subscription pools to list";
// commit be815d04d1722dd8fd40a23c0a7847e97e689f89
if (clienttasks.isPackageVersion("subscription-manager", ">=", "1.13.6-1"))
expectedStdout = "No consumed subscription pools matching the specified criteria were found.";
// commit 2884e33acb35ab4e336fe12dc23de7ab26cc0572 // Bug 1159348 - list --matched should show the filter string when warning about empty matches
if (clienttasks.isPackageVersion("subscription-manager", ">=", "1.13.12-1"))
expectedStdout = String.format("No consumed subscription pools were found matching the service level \"%s\".", servicelevel);
if (expectedProductSubscriptions.isEmpty())
Assert.assertEquals(listResult.getStdout().trim(), expectedStdout, "Expected stdout message when no consumed subscriptions remain after list is filtered by --servicelevel=\"" + servicelevel + "\".");
}
Aggregations