Search in sources :

Example 56 with SSHCommandResult

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

the class SubscriptionManagerTasks method deleteRhnSystemsRegisteredByName.

public void deleteRhnSystemsRegisteredByName(String rhnUsername, String rhnPassword, String rhnHostname, String systemName) {
    String serverUrl = rhnHostname;
    if (!serverUrl.startsWith("http"))
        serverUrl = "https://" + serverUrl;
    String command = String.format("rhn-delete-systems.py --username=%s --password=%s --serverurl=%s --delete-by-name %s", rhnUsername, rhnPassword, serverUrl, systemName);
    SSHCommandResult result = sshCommandRunner.runCommandAndWait(command);
// return (result.getExitCode());
}
Also used : SSHCommandResult(com.redhat.qe.tools.SSHCommandResult)

Example 57 with SSHCommandResult

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

the class ActivationKeyTests method testRegisterWithActivationKeyContainingReleaseVer.

@// update=true,	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-21799", "RHEL7-51616" }, 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 = "Tier3")
@Test(description = "create an activation key, add a release to it, and then register with the activation key", groups = { "Tier3Tests", "blockedByBug-1062292" }, enabled = true)
public // @ImplementsNitrateTest(caseId=)
void testRegisterWithActivationKeyContainingReleaseVer() throws JSONException, Exception {
    // generate a unique activation key name for this test
    String keyName = String.format("ActivationKey%s_WithReleaseVer", System.currentTimeMillis());
    // choose a releaseVer value
    String releaseVer = "R_1.0";
    // create a JSON object to represent the request body
    Map<String, String> mapActivationKeyRequest = new HashMap<String, String>();
    mapActivationKeyRequest.put("name", keyName);
    mapActivationKeyRequest.put("releaseVer", releaseVer);
    JSONObject jsonActivationKeyRequest = new JSONObject(mapActivationKeyRequest);
    // call the candlepin api to create an activation key
    // [root@jsefler-7 ~]# curl --stderr /dev/null --insecure --user testuser1:password --request POST --data '{"name":"ActivationKey1393948948190_WithReleaseVer","releaseVer":"R_1.0"}' --header 'accept: application/json' --header 'content-type: application/json' https://jsefler-f14-candlepin.usersys.redhat.com:8443/candlepin/owners/admin/activation_keys | python -m simplejson/tool
    JSONObject jsonActivationKey = new JSONObject(CandlepinTasks.postResourceUsingRESTfulAPI(sm_clientUsername, sm_clientPassword, sm_serverUrl, "/owners/" + sm_clientOrg + "/activation_keys", jsonActivationKeyRequest.toString()));
    // jsonActivationKey = new JSONObject(CandlepinTasks.getResourceUsingRESTfulAPI(sm_serverAdminUsername,sm_serverAdminPassword,sm_serverUrl,"/activation_keys/"+jsonActivationKey.getString("id")));
    // [root@jsefler-7 ~]# curl --stderr /dev/null --insecure --user admin:admin --request GET https://jsefler-f14-candlepin.usersys.redhat.com:8443/candlepin/activation_keys/8a9087e3448960ba01448dd50b1b2c0b | python -m simplejson/tool
    // {
    // "contentOverrides": [],
    // "created": "2014-03-04T16:02:33.371+0000",
    // "id": "8a9087e3448960ba01448dd50b1b2c0b",
    // "name": "ActivationKey1393948948190_WithReleaseVer",
    // "owner": {
    // "displayName": "Admin Owner",
    // "href": "/owners/admin",
    // "id": "8a9087e3448960ba01448960df840001",
    // "key": "admin"
    // },
    // "pools": [],
    // "releaseVer": {
    // "releaseVer": "R_1.0"
    // },
    // "updated": "2014-03-04T16:02:33.371+0000"
    // }
    // register with the activation key
    clienttasks.register(null, null, sm_clientOrg, null, null, null, null, null, null, null, keyName, null, null, null, true, null, null, null, null, null);
    // verify the current release equals the value set in the activation key
    Assert.assertEquals(clienttasks.getCurrentRelease(), releaseVer, "After registering with an activation key containing a releaseVer, the current release is properly set.");
    // POST to /activation_keys/<id>/release to set an updated releaseVer...
    /* NOT ANYMORE... Candlepin Commit d005f2e7f00546ab5c66208225e99d4db105f33e changed this behavior to use PUT /activation_keys/<id>
		releaseVer = "R_2.0";
		mapActivationKeyRequest.clear();
		mapActivationKeyRequest.put("releaseVer", releaseVer);
		jsonActivationKeyRequest = new JSONObject(mapActivationKeyRequest);
		//	[root@jsefler-7 ~]# curl --stderr /dev/null --insecure --user testuser1:password --request POST --data '{"releaseVer":"R_2.0"}' --header 'accept: application/json' --header 'content-type: application/json' https://jsefler-f14-candlepin.usersys.redhat.com:8443/candlepin/activation_keys/8a9087e3448960ba01448df4e5b92cdb/release
		jsonActivationKey = new JSONObject(CandlepinTasks.postResourceUsingRESTfulAPI(sm_clientUsername, sm_clientPassword, sm_serverUrl, "/activation_keys/"+jsonActivationKey.getString("id")+"/release", jsonActivationKeyRequest.toString()));
		//	[root@jsefler-7 ~]# curl --stderr /dev/null --insecure --user admin:admin --request GET https://jsefler-f14-candlepin.usersys.redhat.com:8443/candlepin/activation_keys/8a9087e3448960ba01448df4e5b92cdb | python -m simplejson/tool
		//	{
		//	    "contentOverrides": [],
		//	    "created": "2014-03-04T16:37:20.953+0000",
		//	    "id": "8a9087e3448960ba01448df4e5b92cdb",
		//	    "name": "ActivationKey1393951040595_WithReleaseVer",
		//	    "owner": {
		//	        "displayName": "Admin Owner",
		//	        "href": "/owners/admin",
		//	        "id": "8a9087e3448960ba01448960df840001",
		//	        "key": "admin"
		//	    },
		//	    "pools": [],
		//	    "releaseVer": {
		//	        "releaseVer": "R_2.0"
		//	    },
		//	    "updated": "2014-03-04T16:37:52.768+0000"
		//	}
		 */
    // PUT to /activation_keys/<id> to set an updated releaseVer...
    releaseVer = "R_2.0";
    mapActivationKeyRequest.clear();
    mapActivationKeyRequest.put("releaseVer", releaseVer);
    jsonActivationKeyRequest = new JSONObject(mapActivationKeyRequest);
    // [root@jsefler-7 ~]# curl --stderr /dev/null --insecure --user testuser1:password --request PUT --data '{"releaseVer":"R_2.0"}' --header 'accept: application/json' --header 'content-type: application/json' https://jsefler-f14-candlepin.usersys.redhat.com:8443/candlepin/activation_keys/8a9087e3452995d301452d14c41e3858 | python -m simplejson/tool
    jsonActivationKey = new JSONObject(CandlepinTasks.putResourceUsingRESTfulAPI(sm_clientUsername, sm_clientPassword, sm_serverUrl, "/activation_keys/" + jsonActivationKey.getString("id"), jsonActivationKeyRequest));
    // [root@jsefler-7 ~]# curl --stderr /dev/null --insecure --user admin:admin --request GET https://jsefler-f14-candlepin.usersys.redhat.com:8443/candlepin/activation_keys/8a9087e3452995d301452d14c41e3858 | python -m simplejson/tool
    // {
    // "contentOverrides": [],
    // "created": "2014-04-04T14:11:46.846+0000",
    // "id": "8a9087e3452995d301452d14c41e3858",
    // "name": "ActivationKey1396620706731_WithReleaseVer",
    // "owner": {
    // "displayName": "Admin Owner",
    // "href": "/owners/admin",
    // "id": "8a9087e3452995d30145299600ac0004",
    // "key": "admin"
    // },
    // "pools": [],
    // "releaseVer": {
    // "releaseVer": "R_2.0"
    // },
    // "serviceLevel": null,
    // "updated": "2014-04-04T14:12:12.546+0000"
    // }
    // reregister with the same activation key
    clienttasks.register(null, null, sm_clientOrg, null, null, null, null, null, null, null, keyName, null, null, null, true, null, null, null, null, null);
    // verify the current release equals the new value set in the activation key
    Assert.assertEquals(clienttasks.getCurrentRelease(), releaseVer, "After registering with an activation key containing an updated releaseVer, the current release is properly set.");
    // finally, verify that there are no contentOverrides
    if (clienttasks.isPackageVersion("subscription-manager", ">=", "1.10.7-1")) {
        SSHCommandResult listResult = clienttasks.repo_override(true, null, (String) null, (String) null, null, null, null, null, null);
        Assert.assertEquals(listResult.getStdout().trim(), "This system does not have any content overrides applied to it.", "After registering with an activation key containing a releaseVer, but no contentOverrides, this is the subscription-manager repo-override report.");
    }
}
Also used : JSONObject(org.json.JSONObject) HashMap(java.util.HashMap) SSHCommandResult(com.redhat.qe.tools.SSHCommandResult) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test)

