Search in sources :

Example 1 with SSHCommandRunner

use of com.redhat.qe.tools.SSHCommandRunner in project rhsm-qe by RedHatQE.

the class SubscriptionManagerCLITestScript method setupBeforeSuite.

// Configuration Methods ***********************************************************************
@BeforeSuite(groups = { "setup" }, description = "subscription manager set up")
public void setupBeforeSuite() throws IOException, JSONException {
    if (isSetupBeforeSuiteComplete)
        return;
    // create SSHCommandRunners to connect to the subscription-manager clients
    File sshKeyPrivateKeyFile = new File(System.getProperty("automation.dir", null) + "/" + sm_sshKeyPrivate);
    if (!sshKeyPrivateKeyFile.exists())
        Assert.fail("Expected to find the private ssh key for automation testing at '" + sshKeyPrivateKeyFile + "'.  Ask the RHSM Automation Administrator for a copy.");
    client1 = new SSHCommandRunner(sm_client1Hostname, sm_client1SSHUser, new File(sm_sshKeyPrivate), sm_sshkeyPassphrase, null);
    if (sm_sshEmergenecyTimeoutMS != null)
        client1.setEmergencyTimeout(Long.valueOf(sm_sshEmergenecyTimeoutMS));
    client1tasks = new SubscriptionManagerTasks(client1);
    client = client1;
    clienttasks = client1tasks;
    // will we be testing multiple clients?
    if (!(sm_client2Hostname.equals(""))) {
        client2 = new SSHCommandRunner(sm_client2Hostname, sm_client2SSHUser, new File(sm_sshKeyPrivate), sm_sshkeyPassphrase, null);
        if (sm_sshEmergenecyTimeoutMS != null)
            client2.setEmergencyTimeout(Long.valueOf(sm_sshEmergenecyTimeoutMS));
        client2tasks = new SubscriptionManagerTasks(client2);
    } else {
        log.info("Multi-client testing will be skipped.");
    }
    // unregister clients in case they are still registered from prior run (DO THIS BEFORE SETTING UP A NEW CANDLEPIN)
    unregisterClientsAfterSuite();
    // Beaker test_log-Setup.log :: [   FAIL   ] :: FIPS on s390 on RHEL <7.1 is not supported (Assert: expected 0, got 1)
    if (client1 != null) {
        Assert.assertEquals(client1.runCommandAndWait("sysctl crypto.fips_enabled").getStdout().trim(), "crypto.fips_enabled = " + (sm_clientFips ? "1" : "0"), "Asserting the expected enablement of FIPS on client '" + sm_client1Hostname + "' before running any tests.");
    }
    if (client2 != null) {
        Assert.assertEquals(client2.runCommandAndWait("sysctl crypto.fips_enabled").getStdout().trim(), "crypto.fips_enabled = " + (sm_clientFips ? "1" : "0"), "Asserting the expected enablement of FIPS on client '" + sm_client2Hostname + "' before running any tests.");
    }
    List<File> generatedProductCertFiles = new ArrayList<File>();
    // can we create an SSHCommandRunner to connect to the candlepin server ?
    if (!sm_serverHostname.equals("") && sm_serverType.equals(CandlepinType.standalone)) {
        server = new SSHCommandRunner(sm_serverHostname, sm_serverSSHUser, new File(sm_sshKeyPrivate), sm_sshkeyPassphrase, null);
        if (sm_sshEmergenecyTimeoutMS != null)
            server.setEmergencyTimeout(Long.valueOf(sm_sshEmergenecyTimeoutMS));
        servertasks = new rhsm.cli.tasks.CandlepinTasks(server, sm_serverInstallDir, sm_serverImportDir, sm_serverType, sm_serverBranch, sm_dbSqlDriver, sm_dbHostname, sm_dbPort, sm_dbName, sm_dbUsername, sm_dbPassword);
    } else {
        log.info("Assuming the server is already setup and running.");
        servertasks = new rhsm.cli.tasks.CandlepinTasks(null, null, null, sm_serverType, sm_serverBranch, sm_dbSqlDriver, sm_dbHostname, sm_dbPort, sm_dbName, sm_dbUsername, sm_dbPassword);
    }
    // setup the candlepin server (only when the candlepin server is standalone)
    if (server != null && sm_serverType.equals(CandlepinType.standalone)) {
        // I suggest manually setting this on hosted and asking calfanso to restart
        if (servertasks.getConfFileParameter("pinsetter.org.fedoraproject.candlepin.pinsetter.tasks.CertificateRevocationListTask.schedule") == null) {
            servertasks.addConfFileParameter("\n# purge the CRL list every 2 min\npinsetter.org.fedoraproject.candlepin.pinsetter.tasks.CertificateRevocationListTask.schedule", "0 0/2 * * * ?");
        } else {
            // every 2 minutes
            servertasks.updateConfFileParameter("pinsetter.org.fedoraproject.candlepin.pinsetter.tasks.CertificateRevocationListTask.schedule", "0 0\\/2 * * * ?");
        }
        servertasks.cleanOutCRL();
        servertasks.deploy();
        server.runCommandAndWait("df -h");
        // log candlepin's starting disk usage (for debugging information only)
        server.runCommandAndWait("sudo " + "ls -Slh " + servertasks.getTomcatLogFile().getParent() + " | head");
        servertasks.setupTranslateToolkitFromTarUrl(sm_translateToolkitTarUrl);
        servertasks.reportAPI();
        // install packages
        SSHCommandResult yumInstallResult = server.runCommandAndWait("sudo " + "yum install -y --quiet hunspell");
        Assert.assertEquals(yumInstallResult.getExitCode(), Integer.valueOf(0), "ExitCode from yum install of packages on server '" + server.getConnection().getRemoteHostname() + "'.");
        // fetch the generated Product Certs
        if (Boolean.valueOf(getProperty("sm.debug.fetchProductCerts", "true"))) {
            log.info("Fetching the generated product certs...");
            // SSHCommandResult result = RemoteFileTasks.runCommandAndAssert(server, "find "+serverInstallDir+servertasks.generatedProductsDir+" -name '*.pem'", 0);
            // SSHCommandResult result = server.runCommandAndWait("find "+sm_serverInstallDir+servertasks.generatedProductsDir+" -name '*.pem'");	// find /root/candlepin/server/generated_certs -name '*.pem'
            // find /home/candlepin/candlepin -name '*.pem' | grep generated_certs
            SSHCommandResult result = server.runCommandAndWait("find " + sm_serverInstallDir + " -name '*.pem' | grep generated_certs");
            String[] remoteFilesAsString = result.getStdout().trim().split("\\n");
            if (remoteFilesAsString.length == 1 && remoteFilesAsString[0].equals(""))
                remoteFilesAsString = new String[] {};
            if (remoteFilesAsString.length == 0)
                log.warning("No generated product certs were found on the candlpin server for use in testing.");
            for (String remoteFileAsString : remoteFilesAsString) {
                File remoteFile = new File(remoteFileAsString);
                File localFile = new File((getProperty("automation.dir", "/tmp") + "/tmp/" + remoteFile.getName()).replace("tmp/tmp", "tmp"));
                // rename the generated productCertFile to help distinguish it from a true RHEL productCertFiles
                File localFileRenamed = new File(localFile.getPath().replace(".pem", "_.pem"));
                RemoteFileTasks.getFile(server, localFile.getParent(), remoteFile.getPath());
                localFile.renameTo(localFileRenamed);
                generatedProductCertFiles.add(localFileRenamed);
            }
        }
    }
    // fetch the candlepin CA Cert
    File serverCaCertFile = serverCaCertFile = fetchServerCaCertFile();
    // setup the client(s) (with the fetched candlepin CA Cert and the generated product certs)
    for (SubscriptionManagerTasks smt : new SubscriptionManagerTasks[] { client2tasks, client1tasks }) {
        if (smt != null)
            setupClient(smt, serverCaCertFile, generatedProductCertFiles);
    }
    // initialize various servertasks instance variables for future reference
    servertasks.initialize(clienttasks.candlepinAdminUsername, clienttasks.candlepinAdminPassword, clienttasks.candlepinUrl);
    // create an artifact to log all the package versions being tested
    // this will be in the automation.dir directory on hudson (workspace/automatjon/sm)
    File file = new File("test-output/version.txt");
    Writer output = new BufferedWriter(new FileWriter(file));
    String infoMsg;
    if (client1 != null) {
        infoMsg = "Client1 System Hostname: " + sm_client1Hostname + "\n";
        log.info(infoMsg);
        output.write(infoMsg + "\n");
        infoMsg = "Beaker Compose: " + client1tasks.compose + "\n";
        log.info(infoMsg);
        output.write(infoMsg + "\n");
        infoMsg = "Installed Packages:";
        log.info(infoMsg);
        output.write(infoMsg + "\n");
        // subscription-manager-0.63-1.el6.i686
        infoMsg = client1.runCommandAndWait("rpm -qa | egrep ^subscription-manager").getStdout();
        log.info(infoMsg);
        output.write(infoMsg + "\n");
        // python-rhsm-0.63-1.el6.i686
        infoMsg = client1.runCommandAndWait("rpm -qa | egrep ^python-rhsm").getStdout();
        log.info(infoMsg);
        output.write(infoMsg + "\n");
        infoMsg = client1.runCommandAndWait("rpm -q --whatprovides /etc/redhat-release").getStdout();
        log.info(infoMsg);
        output.write(infoMsg + "\n");
        infoMsg = "# cat /etc/redhat-release";
        log.info(infoMsg);
        output.write(infoMsg + "\n");
        // Red Hat Enterprise Linux Server release 6.1 Beta (Santiago)
        infoMsg = client1.runCommandAndWait("cat /etc/redhat-release").getStdout();
        log.info(infoMsg);
        output.write(infoMsg + "\n");
        infoMsg = "# uname -a";
        log.info(infoMsg);
        output.write(infoMsg + "\n");
        // Linux jsefler-onprem-server.usersys.redhat.com 2.6.32-122.el6.x86_64 #1 SMP Wed Mar 9 23:54:34 EST 2011 x86_64 x86_64 x86_64 GNU/Linux
        infoMsg = client1.runCommandAndWait("uname -a").getStdout();
        log.info(infoMsg);
        output.write(infoMsg + "\n");
        infoMsg = "# " + client1tasks.listCommand(null, null, null, true, null, null, null, null, null, null, null, null, null, null);
        log.info(infoMsg);
        output.write(infoMsg + "\n");
        infoMsg = client1.runCommandAndWait(client1tasks.listCommand(null, null, null, true, null, null, null, null, null, null, null, null, null, null)).getStdout();
        log.info(infoMsg);
        output.write(infoMsg + "\n");
        for (ProductCert productCert : client1tasks.getCurrentProductCerts()) {
            infoMsg = "# rpm -q --whatprovides " + productCert.file;
            log.info(infoMsg);
            output.write(infoMsg + "\n");
            infoMsg = client1.runCommandAndWait("rpm -q --whatprovides " + productCert.file).getStdout();
            log.info(infoMsg);
            output.write(infoMsg + "\n\n");
        }
        infoMsg = "# cat " + client1tasks.productIdJsonFile;
        log.info(infoMsg);
        output.write(infoMsg + "\n");
        infoMsg = client1.runCommandAndWait("cat " + client1tasks.productIdJsonFile).getStdout();
        log.info(infoMsg);
        output.write(infoMsg + "\n\n");
    }
    if (client2 != null) {
        infoMsg = "Client2 System Hostname: " + sm_client2Hostname + "\n";
        log.info(infoMsg);
        output.write(infoMsg + "\n");
        infoMsg = "Beaker Compose: " + client2tasks.compose + "\n";
        log.info(infoMsg);
        output.write(infoMsg + "\n");
        infoMsg = "Installed Packages:";
        log.info(infoMsg);
        output.write(infoMsg + "\n");
        // subscription-manager-0.63-1.el6.i686
        infoMsg = client2.runCommandAndWait("rpm -qa | egrep ^subscription-manager").getStdout();
        log.info(infoMsg);
        output.write(infoMsg + "\n");
        // python-rhsm-0.63-1.el6.i686
        infoMsg = client2.runCommandAndWait("rpm -qa | egrep ^python-rhsm").getStdout();
        log.info(infoMsg);
        output.write(infoMsg + "\n");
        infoMsg = client2.runCommandAndWait("rpm -q --whatprovides /etc/redhat-release").getStdout();
        log.info(infoMsg);
        output.write(infoMsg + "\n");
        infoMsg = "# cat /etc/redhat-release";
        log.info(infoMsg);
        output.write(infoMsg + "\n");
        // Red Hat Enterprise Linux Server release 6.1 Beta (Santiago)
        infoMsg = client2.runCommandAndWait("cat /etc/redhat-release").getStdout();
        log.info(infoMsg);
        output.write(infoMsg + "\n");
        infoMsg = "# uname -a";
        log.info(infoMsg);
        output.write(infoMsg + "\n");
        // Linux jsefler-onprem-server.usersys.redhat.com 2.6.32-122.el6.x86_64 #1 SMP Wed Mar 9 23:54:34 EST 2011 x86_64 x86_64 x86_64 GNU/Linux
        infoMsg = client2.runCommandAndWait("uname -a").getStdout();
        log.info(infoMsg);
        output.write(infoMsg + "\n");
        infoMsg = "# " + client2tasks.listCommand(null, null, null, true, null, null, null, null, null, null, null, null, null, null);
        log.info(infoMsg);
        output.write(infoMsg + "\n");
        infoMsg = client2.runCommandAndWait(client2tasks.listCommand(null, null, null, true, null, null, null, null, null, null, null, null, null, null)).getStdout();
        log.info(infoMsg);
        output.write(infoMsg + "\n");
        for (ProductCert productCert : client2tasks.getCurrentProductCerts()) {
            infoMsg = "# rpm -q --whatprovides " + productCert.file;
            log.info(infoMsg);
            output.write(infoMsg + "\n");
            infoMsg = client2.runCommandAndWait("rpm -q --whatprovides " + productCert.file).getStdout();
            log.info(infoMsg);
            output.write(infoMsg + "\n\n");
        }
        infoMsg = "# cat " + client2tasks.productIdJsonFile;
        log.info(infoMsg);
        output.write(infoMsg + "\n");
        infoMsg = client2.runCommandAndWait("cat " + client2tasks.productIdJsonFile).getStdout();
        log.info(infoMsg);
        output.write(infoMsg + "\n\n");
    }
    output.close();
    // create an artifact containing package versions that can be uploaded to Polarion Group ID
    String groupId = "";
    if (clienttasks.isPackageVersion("subscription-manager", ">=", "0") != null) {
        groupId += " " + clienttasks.installedPackageVersionMap.get("subscription-manager");
    }
    /* exclude for now since the Polarion Group ID should really be a multi-entry field
		 * RHEL Projects: Use of Group ID and Component for Test Runs
		 * https://projects.engineering.redhat.com/browse/POLARION-1201
		if (clienttasks.isPackageVersion("python-rhsm",">=","0")!=null) {
			groupId += " "+clienttasks.installedPackageVersionMap.get("python-rhsm");
		}
		if (clienttasks.isPackageVersion("subscription-manager-migration-data",">=","0")!=null) {
			groupId += " "+clienttasks.installedPackageVersionMap.get("subscription-manager-migration-data");
		}
		*/
    // strip off .el5
    groupId = groupId.replaceAll("\\.el" + clienttasks.redhatReleaseX, "");
    // strip off .arch
    groupId = groupId.replaceAll("\\." + clienttasks.arch + "|\\.noarch", "");
    groupId = groupId.trim();
    /*File*/
    // this will be in the automation.dir directory on hudson (workspace/automatjon/sm)
    file = new File("test-output/group-id.txt");
    /*Writer*/
    output = new BufferedWriter(new FileWriter(file));
    output.write(groupId);
    output.close();
    isSetupBeforeSuiteComplete = true;
}
Also used : SSHCommandRunner(com.redhat.qe.tools.SSHCommandRunner) FileWriter(java.io.FileWriter) SubscriptionManagerTasks(rhsm.cli.tasks.SubscriptionManagerTasks) ArrayList(java.util.ArrayList) ProductCert(rhsm.data.ProductCert) BufferedWriter(java.io.BufferedWriter) SSHCommandResult(com.redhat.qe.tools.SSHCommandResult) CandlepinTasks(rhsm.cli.tasks.CandlepinTasks) File(java.io.File) Writer(java.io.Writer) BufferedWriter(java.io.BufferedWriter) FileWriter(java.io.FileWriter) BeforeSuite(org.testng.annotations.BeforeSuite)