Example 58 with SSHCommandResult

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

the class ActivationKeyTests method testRegisterWithSequenceOfMultipleActivationKeys.

@// update=true,	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-21803", "RHEL7-51620" }, 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 = "Tier3")
@Test(description = "create many activation keys with one added pool per key and then register with a sequence of many --activationkey parameters asserting each pool per key gets consumed", groups = { "Tier3Tests", "blockedByBug-878986", "blockedByBug-979492", "blockedByBug-1040101" }, enabled = true)
public // @ImplementsNitrateTest(caseId=)
void testRegisterWithSequenceOfMultipleActivationKeys() throws JSONException, Exception {
    // get all of the pools belonging to ownerKey
    JSONArray jsonPools = new JSONArray(CandlepinTasks.getResourceUsingRESTfulAPI(sm_clientUsername, sm_clientPassword, sm_serverUrl, "/owners/" + sm_clientOrg + "/pools?listall=true"));
    if (!(jsonPools.length() > 1))
        throw new SkipException("This test requires more than one pool for org '" + sm_clientOrg + "'.");
    jsonPools = clienttasks.workaroundForBug1040101(jsonPools);
    // process each of the pools adding them to an individual activation key
    List<String> activationKeyNames = new ArrayList<String>();
    Integer addQuantity = null;
    JSONArray jsonPoolsAddedToActivationKey = new JSONArray();
    boolean isSystemVirtual = Boolean.valueOf(clienttasks.getFactValue("virt.is_guest"));
    for (int i = 0; i < jsonPools.length(); i++) {
        JSONObject jsonPool = (JSONObject) jsonPools.get(i);
        // for the purpose of this test, skip pools with no available entitlements (consumed>=quantity) (quantity=-1 is unlimited)
        if (jsonPool.getInt("quantity") > 0 && jsonPool.getInt("consumed") >= jsonPool.getInt("quantity"))
            continue;
        // for the purpose of this test, skip non-system pools otherwise the register will fail with "Consumers of this type are not allowed to subscribe to the pool with id '8a90f8c631ab7ccc0131ab7e46ca0619'."
        if (!CandlepinTasks.isPoolProductConsumableByConsumerType(sm_clientUsername, sm_clientPassword, sm_serverUrl, jsonPool.getString("id"), ConsumerType.system))
            continue;
        // for the purpose of this test, skip physical_only pools when system is virtual otherwise the register will fail with "Pool is restricted to physical systems: '8a9086d344549b0c0144549bf9ae0dd4'."
        if (isSystemVirtual && CandlepinTasks.isPoolRestrictedToPhysicalSystems(sm_clientUsername, sm_clientPassword, sm_serverUrl, jsonPool.getString("id")))
            continue;
        // for the purpose of this test, skip virt_only pools when system is physical otherwise the register will fail with "Pool is restricted to virtual guests: '8a9086d344549b0c0144549bf9ae0dd4'."
        if (!isSystemVirtual && CandlepinTasks.isPoolRestrictedToVirtualSystems(sm_clientUsername, sm_clientPassword, sm_serverUrl, jsonPool.getString("id")))
            continue;
        /* skipping pools that are not NORMAL is more reliable than this...
			// for the purpose of this test, skip virt_only derived_pool when server is standalone otherwise the register will fail with "Unable to entitle consumer to the pool with id '8a90f85733d86b130133d88c09410e5e'.: virt.guest.host.does.not.match.pool.owner"
			//if (servertasks.statusStandalone) {	// 5/29/2014 removed this check, I can't remember why I originally set it 
			// for the purpose of this test, skip virt_only derived_pool when otherwise the register will fail with "Guest's host does not match owner of pool: '8a908775463fef2301464072ee68496e'."
			if (true) {
				String pool_derived = CandlepinTasks.getPoolAttributeValue(jsonPool, "pool_derived");
				String virt_only = CandlepinTasks.getPoolAttributeValue(jsonPool, "virt_only");
				if (pool_derived!=null && virt_only!=null && Boolean.valueOf(pool_derived) && Boolean.valueOf(virt_only)) {
					continue;
				}
			}
			*/
        // for the purpose of this test, skip pools that are not NORMAL (eg. BONUS, ENTITLEMENT_DERIVED, STACK_DERIVED)
        String poolType = (String) CandlepinTasks.getPoolValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, jsonPool.getString("id"), "type");
        if (!poolType.equals("NORMAL"))
            continue;
        // create an activation key
        String activationKeyName = String.format("ActivationKey%sWithPool%sForOrg_%s", System.currentTimeMillis(), jsonPool.getString("id"), sm_clientOrg);
        Map<String, String> mapActivationKeyRequest = new HashMap<String, String>();
        mapActivationKeyRequest.put("name", activationKeyName);
        JSONObject jsonActivationKeyRequest = new JSONObject(mapActivationKeyRequest);
        JSONObject jsonActivationKey = new JSONObject(CandlepinTasks.postResourceUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, "/owners/" + sm_clientOrg + "/activation_keys", jsonActivationKeyRequest.toString()));
        // add the pool to the activation key
        String path = "/activation_keys/" + jsonActivationKey.getString("id") + "/pools/" + jsonPool.getString("id") + (addQuantity == null ? "" : "?quantity=" + addQuantity);
        JSONObject jsonResult = new JSONObject(CandlepinTasks.postResourceUsingRESTfulAPI(sm_clientUsername, sm_clientPassword, sm_serverUrl, path, null));
        // if (clienttasks.isVersion(servertasks.statusVersion, ">", "0.9.30-1")) the POST now returns the jsonActivationKey and formerly returned the jsonPoolAddedToActivationKey	// candlepin commit 82b9af5dc2c63b58447366e680fcf6f156c6049f
        if (jsonResult.has("displayMessage")) {
            Assert.fail("Failed to add pool '" + jsonPool.getString("productId") + "' '" + jsonPool.getString("id") + "' to activation key '" + jsonActivationKey.getString("id") + "'.  DisplayMessage: " + jsonResult.getString("displayMessage"));
        }
        jsonPoolsAddedToActivationKey.put(jsonPool);
        activationKeyNames.add(activationKeyName);
    }
    if (addQuantity == null)
        addQuantity = 1;
    // register with the activation key specified as a single string
    SSHCommandResult registerResult = clienttasks.register(null, null, sm_clientOrg, null, null, null, null, null, null, null, activationKeyNames, null, null, null, true, null, null, null, null, null);
    // assert that all the pools were consumed
    List<ProductSubscription> consumedProductSubscriptions = clienttasks.getCurrentlyConsumedProductSubscriptions();
    for (int i = 0; i < jsonPoolsAddedToActivationKey.length(); i++) {
        JSONObject jsonPoolAdded = (JSONObject) jsonPoolsAddedToActivationKey.get(i);
        // assert that the pool's providedProducts (excluding type=MKT products) are consumed (unless it is a ManagementAddOn product - indicated by no providedProducts)
        assertProvidedProductsFromPoolAreWithinConsumedProductSubscriptionsUsingQuantity(jsonPoolAdded, consumedProductSubscriptions, addQuantity, false);
    }
    Assert.assertEquals(clienttasks.getCurrentEntitlementCertFiles().size(), activationKeyNames.size(), "Expecting a new entitlement cert file in '" + clienttasks.entitlementCertDir + "' for each of the single pooled activation keys used during register.");
}
Also used : HashMap(java.util.HashMap) JSONArray(org.json.JSONArray) ArrayList(java.util.ArrayList) ProductSubscription(rhsm.data.ProductSubscription) JSONObject(org.json.JSONObject) SSHCommandResult(com.redhat.qe.tools.SSHCommandResult) SkipException(org.testng.SkipException) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test)