Example 2 with SSHCommandRunner

use of com.redhat.qe.tools.SSHCommandRunner in project rhsm-qe by RedHatQE.

the class FactsTests method testFactCheckRhelDistribution.

@// update=true	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-36610", "RHEL7-59318" }, 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: facts and rules: fact check RHEL distribution", groups = { "Tier2Tests", "blockedByBug-666540" }, dependsOnGroups = {}, enabled = true)
@ImplementsNitrateTest(caseId = 56329)
public void testFactCheckRhelDistribution() {
    // skip if client1 and client2 are not a Server and Workstation distributions
    SSHCommandRunner workClient = null, servClient = null;
    SubscriptionManagerTasks workClientTasks = null, servClientTasks = null;
    if (client1 != null && client1tasks.getRedhatRelease().startsWith("Red Hat Enterprise Linux Workstation")) {
        workClient = client1;
        workClientTasks = client1tasks;
    }
    if (client2 != null && client2tasks.getRedhatRelease().startsWith("Red Hat Enterprise Linux Workstation")) {
        workClient = client2;
        workClientTasks = client2tasks;
    }
    if (client1 != null && client1tasks.getRedhatRelease().startsWith("Red Hat Enterprise Linux Server")) {
        servClient = client1;
        servClientTasks = client1tasks;
    }
    if (client2 != null && client2tasks.getRedhatRelease().startsWith("Red Hat Enterprise Linux Server")) {
        servClient = client2;
        servClientTasks = client2tasks;
    }
    if (workClient == null || servClient == null) {
        throw new SkipException("This test requires a RHEL Workstation client and a RHEL Server client.");
    }
    // start with fresh registrations using the same clientusername user
    workClientTasks.unregister(null, null, null, null);
    servClientTasks.unregister(null, null, null, null);
    workClientTasks.register(sm_clientUsername, sm_clientPassword, sm_clientOrg, null, null, null, null, null, null, null, (String) null, null, null, null, null, false, null, null, null, null);
    servClientTasks.register(sm_clientUsername, sm_clientPassword, sm_clientOrg, null, null, null, null, null, null, null, (String) null, null, null, null, null, false, null, null, null, null);
    // get all the pools available to each client
    List<SubscriptionPool> workClientPools = workClientTasks.getCurrentlyAvailableSubscriptionPools();
    List<SubscriptionPool> servClientPools = servClientTasks.getCurrentlyAvailableSubscriptionPools();
    log.info("Verifying that the pools available to the Workstation consumer are not identitcal to those available to the Server consumer...");
    if (!(!workClientPools.containsAll(servClientPools) || !servClientPools.containsAll(workClientPools))) {
        // TODO This testcase needs more work.  Running on different variants of RHEL alone is not enough to assert that the available pools are different.  In fact, then should be the same if the subscriptions are all set with a variant attribute of ALL
        throw new SkipException("The info message above is not accurate... The assertion that the pools available to a Workstation consumer versus a Server consumer is applicable ONLY when the org's subscriptions includes a variant aware subscription.  In fact, if the org's subscriptions are all set with a variant attribute of ALL, then the available pools should be identical.  This automated test needs some work.");
    }
    Assert.assertTrue(!workClientPools.containsAll(servClientPools) || !servClientPools.containsAll(workClientPools), "Because the facts of a system client running RHEL Workstation versus RHEL Server should be different, the available subscription pools to these two systems should not be the same.");
// FIXME TODO Verify with development that these are valid asserts
// log.info("Verifying that the pools available to the Workstation consumer do not contain Server in the ProductName...");
// log.info("Verifying that the pools available to the Server consumer do not contain Workstation in the ProductName...");
}
Also used : SSHCommandRunner(com.redhat.qe.tools.SSHCommandRunner) SubscriptionManagerTasks(rhsm.cli.tasks.SubscriptionManagerTasks) SkipException(org.testng.SkipException) SubscriptionPool(rhsm.data.SubscriptionPool) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test) ImplementsNitrateTest(com.redhat.qe.auto.tcms.ImplementsNitrateTest) ImplementsNitrateTest(com.redhat.qe.auto.tcms.ImplementsNitrateTest)