Example 59 with SSHCommandResult

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

the class ActivationKeyTests method testMultiClientAttemptToDeadLockOnRegisterWithActivationKeys.

@// update=true,	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-21791", "RHEL7-51608" }, level = DefTypes.Level.COMPONENT, component = "subscription-manager", testtype = @TestType(testtype = DefTypes.TestTypes.FUNCTIONAL, subtype1 = DefTypes.Subtypes.RELIABILITY, subtype2 = DefTypes.Subtypes.EMPTY), posneg = PosNeg.NEGATIVE, importance = DefTypes.Importance.HIGH, automation = DefTypes.Automation.AUTOMATED, tags = "Tier3")
@Test(description = "attempt to register two different consumers with multiple activation keys (in reverse order) containing many subscriptions", groups = { "Tier3Tests", "blockedByBug-1095939" })
public // @ImplementsNitrateTest(caseId=)
void testMultiClientAttemptToDeadLockOnRegisterWithActivationKeys() throws JSONException, Exception {
    if (client2tasks == null)
        throw new SkipException("This multi-client test requires a second client.");
    // register two clients
    String client1ConsumerId = client1tasks.getCurrentConsumerId(client1tasks.register(sm_client1Username, sm_client1Password, sm_client1Org, null, null, null, null, null, null, null, (List<String>) null, null, null, null, true, false, null, null, null, null));
    String client2ConsumerId = client2tasks.getCurrentConsumerId(client2tasks.register(sm_client2Username, sm_client2Password, sm_client2Org, null, null, null, null, null, null, null, (List<String>) null, null, null, null, true, false, null, null, null, null));
    String client1OwnerKey = CandlepinTasks.getOwnerKeyOfConsumerId(sm_client1Username, sm_client1Password, sm_serverUrl, client1ConsumerId);
    String client2OwnerKey = CandlepinTasks.getOwnerKeyOfConsumerId(sm_client2Username, sm_client2Password, sm_serverUrl, client2ConsumerId);
    if (!client1OwnerKey.equals(client2OwnerKey))
        throw new SkipException("This multi-client test requires that both client registerers belong to the same owner. (client1: username=" + sm_client1Username + " ownerkey=" + client1OwnerKey + ") (client2: username=" + sm_client2Username + " ownerkey=" + client2OwnerKey + ")");
    // get all of the pools belonging to ownerKey
    JSONArray jsonPools = new JSONArray(CandlepinTasks.getResourceUsingRESTfulAPI(sm_clientUsername, sm_clientPassword, sm_serverUrl, "/owners/" + client1OwnerKey + "/pools?listall=true"));
    if (!(jsonPools.length() > 1))
        throw new SkipException("This test requires more than one pool for org '" + sm_client1Org + "'.");
    jsonPools = clienttasks.workaroundForBug1040101(jsonPools);
    // create two activation key each containing the same pools (added in reverse order)
    long currentTimeMillis = System.currentTimeMillis();
    final String activationKeyName1 = String.format("ActivationKey1_%sWithMultiplePoolsForOrgKey_%s", currentTimeMillis, client1OwnerKey);
    final String activationKeyName2 = String.format("ActivationKey2_%sWithMultiplePoolsForOrgKey_%s", currentTimeMillis, client2OwnerKey);
    Map<String, String> mapActivationKeyRequest1 = new HashMap<String, String>() {

        {
            put("name", activationKeyName1);
        }
    };
    Map<String, String> mapActivationKeyRequest2 = new HashMap<String, String>() {

        {
            put("name", activationKeyName2);
        }
    };
    JSONObject jsonActivationKey1 = new JSONObject(CandlepinTasks.postResourceUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, "/owners/" + client1OwnerKey + "/activation_keys", new JSONObject(mapActivationKeyRequest1).toString()));
    JSONObject jsonActivationKey2 = new JSONObject(CandlepinTasks.postResourceUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, "/owners/" + client2OwnerKey + "/activation_keys", new JSONObject(mapActivationKeyRequest2).toString()));
    // process each of the pools to choosing friendly ones to add to the activation keys
    List<String> poolIds = new ArrayList<String>();
    boolean isSystemVirtual = Boolean.valueOf(clienttasks.getFactValue("virt.is_guest"));
    for (int i = 0; i < jsonPools.length(); i++) {
        JSONObject jsonPool = (JSONObject) jsonPools.get(i);
        // for the purpose of this test, skip pools with no available entitlements (consumed>=quantity) (quantity=-1 is unlimited)
        if (jsonPool.getInt("quantity") > 0 && jsonPool.getInt("consumed") >= jsonPool.getInt("quantity"))
            continue;
        // for the purpose of this test, skip pools that do not have at least 4 available entitlements
        if (jsonPool.getInt("quantity") >= 0 && (jsonPool.getInt("quantity") - jsonPool.getInt("consumed")) < 4)
            continue;
        // for the purpose of this test, skip non-system pools otherwise the register will fail with "Consumers of this type are not allowed to subscribe to the pool with id '8a90f8c631ab7ccc0131ab7e46ca0619'."
        if (!CandlepinTasks.isPoolProductConsumableByConsumerType(sm_clientUsername, sm_clientPassword, sm_serverUrl, jsonPool.getString("id"), ConsumerType.system))
            continue;
        // for the purpose of this test, skip physical_only pools when system is virtual otherwise the register will fail with "Pool is restricted to physical systems: '8a9086d344549b0c0144549bf9ae0dd4'."
        if (isSystemVirtual && CandlepinTasks.isPoolRestrictedToPhysicalSystems(sm_clientUsername, sm_clientPassword, sm_serverUrl, jsonPool.getString("id")))
            continue;
        // for the purpose of this test, skip virt_only pools when system is physical otherwise the register will fail with "Pool is restricted to virtual guests: '8a9086d344549b0c0144549bf9ae0dd4'."
        if (!isSystemVirtual && CandlepinTasks.isPoolRestrictedToVirtualSystems(sm_clientUsername, sm_clientPassword, sm_serverUrl, jsonPool.getString("id")))
            continue;
        // for the purpose of this test, skip virt_only derived_pool when server is standalone otherwise the register will fail with "Unable to entitle consumer to the pool with id '8a90f85733d86b130133d88c09410e5e'.: virt.guest.host.does.not.match.pool.owner"
        if (servertasks.statusStandalone) {
            String pool_derived = CandlepinTasks.getPoolAttributeValue(jsonPool, "pool_derived");
            String virt_only = CandlepinTasks.getPoolAttributeValue(jsonPool, "virt_only");
            if (pool_derived != null && virt_only != null && Boolean.valueOf(pool_derived) && Boolean.valueOf(virt_only)) {
                continue;
            }
        }
        // for the purpose of this test, skip non-multi-entitlement pools otherwise the multi-activation key register will fail with "This unit has already had the subscription matching pool ID '8a9087e345a9f5f90145b36429073724' attached."
        if (!CandlepinTasks.isPoolProductMultiEntitlement(sm_clientUsername, sm_clientPassword, sm_serverUrl, jsonPool.getString("id")))
            continue;
        poolIds.add(jsonPool.getString("id"));
    }
    // add each of the pools to jsonActivationKey1
    for (int i = 0; i < poolIds.size(); i++) {
        JSONObject jsonResult1 = new JSONObject(CandlepinTasks.postResourceUsingRESTfulAPI(sm_client1Username, sm_client1Password, sm_serverUrl, "/activation_keys/" + jsonActivationKey1.getString("id") + "/pools/" + poolIds.get(i), /* + (addQuantity==null?"":"?quantity="+addQuantity)*/
        null));
        // if (clienttasks.isVersion(servertasks.statusVersion, ">", "0.9.30-1")) the POST now returns the jsonActivationKey and formerly returned the jsonPoolAddedToActivationKey	// candlepin commit 82b9af5dc2c63b58447366e680fcf6f156c6049f
        if (jsonResult1.has("displayMessage")) {
            Assert.fail("Failed to add pool '" + poolIds.get(i) + "' to activation key '" + jsonActivationKey1.getString("id") + "'.  DisplayMessage: " + jsonResult1.getString("displayMessage"));
        }
    }
    // add each of the pools to jsonActivationKey2 (in reverse order)
    for (int i = poolIds.size() - 1; i >= 0; i--) {
        JSONObject jsonResult2 = new JSONObject(CandlepinTasks.postResourceUsingRESTfulAPI(sm_client2Username, sm_client2Password, sm_serverUrl, "/activation_keys/" + jsonActivationKey2.getString("id") + "/pools/" + poolIds.get(i), /* + (addQuantity==null?"":"?quantity="+addQuantity)*/
        null));
        // if (clienttasks.isVersion(servertasks.statusVersion, ">", "0.9.30-1")) the POST now returns the jsonActivationKey and formerly returned the jsonPoolAddedToActivationKey	// candlepin commit 82b9af5dc2c63b58447366e680fcf6f156c6049f
        if (jsonResult2.has("displayMessage")) {
            Assert.fail("Failed to add pool '" + poolIds.get(i) + "' to activation key '" + jsonActivationKey2.getString("id") + "'.  DisplayMessage: " + jsonResult2.getString("displayMessage"));
        }
    }
    // attempt this test more than once
    for (int attempt = 1; attempt < 5; attempt++) {
        client1tasks.unregister(null, null, null, null);
        client2tasks.unregister(null, null, null, null);
        // register each client simultaneously using the activation keys (one in reverse order of the other)
        log.info("Simultaneously attempting to register with activation keys on '" + client1tasks.hostname + "' and '" + client2tasks.hostname + "'...");
        client1.runCommand(/*AndWait*/
        client1tasks.registerCommand(null, null, client1OwnerKey, null, null, null, null, null, null, null, new ArrayList<String>() {

            {
                add(activationKeyName1);
                add(activationKeyName2);
            }
        }, null, null, null, null, null, null, null, null, null), TestRecords.action());
        client2.runCommand(/*AndWait*/
        client2tasks.registerCommand(null, null, client2OwnerKey, null, null, null, null, null, null, null, new ArrayList<String>() {

            {
                add(activationKeyName2);
                add(activationKeyName1);
            }
        }, null, null, null, null, null, null, null, null, null), TestRecords.action());
        // timeout after 10 min
        client1.waitForWithTimeout(new Long(10 * 60 * 1000));
        // timeout after 10 min
        client2.waitForWithTimeout(new Long(10 * 60 * 1000));
        SSHCommandResult client1Result = client1.getSSHCommandResult();
        SSHCommandResult client2Result = client2.getSSHCommandResult();
        // 201405091623:44.055 - INFO: SSHCommandResult from an attempt to register with activation keys on 'jsefler-7server.usersys.redhat.com':
        // exitCode=255
        // stdout=''
        // stderr='Problem creating unit Consumer [id = 8a9087e345a9f5f90145e2a740c200ad, type = ConsumerType [id=1000, label=system], getName() = jsefler-7server.usersys.redhat.com]'
        // assert the results
        log.info("SSHCommandResult from an attempt to register with activation keys on '" + client1tasks.hostname + "': \n" + client1Result);
        log.info("SSHCommandResult from an attempt to register with activation keys on '" + client2tasks.hostname + "': \n" + client2Result);
        Assert.assertEquals(client1Result.getExitCode(), Integer.valueOf(0), "The exit code from register with activation keys on '" + client1tasks.hostname + "'.");
        // TEMPORARY WORKAROUND FOR BUG: 1183122 - rhsmd/subman dbus traceback on 'attach --pool'
        if (client1Result.getStderr().contains("KeyError: 'product_id'")) {
            boolean invokeWorkaroundWhileBugIsOpen = true;
            String bugId = "1183122";
            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("Encountered bug '" + bugId + "'. Skipping stderr/exitCode assertion from the prior register with activationkey command while bug '" + bugId + "' is open.");
            }
        } else
            // Assert client1Result.getStderr()
            // END OF WORKAROUND
            Assert.assertEquals(client1Result.getStderr(), "", "Stderr from the unsubscribe all on '" + client1tasks.hostname + "'.");
        Assert.assertEquals(client2Result.getExitCode(), Integer.valueOf(0), "The exit code from register with activation keys on '" + client2tasks.hostname + "'.");
        // TEMPORARY WORKAROUND FOR BUG: 1183122 - rhsmd/subman dbus traceback on 'attach --pool'
        if (client2Result.getStderr().contains("KeyError: 'product_id'")) {
            boolean invokeWorkaroundWhileBugIsOpen = true;
            String bugId = "1183122";
            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("Encountered bug '" + bugId + "'. Skipping stderr/exitCode assertion from the prior register with activationkey command while bug '" + bugId + "' is open.");
            }
        } else
            // Assert client2Result.getStderr()
            // END OF WORKAROUND
            Assert.assertEquals(client2Result.getStderr(), "", "Stderr from the unsubscribe all on '" + client2tasks.hostname + "'.");
    }
}
Also used : HashMap(java.util.HashMap) JSONArray(org.json.JSONArray) ArrayList(java.util.ArrayList) BugzillaAPIException(com.redhat.qe.auto.bugzilla.BugzillaAPIException) JSONObject(org.json.JSONObject) SSHCommandResult(com.redhat.qe.tools.SSHCommandResult) ArrayList(java.util.ArrayList) List(java.util.List) SkipException(org.testng.SkipException) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test)

Example 60 with SSHCommandResult

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

the class ActivationKeyTests method testRegisterWithListOfCommaSeparatedActivationKeys.

@// update=true,	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-21802", "RHEL7-51619" }, 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 = "Tier3")
@Test(description = "create many activation keys with one added pool per key and then register with --activationkey=comma_separated_string_of_keys asserting all the pools get consumed", groups = { "Tier3Tests", "blockedByBug-878986", "blockedByBug-979492", "blockedByBug-1040101" }, enabled = true)
public // @ImplementsNitrateTest(caseId=)
void testRegisterWithListOfCommaSeparatedActivationKeys() throws JSONException, Exception {
    // get all of the pools belonging to ownerKey
    JSONArray jsonPools = new JSONArray(CandlepinTasks.getResourceUsingRESTfulAPI(sm_clientUsername, sm_clientPassword, sm_serverUrl, "/owners/" + sm_clientOrg + "/pools?listall=true"));
    if (!(jsonPools.length() > 1))
        throw new SkipException("This test requires more than one pool for org '" + sm_clientOrg + "'.");
    jsonPools = clienttasks.workaroundForBug1040101(jsonPools);
    // process each of the pools adding them to an individual activation key
    List<String> activationKeyNames = new ArrayList<String>();
    Integer addQuantity = null;
    JSONArray jsonPoolsAddedToActivationKey = new JSONArray();
    boolean isSystemVirtual = Boolean.valueOf(clienttasks.getFactValue("virt.is_guest"));
    for (int i = 0; i < jsonPools.length(); i++) {
        JSONObject jsonPool = (JSONObject) jsonPools.get(i);
        // for the purpose of this test, skip pools with no available entitlements (consumed>=quantity) (quantity=-1 is unlimited)
        if (jsonPool.getInt("quantity") > 0 && jsonPool.getInt("consumed") >= jsonPool.getInt("quantity"))
            continue;
        // for the purpose of this test, skip non-system pools otherwise the register will fail with "Consumers of this type are not allowed to subscribe to the pool with id '8a90f8c631ab7ccc0131ab7e46ca0619'."
        if (!CandlepinTasks.isPoolProductConsumableByConsumerType(sm_clientUsername, sm_clientPassword, sm_serverUrl, jsonPool.getString("id"), ConsumerType.system))
            continue;
        // for the purpose of this test, skip physical_only pools when system is virtual otherwise the register will fail with "Pool is restricted to physical systems: '8a9086d344549b0c0144549bf9ae0dd4'."
        if (isSystemVirtual && CandlepinTasks.isPoolRestrictedToPhysicalSystems(sm_clientUsername, sm_clientPassword, sm_serverUrl, jsonPool.getString("id")))
            continue;
        // for the purpose of this test, skip virt_only pools when system is physical otherwise the register will fail with "Pool is restricted to virtual guests: '8a9086d344549b0c0144549bf9ae0dd4'."
        if (!isSystemVirtual && CandlepinTasks.isPoolRestrictedToVirtualSystems(sm_clientUsername, sm_clientPassword, sm_serverUrl, jsonPool.getString("id")))
            continue;
        /* skipping pools that are not NORMAL is more reliable than this...
			// for the purpose of this test, skip virt_only derived_pool when server is standalone otherwise the register will fail with "Unable to entitle consumer to the pool with id '8a90f85733d86b130133d88c09410e5e'.: virt.guest.host.does.not.match.pool.owner"
			//if (servertasks.statusStandalone) {	// 5/29/2014 removed this check, I can't remember why I originally set it 
			// for the purpose of this test, skip virt_only derived_pool when otherwise the register will fail with "Guest's host does not match owner of pool: '8a908775463fef2301464072ee68496e'."
			if (true) {
				String pool_derived = CandlepinTasks.getPoolAttributeValue(jsonPool, "pool_derived");
				String virt_only = CandlepinTasks.getPoolAttributeValue(jsonPool, "virt_only");
				if (pool_derived!=null && virt_only!=null && Boolean.valueOf(pool_derived) && Boolean.valueOf(virt_only)) {
					continue;
				}
			}
			*/
        // for the purpose of this test, skip pools that are not NORMAL (eg. BONUS, ENTITLEMENT_DERIVED, STACK_DERIVED)
        String poolType = (String) CandlepinTasks.getPoolValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, jsonPool.getString("id"), "type");
        if (!poolType.equals("NORMAL"))
            continue;
        // create an activation key
        String activationKeyName = String.format("ActivationKey%sWithPool%sForOrg_%s", System.currentTimeMillis(), jsonPool.getString("id"), sm_clientOrg);
        Map<String, String> mapActivationKeyRequest = new HashMap<String, String>();
        mapActivationKeyRequest.put("name", activationKeyName);
        JSONObject jsonActivationKeyRequest = new JSONObject(mapActivationKeyRequest);
        JSONObject jsonActivationKey = new JSONObject(CandlepinTasks.postResourceUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, "/owners/" + sm_clientOrg + "/activation_keys", jsonActivationKeyRequest.toString()));
        // add the pool to the activation key
        JSONObject jsonResult = new JSONObject(CandlepinTasks.postResourceUsingRESTfulAPI(sm_clientUsername, sm_clientPassword, sm_serverUrl, "/activation_keys/" + jsonActivationKey.getString("id") + "/pools/" + jsonPool.getString("id") + (addQuantity == null ? "" : "?quantity=" + addQuantity), null));
        // if (clienttasks.isVersion(servertasks.statusVersion, ">", "0.9.30-1")) the POST now returns the jsonActivationKey and formerly returned the jsonPoolAddedToActivationKey	// candlepin commit 82b9af5dc2c63b58447366e680fcf6f156c6049f
        if (jsonResult.has("displayMessage")) {
            Assert.fail("Failed to add pool '" + jsonPool.getString("productId") + "' '" + jsonPool.getString("id") + "' to activation key '" + jsonActivationKey.getString("id") + "'.  DisplayMessage: " + jsonResult.getString("displayMessage"));
        }
        jsonPoolsAddedToActivationKey.put(jsonPool);
        activationKeyNames.add(activationKeyName);
    }
    if (addQuantity == null)
        addQuantity = 1;
    // assemble the comma separated list of activation key names
    String commaSeparatedActivationKeyNames = "";
    for (String activationKeyName : activationKeyNames) commaSeparatedActivationKeyNames += activationKeyName + ",";
    // strip off trailing comma
    commaSeparatedActivationKeyNames = commaSeparatedActivationKeyNames.replaceFirst(",$", "");
    // register with the activation key specified as a single string
    SSHCommandResult registerResult = clienttasks.register(null, null, sm_clientOrg, null, null, null, null, null, null, null, commaSeparatedActivationKeyNames, null, null, null, true, null, null, null, null, null);
    // assert that all the pools were consumed
    List<ProductSubscription> consumedProductSubscriptions = clienttasks.getCurrentlyConsumedProductSubscriptions();
    for (int i = 0; i < jsonPoolsAddedToActivationKey.length(); i++) {
        JSONObject jsonPoolAdded = (JSONObject) jsonPoolsAddedToActivationKey.get(i);
        // assert that the pool's providedProducts (excluding type=MKT products) are consumed (unless it is a ManagementAddOn product - indicated by no providedProducts)
        assertProvidedProductsFromPoolAreWithinConsumedProductSubscriptionsUsingQuantity(jsonPoolAdded, consumedProductSubscriptions, addQuantity, false);
    }
    Assert.assertEquals(clienttasks.getCurrentEntitlementCertFiles().size(), activationKeyNames.size(), "Expecting a new entitlement cert file in '" + clienttasks.entitlementCertDir + "' for each of the single pooled activation keys used during register.");
}
Also used : HashMap(java.util.HashMap) JSONArray(org.json.JSONArray) ArrayList(java.util.ArrayList) ProductSubscription(rhsm.data.ProductSubscription) JSONObject(org.json.JSONObject) SSHCommandResult(com.redhat.qe.tools.SSHCommandResult) SkipException(org.testng.SkipException) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test)

Aggregations

SSHCommandResult (com.redhat.qe.tools.SSHCommandResult)553 Test (org.testng.annotations.Test)416 TestDefinition (com.github.redhatqe.polarize.metadata.TestDefinition)401 SkipException (org.testng.SkipException)219 ImplementsNitrateTest (com.redhat.qe.auto.tcms.ImplementsNitrateTest)201 ArrayList (java.util.ArrayList)101 BugzillaAPIException (com.redhat.qe.auto.bugzilla.BugzillaAPIException)79 BigInteger (java.math.BigInteger)68 File (java.io.File)58 SubscriptionPool (rhsm.data.SubscriptionPool)53 JSONObject (org.json.JSONObject)47 HashMap (java.util.HashMap)42 ProductSubscription (rhsm.data.ProductSubscription)31 EntitlementCert (rhsm.data.EntitlementCert)30 List (java.util.List)21 YumRepo (rhsm.data.YumRepo)18 ProductCert (rhsm.data.ProductCert)17 Repo (rhsm.data.Repo)16 InstalledProduct (rhsm.data.InstalledProduct)15 Calendar (java.util.Calendar)13