Example 3 with SSHCommandRunner

use of com.redhat.qe.tools.SSHCommandRunner in project rhsm-qe by RedHatQE.

the class FactsTests method testBypassRulesDueToType.

@Test(description = "subscription-manager: facts and rules: bypass rules due to type", groups = { "Tier2Tests", "blockedByBug-641027" }, dependsOnGroups = {}, // 9/17/2013 this test has been disabled in favor of new BypassRulesDueToTypeAndCapabilities_Test
enabled = false)
// cores, ram, instance_multiplier, derived_product
@ImplementsNitrateTest(caseId = 56331)
public void testBypassRulesDueToType() throws Exception {
    // determine which client is a RHEL Workstation
    SSHCommandRunner client = null;
    SubscriptionManagerTasks clienttasks = null;
    if (client1 != null && client1tasks.getRedhatRelease().startsWith("Red Hat Enterprise Linux Workstation")) {
        client = client1;
        clienttasks = client1tasks;
    } else if (client2 != null && client2tasks.getRedhatRelease().startsWith("Red Hat Enterprise Linux Workstation")) {
        client = client2;
        clienttasks = client2tasks;
    } else {
        throw new SkipException("This test requires a Red Hat Enterprise Linux Workstation.");
    }
    // on a RHEL workstation register to candlepin (as type system)
    clienttasks.unregister(null, null, null, null);
    clienttasks.register(sm_clientUsername, sm_clientPassword, sm_clientOrg, null, ConsumerType.system, null, null, null, null, null, (String) null, null, null, null, null, false, null, null, null, null);
    // get a list of available pools and all available pools (for this system consumer)
    List<SubscriptionPool> compatiblePoolsAsSystemConsumer = clienttasks.getCurrentlyAvailableSubscriptionPools();
    List<SubscriptionPool> allPoolsAsSystemConsumer = clienttasks.getCurrentlyAllAvailableSubscriptionPools();
    Assert.assertFalse(compatiblePoolsAsSystemConsumer.containsAll(allPoolsAsSystemConsumer), "Without bypassing the rules, not *all* pools are available for subscribing by a type=system consumer.");
    Assert.assertTrue(allPoolsAsSystemConsumer.containsAll(compatiblePoolsAsSystemConsumer), "The pools available to a type=system consumer is a subset of --all --available pools.");
    // now register to candlepin (as type candlepin)
    clienttasks.unregister(null, null, null, null);
    clienttasks.register(sm_clientUsername, sm_clientPassword, sm_clientOrg, null, ConsumerType.candlepin, null, null, null, null, null, (String) null, null, null, null, null, false, null, null, null, null);
    // get a list of available pools and all available pools (for this candlepin consumer)
    List<SubscriptionPool> compatiblePoolsAsCandlepinConsumer = clienttasks.getCurrentlyAvailableSubscriptionPools();
    List<SubscriptionPool> allPoolsAsCandlepinConsumer = clienttasks.getCurrentlyAllAvailableSubscriptionPools();
    Assert.assertTrue(compatiblePoolsAsCandlepinConsumer.containsAll(allPoolsAsCandlepinConsumer) && allPoolsAsCandlepinConsumer.containsAll(compatiblePoolsAsCandlepinConsumer), "The pools available to a type=candlepin consumer bypass the rules (list --all --available is identical to list --available).");
    // now assert that all the pools can be subscribed to by the consumer (registered as type candlepin)
    clienttasks.subscribeToTheCurrentlyAvailableSubscriptionPoolsCollectively();
}
Also used : SSHCommandRunner(com.redhat.qe.tools.SSHCommandRunner) SubscriptionManagerTasks(rhsm.cli.tasks.SubscriptionManagerTasks) SkipException(org.testng.SkipException) SubscriptionPool(rhsm.data.SubscriptionPool) Test(org.testng.annotations.Test) ImplementsNitrateTest(com.redhat.qe.auto.tcms.ImplementsNitrateTest) ImplementsNitrateTest(com.redhat.qe.auto.tcms.ImplementsNitrateTest)

Example 4 with SSHCommandRunner

use of com.redhat.qe.tools.SSHCommandRunner in project rhsm-qe by RedHatQE.

the class ConfigTests method testConfigServerTimeouts.

@// update=true,	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-36672", "RHEL7-57876" }, 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 = "verify the [server]server_timeout can be configured and function properly when the server does not respond within the timeout seconds", groups = { "Tier2Tests", "blockedByBug-1346417", "VerifyConfigServerTimeouts_Test" }, priority = 100, enabled = true)
public // @ImplementsNitrateTest(caseId=)
void testConfigServerTimeouts() throws IOException {
    // this bug is specifically designed to test Bug 1346417 - [RFE] Allow users to set socket timeout.
    if (clienttasks.isPackageVersion("python-rhsm", "<", "1.17.3-1")) {
        // python-rhsm commit 5780140650a59d45a03372a0390f92fd7c3301eb Allow users to set socket timeout.
        throw new SkipException("This test applies a newer version of python-rhsm that includes an implementation for RFE Bug 1346417 - Allow users to set socket timeout.");
    }
    // before we test this bug, assert that the manual setup service is running...
    // instructions for setting this up are in scripts/timeout_listener.sh
    // let's use the auto-services.usersys.redhat.com as the timeout listener server sm_basicauthproxyHostname
    SSHCommandRunner timeoutServerCommandRunner = new SSHCommandRunner(sm_basicauthproxyHostname, sm_basicauthproxySSHUser, sm_sshKeyPrivate, sm_sshkeyPassphrase, null);
    if (sm_sshEmergenecyTimeoutMS != null)
        timeoutServerCommandRunner.setEmergencyTimeout(Long.valueOf(sm_sshEmergenecyTimeoutMS));
    SSHCommandResult timeoutServerServiceResult = timeoutServerCommandRunner.runCommandAndWait("systemctl is-active timeout_listener.service");
    Assert.assertContainsMatch(timeoutServerServiceResult.getStdout().trim(), "^active$", "The timeout_listener.service is running.  If this fails, then a one-time setup of the timeout_listener server on '" + sm_basicauthproxyHostname + "' is needed.  See the instructions in the automation scripts/timeout_listener.sh file.");
    // fetch the timeout_listener server  CA Cert
    log.info("Fetching timeout_listener CA cert...");
    // manually created on the timeoutServer as follows...
    File remoteTimeoutServerCaCertFile = new File("/root/timeout_listener/timeout_listener.pem");
    // [root@auto-services timeout_listener]# openssl genrsa -out timeout_listener.key 4096
    // [root@auto-services timeout_listener]# openssl req -new -x509 -key timeout_listener.key -out timeout_listener.pem -days 3650 -subj '/CN=auto-services.usersys.redhat.com/C=US/L=Raleigh'
    File localTimeoutServerCaCertFile = new File((getProperty("automation.dir", "/tmp") + "/tmp/" + remoteTimeoutServerCaCertFile.getName().replace("tmp/tmp", "tmp")));
    RemoteFileTasks.getFile(timeoutServerCommandRunner, localTimeoutServerCaCertFile.getParent(), remoteTimeoutServerCaCertFile.getPath());
    RemoteFileTasks.putFile(client, localTimeoutServerCaCertFile.getPath(), clienttasks.caCertDir + "/", "0644");
    // remember originally configured server configs
    if (serverHostnameConfigured == null)
        serverHostnameConfigured = clienttasks.getConfFileParameter(clienttasks.rhsmConfFile, "server", "hostname");
    if (serverPortConfigured == null)
        serverPortConfigured = clienttasks.getConfFileParameter(clienttasks.rhsmConfFile, "server", "port");
    // make sure server_timeout configuration is absent from the rhsm.conf file
    clienttasks.removeConfFileParameter(clienttasks.rhsmConfFile, "server_timeout");
    // use the config command to set rhsm configurations to point to the timeout server
    List<String[]> listOfSectionNameValues = new ArrayList<String[]>();
    listOfSectionNameValues.add(new String[] { "server", "hostname", sm_basicauthproxyHostname });
    // manually created on the timeoutServer as follows...
    listOfSectionNameValues.add(new String[] { "server", "port", "8883" });
    // [root@auto-services timeout_listener]# yum install nmap-ncat
    // [root@auto-services timeout_listener]# nc --ssl --ssl-key ./timeout_listener.key --ssl-cert ./timeout_listener.pem --listen --keep-open 8883
    clienttasks.config(null, null, true, listOfSectionNameValues);
    String command;
    Long sshCommandTimeout;
    SSHCommandResult result;
    List<String> realTimeList;
    String expectedStdout = "UNKNOWN STDOUT";
    String expectedStderr = "UNKNOWN STDERR";
    String expectedLogMessage = "UNKNOWN LOG ERROR";
    String marker = System.currentTimeMillis() + " Testing VerifyConfigServerTimeouts_Test...";
    String logResult;
    // test the default server_time value of 180 seconds
    if (clienttasks.redhatReleaseX.equals("7")) {
        // 2017-05-12 17:51:10,209 [ERROR] subscription-manager:23673:MainThread @utils.py:274 - Error while checking server version: ('The read operation timed out',)
        // 2017-05-12 17:51:10,209 [ERROR] subscription-manager:23673:MainThread @utils.py:276 - ('The read operation timed out',)
        expectedLogMessage = "Error while checking server version: ('The read operation timed out',)";
        // [root@jsefler-rhel7 ~]# time subscription-manager version
        // Unable to verify server's identity: timed out
        // 
        // real	3m0.568s
        // user	0m0.226s
        // sys		0m0.036s
        expectedStderr = "Unable to verify server's identity: timed out";
        expectedStdout = "";
        if (clienttasks.isPackageVersion("subscription-manager", ">=", "1.18.4-1")) {
            // post commit b0e877cfb099184f9bab1b681a41df9bdd2fb790 m2crypto dependency removal on RHEL7
            // [root@jsefler-rhel7 ~]# time subscription-manager version
            // server type: This system is currently not registered.
            // subscription management server: Unknown
            // subscription management rules: Unknown
            // subscription-manager: 1.19.12-1.el7
            // python-rhsm: 1.19.6-1.el7
            // 
            // real	3m0.482s
            // user	0m0.215s
            // sys	0m0.057s
            expectedStderr = "";
            expectedStdout = "server type: This system is currently not registered.\nsubscription management server: Unknown\nsubscription management rules: Unknown";
        }
    }
    if (clienttasks.redhatReleaseX.equals("6")) {
        // 2017-05-12 18:39:05,350 [ERROR] subscription-manager:14672:MainThread @utils.py:259 - Timeout error while checking server version
        // 2017-05-12 18:39:05,351 [ERROR] subscription-manager:14672:MainThread @utils.py:260 -
        expectedLogMessage = "Timeout error while checking server version";
        // [root@jsefler-rhel6 ~]# time subscription-manager version
        // Unable to verify server's identity:
        // 
        // real	3m0.555s
        // user	0m0.287s
        // sys		0m0.045s
        expectedStderr = "Unable to verify server's identity:";
        expectedStdout = "";
        if (clienttasks.isPackageVersion("subscription-manager", ">=", "1.18.4-1")) {
            // post commit b0e877cfb099184f9bab1b681a41df9bdd2fb790 side affect from m2crypto dependency removal on RHEL7
            // [root@jsefler-rhel6 ~]# subscription-manager version
            // System certificates corrupted. Please reregister.
            expectedStderr = "System certificates corrupted. Please reregister.";
        // Note: This ^ new stderr is not the greatest message; however if you follow the instructions and try to reregister, you will eventually hit the original stderr....
        // [root@jsefler-rhel6 ~]# subscription-manager register --force
        // Registering to: auto-services.usersys.redhat.com:8883/candlepin
        // Username: testuser1
        // Password:
        // Unable to verify server's identity:
        // [root@jsefler-rhel6 ~]#
        }
    }
    // seconds (assumed hard-coded default)
    String serverDefaultTimeout = "180";
    command = "time " + clienttasks.versionCommand(null, null, null, null);
    // seconds	// default server_timeout is 180 seconds
    sshCommandTimeout = new Long(200);
    marker = System.currentTimeMillis() + " Testing VerifyConfigServerTimeouts_Test...";
    RemoteFileTasks.markFile(client, clienttasks.rhsmLogFile, marker);
    result = client.runCommandAndWait(command, Long.valueOf(sshCommandTimeout * 1000));
    clienttasks.logRuntimeErrors(result);
    logResult = RemoteFileTasks.getTailFromMarkedFile(client, clienttasks.rhsmLogFile, marker, "ERROR").trim();
    Assert.assertTrue(logResult.contains(expectedLogMessage), "Log file '" + clienttasks.rhsmLogFile + "' contains expected message '" + expectedLogMessage + "'.");
    // extract the matches to: real	3m0.568s
    realTimeList = getSubstringMatches(result.getStderr(), "real\\s+.*");
    if (realTimeList.size() != 1)
        Assert.fail("Failed to find the real time it took to run command '" + command + "'.  (The automated test gave up waiting for the server to reply after '" + sshCommandTimeout + "' seconds.  Is the server hung?)");
    // using startsWith() to tolerate fractional seconds
    Assert.assertTrue(realTimeList.get(0).replaceFirst("real\\s+", "").startsWith("3m0."), "Testing server_timeout=" + serverDefaultTimeout + " seconds actually times out at this time.");
    Assert.assertTrue(result.getStderr().startsWith(expectedStderr), "When a server_timeout occurs, subscription-manager stderr starts with '" + expectedStderr + "'.");
    Assert.assertTrue(result.getStdout().startsWith(expectedStdout), "When a server_timeout occurs, subscription-manager stdout starts with '" + expectedStdout + "'.");
    // also test a server_time value of N seconds
    for (String server_timeout : Arrays.asList("4", "10")) {
        // seconds
        listOfSectionNameValues.clear();
        listOfSectionNameValues.add(new String[] { "server", "server_timeout", server_timeout });
        clienttasks.config(null, null, true, listOfSectionNameValues);
        command = "time " + clienttasks.versionCommand(null, null, null, null);
        // seconds	// default server_timeout is 180 seconds
        sshCommandTimeout = new Long(200);
        marker = System.currentTimeMillis() + " Testing VerifyConfigServerTimeouts_Test...";
        RemoteFileTasks.markFile(client, clienttasks.rhsmLogFile, marker);
        result = client.runCommandAndWait(command, Long.valueOf(sshCommandTimeout * 1000));
        clienttasks.logRuntimeErrors(result);
        logResult = RemoteFileTasks.getTailFromMarkedFile(client, clienttasks.rhsmLogFile, marker, "ERROR").trim();
        Assert.assertTrue(logResult.contains(expectedLogMessage), "Log file '" + clienttasks.rhsmLogFile + "' contains expected message '" + expectedLogMessage + "'.");
        // extract the matches to: real	3m0.568s
        realTimeList = getSubstringMatches(result.getStderr(), "real\\s+.*");
        if (realTimeList.size() != 1)
            Assert.fail("Failed to find the real time it took to run command '" + command + "'.  (The automated test gave up waiting for the server to reply after '" + sshCommandTimeout + "' seconds.  Is the server hung?)");
        // using startsWith() to tolerate fractional seconds
        Assert.assertTrue(realTimeList.get(0).replaceFirst("real\\s+", "").startsWith("0m" + server_timeout + "."), "Testing server_timeout=" + server_timeout + " seconds actually times out at this time");
        Assert.assertTrue(result.getStderr().startsWith(expectedStderr), "When a server_timeout occurs, subscription-manager stderr starts with '" + expectedStderr + "'.");
        Assert.assertTrue(result.getStdout().startsWith(expectedStdout), "When a server_timeout occurs, subscription-manager stdout starts with '" + expectedStdout + "'.");
    }
}
Also used : SSHCommandRunner(com.redhat.qe.tools.SSHCommandRunner) SSHCommandResult(com.redhat.qe.tools.SSHCommandResult) ArrayList(java.util.ArrayList) SkipException(org.testng.SkipException) File(java.io.File) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test)

Example 5 with SSHCommandRunner

use of com.redhat.qe.tools.SSHCommandRunner in project rhsm-qe by RedHatQE.

the class ProxyTests method setupBeforeClass.

@BeforeClass(groups = { "setup" })
public void setupBeforeClass() throws IOException {
    basicauthproxy = new SSHCommandRunner(sm_basicauthproxyHostname, sm_basicauthproxySSHUser, sm_sshKeyPrivate, sm_sshkeyPassphrase, null);
    noauthproxy = new SSHCommandRunner(sm_noauthproxyHostname, sm_noauthproxySSHUser, sm_sshKeyPrivate, sm_sshkeyPassphrase, null);
    unauthproxy = new SSHCommandRunner(sm_unauthproxyHostname, sm_unauthproxySSHUser, sm_sshKeyPrivate, sm_sshkeyPassphrase, null);
    if (sm_sshEmergenecyTimeoutMS != null)
        basicauthproxy.setEmergencyTimeout(Long.valueOf(sm_sshEmergenecyTimeoutMS));
    if (sm_sshEmergenecyTimeoutMS != null)
        noauthproxy.setEmergencyTimeout(Long.valueOf(sm_sshEmergenecyTimeoutMS));
    if (sm_sshEmergenecyTimeoutMS != null)
        unauthproxy.setEmergencyTimeout(Long.valueOf(sm_sshEmergenecyTimeoutMS));
    if (clienttasks != null)
        nErrMsg = clienttasks.msg_NetworkErrorUnableToConnect;
    if (clienttasks != null)
        pErrMsg = clienttasks.msg_ProxyConnectionFailed;
    if (clienttasks != null)
        pErr407Msg = clienttasks.msg_ProxyConnectionFailed407;
    if (clienttasks != null)
        pErrConMsg = clienttasks.msg_ProxyErrorUnableToConnect;
    if (clienttasks != null) {
        String hostname = clienttasks.getConfParameter("hostname");
        String prefix = clienttasks.getConfParameter("prefix");
        String port = clienttasks.getConfParameter("port");
        // Unable to reach the server at jsefler-candlepin7.usersys.redhat.com:8443/candlepin	// Last request from /var/log/rhsm/rhsm.log results in: error: Tunnel connection failed: 407 Proxy Authentication Required
        rErrMsg = "Unable to reach the server at " + hostname + ":" + port + prefix;
    }
    if (clienttasks != null)
        ipv4_address = clienttasks.getIPV4Address();
}
Also used : SSHCommandRunner(com.redhat.qe.tools.SSHCommandRunner) BeforeClass(org.testng.annotations.BeforeClass)

Aggregations

SSHCommandRunner (com.redhat.qe.tools.SSHCommandRunner)6 SkipException (org.testng.SkipException)3 Test (org.testng.annotations.Test)3 SubscriptionManagerTasks (rhsm.cli.tasks.SubscriptionManagerTasks)3 TestDefinition (com.github.redhatqe.polarize.metadata.TestDefinition)2 ImplementsNitrateTest (com.redhat.qe.auto.tcms.ImplementsNitrateTest)2 SSHCommandResult (com.redhat.qe.tools.SSHCommandResult)2 File (java.io.File)2 ArrayList (java.util.ArrayList)2 BeforeClass (org.testng.annotations.BeforeClass)2 SubscriptionPool (rhsm.data.SubscriptionPool)2 BufferedWriter (java.io.BufferedWriter)1 FileWriter (java.io.FileWriter)1 Writer (java.io.Writer)1 BeforeSuite (org.testng.annotations.BeforeSuite)1 CandlepinTasks (rhsm.cli.tasks.CandlepinTasks)1 ProductCert (rhsm.data.ProductCert)1