diff --git a/test/scripts/checkOutOfMemory.sh b/test/scripts/checkOutOfMemory.sh index 9baf0df1a07..a3c04928676 100755 --- a/test/scripts/checkOutOfMemory.sh +++ b/test/scripts/checkOutOfMemory.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/bin/bash # Copyright 2012 Citrix Systems, Inc. Licensed under the # Apache License, Version 2.0 (the "License"); you may not use this # file except in compliance with the License. Citrix Systems, Inc. @@ -16,18 +16,18 @@ - -while true -do -sleep 600 -pid=`ps -ef | grep 'management.jmxremote' | grep -v 'cloud-management' | grep -v grep | awk '{print \$2}'` -if grep -q java.lang.OutOfMemoryError /var/log/vmops/vmops.log -then -while true -do -t=$(date +"%h%d_%H_%M_%S") -jmap -dump:format=b,file=/root/dump/heap.bin.$t $pid -sleep 1800 -done -fi + +while true +do +sleep 600 +pid=`ps -ef | grep 'management.jmxremote' | grep -v 'cloud-management' | grep -v grep | awk '{print \$2}'` +if grep -q java.lang.OutOfMemoryError /var/log/vmops/vmops.log +then +while true +do +t=$(date +"%h%d_%H_%M_%S") +jmap -dump:format=b,file=/root/dump/heap.bin.$t $pid +sleep 1800 +done +fi done \ No newline at end of file diff --git a/test/src/com/cloud/sample/UserCloudAPIExecutor.java b/test/src/com/cloud/sample/UserCloudAPIExecutor.java index d558ac25f3d..7a2880860fb 100644 --- a/test/src/com/cloud/sample/UserCloudAPIExecutor.java +++ b/test/src/com/cloud/sample/UserCloudAPIExecutor.java @@ -10,176 +10,176 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.sample; - -import java.io.FileInputStream; -import java.net.URLEncoder; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Properties; -import java.util.StringTokenizer; - -import javax.crypto.Mac; -import javax.crypto.spec.SecretKeySpec; - -import org.apache.commons.httpclient.HttpClient; -import org.apache.commons.httpclient.HttpMethod; -import org.apache.commons.httpclient.methods.GetMethod; - -import com.cloud.utils.encoding.Base64; - -/** +package com.cloud.sample; + +import java.io.FileInputStream; +import java.net.URLEncoder; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Properties; +import java.util.StringTokenizer; + +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; + +import org.apache.commons.httpclient.HttpClient; +import org.apache.commons.httpclient.HttpMethod; +import org.apache.commons.httpclient.methods.GetMethod; + +import com.cloud.utils.encoding.Base64; + +/** * * * * - * - * - * - * - * - */ - -/** - * Sample CloudStack Management User API Executor. - * - * Prerequisites: - Edit usercloud.properties to include your host, apiUrl, apiKey, and secretKey - Use ./executeUserAPI.sh to - * execute this test class - * - * @author will - * - */ -public class UserCloudAPIExecutor { - public static void main(String[] args) { - // Host - String host = null; - - // Fully qualified URL with http(s)://host:port - String apiUrl = null; - - // ApiKey and secretKey as given by your CloudStack vendor - String apiKey = null; - String secretKey = null; - - try { - Properties prop = new Properties(); - prop.load(new FileInputStream("usercloud.properties")); - - // host - host = prop.getProperty("host"); - if (host == null) { - System.out.println("Please specify a valid host in the format of http(s)://:/client/api in your usercloud.properties file."); - } - - // apiUrl - apiUrl = prop.getProperty("apiUrl"); - if (apiUrl == null) { - System.out.println("Please specify a valid API URL in the format of command=¶m1=¶m2=... in your usercloud.properties file."); - } - - // apiKey - apiKey = prop.getProperty("apiKey"); - if (apiKey == null) { - System.out.println("Please specify your API Key as provided by your CloudStack vendor in your usercloud.properties file."); - } - - // secretKey - secretKey = prop.getProperty("secretKey"); - if (secretKey == null) { - System.out.println("Please specify your secret Key as provided by your CloudStack vendor in your usercloud.properties file."); - } - - if (apiUrl == null || apiKey == null || secretKey == null) { - return; - } - - System.out.println("Constructing API call to host = '" + host + "' with API command = '" + apiUrl + "' using apiKey = '" + apiKey + "' and secretKey = '" + secretKey + "'"); - - // Step 1: Make sure your APIKey is URL encoded - String encodedApiKey = URLEncoder.encode(apiKey, "UTF-8"); - - // Step 2: URL encode each parameter value, then sort the parameters and apiKey in - // alphabetical order, and then toLowerCase all the parameters, parameter values and apiKey. - // Please note that if any parameters with a '&' as a value will cause this test client to fail since we are using - // '&' to delimit - // the string - List sortedParams = new ArrayList(); - sortedParams.add("apikey=" + encodedApiKey.toLowerCase()); - StringTokenizer st = new StringTokenizer(apiUrl, "&"); - String url = null; - boolean first = true; - while (st.hasMoreTokens()) { - String paramValue = st.nextToken(); - String param = paramValue.substring(0, paramValue.indexOf("=")); - String value = URLEncoder.encode(paramValue.substring(paramValue.indexOf("=") + 1, paramValue.length()), "UTF-8"); - if (first) { - url = param + "=" + value; - first = false; - } else { - url = url + "&" + param + "=" + value; - } - sortedParams.add(param.toLowerCase() + "=" + value.toLowerCase()); - } - Collections.sort(sortedParams); - - System.out.println("Sorted Parameters: " + sortedParams); - - // Step 3: Construct the sorted URL and sign and URL encode the sorted URL with your secret key - String sortedUrl = null; - first = true; - for (String param : sortedParams) { - if (first) { - sortedUrl = param; - first = false; - } else { - sortedUrl = sortedUrl + "&" + param; - } - } - System.out.println("sorted URL : " + sortedUrl); - String encodedSignature = signRequest(sortedUrl, secretKey); - - // Step 4: Construct the final URL we want to send to the CloudStack Management Server - // Final result should look like: - // http(s)://://client/api?&apiKey=&signature= - String finalUrl = host + "?" + url + "&apiKey=" + apiKey + "&signature=" + encodedSignature; - System.out.println("final URL : " + finalUrl); - - // Step 5: Perform a HTTP GET on this URL to execute the command - HttpClient client = new HttpClient(); - HttpMethod method = new GetMethod(finalUrl); - int responseCode = client.executeMethod(method); - if (responseCode == 200) { - // SUCCESS! - System.out.println("Successfully executed command"); - } else { - // FAILED! - System.out.println("Unable to execute command with response code: " + responseCode); - } - - } catch (Throwable t) { - System.out.println(t); - } - } - - /** - * 1. Signs a string with a secret key using SHA-1 2. Base64 encode the result 3. URL encode the final result - * - * @param request - * @param key - * @return - */ - public static String signRequest(String request, String key) { - try { - Mac mac = Mac.getInstance("HmacSHA1"); - SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "HmacSHA1"); - mac.init(keySpec); - mac.update(request.getBytes()); - byte[] encryptedBytes = mac.doFinal(); - return URLEncoder.encode(Base64.encodeBytes(encryptedBytes), "UTF-8"); - } catch (Exception ex) { - System.out.println(ex); - } - return null; - } -} + * + * + * + * + * + */ + +/** + * Sample CloudStack Management User API Executor. + * + * Prerequisites: - Edit usercloud.properties to include your host, apiUrl, apiKey, and secretKey - Use ./executeUserAPI.sh to + * execute this test class + * + * @author will + * + */ +public class UserCloudAPIExecutor { + public static void main(String[] args) { + // Host + String host = null; + + // Fully qualified URL with http(s)://host:port + String apiUrl = null; + + // ApiKey and secretKey as given by your CloudStack vendor + String apiKey = null; + String secretKey = null; + + try { + Properties prop = new Properties(); + prop.load(new FileInputStream("usercloud.properties")); + + // host + host = prop.getProperty("host"); + if (host == null) { + System.out.println("Please specify a valid host in the format of http(s)://:/client/api in your usercloud.properties file."); + } + + // apiUrl + apiUrl = prop.getProperty("apiUrl"); + if (apiUrl == null) { + System.out.println("Please specify a valid API URL in the format of command=¶m1=¶m2=... in your usercloud.properties file."); + } + + // apiKey + apiKey = prop.getProperty("apiKey"); + if (apiKey == null) { + System.out.println("Please specify your API Key as provided by your CloudStack vendor in your usercloud.properties file."); + } + + // secretKey + secretKey = prop.getProperty("secretKey"); + if (secretKey == null) { + System.out.println("Please specify your secret Key as provided by your CloudStack vendor in your usercloud.properties file."); + } + + if (apiUrl == null || apiKey == null || secretKey == null) { + return; + } + + System.out.println("Constructing API call to host = '" + host + "' with API command = '" + apiUrl + "' using apiKey = '" + apiKey + "' and secretKey = '" + secretKey + "'"); + + // Step 1: Make sure your APIKey is URL encoded + String encodedApiKey = URLEncoder.encode(apiKey, "UTF-8"); + + // Step 2: URL encode each parameter value, then sort the parameters and apiKey in + // alphabetical order, and then toLowerCase all the parameters, parameter values and apiKey. + // Please note that if any parameters with a '&' as a value will cause this test client to fail since we are using + // '&' to delimit + // the string + List sortedParams = new ArrayList(); + sortedParams.add("apikey=" + encodedApiKey.toLowerCase()); + StringTokenizer st = new StringTokenizer(apiUrl, "&"); + String url = null; + boolean first = true; + while (st.hasMoreTokens()) { + String paramValue = st.nextToken(); + String param = paramValue.substring(0, paramValue.indexOf("=")); + String value = URLEncoder.encode(paramValue.substring(paramValue.indexOf("=") + 1, paramValue.length()), "UTF-8"); + if (first) { + url = param + "=" + value; + first = false; + } else { + url = url + "&" + param + "=" + value; + } + sortedParams.add(param.toLowerCase() + "=" + value.toLowerCase()); + } + Collections.sort(sortedParams); + + System.out.println("Sorted Parameters: " + sortedParams); + + // Step 3: Construct the sorted URL and sign and URL encode the sorted URL with your secret key + String sortedUrl = null; + first = true; + for (String param : sortedParams) { + if (first) { + sortedUrl = param; + first = false; + } else { + sortedUrl = sortedUrl + "&" + param; + } + } + System.out.println("sorted URL : " + sortedUrl); + String encodedSignature = signRequest(sortedUrl, secretKey); + + // Step 4: Construct the final URL we want to send to the CloudStack Management Server + // Final result should look like: + // http(s)://://client/api?&apiKey=&signature= + String finalUrl = host + "?" + url + "&apiKey=" + apiKey + "&signature=" + encodedSignature; + System.out.println("final URL : " + finalUrl); + + // Step 5: Perform a HTTP GET on this URL to execute the command + HttpClient client = new HttpClient(); + HttpMethod method = new GetMethod(finalUrl); + int responseCode = client.executeMethod(method); + if (responseCode == 200) { + // SUCCESS! + System.out.println("Successfully executed command"); + } else { + // FAILED! + System.out.println("Unable to execute command with response code: " + responseCode); + } + + } catch (Throwable t) { + System.out.println(t); + } + } + + /** + * 1. Signs a string with a secret key using SHA-1 2. Base64 encode the result 3. URL encode the final result + * + * @param request + * @param key + * @return + */ + public static String signRequest(String request, String key) { + try { + Mac mac = Mac.getInstance("HmacSHA1"); + SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "HmacSHA1"); + mac.init(keySpec); + mac.update(request.getBytes()); + byte[] encryptedBytes = mac.doFinal(); + return URLEncoder.encode(Base64.encodeBytes(encryptedBytes), "UTF-8"); + } catch (Exception ex) { + System.out.println(ex); + } + return null; + } +} diff --git a/test/src/com/cloud/test/longrun/BuildGuestNetwork.java b/test/src/com/cloud/test/longrun/BuildGuestNetwork.java index bdd56a2fd4c..236c9ea46a4 100644 --- a/test/src/com/cloud/test/longrun/BuildGuestNetwork.java +++ b/test/src/com/cloud/test/longrun/BuildGuestNetwork.java @@ -10,115 +10,115 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.test.longrun; - -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; -import java.util.Random; - - -import org.apache.log4j.Logger; - - -public class BuildGuestNetwork { - - public static final Logger s_logger= Logger.getLogger(BuildGuestNetwork.class.getClass()); - private static final int _apiPort=8096; - private static final int _developerPort=8080; - private static final String _apiUrl = "/client/api"; - private static int numVM=1; - private static long zoneId=-1L; - private static long templateId=3; - private static long serviceOfferingId=1; - - - - public static void main (String[] args){ - - List argsList = Arrays.asList(args); - Iterator iter = argsList.iterator(); - String host = "http://localhost"; - int numThreads = 1; - - while (iter.hasNext()){ - String arg = iter.next(); - if (arg.equals("-h")){ - host="http://"+iter.next(); - } - if (arg.equals("-t")){ - numThreads=Integer.parseInt(iter.next()); - } - if (arg.equals("-n")){ - numVM=Integer.parseInt(iter.next()); - } - if (arg.equals("-z")){ - zoneId=Integer.parseInt(iter.next()); - } - - if (arg.equals("-e")){ - templateId=Integer.parseInt(iter.next()); - } - - if (arg.equals("-s")){ - serviceOfferingId=Integer.parseInt(iter.next()); - } - } - - final String server = host + ":" + _apiPort + "/"; - final String developerServer = host + ":" + _developerPort + _apiUrl; - s_logger.info("Starting test in "+numThreads+" thread(s). Each thread is launching "+numVM+" VMs"); - - for (int i=0; i argsList = Arrays.asList(args); + Iterator iter = argsList.iterator(); + String host = "http://localhost"; + int numThreads = 1; + + while (iter.hasNext()){ + String arg = iter.next(); + if (arg.equals("-h")){ + host="http://"+iter.next(); + } + if (arg.equals("-t")){ + numThreads=Integer.parseInt(iter.next()); + } + if (arg.equals("-n")){ + numVM=Integer.parseInt(iter.next()); + } + if (arg.equals("-z")){ + zoneId=Integer.parseInt(iter.next()); + } + + if (arg.equals("-e")){ + templateId=Integer.parseInt(iter.next()); + } + + if (arg.equals("-s")){ + serviceOfferingId=Integer.parseInt(iter.next()); + } + } + + final String server = host + ":" + _apiPort + "/"; + final String developerServer = host + ":" + _developerPort + _apiUrl; + s_logger.info("Starting test in "+numThreads+" thread(s). Each thread is launching "+numVM+" VMs"); + + for (int i=0; i argsList = Arrays.asList(args); - Iterator iter = argsList.iterator(); - String host = "http://localhost"; - int numThreads = 1; - - while (iter.hasNext()){ - String arg = iter.next(); - if (arg.equals("-h")){ - host="http://"+iter.next(); - } - if (arg.equals("-t")){ - numThreads=Integer.parseInt(iter.next()); - } - if (arg.equals("-n")){ - numVM=Integer.parseInt(iter.next()); - } - } - - final String server = host + ":" + _apiPort + "/"; - final String developerServer = host + ":" + _developerPort + _apiUrl; - - s_logger.info("Starting test in "+numThreads+" thread(s). Each thread is launching "+numVM+" VMs"); - - for (int i=0; i errorInfo = TestClientWithAPI.getSingleValueFromXML(is, - new String[] { "errorCode", "description" }); - s_logger - .error("create ip forwarding rule (linux) test failed with errorCode: " - + errorInfo.get("errorCode") - + " and description: " - + errorInfo.get("description")); - } else { - s_logger.error("internal error processing request: " - + method.getStatusText()); - } - return responseCode; - } - - + + + +public class PerformanceWithAPI { + +public static final Logger s_logger= Logger.getLogger(PerformanceWithAPI.class.getClass()); +private static final int _retry=10; +private static final int _apiPort=8096; +private static int numVM=2; +private static final long _zoneId=-1L; +private static final long _templateId=3; +private static final long _serviceOfferingId=1; +private static final String _apiUrl = "/client/api"; +private static final int _developerPort=8080; + + + + public static void main (String[] args){ + + List argsList = Arrays.asList(args); + Iterator iter = argsList.iterator(); + String host = "http://localhost"; + int numThreads = 1; + + while (iter.hasNext()){ + String arg = iter.next(); + if (arg.equals("-h")){ + host="http://"+iter.next(); + } + if (arg.equals("-t")){ + numThreads=Integer.parseInt(iter.next()); + } + if (arg.equals("-n")){ + numVM=Integer.parseInt(iter.next()); + } + } + + final String server = host + ":" + _apiPort + "/"; + final String developerServer = host + ":" + _developerPort + _apiUrl; + + s_logger.info("Starting test in "+numThreads+" thread(s). Each thread is launching "+numVM+" VMs"); + + for (int i=0; i errorInfo = TestClientWithAPI.getSingleValueFromXML(is, + new String[] { "errorCode", "description" }); + s_logger + .error("create ip forwarding rule (linux) test failed with errorCode: " + + errorInfo.get("errorCode") + + " and description: " + + errorInfo.get("description")); + } else { + s_logger.error("internal error processing request: " + + method.getStatusText()); + } + return responseCode; + } + + } \ No newline at end of file diff --git a/test/src/com/cloud/test/longrun/User.java b/test/src/com/cloud/test/longrun/User.java index 8ada429f479..7ff4674eb1a 100644 --- a/test/src/com/cloud/test/longrun/User.java +++ b/test/src/com/cloud/test/longrun/User.java @@ -10,225 +10,225 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.test.longrun; -import java.util.ArrayList; -import java.util.Map; -import java.io.InputStream; -import java.io.IOException; -import java.net.URLEncoder; - -import org.apache.commons.httpclient.HttpClient; -import org.apache.commons.httpclient.HttpException; -import org.apache.commons.httpclient.HttpMethod; -import org.apache.commons.httpclient.methods.GetMethod; -import org.apache.log4j.Logger; - +package com.cloud.test.longrun; +import java.util.ArrayList; +import java.util.Map; +import java.io.InputStream; +import java.io.IOException; +import java.net.URLEncoder; + +import org.apache.commons.httpclient.HttpClient; +import org.apache.commons.httpclient.HttpException; +import org.apache.commons.httpclient.HttpMethod; +import org.apache.commons.httpclient.methods.GetMethod; +import org.apache.log4j.Logger; + import com.cloud.test.stress.TestClientWithAPI; - - - -public class User { - public static final Logger s_logger= Logger.getLogger(User.class.getClass()); - - private ArrayList virtualMachines; - private ArrayList publicIp; - private String server; - private String developerServer; - private String userName; - private String userId; - private String apiKey; - private String secretKey; - private String password; - private String encryptedPassword; - - - public User(String userName, String password, String server, String developerServer) - { - this.server=server; - this.developerServer=developerServer; - this.userName=userName; - this.password=password; - this.virtualMachines = new ArrayList(); - this.publicIp = new ArrayList(); - } - - public ArrayList getVirtualMachines() { - return virtualMachines; - } - - - public void setVirtualMachines(ArrayList virtualMachines) { - this.virtualMachines = virtualMachines; - } - - - public String getUserId() { - return userId; - } - - - public void setUserId(String userId) { - this.userId = userId; - } - - - public ArrayList getPublicIp() { - return publicIp; - } - - - public void setPublicIp(ArrayList publicIp) { - this.publicIp = publicIp; - } - - - - public String getServer() { - return server; - } - - - - public void setServer(String server) { - this.server = server; - } - - - - public String getUserName() { - return userName; - } - - - - public void setUserName(String userName) { - this.userName = userName; - } - - - public String getApiKey() { - return apiKey; - } - - public void setApiKey(String apiKey) { - this.apiKey = apiKey; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - public String getSecretKey() { - return secretKey; - } - - public void setSecretKey(String secretKey) { - this.secretKey = secretKey; - } - - - - public String getDeveloperServer() { - return developerServer; - } - - public void setDeveloperServer(String developerServer) { - this.developerServer = developerServer; - } - - public void launchUser() throws IOException { - String encodedUsername = URLEncoder.encode(this.getUserName(), "UTF-8"); - this.encryptedPassword=TestClientWithAPI.createMD5Password(this.getPassword()); - String encodedPassword = URLEncoder.encode(this.encryptedPassword, "UTF-8"); - String url = this.server + "?command=createUser&username=" + encodedUsername - + "&password=" + encodedPassword - + "&firstname=Test&lastname=Test&email=alena@vmops.com&domainId=1"; - String userIdStr=null; - HttpClient client = new HttpClient(); - HttpMethod method = new GetMethod(url); - int responseCode = client.executeMethod(method); - - if (responseCode == 200) { - InputStream is = method.getResponseBodyAsStream(); - Map userIdValues = TestClientWithAPI.getSingleValueFromXML(is, - new String[] { "id" }); - userIdStr = userIdValues.get("id"); - if ((userIdStr != null) && (Long.parseLong(userIdStr)!=-1)) { - this.setUserId(userIdStr); - } - } - } - - public void retrievePublicIp(long zoneId) throws IOException{ - - String encodedApiKey = URLEncoder.encode(this.apiKey, "UTF-8"); - String encodedZoneId=URLEncoder.encode(""+zoneId,"UTF-8"); - String requestToSign = "apiKey=" + encodedApiKey - + "&command=associateIpAddress" + "&zoneId="+encodedZoneId; - requestToSign = requestToSign.toLowerCase(); - String signature = TestClientWithAPI.signRequest(requestToSign, this.secretKey); - String encodedSignature = URLEncoder.encode(signature, "UTF-8"); - - String url = this.developerServer + "?command=associateIpAddress" + "&apiKey=" - + encodedApiKey + "&zoneId="+encodedZoneId+"&signature=" - + encodedSignature; - - HttpClient client = new HttpClient(); - HttpMethod method = new GetMethod(url); - int responseCode=client.executeMethod(method); - if (responseCode == 200) { - InputStream is = method.getResponseBodyAsStream(); - Map values = TestClientWithAPI.getSingleValueFromXML(is, - new String[] { "ipaddress" }); - this.getPublicIp().add(values.get("ipaddress")); - s_logger.info("Ip address is " + values.get("ipaddress")); - } else if (responseCode == 500) { - InputStream is = method.getResponseBodyAsStream(); - Map errorInfo = TestClientWithAPI.getSingleValueFromXML(is, - new String[] { "errorcode", "description" }); - s_logger.error("associate ip test failed with errorCode: " - + errorInfo.get("errorCode") + " and description: " - + errorInfo.get("description")); - } else { - s_logger.error("internal error processing request: " - + method.getStatusText()); - } - - } - - public void registerUser()throws HttpException, IOException{ - - String encodedUsername = URLEncoder.encode(this.userName, "UTF-8"); - String encodedPassword = URLEncoder.encode(this.password, "UTF-8"); - String url = server + "?command=register&username=" + encodedUsername - + "&domainid=1"; - s_logger.info("registering: " + this.userName+" with url "+url); - HttpClient client = new HttpClient(); - HttpMethod method = new GetMethod(url); - int responseCode = client.executeMethod(method); - if (responseCode == 200) { - InputStream is = method.getResponseBodyAsStream(); - Map requestKeyValues = TestClientWithAPI.getSingleValueFromXML(is, - new String[] { "apikey", "secretkey" }); - this.setApiKey(requestKeyValues.get("apikey")); - this.setSecretKey(requestKeyValues.get("secretkey")); - } else if (responseCode == 500) { - InputStream is = method.getResponseBodyAsStream(); - Map errorInfo = TestClientWithAPI.getSingleValueFromXML(is, - new String[] { "errorcode", "description" }); - s_logger.error("registration failed with errorCode: " - + errorInfo.get("errorCode") + " and description: " - + errorInfo.get("description")); - } else { - s_logger.error("internal error processing request: " - + method.getStatusText()); - } - } - -} - - + + + +public class User { + public static final Logger s_logger= Logger.getLogger(User.class.getClass()); + + private ArrayList virtualMachines; + private ArrayList publicIp; + private String server; + private String developerServer; + private String userName; + private String userId; + private String apiKey; + private String secretKey; + private String password; + private String encryptedPassword; + + + public User(String userName, String password, String server, String developerServer) + { + this.server=server; + this.developerServer=developerServer; + this.userName=userName; + this.password=password; + this.virtualMachines = new ArrayList(); + this.publicIp = new ArrayList(); + } + + public ArrayList getVirtualMachines() { + return virtualMachines; + } + + + public void setVirtualMachines(ArrayList virtualMachines) { + this.virtualMachines = virtualMachines; + } + + + public String getUserId() { + return userId; + } + + + public void setUserId(String userId) { + this.userId = userId; + } + + + public ArrayList getPublicIp() { + return publicIp; + } + + + public void setPublicIp(ArrayList publicIp) { + this.publicIp = publicIp; + } + + + + public String getServer() { + return server; + } + + + + public void setServer(String server) { + this.server = server; + } + + + + public String getUserName() { + return userName; + } + + + + public void setUserName(String userName) { + this.userName = userName; + } + + + public String getApiKey() { + return apiKey; + } + + public void setApiKey(String apiKey) { + this.apiKey = apiKey; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getSecretKey() { + return secretKey; + } + + public void setSecretKey(String secretKey) { + this.secretKey = secretKey; + } + + + + public String getDeveloperServer() { + return developerServer; + } + + public void setDeveloperServer(String developerServer) { + this.developerServer = developerServer; + } + + public void launchUser() throws IOException { + String encodedUsername = URLEncoder.encode(this.getUserName(), "UTF-8"); + this.encryptedPassword=TestClientWithAPI.createMD5Password(this.getPassword()); + String encodedPassword = URLEncoder.encode(this.encryptedPassword, "UTF-8"); + String url = this.server + "?command=createUser&username=" + encodedUsername + + "&password=" + encodedPassword + + "&firstname=Test&lastname=Test&email=alena@vmops.com&domainId=1"; + String userIdStr=null; + HttpClient client = new HttpClient(); + HttpMethod method = new GetMethod(url); + int responseCode = client.executeMethod(method); + + if (responseCode == 200) { + InputStream is = method.getResponseBodyAsStream(); + Map userIdValues = TestClientWithAPI.getSingleValueFromXML(is, + new String[] { "id" }); + userIdStr = userIdValues.get("id"); + if ((userIdStr != null) && (Long.parseLong(userIdStr)!=-1)) { + this.setUserId(userIdStr); + } + } + } + + public void retrievePublicIp(long zoneId) throws IOException{ + + String encodedApiKey = URLEncoder.encode(this.apiKey, "UTF-8"); + String encodedZoneId=URLEncoder.encode(""+zoneId,"UTF-8"); + String requestToSign = "apiKey=" + encodedApiKey + + "&command=associateIpAddress" + "&zoneId="+encodedZoneId; + requestToSign = requestToSign.toLowerCase(); + String signature = TestClientWithAPI.signRequest(requestToSign, this.secretKey); + String encodedSignature = URLEncoder.encode(signature, "UTF-8"); + + String url = this.developerServer + "?command=associateIpAddress" + "&apiKey=" + + encodedApiKey + "&zoneId="+encodedZoneId+"&signature=" + + encodedSignature; + + HttpClient client = new HttpClient(); + HttpMethod method = new GetMethod(url); + int responseCode=client.executeMethod(method); + if (responseCode == 200) { + InputStream is = method.getResponseBodyAsStream(); + Map values = TestClientWithAPI.getSingleValueFromXML(is, + new String[] { "ipaddress" }); + this.getPublicIp().add(values.get("ipaddress")); + s_logger.info("Ip address is " + values.get("ipaddress")); + } else if (responseCode == 500) { + InputStream is = method.getResponseBodyAsStream(); + Map errorInfo = TestClientWithAPI.getSingleValueFromXML(is, + new String[] { "errorcode", "description" }); + s_logger.error("associate ip test failed with errorCode: " + + errorInfo.get("errorCode") + " and description: " + + errorInfo.get("description")); + } else { + s_logger.error("internal error processing request: " + + method.getStatusText()); + } + + } + + public void registerUser()throws HttpException, IOException{ + + String encodedUsername = URLEncoder.encode(this.userName, "UTF-8"); + String encodedPassword = URLEncoder.encode(this.password, "UTF-8"); + String url = server + "?command=register&username=" + encodedUsername + + "&domainid=1"; + s_logger.info("registering: " + this.userName+" with url "+url); + HttpClient client = new HttpClient(); + HttpMethod method = new GetMethod(url); + int responseCode = client.executeMethod(method); + if (responseCode == 200) { + InputStream is = method.getResponseBodyAsStream(); + Map requestKeyValues = TestClientWithAPI.getSingleValueFromXML(is, + new String[] { "apikey", "secretkey" }); + this.setApiKey(requestKeyValues.get("apikey")); + this.setSecretKey(requestKeyValues.get("secretkey")); + } else if (responseCode == 500) { + InputStream is = method.getResponseBodyAsStream(); + Map errorInfo = TestClientWithAPI.getSingleValueFromXML(is, + new String[] { "errorcode", "description" }); + s_logger.error("registration failed with errorCode: " + + errorInfo.get("errorCode") + " and description: " + + errorInfo.get("description")); + } else { + s_logger.error("internal error processing request: " + + method.getStatusText()); + } + } + +} + + diff --git a/test/src/com/cloud/test/longrun/VirtualMachine.java b/test/src/com/cloud/test/longrun/VirtualMachine.java index a865c11e131..24cd2069658 100644 --- a/test/src/com/cloud/test/longrun/VirtualMachine.java +++ b/test/src/com/cloud/test/longrun/VirtualMachine.java @@ -10,103 +10,103 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.test.longrun; - -import java.io.InputStream; -import java.net.URLEncoder; -import java.util.Map; - -import org.apache.commons.httpclient.HttpClient; -import org.apache.commons.httpclient.HttpMethod; -import org.apache.commons.httpclient.methods.GetMethod; -import org.apache.log4j.Logger; - +package com.cloud.test.longrun; + +import java.io.InputStream; +import java.net.URLEncoder; +import java.util.Map; + +import org.apache.commons.httpclient.HttpClient; +import org.apache.commons.httpclient.HttpMethod; +import org.apache.commons.httpclient.methods.GetMethod; +import org.apache.log4j.Logger; + import com.cloud.test.stress.TestClientWithAPI; - - -import java.io.IOException; - - -public class VirtualMachine { - public static final Logger s_logger= Logger.getLogger(VirtualMachine.class.getClass()); - - private String privateIp; - private String userId; - - - public VirtualMachine(String userId){ - this.userId=userId; - } - - - public String getPrivateIp() { - return privateIp; - } - - - public void setPrivateIp(String privateIp) { - this.privateIp = privateIp; - } - - - public String getUserId() { - return userId; - } - - - public void setUserId(String userId) { - this.userId = userId; - } - - - public void deployVM(long zoneId, long serviceOfferingId, long templateId, String server, String apiKey, String secretKey) throws IOException{ - - String encodedZoneId = URLEncoder.encode("" + zoneId, "UTF-8"); - String encodedServiceOfferingId = URLEncoder.encode("" - + serviceOfferingId, "UTF-8"); - String encodedTemplateId = URLEncoder.encode("" + templateId, - "UTF-8"); - String encodedApiKey=URLEncoder.encode(apiKey, "UTF-8"); - String requestToSign = "apiKey=" + encodedApiKey - + "&command=deployVirtualMachine&serviceOfferingId=" - + encodedServiceOfferingId + "&templateId=" - + encodedTemplateId + "&zoneId=" + encodedZoneId; - - requestToSign = requestToSign.toLowerCase(); - String signature = TestClientWithAPI.signRequest(requestToSign, secretKey); - String encodedSignature = URLEncoder.encode(signature, "UTF-8"); - String url = server + "?command=deployVirtualMachine" - + "&zoneId=" + encodedZoneId + "&serviceOfferingId=" - + encodedServiceOfferingId + "&templateId=" - + encodedTemplateId + "&apiKey=" + encodedApiKey - + "&signature=" + encodedSignature; - - s_logger.info("Sending this request to deploy a VM: "+url); - HttpClient client = new HttpClient(); - HttpMethod method = new GetMethod(url); - int responseCode = client.executeMethod(method); - s_logger.info("deploy linux vm response code: " + responseCode); - if (responseCode == 200) { - InputStream is = method.getResponseBodyAsStream(); - Map values = TestClientWithAPI.getSingleValueFromXML(is, - new String[] { "id", "ipaddress" }); - long linuxVMId = Long.parseLong(values.get("id")); - s_logger.info("got linux virtual machine id: " + linuxVMId); - this.setPrivateIp(values.get("ipaddress")); - - } else if (responseCode == 500) { - InputStream is = method.getResponseBodyAsStream(); - Map errorInfo = TestClientWithAPI.getSingleValueFromXML(is, - new String[] { "errorcode", "description" }); - s_logger.error("deploy linux vm test failed with errorCode: " - + errorInfo.get("errorCode") + " and description: " - + errorInfo.get("description")); - } else { - s_logger.error("internal error processing request: " - + method.getStatusText()); - } - } - - - -} + + +import java.io.IOException; + + +public class VirtualMachine { + public static final Logger s_logger= Logger.getLogger(VirtualMachine.class.getClass()); + + private String privateIp; + private String userId; + + + public VirtualMachine(String userId){ + this.userId=userId; + } + + + public String getPrivateIp() { + return privateIp; + } + + + public void setPrivateIp(String privateIp) { + this.privateIp = privateIp; + } + + + public String getUserId() { + return userId; + } + + + public void setUserId(String userId) { + this.userId = userId; + } + + + public void deployVM(long zoneId, long serviceOfferingId, long templateId, String server, String apiKey, String secretKey) throws IOException{ + + String encodedZoneId = URLEncoder.encode("" + zoneId, "UTF-8"); + String encodedServiceOfferingId = URLEncoder.encode("" + + serviceOfferingId, "UTF-8"); + String encodedTemplateId = URLEncoder.encode("" + templateId, + "UTF-8"); + String encodedApiKey=URLEncoder.encode(apiKey, "UTF-8"); + String requestToSign = "apiKey=" + encodedApiKey + + "&command=deployVirtualMachine&serviceOfferingId=" + + encodedServiceOfferingId + "&templateId=" + + encodedTemplateId + "&zoneId=" + encodedZoneId; + + requestToSign = requestToSign.toLowerCase(); + String signature = TestClientWithAPI.signRequest(requestToSign, secretKey); + String encodedSignature = URLEncoder.encode(signature, "UTF-8"); + String url = server + "?command=deployVirtualMachine" + + "&zoneId=" + encodedZoneId + "&serviceOfferingId=" + + encodedServiceOfferingId + "&templateId=" + + encodedTemplateId + "&apiKey=" + encodedApiKey + + "&signature=" + encodedSignature; + + s_logger.info("Sending this request to deploy a VM: "+url); + HttpClient client = new HttpClient(); + HttpMethod method = new GetMethod(url); + int responseCode = client.executeMethod(method); + s_logger.info("deploy linux vm response code: " + responseCode); + if (responseCode == 200) { + InputStream is = method.getResponseBodyAsStream(); + Map values = TestClientWithAPI.getSingleValueFromXML(is, + new String[] { "id", "ipaddress" }); + long linuxVMId = Long.parseLong(values.get("id")); + s_logger.info("got linux virtual machine id: " + linuxVMId); + this.setPrivateIp(values.get("ipaddress")); + + } else if (responseCode == 500) { + InputStream is = method.getResponseBodyAsStream(); + Map errorInfo = TestClientWithAPI.getSingleValueFromXML(is, + new String[] { "errorcode", "description" }); + s_logger.error("deploy linux vm test failed with errorCode: " + + errorInfo.get("errorCode") + " and description: " + + errorInfo.get("description")); + } else { + s_logger.error("internal error processing request: " + + method.getStatusText()); + } + } + + + +} diff --git a/test/src/com/cloud/test/longrun/guestNetwork.java b/test/src/com/cloud/test/longrun/guestNetwork.java index 54f2df908f2..e9bafcd8256 100644 --- a/test/src/com/cloud/test/longrun/guestNetwork.java +++ b/test/src/com/cloud/test/longrun/guestNetwork.java @@ -10,94 +10,94 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.test.longrun; -import java.util.ArrayList; -import java.util.Random; -import org.apache.log4j.Logger; -import org.apache.log4j.NDC; -import com.trilead.ssh2.Connection; -import com.trilead.ssh2.Session; - - -public class guestNetwork implements Runnable{ - public static final Logger s_logger= Logger.getLogger(guestNetwork.class.getClass()); - - private String publicIp; - private ArrayList virtualMachines; - private int retryNum; - - public guestNetwork(String publicIp, int retryNum){ - this.publicIp=publicIp; - this.retryNum=retryNum; - } - - public ArrayList getVirtualMachines() { - return virtualMachines; - } - - public void setVirtualMachines(ArrayList virtualMachines) { - this.virtualMachines = virtualMachines; - } - - public void run(){ - NDC.push("Following thread has started"+Thread.currentThread().getName()); - int retry = 0; - - //Start copying files between machines in the network - s_logger.info("The size of the array is " + this.virtualMachines.size()); - while (true) { - try { - if (retry > 0) { - s_logger.info("Retry attempt : " + retry - + " ...sleeping 120 seconds before next attempt"); - Thread.sleep(120000); - } - for (VirtualMachine vm: this.virtualMachines ){ - - s_logger.info("Attempting to SSH into linux host " + this.publicIp - + " with retry attempt: " + retry); - Connection conn = new Connection(this.publicIp); - conn.connect(null, 600000, 600000); - - s_logger.info("SSHed successfully into linux host " + this.publicIp); - - boolean isAuthenticated = conn.authenticateWithPassword("root", - "password"); - - if (isAuthenticated == false) { - s_logger.info("Authentication failed"); - } - //execute copy command - Session sess = conn.openSession(); - String fileName; - Random ran = new Random(); - fileName=Math.abs(ran.nextInt())+"-file"; - String copyCommand = new String ("./scpScript "+vm.getPrivateIp()+" "+fileName); - s_logger.info("Executing " + copyCommand); - sess.execCommand(copyCommand); - Thread.sleep(120000); - sess.close(); - - //execute wget command - sess = conn.openSession(); - String downloadCommand = new String ("wget http://172.16.0.220/scripts/checkDiskSpace.sh; chmod +x *sh; ./checkDiskSpace.sh; rm -rf checkDiskSpace.sh"); - s_logger.info("Executing " + downloadCommand); - sess.execCommand(downloadCommand); - Thread.sleep(120000); - sess.close(); - - //close the connection - conn.close(); - } - }catch (Exception ex) { - s_logger.error(ex); - retry++; - if (retry == retryNum) { - s_logger.info("Performance Guest Network test failed with error " - + ex.getMessage()) ; - } - } - } - - } -} +package com.cloud.test.longrun; +import java.util.ArrayList; +import java.util.Random; +import org.apache.log4j.Logger; +import org.apache.log4j.NDC; +import com.trilead.ssh2.Connection; +import com.trilead.ssh2.Session; + + +public class guestNetwork implements Runnable{ + public static final Logger s_logger= Logger.getLogger(guestNetwork.class.getClass()); + + private String publicIp; + private ArrayList virtualMachines; + private int retryNum; + + public guestNetwork(String publicIp, int retryNum){ + this.publicIp=publicIp; + this.retryNum=retryNum; + } + + public ArrayList getVirtualMachines() { + return virtualMachines; + } + + public void setVirtualMachines(ArrayList virtualMachines) { + this.virtualMachines = virtualMachines; + } + + public void run(){ + NDC.push("Following thread has started"+Thread.currentThread().getName()); + int retry = 0; + + //Start copying files between machines in the network + s_logger.info("The size of the array is " + this.virtualMachines.size()); + while (true) { + try { + if (retry > 0) { + s_logger.info("Retry attempt : " + retry + + " ...sleeping 120 seconds before next attempt"); + Thread.sleep(120000); + } + for (VirtualMachine vm: this.virtualMachines ){ + + s_logger.info("Attempting to SSH into linux host " + this.publicIp + + " with retry attempt: " + retry); + Connection conn = new Connection(this.publicIp); + conn.connect(null, 600000, 600000); + + s_logger.info("SSHed successfully into linux host " + this.publicIp); + + boolean isAuthenticated = conn.authenticateWithPassword("root", + "password"); + + if (isAuthenticated == false) { + s_logger.info("Authentication failed"); + } + //execute copy command + Session sess = conn.openSession(); + String fileName; + Random ran = new Random(); + fileName=Math.abs(ran.nextInt())+"-file"; + String copyCommand = new String ("./scpScript "+vm.getPrivateIp()+" "+fileName); + s_logger.info("Executing " + copyCommand); + sess.execCommand(copyCommand); + Thread.sleep(120000); + sess.close(); + + //execute wget command + sess = conn.openSession(); + String downloadCommand = new String ("wget http://172.16.0.220/scripts/checkDiskSpace.sh; chmod +x *sh; ./checkDiskSpace.sh; rm -rf checkDiskSpace.sh"); + s_logger.info("Executing " + downloadCommand); + sess.execCommand(downloadCommand); + Thread.sleep(120000); + sess.close(); + + //close the connection + conn.close(); + } + }catch (Exception ex) { + s_logger.error(ex); + retry++; + if (retry == retryNum) { + s_logger.info("Performance Guest Network test failed with error " + + ex.getMessage()) ; + } + } + } + + } +} diff --git a/test/src/com/cloud/test/regression/DelegatedAdminTest.java b/test/src/com/cloud/test/regression/DelegatedAdminTest.java index 74e5f2a4f54..6ade35f8512 100644 --- a/test/src/com/cloud/test/regression/DelegatedAdminTest.java +++ b/test/src/com/cloud/test/regression/DelegatedAdminTest.java @@ -10,119 +10,119 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.test.regression; - - -import java.util.HashMap; - -import org.apache.log4j.Logger; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -import com.cloud.test.regression.ApiCommand.ResponseType; - -public class DelegatedAdminTest extends TestCase{ - -public static final Logger s_logger = Logger.getLogger(DelegatedAdminTest.class.getName()); - - public DelegatedAdminTest(){ - this.setClient(); - this.setParam(new HashMap()); - } - - public boolean executeTest(){ - int error=0; - - for (Document eachElement: this.getInputFile()) { - - Element rootElement = eachElement.getDocumentElement(); - NodeList commandLst = rootElement.getElementsByTagName("command"); - - //Analyze each command, send request and build the array list of api commands - for (int i=0; i()); + } + + public boolean executeTest(){ + int error=0; + + for (Document eachElement: this.getInputFile()) { + + Element rootElement = eachElement.getDocumentElement(); + NodeList commandLst = rootElement.getElementsByTagName("command"); + + //Analyze each command, send request and build the array list of api commands + for (int i=0; i()); - } - - - public boolean executeTest() { - int error=0; - Element rootElement = this.getInputFile().get(0).getDocumentElement(); - NodeList commandLst = rootElement.getElementsByTagName("command"); - - //Analyze each command, send request and build the array list of api commands - for (int i=0; i argsList = Arrays.asList(args); - Iterator iter = argsList.iterator(); - String host = null; - String file = null; - - while (iter.hasNext()) { - String arg = iter.next(); - // management server host - if (arg.equals("-h")) { - host = iter.next(); - } - if (arg.equals("-f")) { - file = iter.next(); - } - } - +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +import org.apache.log4j.Logger; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +public class Deploy extends TestCase{ + public static final Logger s_logger = Logger.getLogger(Deploy.class.getName()); + + public Deploy(){ + this.setClient(); + this.setParam(new HashMap()); + } + + + public boolean executeTest() { + int error=0; + Element rootElement = this.getInputFile().get(0).getDocumentElement(); + NodeList commandLst = rootElement.getElementsByTagName("command"); + + //Analyze each command, send request and build the array list of api commands + for (int i=0; i argsList = Arrays.asList(args); + Iterator iter = argsList.iterator(); + String host = null; + String file = null; + + while (iter.hasNext()) { + String arg = iter.next(); + // management server host + if (arg.equals("-h")) { + host = iter.next(); + } + if (arg.equals("-f")) { + file = iter.next(); + } + } + Deploy deploy = new Deploy (); ArrayList inputFile = new ArrayList(); - inputFile.add(file); - deploy.setInputFile(inputFile); - deploy.setTestCaseName("Management server deployment"); - deploy.getParam().put("hostip", host); - deploy.getParam().put("apicommands", "../metadata/func/commands"); - deploy.setCommands(); - - s_logger.info("Starting deployment against host " + host); - - boolean result = deploy.executeTest(); - if (result == false) { - s_logger.error("DEPLOYMENT FAILED"); - System.exit(1); - } - else { - s_logger.info("DEPLOYMENT IS SUCCESSFUL"); - } - - } - -} - + inputFile.add(file); + deploy.setInputFile(inputFile); + deploy.setTestCaseName("Management server deployment"); + deploy.getParam().put("hostip", host); + deploy.getParam().put("apicommands", "../metadata/func/commands"); + deploy.setCommands(); + + s_logger.info("Starting deployment against host " + host); + + boolean result = deploy.executeTest(); + if (result == false) { + s_logger.error("DEPLOYMENT FAILED"); + System.exit(1); + } + else { + s_logger.info("DEPLOYMENT IS SUCCESSFUL"); + } + + } + +} + diff --git a/test/src/com/cloud/test/regression/EventsApiTest.java b/test/src/com/cloud/test/regression/EventsApiTest.java index 55a34282d82..8e5e9e5d6da 100644 --- a/test/src/com/cloud/test/regression/EventsApiTest.java +++ b/test/src/com/cloud/test/regression/EventsApiTest.java @@ -10,165 +10,165 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.test.regression; - -import java.sql.Statement; -import java.util.HashMap; - -import org.apache.log4j.Logger; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - +package com.cloud.test.regression; + +import java.sql.Statement; +import java.util.HashMap; + +import org.apache.log4j.Logger; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + import com.cloud.test.regression.ApiCommand.ResponseType; -import com.trilead.ssh2.Connection; -import com.trilead.ssh2.Session; - -public class EventsApiTest extends TestCase{ -public static final Logger s_logger = Logger.getLogger(EventsApiTest.class.getName()); - - - public EventsApiTest(){ - this.setClient(); - this.setParam(new HashMap()); - } - - public boolean executeTest(){ - int error=0; - Element rootElement = this.getInputFile().get(0).getDocumentElement(); - NodeList commandLst = rootElement.getElementsByTagName("command"); - - - //Analyze each command, send request and build the array list of api commands - for (int i=0; i expectedEvents = new HashMap(); - expectedEvents.put("VM.START", 1); - boolean eventResult = ApiCommand.verifyEvents(expectedEvents, "INFO", "http://" + this.getParam().get("hostip") + ":8096", "userid=" + this.getParam().get("userid1") + "&type=VM.START"); - s_logger.info("Test case 97 - listEvent command verification result is " + eventResult); - - //verify error events - eventResult = ApiCommand.verifyEvents("../metadata/error_events.properties", "ERROR", "http://" + this.getParam().get("hostip") + ":8096", this.getParam().get("erroruseraccount")); - s_logger.info("listEvent command verification result is " + eventResult); - - - if (error != 0) - return false; - else - return true; - } -} +import com.trilead.ssh2.Connection; +import com.trilead.ssh2.Session; + +public class EventsApiTest extends TestCase{ +public static final Logger s_logger = Logger.getLogger(EventsApiTest.class.getName()); + + + public EventsApiTest(){ + this.setClient(); + this.setParam(new HashMap()); + } + + public boolean executeTest(){ + int error=0; + Element rootElement = this.getInputFile().get(0).getDocumentElement(); + NodeList commandLst = rootElement.getElementsByTagName("command"); + + + //Analyze each command, send request and build the array list of api commands + for (int i=0; i expectedEvents = new HashMap(); + expectedEvents.put("VM.START", 1); + boolean eventResult = ApiCommand.verifyEvents(expectedEvents, "INFO", "http://" + this.getParam().get("hostip") + ":8096", "userid=" + this.getParam().get("userid1") + "&type=VM.START"); + s_logger.info("Test case 97 - listEvent command verification result is " + eventResult); + + //verify error events + eventResult = ApiCommand.verifyEvents("../metadata/error_events.properties", "ERROR", "http://" + this.getParam().get("hostip") + ":8096", this.getParam().get("erroruseraccount")); + s_logger.info("listEvent command verification result is " + eventResult); + + + if (error != 0) + return false; + else + return true; + } +} diff --git a/test/src/com/cloud/test/regression/HA.java b/test/src/com/cloud/test/regression/HA.java index 9ff843d0bc6..cdf2a1c052f 100644 --- a/test/src/com/cloud/test/regression/HA.java +++ b/test/src/com/cloud/test/regression/HA.java @@ -10,65 +10,65 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.test.regression; - -import org.apache.log4j.Logger; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -import com.cloud.test.regression.ApiCommand.ResponseType; - -public class HA extends TestCase{ - - public static final Logger s_logger = Logger.getLogger(HA.class.getName()); - - public HA(){ - this.setClient(); - } - - public boolean executeTest(){ - int error=0; - Element rootElement = this.getInputFile().get(0).getDocumentElement(); - NodeList commandLst = rootElement.getElementsByTagName("command"); - - //Analyze each command, send request and build the array list of api commands - for (int i=0; i()); - } - - public boolean executeTest(){ - - int error=0; - Element rootElement = this.getInputFile().get(0).getDocumentElement(); - NodeList commandLst = rootElement.getElementsByTagName("command"); - - //Analyze each command, send request and build the array list of api commands - for (int i=0; i port = new ArrayList(); -// for (int i=1; i<65536; i++){ -// port.add(Integer.toString(i)); -// } -// -// //try all public ports -// for (String portValue : port) { -// try { -// String url = this.getHost() + ":8096/?command=createOrUpdateLoadBalancerRule&account=" + this.getParam().get("accountname") + "&publicip=" + this.getParam().get("boundaryip") + -// "&privateip=" + this.getParam().get("vmipaddress") + "&privateport=22&protocol=tcp&publicport=" + portValue; -// HttpClient client = new HttpClient(); -// HttpMethod method = new GetMethod(url); -// int responseCode = client.executeMethod(method); -// if (responseCode != 200 ) { -// error++; -// s_logger.error("Can't create LB rule for the public port " + portValue + ". Request was sent with url " + url); -// } -// }catch (Exception ex) { -// s_logger.error(ex); -// } -// } -// -// //try all private ports -// for (String portValue : port) { -// try { -// String url = this.getHost() + ":8096/?command=createOrUpdateLoadBalancerRule&account=" + this.getParam().get("accountname") + "&publicip=" + this.getParam().get("boundaryip") + -// "&privateip=" + this.getParam().get("vmipaddress") + "&publicport=22&protocol=tcp&privateport=" + portValue; -// HttpClient client = new HttpClient(); -// HttpMethod method = new GetMethod(url); -// int responseCode = client.executeMethod(method); -// if (responseCode != 200 ) { -// error++; -// s_logger.error("Can't create LB rule for the private port " + portValue + ". Request was sent with url " + url); -// } -// }catch (Exception ex) { -// s_logger.error(ex); -// } -// } - - - if (error != 0) - return false; - else - return true; - } - -} + + +public class LoadBalancingTest extends TestCase{ + + public static final Logger s_logger = Logger.getLogger(LoadBalancingTest.class.getName()); + + public LoadBalancingTest(){ + this.setClient(); + this.setParam(new HashMap()); + } + + public boolean executeTest(){ + + int error=0; + Element rootElement = this.getInputFile().get(0).getDocumentElement(); + NodeList commandLst = rootElement.getElementsByTagName("command"); + + //Analyze each command, send request and build the array list of api commands + for (int i=0; i port = new ArrayList(); +// for (int i=1; i<65536; i++){ +// port.add(Integer.toString(i)); +// } +// +// //try all public ports +// for (String portValue : port) { +// try { +// String url = this.getHost() + ":8096/?command=createOrUpdateLoadBalancerRule&account=" + this.getParam().get("accountname") + "&publicip=" + this.getParam().get("boundaryip") + +// "&privateip=" + this.getParam().get("vmipaddress") + "&privateport=22&protocol=tcp&publicport=" + portValue; +// HttpClient client = new HttpClient(); +// HttpMethod method = new GetMethod(url); +// int responseCode = client.executeMethod(method); +// if (responseCode != 200 ) { +// error++; +// s_logger.error("Can't create LB rule for the public port " + portValue + ". Request was sent with url " + url); +// } +// }catch (Exception ex) { +// s_logger.error(ex); +// } +// } +// +// //try all private ports +// for (String portValue : port) { +// try { +// String url = this.getHost() + ":8096/?command=createOrUpdateLoadBalancerRule&account=" + this.getParam().get("accountname") + "&publicip=" + this.getParam().get("boundaryip") + +// "&privateip=" + this.getParam().get("vmipaddress") + "&publicport=22&protocol=tcp&privateport=" + portValue; +// HttpClient client = new HttpClient(); +// HttpMethod method = new GetMethod(url); +// int responseCode = client.executeMethod(method); +// if (responseCode != 200 ) { +// error++; +// s_logger.error("Can't create LB rule for the private port " + portValue + ". Request was sent with url " + url); +// } +// }catch (Exception ex) { +// s_logger.error(ex); +// } +// } + + + if (error != 0) + return false; + else + return true; + } + +} diff --git a/test/src/com/cloud/test/regression/PortForwardingTest.java b/test/src/com/cloud/test/regression/PortForwardingTest.java index 13dc42429a4..2942edace53 100644 --- a/test/src/com/cloud/test/regression/PortForwardingTest.java +++ b/test/src/com/cloud/test/regression/PortForwardingTest.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.test.regression; - +package com.cloud.test.regression; + import java.util.HashMap; import org.apache.log4j.Logger; @@ -20,123 +20,123 @@ import org.w3c.dom.Node; import org.w3c.dom.NodeList; import com.cloud.test.regression.ApiCommand.ResponseType; - -public class PortForwardingTest extends TestCase{ - public static final Logger s_logger = Logger.getLogger(PortForwardingTest.class.getName()); - - public PortForwardingTest(){ - this.setClient(); - this.setParam(new HashMap()); - } - - public boolean executeTest(){ - - int error=0; - Element rootElement = this.getInputFile().get(0).getDocumentElement(); - NodeList commandLst = rootElement.getElementsByTagName("command"); - - //Analyze each command, send request and build the array list of api commands - for (int i=0; i port = new ArrayList(); -// for (int i=1; i<65536; i++){ -// port.add(Integer.toString(i)); -// } -// -// //try all public ports -// for (String portValue : port) { -// try { -// s_logger.info("public port is " + portValue); -// String url = this.getHost() + ":8096/?command=createOrUpdateIpForwardingRule&account=" + this.getParam().get("accountname") + "&publicip=" + this.getParam().get("boundaryip") + -// "&privateip=" + this.getParam().get("vmipaddress") + "&privateport=22&protocol=tcp&publicport=" + portValue; -// HttpClient client = new HttpClient(); -// HttpMethod method = new GetMethod(url); -// int responseCode = client.executeMethod(method); -// if (responseCode != 200 ) { -// error++; -// s_logger.error("Can't create portForwarding rule for the public port " + portValue + ". Request was sent with url " + url); -// } -// }catch (Exception ex) { -// s_logger.error(ex); -// } -// } -// -// //try all private ports -// for (String portValue : port) { -// try { -// String url = this.getHost() + ":8096/?command=createOrUpdateIpForwardingRule&account=" + this.getParam().get("accountname") + "&publicip=" + this.getParam().get("boundaryip") + -// "&privateip=" + this.getParam().get("vmipaddress") + "&publicport=22&protocol=tcp&privateport=" + portValue; -// HttpClient client = new HttpClient(); -// HttpMethod method = new GetMethod(url); -// int responseCode = client.executeMethod(method); -// if (responseCode != 200 ) { -// error++; -// s_logger.error("Can't create portForwarding rule for the private port " + portValue + ". Request was sent with url " + url); -// } -// }catch (Exception ex) { -// s_logger.error(ex); -// } -// } - - - if (error != 0) - return false; - else - return true; - } - -} + +public class PortForwardingTest extends TestCase{ + public static final Logger s_logger = Logger.getLogger(PortForwardingTest.class.getName()); + + public PortForwardingTest(){ + this.setClient(); + this.setParam(new HashMap()); + } + + public boolean executeTest(){ + + int error=0; + Element rootElement = this.getInputFile().get(0).getDocumentElement(); + NodeList commandLst = rootElement.getElementsByTagName("command"); + + //Analyze each command, send request and build the array list of api commands + for (int i=0; i port = new ArrayList(); +// for (int i=1; i<65536; i++){ +// port.add(Integer.toString(i)); +// } +// +// //try all public ports +// for (String portValue : port) { +// try { +// s_logger.info("public port is " + portValue); +// String url = this.getHost() + ":8096/?command=createOrUpdateIpForwardingRule&account=" + this.getParam().get("accountname") + "&publicip=" + this.getParam().get("boundaryip") + +// "&privateip=" + this.getParam().get("vmipaddress") + "&privateport=22&protocol=tcp&publicport=" + portValue; +// HttpClient client = new HttpClient(); +// HttpMethod method = new GetMethod(url); +// int responseCode = client.executeMethod(method); +// if (responseCode != 200 ) { +// error++; +// s_logger.error("Can't create portForwarding rule for the public port " + portValue + ". Request was sent with url " + url); +// } +// }catch (Exception ex) { +// s_logger.error(ex); +// } +// } +// +// //try all private ports +// for (String portValue : port) { +// try { +// String url = this.getHost() + ":8096/?command=createOrUpdateIpForwardingRule&account=" + this.getParam().get("accountname") + "&publicip=" + this.getParam().get("boundaryip") + +// "&privateip=" + this.getParam().get("vmipaddress") + "&publicport=22&protocol=tcp&privateport=" + portValue; +// HttpClient client = new HttpClient(); +// HttpMethod method = new GetMethod(url); +// int responseCode = client.executeMethod(method); +// if (responseCode != 200 ) { +// error++; +// s_logger.error("Can't create portForwarding rule for the private port " + portValue + ". Request was sent with url " + url); +// } +// }catch (Exception ex) { +// s_logger.error(ex); +// } +// } + + + if (error != 0) + return false; + else + return true; + } + +} diff --git a/test/src/com/cloud/test/regression/SanityTest.java b/test/src/com/cloud/test/regression/SanityTest.java index ef7e3cc4b9a..343cbbf11a5 100644 --- a/test/src/com/cloud/test/regression/SanityTest.java +++ b/test/src/com/cloud/test/regression/SanityTest.java @@ -12,71 +12,71 @@ // Automatically generated by addcopyright.py at 04/03/2012 package com.cloud.test.regression; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.apache.log4j.Logger; - -public class SanityTest extends TestCase{ - - public static final Logger s_logger = Logger.getLogger(SanityTest.class.getName()); - - public SanityTest(){ - this.setClient(); - } - - public boolean executeTest(){ - int error=0; - Element rootElement = this.getInputFile().get(0).getDocumentElement(); - NodeList commandLst = rootElement.getElementsByTagName("command"); - //Analyze each command, send request and build the array list of api commands - for (int i=0; i()); - } - - public boolean executeTest(){ - - int error=0; - Element rootElement = this.getInputFile().get(0).getDocumentElement(); - NodeList commandLst = rootElement.getElementsByTagName("command"); - - //Analyze each command, send request and build the array list of api commands - for (int i=0; i port = new ArrayList(); - for (int j=1; j<1000; j++){ - port.add(Integer.toString(j)); - } - - //try all public ports - for (String portValue : port) { - try { - s_logger.info("public port is " + portValue); - String url = "http://" + this.getParam().get("hostip") + ":8096/?command=createNetworkRule&publicPort=" + portValue + "&privatePort=22&protocol=tcp&isForward=true&securityGroupId=1&account=admin"; - HttpClient client = new HttpClient(); - HttpMethod method = new GetMethod(url); - int responseCode = client.executeMethod(method); - if (responseCode != 200 ) { - error++; - s_logger.error("Can't create portForwarding network rule for the public port " + portValue + ". Request was sent with url " + url); - } - }catch (Exception ex) { - s_logger.error(ex); - } - } - - - if (error != 0) - return false; - else - return true; - } -} +package com.cloud.test.regression; + +import java.util.ArrayList; +import java.util.HashMap; + +import org.apache.commons.httpclient.HttpClient; +import org.apache.commons.httpclient.HttpMethod; +import org.apache.commons.httpclient.methods.GetMethod; +import org.apache.log4j.Logger; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +public class Test extends TestCase{ + public static final Logger s_logger = Logger.getLogger(Test.class.getName()); + + public Test(){ + this.setClient(); + this.setParam(new HashMap()); + } + + public boolean executeTest(){ + + int error=0; + Element rootElement = this.getInputFile().get(0).getDocumentElement(); + NodeList commandLst = rootElement.getElementsByTagName("command"); + + //Analyze each command, send request and build the array list of api commands + for (int i=0; i port = new ArrayList(); + for (int j=1; j<1000; j++){ + port.add(Integer.toString(j)); + } + + //try all public ports + for (String portValue : port) { + try { + s_logger.info("public port is " + portValue); + String url = "http://" + this.getParam().get("hostip") + ":8096/?command=createNetworkRule&publicPort=" + portValue + "&privatePort=22&protocol=tcp&isForward=true&securityGroupId=1&account=admin"; + HttpClient client = new HttpClient(); + HttpMethod method = new GetMethod(url); + int responseCode = client.executeMethod(method); + if (responseCode != 200 ) { + error++; + s_logger.error("Can't create portForwarding network rule for the public port " + portValue + ". Request was sent with url " + url); + } + }catch (Exception ex) { + s_logger.error(ex); + } + } + + + if (error != 0) + return false; + else + return true; + } +} diff --git a/test/src/com/cloud/test/regression/TestCase.java b/test/src/com/cloud/test/regression/TestCase.java index 8b68e52e1b3..3eefa4c1507 100644 --- a/test/src/com/cloud/test/regression/TestCase.java +++ b/test/src/com/cloud/test/regression/TestCase.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.test.regression; - +package com.cloud.test.regression; + import java.io.File; import java.io.FileInputStream; import java.sql.Connection; @@ -27,24 +27,24 @@ import javax.xml.parsers.DocumentBuilderFactory; import org.apache.commons.httpclient.HttpClient; import org.apache.log4j.Logger; import org.w3c.dom.Document; - - -public abstract class TestCase{ - - public static Logger s_logger = Logger.getLogger(TestCase.class.getName()); - private Connection conn; - private ArrayList inputFile = new ArrayList (); - private HttpClient client; - private String testCaseName; + + +public abstract class TestCase{ + + public static Logger s_logger = Logger.getLogger(TestCase.class.getName()); + private Connection conn; + private ArrayList inputFile = new ArrayList (); + private HttpClient client; + private String testCaseName; private HashMap param = new HashMap (); - private HashMap commands = new HashMap (); - - public HashMap getParam() { - return param; - } - - public void setParam(HashMap param) { - this.param = param; + private HashMap commands = new HashMap (); + + public HashMap getParam() { + return param; + } + + public void setParam(HashMap param) { + this.param = param; } @@ -73,26 +73,26 @@ public abstract class TestCase{ s_logger.info("Unable to find the file " + param.get("apicommands") + " due to following exception " + ex); } - } - - public Connection getConn() { - return conn; - } - - public void setConn(String dbPassword) { - this.conn = null; - try { - Class.forName("com.mysql.jdbc.Driver"); - this.conn=DriverManager.getConnection("jdbc:mysql://" + param.get("db") + "/cloud", "root", dbPassword); - if (!this.conn.isValid(0)) { - s_logger.error("Connection to DB failed to establish"); - } - - }catch (Exception ex) { - s_logger.error(ex); - } - } - + } + + public Connection getConn() { + return conn; + } + + public void setConn(String dbPassword) { + this.conn = null; + try { + Class.forName("com.mysql.jdbc.Driver"); + this.conn=DriverManager.getConnection("jdbc:mysql://" + param.get("db") + "/cloud", "root", dbPassword); + if (!this.conn.isValid(0)) { + s_logger.error("Connection to DB failed to establish"); + } + + }catch (Exception ex) { + s_logger.error(ex); + } + } + public void setInputFile (ArrayList fileNameInput) { for (String fileName: fileNameInput) { File file = new File(fileName); @@ -106,31 +106,31 @@ public abstract class TestCase{ s_logger.error("Unable to load " + fileName + " due to ", ex); } this.inputFile.add(doc); - } - } - - public ArrayList getInputFile() { - return inputFile; - } - - public void setTestCaseName(String testCaseName) { - this.testCaseName = testCaseName; - } - - public String getTestCaseName(){ - return this.testCaseName; - } - - public void setClient() { - HttpClient client = new HttpClient(); - this.client = client; - } - - public HttpClient getClient() { - return this.client; - } - - //abstract methods - public abstract boolean executeTest(); - -} + } + } + + public ArrayList getInputFile() { + return inputFile; + } + + public void setTestCaseName(String testCaseName) { + this.testCaseName = testCaseName; + } + + public String getTestCaseName(){ + return this.testCaseName; + } + + public void setClient() { + HttpClient client = new HttpClient(); + this.client = client; + } + + public HttpClient getClient() { + return this.client; + } + + //abstract methods + public abstract boolean executeTest(); + +} diff --git a/test/src/com/cloud/test/regression/VMApiTest.java b/test/src/com/cloud/test/regression/VMApiTest.java index 30a086cafc7..917b5bf9d01 100644 --- a/test/src/com/cloud/test/regression/VMApiTest.java +++ b/test/src/com/cloud/test/regression/VMApiTest.java @@ -10,55 +10,55 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.test.regression; - -import java.util.HashMap; - -import org.apache.log4j.Logger; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; +package com.cloud.test.regression; + +import java.util.HashMap; + +import org.apache.log4j.Logger; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; import com.cloud.test.regression.ApiCommand.ResponseType; - - -public class VMApiTest extends TestCase{ -public static final Logger s_logger = Logger.getLogger(VMApiTest.class.getName()); - - - public VMApiTest(){ - this.setClient(); - this.setParam(new HashMap()); - } - - public boolean executeTest(){ - int error=0; - Element rootElement = this.getInputFile().get(0).getDocumentElement(); - NodeList commandLst = rootElement.getElementsByTagName("command"); - - //Analyze each command, send request and build the array list of api commands - for (int i=0; i()); + } + + public boolean executeTest(){ + int error=0; + Element rootElement = this.getInputFile().get(0).getDocumentElement(); + NodeList commandLst = rootElement.getElementsByTagName("command"); + + //Analyze each command, send request and build the array list of api commands + for (int i=0; i _linuxIP = new ThreadLocal(); - private static ThreadLocal _linuxVmId = new ThreadLocal(); - private static ThreadLocal _linuxVmId1 = new ThreadLocal(); - private static ThreadLocal _linuxPassword = new ThreadLocal(); - private static ThreadLocal _windowsIP = new ThreadLocal(); - private static ThreadLocal _secretKey = new ThreadLocal(); - private static ThreadLocal _apiKey = new ThreadLocal(); - private static ThreadLocal _userId = new ThreadLocal(); - private static ThreadLocal _account = new ThreadLocal(); - private static ThreadLocal _domainRouterId = new ThreadLocal(); - private static ThreadLocal _newVolume = new ThreadLocal(); - private static ThreadLocal _newVolume1 = new ThreadLocal(); - private static DocumentBuilderFactory factory = DocumentBuilderFactory - .newInstance(); - private static int usageIterator = 1; - private static int numThreads = 1; - private static int wait = 5000; - private static String accountName = null; - private static String zoneId = "1"; - private static String serviceOfferingId = "13"; - private static String diskOfferingId="11"; - private static String diskOfferingId1="12"; - - private static final int MAX_RETRY_LINUX = 10; - private static final int MAX_RETRY_WIN = 10; - - - public static void main(String[] args) { - String host = "http://localhost"; - String port = "8092"; - String devPort = "8080"; - String apiUrl = "/client/api"; - - try { - // Parameters - List argsList = Arrays.asList(args); - Iterator iter = argsList.iterator(); - while (iter.hasNext()) { - String arg = iter.next(); - // host - if (arg.equals("-h")) { - host = "http://" + iter.next(); - } - - if (arg.equals("-p")) { - port = iter.next(); - } - if (arg.equals("-dp")) { - devPort = iter.next(); - } - - if (arg.equals("-t")) { - numThreads = Integer.parseInt(iter.next()); - } - - if (arg.equals("-s")) { - sleepTime = Long.parseLong(iter.next()); - } - if (arg.equals("-a")) { - accountName = iter.next(); - } - - if (arg.equals("-c")) { - cleanUp = Boolean.parseBoolean(iter.next()); - if (!cleanUp) - sleepTime = 0L; // no need to wait if we don't ever - // cleanup - } - - if (arg.equals("-r")) { - repeat = Boolean.parseBoolean(iter.next()); - } - - if (arg.equals("-i")) { - internet = Boolean.parseBoolean(iter.next()); - } - - if (arg.equals("-w")) { - wait = Integer.parseInt(iter.next()); - } - - if (arg.equals("-z")) { - zoneId = iter.next(); - } - - if (arg.equals("-so")) { - serviceOfferingId = iter.next(); - } - - } - - final String server = host + ":" + port + "/"; - final String developerServer = host + ":" + devPort + apiUrl; - s_logger.info("Starting test against server: " + server + " with " - + numThreads + " thread(s)"); - if (cleanUp) - s_logger.info("Clean up is enabled, each test will wait " - + sleepTime + " ms before cleaning up"); - - - - for (int i = 0; i < numThreads; i++) { - new Thread(new Runnable() { - public void run() { - do { - String username = null; - try { - long now = System.currentTimeMillis(); - Random ran = new Random(); - username = Math.abs(ran.nextInt())+ "-user"; - NDC.push(username); - - s_logger.info("Starting test for the user " + username); - int response = executeDeployment(server, - developerServer, username); - boolean success = false; - String reason = null; - - - - - if (response == 200) { - success = true; - if (internet) { - s_logger - .info("Deploy successful...waiting 5 minute before SSH tests"); - Thread.sleep(300000L); // Wait 60 - // seconds so - // the windows VM - // can boot up and do a sys prep. - - s_logger.info("Begin Linux SSH test for account " + _account.get()); - reason = sshTest(_linuxIP.get(), _linuxPassword.get()); - - - if (reason == null) { - s_logger - .info("Linux SSH test successful for account " + _account.get()); - } - } - if (reason == null) { - if (internet) { - s_logger - .info("Windows SSH test successful for account " + _account.get()); - } else { - s_logger - .info("deploy test successful....now cleaning up"); - if (cleanUp) { - s_logger - .info("Waiting " - + sleepTime - + " ms before cleaning up vms"); - Thread.sleep(sleepTime); - } else { - success = true; - } - } - - if (usageIterator >= numThreads) { - int eventsAndBillingResponseCode = - executeEventsAndBilling(server, developerServer); - s_logger.info("events and usage records command finished with response code: " - + eventsAndBillingResponseCode); - usageIterator = 1; - - } - else { - s_logger.info("Skipping events and usage records for this user: usageIterator " + usageIterator+ " and number of Threads " + numThreads); - usageIterator++; - } - - if ((users == null) && (accountName == null)) { - s_logger - .info("Sending cleanup command"); - int cleanupResponseCode = executeCleanup( - server, developerServer, username); - s_logger - .info("cleanup command finished with response code: " - + cleanupResponseCode); - success = (cleanupResponseCode == 200); - } else { - s_logger - .info("Sending stop DomR / destroy VM command"); - int stopResponseCode = executeStop( - server, developerServer, - username); - s_logger - .info("stop(destroy) command finished with response code: " - + stopResponseCode); - success = (stopResponseCode == 200); - } - - } else { - // Just stop but don't destroy the - // VMs/Routers - s_logger - .info("SSH test failed for account " + _account.get() + "with reason '" - + reason - + "', stopping VMs"); - int stopResponseCode = executeStop( - server, developerServer, - username); - s_logger - .info("stop command finished with response code: " - + stopResponseCode); - success = false; // since the SSH test - // failed, mark the - // whole test as - // failure - } - } else { - // Just stop but don't destroy the - // VMs/Routers - s_logger - .info("Deploy test failed with reason '" - + reason - + "', stopping VMs"); - int stopResponseCode = executeStop(server, - developerServer, username); - s_logger - .info("stop command finished with response code: " - + stopResponseCode); - success = false; // since the deploy test - // failed, mark the - // whole test as failure - } - - if (success) { - s_logger - .info("***** Completed test for user : " - + username - + " in " - + ((System - .currentTimeMillis() - now) / 1000L) - + " seconds"); - - } else { - s_logger - .info("##### FAILED test for user : " - + username - + " in " - + ((System - .currentTimeMillis() - now) / 1000L) - + " seconds with reason : " - + reason); - } - s_logger.info("Sleeping for " + wait + " seconds before starting next iteration"); - Thread.sleep(wait); - } catch (Exception e) { - s_logger.warn("Error in thread", e); - try { - int stopResponseCode = executeStop(server, - developerServer, username); - s_logger.info("stop response code: " - + stopResponseCode); - } catch (Exception e1) { - } - } finally { - NDC.clear(); - } - } while (repeat); - } - }).start(); - } - } catch (Exception e) { - s_logger.error(e); - } - } - - - public static Map> getMultipleValuesFromXML( - InputStream is, String[] tagNames) { - Map> returnValues = new HashMap>(); - try { - DocumentBuilder docBuilder = factory.newDocumentBuilder(); - Document doc = docBuilder.parse(is); - Element rootElement = doc.getDocumentElement(); - for (int i = 0; i < tagNames.length; i++) { - NodeList targetNodes = rootElement - .getElementsByTagName(tagNames[i]); - if (targetNodes.getLength() <= 0) { - s_logger.error("no " + tagNames[i] - + " tag in XML response...returning null"); - } else { - List valueList = new ArrayList(); - for (int j = 0; j < targetNodes.getLength(); j++) { - Node node = targetNodes.item(j); - valueList.add(node.getTextContent()); - } - returnValues.put(tagNames[i], valueList); - } - } - } catch (Exception ex) { - s_logger.error(ex); - } - return returnValues; - } - - public static Map getSingleValueFromXML(InputStream is, - String[] tagNames) { - Map returnValues = new HashMap(); - try { - DocumentBuilder docBuilder = factory.newDocumentBuilder(); - Document doc = docBuilder.parse(is); - Element rootElement = doc.getDocumentElement(); - - for (int i = 0; i < tagNames.length; i++) { - NodeList targetNodes = rootElement - .getElementsByTagName(tagNames[i]); - if (targetNodes.getLength() <= 0) { - s_logger.error("no " + tagNames[i] - + " tag in XML response...returning null"); - } else { - returnValues.put(tagNames[i], targetNodes.item(0) - .getTextContent()); - } - } - } catch (Exception ex) { - s_logger.error("error processing XML", ex); - } - return returnValues; - } - - public static Map getSingleValueFromXML(Element rootElement, - String[] tagNames) { - Map returnValues = new HashMap(); - if (rootElement == null) { - s_logger.error("Root element is null, can't get single value from xml"); - return null; - } - try { - for (int i = 0; i < tagNames.length; i++) { - NodeList targetNodes = rootElement - .getElementsByTagName(tagNames[i]); - if (targetNodes.getLength() <= 0) { - s_logger.error("no " + tagNames[i] - + " tag in XML response...returning null"); - } else { - returnValues.put(tagNames[i], targetNodes.item(0) - .getTextContent()); - } - } - } catch (Exception ex) { - s_logger.error("error processing XML", ex); - } - return returnValues; - } - - - private static List getNonSourceNatIPs(InputStream is) { - List returnValues = new ArrayList(); - try { - DocumentBuilder docBuilder = factory.newDocumentBuilder(); - Document doc = docBuilder.parse(is); - Element rootElement = doc.getDocumentElement(); - NodeList allocatedIpAddrNodes = rootElement - .getElementsByTagName("publicipaddress"); - for (int i = 0; i < allocatedIpAddrNodes.getLength(); i++) { - Node allocatedIpAddrNode = allocatedIpAddrNodes.item(i); - NodeList childNodes = allocatedIpAddrNode.getChildNodes(); - String ipAddress = null; - boolean isSourceNat = true; // assume it's source nat until we - // find otherwise - for (int j = 0; j < childNodes.getLength(); j++) { - Node n = childNodes.item(j); - if ("ipaddress".equals(n.getNodeName())) { - ipAddress = n.getTextContent(); - } else if ("issourcenat".equals(n.getNodeName())) { - isSourceNat = Boolean.parseBoolean(n.getTextContent()); - } - } - if ((ipAddress != null) && !isSourceNat) { - returnValues.add(ipAddress); - } - } - } catch (Exception ex) { - s_logger.error(ex); - } - return returnValues; - } - - private static List getSourceNatIPs(InputStream is) { - List returnValues = new ArrayList(); - try { - DocumentBuilder docBuilder = factory.newDocumentBuilder(); - Document doc = docBuilder.parse(is); - Element rootElement = doc.getDocumentElement(); - NodeList allocatedIpAddrNodes = rootElement - .getElementsByTagName("publicipaddress"); - for (int i = 0; i < allocatedIpAddrNodes.getLength(); i++) { - Node allocatedIpAddrNode = allocatedIpAddrNodes.item(i); - NodeList childNodes = allocatedIpAddrNode.getChildNodes(); - String ipAddress = null; - boolean isSourceNat = false; // assume it's *not* source nat until we find otherwise - for (int j = 0; j < childNodes.getLength(); j++) { - Node n = childNodes.item(j); - if ("ipaddress".equals(n.getNodeName())) { - ipAddress = n.getTextContent(); - } else if ("issourcenat".equals(n.getNodeName())) { - isSourceNat = Boolean.parseBoolean(n.getTextContent()); - } - } - if ((ipAddress != null) && isSourceNat) { - returnValues.add(ipAddress); - } - } - } catch (Exception ex) { - s_logger.error(ex); - } - return returnValues; - } - - private static String executeRegistration(String server, String username, - String password) throws HttpException, IOException { - String url = server + "?command=registerUserKeys&id=" + _userId.get().toString(); - s_logger.info("registering: " + username); - String returnValue = null; - HttpClient client = new HttpClient(); - HttpMethod method = new GetMethod(url); - int responseCode = client.executeMethod(method); - if (responseCode == 200) { - InputStream is = method.getResponseBodyAsStream(); - Map requestKeyValues = getSingleValueFromXML(is, - new String[] { "apikey", "secretkey" }); - _apiKey.set(requestKeyValues.get("apikey")); - returnValue = requestKeyValues.get("secretkey"); - } else { - s_logger.error("registration failed with error code: " + responseCode); - } - return returnValue; - } - - private static Integer executeDeployment(String server, String developerServer, - String username) throws HttpException, IOException { - // test steps: - // - create user - // - deploy Windows VM - // - deploy Linux VM - // - associate IP address - // - create two IP forwarding rules - // - create load balancer rule - // - list IP forwarding rules - // - list load balancer rules - - // ----------------------------- - // CREATE USER - // ----------------------------- - String encodedUsername = URLEncoder.encode(username, "UTF-8"); - String encryptedPassword = createMD5Password(username); - String encodedPassword = URLEncoder.encode(encryptedPassword, "UTF-8"); - - String url = server + "?command=createUser&username=" + encodedUsername - + "&password=" + encodedPassword - + "&firstname=Test&lastname=Test&email=test@vmops.com&domainId=1&accounttype=0"; - if (accountName != null ) { - url = server + "?command=createUser&username=" + encodedUsername - + "&password=" + encodedPassword - + "&firstname=Test&lastname=Test&email=test@vmops.com&domainId=1&accounttype=0&account=" + accountName; - } - HttpClient client = new HttpClient(); - HttpMethod method = new GetMethod(url); - int responseCode = client.executeMethod(method); - long userId = -1; - if (responseCode == 200) { - InputStream is = method.getResponseBodyAsStream(); - Map userIdValues = getSingleValueFromXML(is, - new String[] { "id", "account" }); - String userIdStr = userIdValues.get("id"); - s_logger.info("created user " + username + " with id "+ userIdStr); - if (userIdStr != null) { - userId = Long.parseLong(userIdStr); - _userId.set(userId); - _account.set(userIdValues.get("account")); - if (userId == -1) { - s_logger - .error("create user (" + username + ") failed to retrieve a valid user id, aborting depolyment test"); - return -1; - } - } - } else { - s_logger.error("create user test failed for user " + username + " with error code :" + responseCode); - return responseCode; - } - - _secretKey.set(executeRegistration(server, username, username)); - - if (_secretKey.get() == null) { - s_logger - .error("FAILED to retrieve secret key during registration, skipping user: " - + username); - return -1; - } else { - s_logger.info("got secret key: " + _secretKey.get()); - s_logger.info("got api key: " + _apiKey.get()); - } - - - // --------------------------------- - // CREATE NETWORK GROUP AND ADD INGRESS RULE TO IT - // --------------------------------- - String networkAccount = null; - if (accountName != null) { - networkAccount = accountName; - } - else { - networkAccount = encodedUsername; - } - String encodedApiKey = URLEncoder.encode(_apiKey.get(), "UTF-8"); - String requestToSign = "apikey=" + encodedApiKey - + "&command=createSecurityGroup&name=" + encodedUsername; - requestToSign = requestToSign.toLowerCase(); - String signature = signRequest(requestToSign, _secretKey.get()); - String encodedSignature = URLEncoder.encode(signature, "UTF-8"); - url = developerServer + "?command=createSecurityGroup&name=" + encodedUsername + "&apikey=" + encodedApiKey - + "&signature=" + encodedSignature; - method = new GetMethod(url); - responseCode = client.executeMethod(method); - if (responseCode == 200) { - InputStream is = method.getResponseBodyAsStream(); - Map values = getSingleValueFromXML(is, - new String[] { "id" }); - - if (values.get("id") == null) { - s_logger.info("Create network rule response code: 401"); - return 401; - } - else { - s_logger.info("Create security group response code: " + responseCode); - } - } else { - s_logger.error("Create security group failed with error code: " + responseCode + ". Following URL was sent: " + url); - return responseCode; - } - - - String encodedCidr = URLEncoder.encode("192.168.1.143/32", "UTF-8"); - url = server + "?command=authorizeSecurityGroupIngress&cidrlist=" + encodedCidr + "&endport=22&" + - "securitygroupname=" + encodedUsername +"&protocol=tcp&startport=22&account=" + networkAccount + "&domainid=1"; - - method = new GetMethod(url); - responseCode = client.executeMethod(method); - if (responseCode == 200) { - InputStream input = method.getResponseBodyAsStream(); - Element el = queryAsyncJobResult(server, input); - Map values = getSingleValueFromXML(el, - new String[] { "id" }); - - if (values.get("id") == null) { - s_logger.info("Authorise security group ingress response code: 401"); - return 401; - } - else { - s_logger.info("Authorise security group ingress response code: " + responseCode); - } - } else { - s_logger.error("Authorise security group ingress failed with error code: " + responseCode + ". Following URL was sent: " + url); - return responseCode; - } - - - - // --------------------------------- - // DEPLOY LINUX VM - // --------------------------------- - { - long templateId = 2; - String encodedZoneId = URLEncoder.encode("" + zoneId, "UTF-8"); - String encodedServiceOfferingId = URLEncoder.encode("" - + serviceOfferingId, "UTF-8"); - String encodedTemplateId = URLEncoder.encode("" + templateId, - "UTF-8"); - encodedApiKey = URLEncoder.encode(_apiKey.get(), "UTF-8"); - requestToSign = "apikey=" + encodedApiKey - + "&command=deployVirtualMachine&securitygrouplist=" + encodedUsername + "&serviceofferingid=" - + encodedServiceOfferingId + "&templateid=" - + encodedTemplateId + "&zoneid=" + encodedZoneId; - requestToSign = requestToSign.toLowerCase(); - signature = signRequest(requestToSign, _secretKey.get()); - encodedSignature = URLEncoder.encode(signature, "UTF-8"); - url = developerServer + "?command=deployVirtualMachine&securitygrouplist=" + encodedUsername + "&zoneid=" + encodedZoneId + "&serviceofferingid=" - + encodedServiceOfferingId + "&templateid=" - + encodedTemplateId + "&apikey=" + encodedApiKey - + "&signature=" + encodedSignature; - - method = new GetMethod(url); - responseCode = client.executeMethod(method); - if (responseCode == 200) { - InputStream input = method.getResponseBodyAsStream(); - Element el = queryAsyncJobResult(server, input); - Map values = getSingleValueFromXML(el, - new String[] { "id", "ipaddress" }); - - if ((values.get("ipaddress") == null) || (values - .get("id") == null)) { - s_logger.info("deploy linux vm response code: 401"); - return 401; - } - else { - s_logger.info("deploy linux vm response code: " + responseCode); - long linuxVMId = Long.parseLong(values.get("id")); - s_logger.info("got linux virtual machine id: " + linuxVMId); - _linuxVmId.set(values.get("id")); - _linuxIP.set(values.get("ipaddress")); - _linuxPassword.set("rs-ccb35ea5"); - } - } else { - s_logger.error("deploy linux vm failed with error code: " + responseCode + ". Following URL was sent: " + url); - return responseCode; - } - } - - - - //Create a new volume - { - url = server + "?command=createVolume&diskofferingid=" + diskOfferingId + "&zoneid=" + zoneId + "&name=newvolume&account=" + _account.get() + "&domainid=1"; - s_logger.info("Creating volume...."); - client = new HttpClient(); - method = new GetMethod(url); - responseCode = client.executeMethod(method); - if (responseCode == 200) { - InputStream input = method.getResponseBodyAsStream(); - Element el = queryAsyncJobResult(server, input); - Map values = getSingleValueFromXML(el, - new String[] { "id" }); - - if (values.get("id") == null) { - s_logger.info("create volume response code: 401"); - return 401; - } - else { - s_logger.info("create volume response code: " + responseCode); - String volumeId = values.get("id"); - s_logger.info("got volume id: " + volumeId); - _newVolume.set(volumeId); - } - } else { - s_logger.error("create volume failed with error code: " + responseCode + ". Following URL was sent: " + url); - return responseCode; - } - } - - //attach a new volume to the vm - { - url = server + "?command=attachVolume&id=" + _newVolume.get() + "&virtualmachineid=" + _linuxVmId.get(); - s_logger.info("Attaching volume with id " + _newVolume.get() + " to the vm " + _linuxVmId.get()); - client = new HttpClient(); - method = new GetMethod(url); - responseCode = client.executeMethod(method); - s_logger.info("Attach data volume response code: " + responseCode); - if (responseCode == 200) { - InputStream input = method.getResponseBodyAsStream(); - Element el = queryAsyncJobResult(server, input); - Map values = getSingleValueFromXML(el, - new String[] { "id" }); - - if (values.get("id") == null) { - s_logger.info("Attach volume response code: 401"); - return 401; - } - else { - s_logger.info("Attach volume response code: " + responseCode); - } - } else { - s_logger.error("Attach volume failed with error code: " + responseCode + ". Following URL was sent: " + url); - return responseCode; - } - } - - //DEPLOY SECOND VM, ADD VOLUME TO IT - - // --------------------------------- - // DEPLOY another linux vm - // --------------------------------- - { - long templateId = 2; - String encodedZoneId = URLEncoder.encode("" + zoneId, "UTF-8"); - String encodedServiceOfferingId = URLEncoder.encode("" - + serviceOfferingId, "UTF-8"); - String encodedTemplateId = URLEncoder.encode("" + templateId, - "UTF-8"); - encodedApiKey = URLEncoder.encode(_apiKey.get(), "UTF-8"); - requestToSign = "apikey=" + encodedApiKey - + "&command=deployVirtualMachine&securitygrouplist=" + encodedUsername + "&serviceofferingid=" - + encodedServiceOfferingId + "&templateid=" - + encodedTemplateId + "&zoneid=" + encodedZoneId; - requestToSign = requestToSign.toLowerCase(); - signature = signRequest(requestToSign, _secretKey.get()); - encodedSignature = URLEncoder.encode(signature, "UTF-8"); - url = developerServer + "?command=deployVirtualMachine&securitygrouplist=" + encodedUsername + "&zoneid=" + encodedZoneId + "&serviceofferingid=" - + encodedServiceOfferingId + "&templateid=" - + encodedTemplateId + "&apikey=" + encodedApiKey - + "&signature=" + encodedSignature; - - method = new GetMethod(url); - responseCode = client.executeMethod(method); - if (responseCode == 200) { - InputStream input = method.getResponseBodyAsStream(); - Element el = queryAsyncJobResult(server, input); - Map values = getSingleValueFromXML(el, - new String[] { "id", "ipaddress" }); - - if ((values.get("ipaddress") == null) || (values - .get("id") == null)) { - s_logger.info("deploy linux vm response code: 401"); - return 401; - } - else { - s_logger.info("deploy linux vm response code: " + responseCode); - long linuxVMId = Long.parseLong(values.get("id")); - s_logger.info("got linux virtual machine id: " + linuxVMId); - _linuxVmId1.set(values.get("id")); - } - } else { - s_logger.error("deploy linux vm failed with error code: " + responseCode + ". Following URL was sent: " + url); - return responseCode; - } - } - - - - //Create a new volume - { - url = server + "?command=createVolume&diskofferingid=" + diskOfferingId1 + "&zoneid=" + zoneId + "&name=newvolume1&account=" + _account.get() + "&domainid=1"; - s_logger.info("Creating volume...."); - client = new HttpClient(); - method = new GetMethod(url); - responseCode = client.executeMethod(method); - if (responseCode == 200) { - InputStream input = method.getResponseBodyAsStream(); - Element el = queryAsyncJobResult(server, input); - Map values = getSingleValueFromXML(el, - new String[] { "id" }); - - if (values.get("id") == null) { - s_logger.info("create volume response code: 401"); - return 401; - } - else { - s_logger.info("create volume response code: " + responseCode); - String volumeId = values.get("id"); - s_logger.info("got volume id: " + volumeId); - _newVolume1.set(volumeId); - } - } else { - s_logger.error("create volume failed with error code: " + responseCode + ". Following URL was sent: " + url); - return responseCode; - } - } - - //attach a new volume to the vm - { - url = server + "?command=attachVolume&id=" + _newVolume1.get() + "&virtualmachineid=" + _linuxVmId1.get(); - s_logger.info("Attaching volume with id " + _newVolume1.get() + " to the vm " + _linuxVmId1.get()); - client = new HttpClient(); - method = new GetMethod(url); - responseCode = client.executeMethod(method); - s_logger.info("Attach data volume response code: " + responseCode); - if (responseCode == 200) { - InputStream input = method.getResponseBodyAsStream(); - Element el = queryAsyncJobResult(server, input); - Map values = getSingleValueFromXML(el, - new String[] { "id" }); - - if (values.get("id") == null) { - s_logger.info("Attach volume response code: 401"); - return 401; - } - else { - s_logger.info("Attach volume response code: " + responseCode); - } - } else { - s_logger.error("Attach volume failed with error code: " + responseCode + ". Following URL was sent: " + url); - return responseCode; - } - } - return 200; - } - - - - - private static int executeCleanup(String server, String developerServer, String username) - throws HttpException, IOException { - // test steps: - // - get user - // - delete user - - // ----------------------------- - // GET USER - // ----------------------------- - String userId = _userId.get().toString(); - String encodedUserId = URLEncoder.encode(userId, "UTF-8"); - String url = server + "?command=listUsers&id=" + encodedUserId; - s_logger.info("Cleaning up resources for user: " + userId + " with url " + url); - HttpClient client = new HttpClient(); - HttpMethod method = new GetMethod(url); - int responseCode = client.executeMethod(method); - s_logger.info("get user response code: " + responseCode); - if (responseCode == 200) { - InputStream is = method.getResponseBodyAsStream(); - Map userInfo = getSingleValueFromXML(is, - new String[] { "username", "id", "account" }); - if (!username.equals(userInfo.get("username"))) { - s_logger - .error("get user failed to retrieve requested user, aborting cleanup test" + ". Following URL was sent: " + url); - return -1; - } - - } else { - s_logger.error("get user failed with error code: " + responseCode + ". Following URL was sent: " + url); - return responseCode; - } - - // ----------------------------- - // UPDATE USER - // ----------------------------- - { - url = server + "?command=updateUser&id=" + userId - + "&firstname=delete&lastname=me"; - client = new HttpClient(); - method = new GetMethod(url); - responseCode = client.executeMethod(method); - s_logger.info("update user response code: " + responseCode); - if (responseCode == 200) { - InputStream is = method.getResponseBodyAsStream(); - Map success = getSingleValueFromXML(is, - new String[] { "success" }); - s_logger - .info("update user..success? " + success.get("success")); - } else { - s_logger.error("update user failed with error code: " + responseCode + ". Following URL was sent: " + url); - return responseCode; - } - } - - // ----------------------------- - // Execute reboot/stop/start commands for the VMs before deleting the account - made to exercise xen - // ----------------------------- - - //Reboot centos VM - String encodedApiKey = URLEncoder.encode(_apiKey.get(), "UTF-8"); - String requestToSign = "apikey=" + encodedApiKey + "&command=rebootVirtualMachine&id=" + _linuxVmId.get(); - requestToSign = requestToSign.toLowerCase(); - String signature = signRequest(requestToSign, _secretKey.get()); - String encodedSignature = URLEncoder.encode(signature, "UTF-8"); - - url = developerServer + "?command=rebootVirtualMachine&id=" + _linuxVmId.get() + "&apikey=" - + encodedApiKey + "&signature=" + encodedSignature; - client = new HttpClient(); - method = new GetMethod(url); - responseCode = client.executeMethod(method); - s_logger.info("Reboot VM response code: " - + responseCode); - if (responseCode == 200) { - InputStream input = method.getResponseBodyAsStream(); - Element el = queryAsyncJobResult(server, input); - Map success = getSingleValueFromXML(el, - new String[] { "success" }); - s_logger.info("VM was rebooted with the status: " - + success.get("success")); - } else { - s_logger.error(" VM test failed with error code: " + responseCode + ". Following URL was sent: " + url); - return responseCode; - } - - //Stop centos VM - requestToSign = "apikey=" + encodedApiKey + "&command=stopVirtualMachine&id=" + _linuxVmId.get(); - requestToSign = requestToSign.toLowerCase(); - signature = signRequest(requestToSign, _secretKey.get()); - encodedSignature = URLEncoder.encode(signature, "UTF-8"); - - url = developerServer + "?command=stopVirtualMachine&id=" + _linuxVmId.get() + "&apikey=" - + encodedApiKey + "&signature=" + encodedSignature; - client = new HttpClient(); - method = new GetMethod(url); - responseCode = client.executeMethod(method); - s_logger.info("Stop VM response code: " - + responseCode); - if (responseCode == 200) { - InputStream input = method.getResponseBodyAsStream(); - Element el = queryAsyncJobResult(server, input); - Map success = getSingleValueFromXML(el, - new String[] { "success" }); - s_logger.info("VM was stopped with the status: " - + success.get("success")); - } else { - s_logger.error("Stop VM test failed with error code: " + responseCode + ". Following URL was sent: " + url); - return responseCode; - } - - //Start centos VM - requestToSign = "apikey=" + encodedApiKey + "&command=startVirtualMachine&id=" + _linuxVmId.get(); - requestToSign = requestToSign.toLowerCase(); - signature = signRequest(requestToSign, _secretKey.get()); - encodedSignature = URLEncoder.encode(signature, "UTF-8"); - - url = developerServer + "?command=startVirtualMachine&id=" + _linuxVmId.get() + "&apikey=" - + encodedApiKey + "&signature=" + encodedSignature; - client = new HttpClient(); - method = new GetMethod(url); - responseCode = client.executeMethod(method); - s_logger.info("Start VM response code: " - + responseCode); - - if (responseCode == 200) { - InputStream input = method.getResponseBodyAsStream(); - Element el = queryAsyncJobResult(server, input); - Map success = getSingleValueFromXML(el, - new String[] { "id" }); - - if (success.get("id") == null) { - s_logger.info("Start linux vm response code: 401"); - return 401; - } - else { - s_logger.info("Start vm response code: " + responseCode); - } - - s_logger.info("VM was started with the status: " - + success.get("success")); - } else { - s_logger.error("Start VM test failed with error code: " + responseCode + ". Following URL was sent: " + url); - return responseCode; - } - -//// // ----------------------------- -//// // DISABLE USER -//// // ----------------------------- -// { -// url = server + "?command=disableUser&id=" + userId; -// client = new HttpClient(); -// method = new GetMethod(url); -// responseCode = client.executeMethod(method); -// s_logger.info("disable user response code: " + responseCode); -// if (responseCode == 200) { -// InputStream input = method.getResponseBodyAsStream(); -// Element el = queryAsyncJobResult(server, input); -// s_logger -// .info("Disabled user successfully"); -// } else { -// s_logger.error("disable user failed with error code: " + responseCode + ". Following URL was sent: " + url); -// return responseCode; -// } -// } - - // ----------------------------- - // DELETE USER - // ----------------------------- - { - url = server + "?command=deleteUser&id=" + userId; - client = new HttpClient(); - method = new GetMethod(url); - responseCode = client.executeMethod(method); - s_logger.info("delete user response code: " + responseCode); - if (responseCode == 200) { - InputStream input = method.getResponseBodyAsStream(); - Element el = queryAsyncJobResult(server, input); - s_logger - .info("Deleted user successfully"); - } else { - s_logger.error("delete user failed with error code: " + responseCode + ". Following URL was sent: " + url); - return responseCode; - } - } - return responseCode; - } - - private static int executeEventsAndBilling(String server, String developerServer) - throws HttpException, IOException { - // test steps: - // - get all the events in the system for all users in the system - // - generate all the usage records in the system - // - get all the usage records in the system - - // ----------------------------- - // GET EVENTS - // ----------------------------- - String url =server+"?command=listEvents&page=1&account=" + _account.get(); - - s_logger.info("Getting events for the account " + _account.get()); - HttpClient client = new HttpClient(); - HttpMethod method = new GetMethod(url); - int responseCode = client.executeMethod(method); - s_logger.info("get events response code: " + responseCode); - if (responseCode == 200) { - InputStream is = method.getResponseBodyAsStream(); - Map> eventDescriptions = getMultipleValuesFromXML( - is, new String[] { "description" }); - List descriptionText = eventDescriptions.get("description"); - if (descriptionText == null) { - s_logger.info("no events retrieved..."); - } else { - for (String text : descriptionText) { - s_logger.info("event: " + text); - } - } - } else { - s_logger.error("list events failed with error code: " + responseCode + ". Following URL was sent: " + url); - - return responseCode; - } - return responseCode; - } - - - private static int executeStop(String server, String developerServer, - String username) throws HttpException, IOException { - // test steps: - // - get userId for the given username - // - list virtual machines for the user - // - stop all virtual machines - // - get ip addresses for the user - // - release ip addresses - - // ----------------------------- - // GET USER - // ----------------------------- - String userId = _userId.get().toString(); - String encodedUserId = URLEncoder.encode(userId, "UTF-8"); - - String url = server + "?command=listUsers&id=" + encodedUserId; - s_logger.info("Stopping resources for user: " + username); - HttpClient client = new HttpClient(); - HttpMethod method = new GetMethod(url); - int responseCode = client.executeMethod(method); - s_logger.info("get user response code: " + responseCode); - if (responseCode == 200) { - InputStream is = method.getResponseBodyAsStream(); - Map userIdValues = getSingleValueFromXML(is, - new String[] { "id" }); - String userIdStr = userIdValues.get("id"); - if (userIdStr != null) { - userId = userIdStr; - if (userId == null) { - s_logger - .error("get user failed to retrieve a valid user id, aborting depolyment test" + ". Following URL was sent: " + url); - return -1; - } - } - } else { - s_logger.error("get user failed with error code: " + responseCode + ". Following URL was sent: " + url); - return responseCode; - } - - { - // ---------------------------------- - // LIST VIRTUAL MACHINES - // ---------------------------------- - String encodedApiKey = URLEncoder.encode(_apiKey.get(), "UTF-8"); - String requestToSign = "apikey=" + encodedApiKey - + "&command=listVirtualMachines"; - requestToSign = requestToSign.toLowerCase(); - String signature = signRequest(requestToSign, _secretKey.get()); - String encodedSignature = URLEncoder.encode(signature, "UTF-8"); - - url = developerServer + "?command=listVirtualMachines&apikey=" + encodedApiKey + "&signature=" - + encodedSignature; - - s_logger.info("Listing all virtual machines for the user with url " + url); - String[] vmIds = null; - client = new HttpClient(); - method = new GetMethod(url); - responseCode = client.executeMethod(method); - s_logger.info("list virtual machines response code: " - + responseCode); - if (responseCode == 200) { - InputStream is = method.getResponseBodyAsStream(); - Map> vmIdValues = getMultipleValuesFromXML( - is, new String[] { "id" }); - if (vmIdValues.containsKey("id")) { - List vmIdList = vmIdValues.get("id"); - if (vmIdList != null) { - vmIds = new String[vmIdList.size()]; - vmIdList.toArray(vmIds); - String vmIdLogStr = ""; - if ((vmIds != null) && (vmIds.length > 0)) { - vmIdLogStr = vmIds[0]; - for (int i = 1; i < vmIds.length; i++) { - vmIdLogStr = vmIdLogStr + "," + vmIds[i]; - } - } - s_logger.info("got virtual machine ids: " + vmIdLogStr); - } - } - - - } else { - s_logger.error("list virtual machines test failed with error code: " + responseCode + ". Following URL was sent: " + url); - return responseCode; - } - - - // ---------------------------------- - // STOP/DESTROY VIRTUAL MACHINES - // ---------------------------------- - if (vmIds != null) { - for (String vmId : vmIds) { - requestToSign = "apikey=" + encodedApiKey + "&command=stopVirtualMachine&id=" + vmId; - requestToSign = requestToSign.toLowerCase(); - signature = signRequest(requestToSign, _secretKey.get()); - encodedSignature = URLEncoder.encode(signature, "UTF-8"); - - url = developerServer + "?command=stopVirtualMachine&id=" + vmId + "&apikey=" - + encodedApiKey + "&signature=" + encodedSignature; - client = new HttpClient(); - method = new GetMethod(url); - responseCode = client.executeMethod(method); - s_logger.info("StopVirtualMachine" + " [" + vmId + "] response code: " - + responseCode); - if (responseCode == 200) { - InputStream input = method.getResponseBodyAsStream(); - Element el = queryAsyncJobResult(server, input); - Map success = getSingleValueFromXML(el, - new String[] { "success" }); - s_logger.info("StopVirtualMachine..success? " - + success.get("success")); - } else { - s_logger.error("Stop virtual machine test failed with error code: " + responseCode + ". Following URL was sent: " + url); - return responseCode; - } - } - } - -// { -// url = server + "?command=deleteUser&id=" + userId; -// client = new HttpClient(); -// method = new GetMethod(url); -// responseCode = client.executeMethod(method); -// s_logger.info("delete user response code: " + responseCode); -// if (responseCode == 200) { -// InputStream input = method.getResponseBodyAsStream(); -// Element el = queryAsyncJobResult(server, input); -// s_logger -// .info("Deleted user successfully"); -// } else { -// s_logger.error("delete user failed with error code: " + responseCode + ". Following URL was sent: " + url); -// return responseCode; -// } -// } - - - } - - _linuxIP.set(""); - _linuxVmId.set(""); - _linuxPassword.set(""); - _windowsIP.set(""); - _secretKey.set(""); - _apiKey.set(""); - _userId.set(Long.parseLong("0")); - _account.set(""); - _domainRouterId.set(""); - return responseCode; - } - - public static String signRequest(String request, String key) { - try { - Mac mac = Mac.getInstance("HmacSHA1"); - SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), - "HmacSHA1"); - mac.init(keySpec); - mac.update(request.getBytes()); - byte[] encryptedBytes = mac.doFinal(); - return Base64.encodeBytes(encryptedBytes); - } catch (Exception ex) { - s_logger.error("unable to sign request", ex); - } - return null; - } - - private static String sshWinTest(String host) { - if (host == null) { - s_logger - .info("Did not receive a host back from test, ignoring win ssh test"); - return null; - } - - // We will retry 5 times before quitting - int retry = 1; - - while (true) { - try { - if (retry > 0) { - s_logger.info("Retry attempt : " + retry - + " ...sleeping 300 seconds before next attempt. Account is " + _account.get()); - Thread.sleep(300000); - } - - s_logger.info("Attempting to SSH into windows host " + host - + " with retry attempt: " + retry + " for account " + _account.get()); - - Connection conn = new Connection(host); - conn.connect(null, 60000, 60000); - - s_logger.info("User " + _account.get() + " ssHed successfully into windows host " + host); - boolean success = false; - boolean isAuthenticated = conn.authenticateWithPassword( - "Administrator", "password"); - if (isAuthenticated == false) { - return "Authentication failed"; - } - else { - s_logger.info("Authentication is successfull"); - } - - try { - SCPClient scp = new SCPClient(conn); - scp.put("wget.exe", "wget.exe", "C:\\Users\\Administrator", "0777"); - s_logger.info("Successfully put wget.exe file"); - } catch (Exception ex) { - s_logger.error("Unable to put wget.exe " + ex); - } - - if (conn == null ){ - s_logger.error("Connection is null"); - } - Session sess = conn.openSession(); - - s_logger.info("User + " + _account.get() + " executing : wget http://192.168.1.250/dump.bin"); - sess - .execCommand("wget http://192.168.1.250/dump.bin && dir dump.bin"); - - InputStream stdout = sess.getStdout(); - InputStream stderr = sess.getStderr(); - - byte[] buffer = new byte[8192]; - while (true) { - if ((stdout.available() == 0) && (stderr.available() == 0)) { - int conditions = sess.waitForCondition( - ChannelCondition.STDOUT_DATA - | ChannelCondition.STDERR_DATA - | ChannelCondition.EOF, 120000); - - if ((conditions & ChannelCondition.TIMEOUT) != 0) { - s_logger - .info("Timeout while waiting for data from peer."); - return null; - } - - if ((conditions & ChannelCondition.EOF) != 0) { - if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) == 0) { - break; - } - } - } - - while (stdout.available() > 0) { - success = true; - int len = stdout.read(buffer); - if (len > 0) // this check is somewhat paranoid - s_logger.info(new String(buffer, 0, len)); - } - - while (stderr.available() > 0) { - /* int len = */stderr.read(buffer); - } - } - sess.close(); - conn.close(); - - if (success) { - Thread.sleep(120000); - return null; - } else { - retry++; - if (retry == MAX_RETRY_WIN) { - return "SSH Windows Network test fail for account " + _account.get(); - } - } - } catch (Exception e) { - s_logger.error(e); - retry++; - if (retry == MAX_RETRY_WIN) { - return "SSH Windows Network test fail with error " - + e.getMessage(); - } - } - } - } - - private static String sshTest(String host, String password) { - int i = 0; - if (host == null) { - s_logger - .info("Did not receive a host back from test, ignoring ssh test"); - return null; - } - - if (password == null){ - s_logger.info("Did not receive a password back from test, ignoring ssh test"); - return null; - } - - // We will retry 5 times before quitting - String result = null; - int retry = 0; - - while (true) { - try { - if (retry > 0) { - s_logger.info("Retry attempt : " + retry - + " ...sleeping 120 seconds before next attempt. Account is " + _account.get()); - Thread.sleep(120000); - } - - s_logger.info("Attempting to SSH into linux host " + host - + " with retry attempt: " + retry + ". Account is " + _account.get()); - - Connection conn = new Connection(host); - conn.connect(null, 60000, 60000); - - s_logger.info("User + " + _account.get() + " ssHed successfully into linux host " + host); - - boolean isAuthenticated = conn.authenticateWithPassword("root", - password); - - if (isAuthenticated == false) { - s_logger.info("Authentication failed for root with password" + password); - return "Authentication failed"; - - } - - boolean success = false; - String linuxCommand = null; - - if (i % 10 == 0) - linuxCommand = "rm -rf *; wget http://192.168.1.250/dump.bin && ls -al dump.bin"; - else - linuxCommand = "wget http://192.168.1.250/dump.bin && ls -al dump.bin"; - - Session sess = conn.openSession(); - s_logger.info("User " + _account.get() + " executing : " + linuxCommand); - sess.execCommand(linuxCommand); - - InputStream stdout = sess.getStdout(); - InputStream stderr = sess.getStderr(); - - - byte[] buffer = new byte[8192]; - while (true) { - if ((stdout.available() == 0) && (stderr.available() == 0)) { - int conditions = sess.waitForCondition( - ChannelCondition.STDOUT_DATA - | ChannelCondition.STDERR_DATA - | ChannelCondition.EOF, 120000); - - if ((conditions & ChannelCondition.TIMEOUT) != 0) { - s_logger - .info("Timeout while waiting for data from peer."); - return null; - } - - if ((conditions & ChannelCondition.EOF) != 0) { - if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) == 0) { - break; - } - } - } - - while (stdout.available() > 0) { - success = true; - int len = stdout.read(buffer); - if (len > 0) // this check is somewhat paranoid - s_logger.info(new String(buffer, 0, len)); - } - - while (stderr.available() > 0) { - /* int len = */stderr.read(buffer); - } - } - - sess.close(); - conn.close(); - - if (!success) { - retry++; - if (retry == MAX_RETRY_LINUX) { - result = "SSH Linux Network test fail"; - } - } - - return result; - } catch (Exception e) { - retry++; - s_logger.error("SSH Linux Network test fail with error"); - if (retry == MAX_RETRY_LINUX) { - return "SSH Linux Network test fail with error " - + e.getMessage(); - } - } - i++; - } - } - - public static String createMD5Password(String password) { - MessageDigest md5; - - try { - md5 = MessageDigest.getInstance("MD5"); - } catch (NoSuchAlgorithmException e) { - throw new CloudRuntimeException("Error", e); - } - - md5.reset(); - BigInteger pwInt = new BigInteger(1, md5.digest(password.getBytes())); - - // make sure our MD5 hash value is 32 digits long... - StringBuffer sb = new StringBuffer(); - String pwStr = pwInt.toString(16); - int padding = 32 - pwStr.length(); - for (int i = 0; i < padding; i++) { - sb.append('0'); - } - sb.append(pwStr); - return sb.toString(); - } - - - public static Element queryAsyncJobResult (String host, InputStream inputStream) { - Element returnBody = null; - - Map values = getSingleValueFromXML(inputStream, - new String[] { "jobid" }); - String jobId = values.get("jobid"); - - if (jobId == null) { - s_logger.error("Unable to get a jobId"); - return null; - } - - //s_logger.info("Job id is " + jobId); - String resultUrl = host + "?command=queryAsyncJobResult&jobid=" + jobId; - HttpClient client = new HttpClient(); - HttpMethod method = new GetMethod(resultUrl); - while (true) { - try { - client.executeMethod(method); - //s_logger.info("Method is executed successfully. Following url was sent " + resultUrl); - InputStream is = method.getResponseBodyAsStream(); - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = factory.newDocumentBuilder(); - Document doc = builder.parse(is); - returnBody = doc.getDocumentElement(); - doc.getDocumentElement().normalize(); - Element jobStatusTag = (Element) returnBody.getElementsByTagName("jobstatus").item(0); - String jobStatus = jobStatusTag.getTextContent(); - if(jobStatus.equals("0")) { - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - } - } else { - break; - } - - } catch (Exception ex) { - s_logger.error(ex); - } - } - return returnBody; - } - -} +package com.cloud.test.stress; + +import java.io.IOException; +import java.io.InputStream; +import java.math.BigInteger; +import java.net.URLEncoder; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Random; + +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; + +import org.apache.commons.httpclient.HttpClient; +import org.apache.commons.httpclient.HttpException; +import org.apache.commons.httpclient.HttpMethod; +import org.apache.commons.httpclient.methods.GetMethod; +import org.apache.log4j.Logger; +import org.apache.log4j.NDC; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + + +import com.cloud.utils.encoding.Base64; +import com.cloud.utils.exception.CloudRuntimeException; +import com.trilead.ssh2.ChannelCondition; +import com.trilead.ssh2.Connection; +import com.trilead.ssh2.SCPClient; +import com.trilead.ssh2.Session; + +public class StressTestDirectAttach { + private static long sleepTime = 180000L; // default 0 + private static boolean cleanUp = true; + public static final Logger s_logger = Logger + .getLogger(TestClientWithAPI.class.getName()); + private static boolean repeat = true; + private static String[] users = null; + private static boolean internet = false; + private static ThreadLocal _linuxIP = new ThreadLocal(); + private static ThreadLocal _linuxVmId = new ThreadLocal(); + private static ThreadLocal _linuxVmId1 = new ThreadLocal(); + private static ThreadLocal _linuxPassword = new ThreadLocal(); + private static ThreadLocal _windowsIP = new ThreadLocal(); + private static ThreadLocal _secretKey = new ThreadLocal(); + private static ThreadLocal _apiKey = new ThreadLocal(); + private static ThreadLocal _userId = new ThreadLocal(); + private static ThreadLocal _account = new ThreadLocal(); + private static ThreadLocal _domainRouterId = new ThreadLocal(); + private static ThreadLocal _newVolume = new ThreadLocal(); + private static ThreadLocal _newVolume1 = new ThreadLocal(); + private static DocumentBuilderFactory factory = DocumentBuilderFactory + .newInstance(); + private static int usageIterator = 1; + private static int numThreads = 1; + private static int wait = 5000; + private static String accountName = null; + private static String zoneId = "1"; + private static String serviceOfferingId = "13"; + private static String diskOfferingId="11"; + private static String diskOfferingId1="12"; + + private static final int MAX_RETRY_LINUX = 10; + private static final int MAX_RETRY_WIN = 10; + + + public static void main(String[] args) { + String host = "http://localhost"; + String port = "8092"; + String devPort = "8080"; + String apiUrl = "/client/api"; + + try { + // Parameters + List argsList = Arrays.asList(args); + Iterator iter = argsList.iterator(); + while (iter.hasNext()) { + String arg = iter.next(); + // host + if (arg.equals("-h")) { + host = "http://" + iter.next(); + } + + if (arg.equals("-p")) { + port = iter.next(); + } + if (arg.equals("-dp")) { + devPort = iter.next(); + } + + if (arg.equals("-t")) { + numThreads = Integer.parseInt(iter.next()); + } + + if (arg.equals("-s")) { + sleepTime = Long.parseLong(iter.next()); + } + if (arg.equals("-a")) { + accountName = iter.next(); + } + + if (arg.equals("-c")) { + cleanUp = Boolean.parseBoolean(iter.next()); + if (!cleanUp) + sleepTime = 0L; // no need to wait if we don't ever + // cleanup + } + + if (arg.equals("-r")) { + repeat = Boolean.parseBoolean(iter.next()); + } + + if (arg.equals("-i")) { + internet = Boolean.parseBoolean(iter.next()); + } + + if (arg.equals("-w")) { + wait = Integer.parseInt(iter.next()); + } + + if (arg.equals("-z")) { + zoneId = iter.next(); + } + + if (arg.equals("-so")) { + serviceOfferingId = iter.next(); + } + + } + + final String server = host + ":" + port + "/"; + final String developerServer = host + ":" + devPort + apiUrl; + s_logger.info("Starting test against server: " + server + " with " + + numThreads + " thread(s)"); + if (cleanUp) + s_logger.info("Clean up is enabled, each test will wait " + + sleepTime + " ms before cleaning up"); + + + + for (int i = 0; i < numThreads; i++) { + new Thread(new Runnable() { + public void run() { + do { + String username = null; + try { + long now = System.currentTimeMillis(); + Random ran = new Random(); + username = Math.abs(ran.nextInt())+ "-user"; + NDC.push(username); + + s_logger.info("Starting test for the user " + username); + int response = executeDeployment(server, + developerServer, username); + boolean success = false; + String reason = null; + + + + + if (response == 200) { + success = true; + if (internet) { + s_logger + .info("Deploy successful...waiting 5 minute before SSH tests"); + Thread.sleep(300000L); // Wait 60 + // seconds so + // the windows VM + // can boot up and do a sys prep. + + s_logger.info("Begin Linux SSH test for account " + _account.get()); + reason = sshTest(_linuxIP.get(), _linuxPassword.get()); + + + if (reason == null) { + s_logger + .info("Linux SSH test successful for account " + _account.get()); + } + } + if (reason == null) { + if (internet) { + s_logger + .info("Windows SSH test successful for account " + _account.get()); + } else { + s_logger + .info("deploy test successful....now cleaning up"); + if (cleanUp) { + s_logger + .info("Waiting " + + sleepTime + + " ms before cleaning up vms"); + Thread.sleep(sleepTime); + } else { + success = true; + } + } + + if (usageIterator >= numThreads) { + int eventsAndBillingResponseCode = + executeEventsAndBilling(server, developerServer); + s_logger.info("events and usage records command finished with response code: " + + eventsAndBillingResponseCode); + usageIterator = 1; + + } + else { + s_logger.info("Skipping events and usage records for this user: usageIterator " + usageIterator+ " and number of Threads " + numThreads); + usageIterator++; + } + + if ((users == null) && (accountName == null)) { + s_logger + .info("Sending cleanup command"); + int cleanupResponseCode = executeCleanup( + server, developerServer, username); + s_logger + .info("cleanup command finished with response code: " + + cleanupResponseCode); + success = (cleanupResponseCode == 200); + } else { + s_logger + .info("Sending stop DomR / destroy VM command"); + int stopResponseCode = executeStop( + server, developerServer, + username); + s_logger + .info("stop(destroy) command finished with response code: " + + stopResponseCode); + success = (stopResponseCode == 200); + } + + } else { + // Just stop but don't destroy the + // VMs/Routers + s_logger + .info("SSH test failed for account " + _account.get() + "with reason '" + + reason + + "', stopping VMs"); + int stopResponseCode = executeStop( + server, developerServer, + username); + s_logger + .info("stop command finished with response code: " + + stopResponseCode); + success = false; // since the SSH test + // failed, mark the + // whole test as + // failure + } + } else { + // Just stop but don't destroy the + // VMs/Routers + s_logger + .info("Deploy test failed with reason '" + + reason + + "', stopping VMs"); + int stopResponseCode = executeStop(server, + developerServer, username); + s_logger + .info("stop command finished with response code: " + + stopResponseCode); + success = false; // since the deploy test + // failed, mark the + // whole test as failure + } + + if (success) { + s_logger + .info("***** Completed test for user : " + + username + + " in " + + ((System + .currentTimeMillis() - now) / 1000L) + + " seconds"); + + } else { + s_logger + .info("##### FAILED test for user : " + + username + + " in " + + ((System + .currentTimeMillis() - now) / 1000L) + + " seconds with reason : " + + reason); + } + s_logger.info("Sleeping for " + wait + " seconds before starting next iteration"); + Thread.sleep(wait); + } catch (Exception e) { + s_logger.warn("Error in thread", e); + try { + int stopResponseCode = executeStop(server, + developerServer, username); + s_logger.info("stop response code: " + + stopResponseCode); + } catch (Exception e1) { + } + } finally { + NDC.clear(); + } + } while (repeat); + } + }).start(); + } + } catch (Exception e) { + s_logger.error(e); + } + } + + + public static Map> getMultipleValuesFromXML( + InputStream is, String[] tagNames) { + Map> returnValues = new HashMap>(); + try { + DocumentBuilder docBuilder = factory.newDocumentBuilder(); + Document doc = docBuilder.parse(is); + Element rootElement = doc.getDocumentElement(); + for (int i = 0; i < tagNames.length; i++) { + NodeList targetNodes = rootElement + .getElementsByTagName(tagNames[i]); + if (targetNodes.getLength() <= 0) { + s_logger.error("no " + tagNames[i] + + " tag in XML response...returning null"); + } else { + List valueList = new ArrayList(); + for (int j = 0; j < targetNodes.getLength(); j++) { + Node node = targetNodes.item(j); + valueList.add(node.getTextContent()); + } + returnValues.put(tagNames[i], valueList); + } + } + } catch (Exception ex) { + s_logger.error(ex); + } + return returnValues; + } + + public static Map getSingleValueFromXML(InputStream is, + String[] tagNames) { + Map returnValues = new HashMap(); + try { + DocumentBuilder docBuilder = factory.newDocumentBuilder(); + Document doc = docBuilder.parse(is); + Element rootElement = doc.getDocumentElement(); + + for (int i = 0; i < tagNames.length; i++) { + NodeList targetNodes = rootElement + .getElementsByTagName(tagNames[i]); + if (targetNodes.getLength() <= 0) { + s_logger.error("no " + tagNames[i] + + " tag in XML response...returning null"); + } else { + returnValues.put(tagNames[i], targetNodes.item(0) + .getTextContent()); + } + } + } catch (Exception ex) { + s_logger.error("error processing XML", ex); + } + return returnValues; + } + + public static Map getSingleValueFromXML(Element rootElement, + String[] tagNames) { + Map returnValues = new HashMap(); + if (rootElement == null) { + s_logger.error("Root element is null, can't get single value from xml"); + return null; + } + try { + for (int i = 0; i < tagNames.length; i++) { + NodeList targetNodes = rootElement + .getElementsByTagName(tagNames[i]); + if (targetNodes.getLength() <= 0) { + s_logger.error("no " + tagNames[i] + + " tag in XML response...returning null"); + } else { + returnValues.put(tagNames[i], targetNodes.item(0) + .getTextContent()); + } + } + } catch (Exception ex) { + s_logger.error("error processing XML", ex); + } + return returnValues; + } + + + private static List getNonSourceNatIPs(InputStream is) { + List returnValues = new ArrayList(); + try { + DocumentBuilder docBuilder = factory.newDocumentBuilder(); + Document doc = docBuilder.parse(is); + Element rootElement = doc.getDocumentElement(); + NodeList allocatedIpAddrNodes = rootElement + .getElementsByTagName("publicipaddress"); + for (int i = 0; i < allocatedIpAddrNodes.getLength(); i++) { + Node allocatedIpAddrNode = allocatedIpAddrNodes.item(i); + NodeList childNodes = allocatedIpAddrNode.getChildNodes(); + String ipAddress = null; + boolean isSourceNat = true; // assume it's source nat until we + // find otherwise + for (int j = 0; j < childNodes.getLength(); j++) { + Node n = childNodes.item(j); + if ("ipaddress".equals(n.getNodeName())) { + ipAddress = n.getTextContent(); + } else if ("issourcenat".equals(n.getNodeName())) { + isSourceNat = Boolean.parseBoolean(n.getTextContent()); + } + } + if ((ipAddress != null) && !isSourceNat) { + returnValues.add(ipAddress); + } + } + } catch (Exception ex) { + s_logger.error(ex); + } + return returnValues; + } + + private static List getSourceNatIPs(InputStream is) { + List returnValues = new ArrayList(); + try { + DocumentBuilder docBuilder = factory.newDocumentBuilder(); + Document doc = docBuilder.parse(is); + Element rootElement = doc.getDocumentElement(); + NodeList allocatedIpAddrNodes = rootElement + .getElementsByTagName("publicipaddress"); + for (int i = 0; i < allocatedIpAddrNodes.getLength(); i++) { + Node allocatedIpAddrNode = allocatedIpAddrNodes.item(i); + NodeList childNodes = allocatedIpAddrNode.getChildNodes(); + String ipAddress = null; + boolean isSourceNat = false; // assume it's *not* source nat until we find otherwise + for (int j = 0; j < childNodes.getLength(); j++) { + Node n = childNodes.item(j); + if ("ipaddress".equals(n.getNodeName())) { + ipAddress = n.getTextContent(); + } else if ("issourcenat".equals(n.getNodeName())) { + isSourceNat = Boolean.parseBoolean(n.getTextContent()); + } + } + if ((ipAddress != null) && isSourceNat) { + returnValues.add(ipAddress); + } + } + } catch (Exception ex) { + s_logger.error(ex); + } + return returnValues; + } + + private static String executeRegistration(String server, String username, + String password) throws HttpException, IOException { + String url = server + "?command=registerUserKeys&id=" + _userId.get().toString(); + s_logger.info("registering: " + username); + String returnValue = null; + HttpClient client = new HttpClient(); + HttpMethod method = new GetMethod(url); + int responseCode = client.executeMethod(method); + if (responseCode == 200) { + InputStream is = method.getResponseBodyAsStream(); + Map requestKeyValues = getSingleValueFromXML(is, + new String[] { "apikey", "secretkey" }); + _apiKey.set(requestKeyValues.get("apikey")); + returnValue = requestKeyValues.get("secretkey"); + } else { + s_logger.error("registration failed with error code: " + responseCode); + } + return returnValue; + } + + private static Integer executeDeployment(String server, String developerServer, + String username) throws HttpException, IOException { + // test steps: + // - create user + // - deploy Windows VM + // - deploy Linux VM + // - associate IP address + // - create two IP forwarding rules + // - create load balancer rule + // - list IP forwarding rules + // - list load balancer rules + + // ----------------------------- + // CREATE USER + // ----------------------------- + String encodedUsername = URLEncoder.encode(username, "UTF-8"); + String encryptedPassword = createMD5Password(username); + String encodedPassword = URLEncoder.encode(encryptedPassword, "UTF-8"); + + String url = server + "?command=createUser&username=" + encodedUsername + + "&password=" + encodedPassword + + "&firstname=Test&lastname=Test&email=test@vmops.com&domainId=1&accounttype=0"; + if (accountName != null ) { + url = server + "?command=createUser&username=" + encodedUsername + + "&password=" + encodedPassword + + "&firstname=Test&lastname=Test&email=test@vmops.com&domainId=1&accounttype=0&account=" + accountName; + } + HttpClient client = new HttpClient(); + HttpMethod method = new GetMethod(url); + int responseCode = client.executeMethod(method); + long userId = -1; + if (responseCode == 200) { + InputStream is = method.getResponseBodyAsStream(); + Map userIdValues = getSingleValueFromXML(is, + new String[] { "id", "account" }); + String userIdStr = userIdValues.get("id"); + s_logger.info("created user " + username + " with id "+ userIdStr); + if (userIdStr != null) { + userId = Long.parseLong(userIdStr); + _userId.set(userId); + _account.set(userIdValues.get("account")); + if (userId == -1) { + s_logger + .error("create user (" + username + ") failed to retrieve a valid user id, aborting depolyment test"); + return -1; + } + } + } else { + s_logger.error("create user test failed for user " + username + " with error code :" + responseCode); + return responseCode; + } + + _secretKey.set(executeRegistration(server, username, username)); + + if (_secretKey.get() == null) { + s_logger + .error("FAILED to retrieve secret key during registration, skipping user: " + + username); + return -1; + } else { + s_logger.info("got secret key: " + _secretKey.get()); + s_logger.info("got api key: " + _apiKey.get()); + } + + + // --------------------------------- + // CREATE NETWORK GROUP AND ADD INGRESS RULE TO IT + // --------------------------------- + String networkAccount = null; + if (accountName != null) { + networkAccount = accountName; + } + else { + networkAccount = encodedUsername; + } + String encodedApiKey = URLEncoder.encode(_apiKey.get(), "UTF-8"); + String requestToSign = "apikey=" + encodedApiKey + + "&command=createSecurityGroup&name=" + encodedUsername; + requestToSign = requestToSign.toLowerCase(); + String signature = signRequest(requestToSign, _secretKey.get()); + String encodedSignature = URLEncoder.encode(signature, "UTF-8"); + url = developerServer + "?command=createSecurityGroup&name=" + encodedUsername + "&apikey=" + encodedApiKey + + "&signature=" + encodedSignature; + method = new GetMethod(url); + responseCode = client.executeMethod(method); + if (responseCode == 200) { + InputStream is = method.getResponseBodyAsStream(); + Map values = getSingleValueFromXML(is, + new String[] { "id" }); + + if (values.get("id") == null) { + s_logger.info("Create network rule response code: 401"); + return 401; + } + else { + s_logger.info("Create security group response code: " + responseCode); + } + } else { + s_logger.error("Create security group failed with error code: " + responseCode + ". Following URL was sent: " + url); + return responseCode; + } + + + String encodedCidr = URLEncoder.encode("192.168.1.143/32", "UTF-8"); + url = server + "?command=authorizeSecurityGroupIngress&cidrlist=" + encodedCidr + "&endport=22&" + + "securitygroupname=" + encodedUsername +"&protocol=tcp&startport=22&account=" + networkAccount + "&domainid=1"; + + method = new GetMethod(url); + responseCode = client.executeMethod(method); + if (responseCode == 200) { + InputStream input = method.getResponseBodyAsStream(); + Element el = queryAsyncJobResult(server, input); + Map values = getSingleValueFromXML(el, + new String[] { "id" }); + + if (values.get("id") == null) { + s_logger.info("Authorise security group ingress response code: 401"); + return 401; + } + else { + s_logger.info("Authorise security group ingress response code: " + responseCode); + } + } else { + s_logger.error("Authorise security group ingress failed with error code: " + responseCode + ". Following URL was sent: " + url); + return responseCode; + } + + + + // --------------------------------- + // DEPLOY LINUX VM + // --------------------------------- + { + long templateId = 2; + String encodedZoneId = URLEncoder.encode("" + zoneId, "UTF-8"); + String encodedServiceOfferingId = URLEncoder.encode("" + + serviceOfferingId, "UTF-8"); + String encodedTemplateId = URLEncoder.encode("" + templateId, + "UTF-8"); + encodedApiKey = URLEncoder.encode(_apiKey.get(), "UTF-8"); + requestToSign = "apikey=" + encodedApiKey + + "&command=deployVirtualMachine&securitygrouplist=" + encodedUsername + "&serviceofferingid=" + + encodedServiceOfferingId + "&templateid=" + + encodedTemplateId + "&zoneid=" + encodedZoneId; + requestToSign = requestToSign.toLowerCase(); + signature = signRequest(requestToSign, _secretKey.get()); + encodedSignature = URLEncoder.encode(signature, "UTF-8"); + url = developerServer + "?command=deployVirtualMachine&securitygrouplist=" + encodedUsername + "&zoneid=" + encodedZoneId + "&serviceofferingid=" + + encodedServiceOfferingId + "&templateid=" + + encodedTemplateId + "&apikey=" + encodedApiKey + + "&signature=" + encodedSignature; + + method = new GetMethod(url); + responseCode = client.executeMethod(method); + if (responseCode == 200) { + InputStream input = method.getResponseBodyAsStream(); + Element el = queryAsyncJobResult(server, input); + Map values = getSingleValueFromXML(el, + new String[] { "id", "ipaddress" }); + + if ((values.get("ipaddress") == null) || (values + .get("id") == null)) { + s_logger.info("deploy linux vm response code: 401"); + return 401; + } + else { + s_logger.info("deploy linux vm response code: " + responseCode); + long linuxVMId = Long.parseLong(values.get("id")); + s_logger.info("got linux virtual machine id: " + linuxVMId); + _linuxVmId.set(values.get("id")); + _linuxIP.set(values.get("ipaddress")); + _linuxPassword.set("rs-ccb35ea5"); + } + } else { + s_logger.error("deploy linux vm failed with error code: " + responseCode + ". Following URL was sent: " + url); + return responseCode; + } + } + + + + //Create a new volume + { + url = server + "?command=createVolume&diskofferingid=" + diskOfferingId + "&zoneid=" + zoneId + "&name=newvolume&account=" + _account.get() + "&domainid=1"; + s_logger.info("Creating volume...."); + client = new HttpClient(); + method = new GetMethod(url); + responseCode = client.executeMethod(method); + if (responseCode == 200) { + InputStream input = method.getResponseBodyAsStream(); + Element el = queryAsyncJobResult(server, input); + Map values = getSingleValueFromXML(el, + new String[] { "id" }); + + if (values.get("id") == null) { + s_logger.info("create volume response code: 401"); + return 401; + } + else { + s_logger.info("create volume response code: " + responseCode); + String volumeId = values.get("id"); + s_logger.info("got volume id: " + volumeId); + _newVolume.set(volumeId); + } + } else { + s_logger.error("create volume failed with error code: " + responseCode + ". Following URL was sent: " + url); + return responseCode; + } + } + + //attach a new volume to the vm + { + url = server + "?command=attachVolume&id=" + _newVolume.get() + "&virtualmachineid=" + _linuxVmId.get(); + s_logger.info("Attaching volume with id " + _newVolume.get() + " to the vm " + _linuxVmId.get()); + client = new HttpClient(); + method = new GetMethod(url); + responseCode = client.executeMethod(method); + s_logger.info("Attach data volume response code: " + responseCode); + if (responseCode == 200) { + InputStream input = method.getResponseBodyAsStream(); + Element el = queryAsyncJobResult(server, input); + Map values = getSingleValueFromXML(el, + new String[] { "id" }); + + if (values.get("id") == null) { + s_logger.info("Attach volume response code: 401"); + return 401; + } + else { + s_logger.info("Attach volume response code: " + responseCode); + } + } else { + s_logger.error("Attach volume failed with error code: " + responseCode + ". Following URL was sent: " + url); + return responseCode; + } + } + + //DEPLOY SECOND VM, ADD VOLUME TO IT + + // --------------------------------- + // DEPLOY another linux vm + // --------------------------------- + { + long templateId = 2; + String encodedZoneId = URLEncoder.encode("" + zoneId, "UTF-8"); + String encodedServiceOfferingId = URLEncoder.encode("" + + serviceOfferingId, "UTF-8"); + String encodedTemplateId = URLEncoder.encode("" + templateId, + "UTF-8"); + encodedApiKey = URLEncoder.encode(_apiKey.get(), "UTF-8"); + requestToSign = "apikey=" + encodedApiKey + + "&command=deployVirtualMachine&securitygrouplist=" + encodedUsername + "&serviceofferingid=" + + encodedServiceOfferingId + "&templateid=" + + encodedTemplateId + "&zoneid=" + encodedZoneId; + requestToSign = requestToSign.toLowerCase(); + signature = signRequest(requestToSign, _secretKey.get()); + encodedSignature = URLEncoder.encode(signature, "UTF-8"); + url = developerServer + "?command=deployVirtualMachine&securitygrouplist=" + encodedUsername + "&zoneid=" + encodedZoneId + "&serviceofferingid=" + + encodedServiceOfferingId + "&templateid=" + + encodedTemplateId + "&apikey=" + encodedApiKey + + "&signature=" + encodedSignature; + + method = new GetMethod(url); + responseCode = client.executeMethod(method); + if (responseCode == 200) { + InputStream input = method.getResponseBodyAsStream(); + Element el = queryAsyncJobResult(server, input); + Map values = getSingleValueFromXML(el, + new String[] { "id", "ipaddress" }); + + if ((values.get("ipaddress") == null) || (values + .get("id") == null)) { + s_logger.info("deploy linux vm response code: 401"); + return 401; + } + else { + s_logger.info("deploy linux vm response code: " + responseCode); + long linuxVMId = Long.parseLong(values.get("id")); + s_logger.info("got linux virtual machine id: " + linuxVMId); + _linuxVmId1.set(values.get("id")); + } + } else { + s_logger.error("deploy linux vm failed with error code: " + responseCode + ". Following URL was sent: " + url); + return responseCode; + } + } + + + + //Create a new volume + { + url = server + "?command=createVolume&diskofferingid=" + diskOfferingId1 + "&zoneid=" + zoneId + "&name=newvolume1&account=" + _account.get() + "&domainid=1"; + s_logger.info("Creating volume...."); + client = new HttpClient(); + method = new GetMethod(url); + responseCode = client.executeMethod(method); + if (responseCode == 200) { + InputStream input = method.getResponseBodyAsStream(); + Element el = queryAsyncJobResult(server, input); + Map values = getSingleValueFromXML(el, + new String[] { "id" }); + + if (values.get("id") == null) { + s_logger.info("create volume response code: 401"); + return 401; + } + else { + s_logger.info("create volume response code: " + responseCode); + String volumeId = values.get("id"); + s_logger.info("got volume id: " + volumeId); + _newVolume1.set(volumeId); + } + } else { + s_logger.error("create volume failed with error code: " + responseCode + ". Following URL was sent: " + url); + return responseCode; + } + } + + //attach a new volume to the vm + { + url = server + "?command=attachVolume&id=" + _newVolume1.get() + "&virtualmachineid=" + _linuxVmId1.get(); + s_logger.info("Attaching volume with id " + _newVolume1.get() + " to the vm " + _linuxVmId1.get()); + client = new HttpClient(); + method = new GetMethod(url); + responseCode = client.executeMethod(method); + s_logger.info("Attach data volume response code: " + responseCode); + if (responseCode == 200) { + InputStream input = method.getResponseBodyAsStream(); + Element el = queryAsyncJobResult(server, input); + Map values = getSingleValueFromXML(el, + new String[] { "id" }); + + if (values.get("id") == null) { + s_logger.info("Attach volume response code: 401"); + return 401; + } + else { + s_logger.info("Attach volume response code: " + responseCode); + } + } else { + s_logger.error("Attach volume failed with error code: " + responseCode + ". Following URL was sent: " + url); + return responseCode; + } + } + return 200; + } + + + + + private static int executeCleanup(String server, String developerServer, String username) + throws HttpException, IOException { + // test steps: + // - get user + // - delete user + + // ----------------------------- + // GET USER + // ----------------------------- + String userId = _userId.get().toString(); + String encodedUserId = URLEncoder.encode(userId, "UTF-8"); + String url = server + "?command=listUsers&id=" + encodedUserId; + s_logger.info("Cleaning up resources for user: " + userId + " with url " + url); + HttpClient client = new HttpClient(); + HttpMethod method = new GetMethod(url); + int responseCode = client.executeMethod(method); + s_logger.info("get user response code: " + responseCode); + if (responseCode == 200) { + InputStream is = method.getResponseBodyAsStream(); + Map userInfo = getSingleValueFromXML(is, + new String[] { "username", "id", "account" }); + if (!username.equals(userInfo.get("username"))) { + s_logger + .error("get user failed to retrieve requested user, aborting cleanup test" + ". Following URL was sent: " + url); + return -1; + } + + } else { + s_logger.error("get user failed with error code: " + responseCode + ". Following URL was sent: " + url); + return responseCode; + } + + // ----------------------------- + // UPDATE USER + // ----------------------------- + { + url = server + "?command=updateUser&id=" + userId + + "&firstname=delete&lastname=me"; + client = new HttpClient(); + method = new GetMethod(url); + responseCode = client.executeMethod(method); + s_logger.info("update user response code: " + responseCode); + if (responseCode == 200) { + InputStream is = method.getResponseBodyAsStream(); + Map success = getSingleValueFromXML(is, + new String[] { "success" }); + s_logger + .info("update user..success? " + success.get("success")); + } else { + s_logger.error("update user failed with error code: " + responseCode + ". Following URL was sent: " + url); + return responseCode; + } + } + + // ----------------------------- + // Execute reboot/stop/start commands for the VMs before deleting the account - made to exercise xen + // ----------------------------- + + //Reboot centos VM + String encodedApiKey = URLEncoder.encode(_apiKey.get(), "UTF-8"); + String requestToSign = "apikey=" + encodedApiKey + "&command=rebootVirtualMachine&id=" + _linuxVmId.get(); + requestToSign = requestToSign.toLowerCase(); + String signature = signRequest(requestToSign, _secretKey.get()); + String encodedSignature = URLEncoder.encode(signature, "UTF-8"); + + url = developerServer + "?command=rebootVirtualMachine&id=" + _linuxVmId.get() + "&apikey=" + + encodedApiKey + "&signature=" + encodedSignature; + client = new HttpClient(); + method = new GetMethod(url); + responseCode = client.executeMethod(method); + s_logger.info("Reboot VM response code: " + + responseCode); + if (responseCode == 200) { + InputStream input = method.getResponseBodyAsStream(); + Element el = queryAsyncJobResult(server, input); + Map success = getSingleValueFromXML(el, + new String[] { "success" }); + s_logger.info("VM was rebooted with the status: " + + success.get("success")); + } else { + s_logger.error(" VM test failed with error code: " + responseCode + ". Following URL was sent: " + url); + return responseCode; + } + + //Stop centos VM + requestToSign = "apikey=" + encodedApiKey + "&command=stopVirtualMachine&id=" + _linuxVmId.get(); + requestToSign = requestToSign.toLowerCase(); + signature = signRequest(requestToSign, _secretKey.get()); + encodedSignature = URLEncoder.encode(signature, "UTF-8"); + + url = developerServer + "?command=stopVirtualMachine&id=" + _linuxVmId.get() + "&apikey=" + + encodedApiKey + "&signature=" + encodedSignature; + client = new HttpClient(); + method = new GetMethod(url); + responseCode = client.executeMethod(method); + s_logger.info("Stop VM response code: " + + responseCode); + if (responseCode == 200) { + InputStream input = method.getResponseBodyAsStream(); + Element el = queryAsyncJobResult(server, input); + Map success = getSingleValueFromXML(el, + new String[] { "success" }); + s_logger.info("VM was stopped with the status: " + + success.get("success")); + } else { + s_logger.error("Stop VM test failed with error code: " + responseCode + ". Following URL was sent: " + url); + return responseCode; + } + + //Start centos VM + requestToSign = "apikey=" + encodedApiKey + "&command=startVirtualMachine&id=" + _linuxVmId.get(); + requestToSign = requestToSign.toLowerCase(); + signature = signRequest(requestToSign, _secretKey.get()); + encodedSignature = URLEncoder.encode(signature, "UTF-8"); + + url = developerServer + "?command=startVirtualMachine&id=" + _linuxVmId.get() + "&apikey=" + + encodedApiKey + "&signature=" + encodedSignature; + client = new HttpClient(); + method = new GetMethod(url); + responseCode = client.executeMethod(method); + s_logger.info("Start VM response code: " + + responseCode); + + if (responseCode == 200) { + InputStream input = method.getResponseBodyAsStream(); + Element el = queryAsyncJobResult(server, input); + Map success = getSingleValueFromXML(el, + new String[] { "id" }); + + if (success.get("id") == null) { + s_logger.info("Start linux vm response code: 401"); + return 401; + } + else { + s_logger.info("Start vm response code: " + responseCode); + } + + s_logger.info("VM was started with the status: " + + success.get("success")); + } else { + s_logger.error("Start VM test failed with error code: " + responseCode + ". Following URL was sent: " + url); + return responseCode; + } + +//// // ----------------------------- +//// // DISABLE USER +//// // ----------------------------- +// { +// url = server + "?command=disableUser&id=" + userId; +// client = new HttpClient(); +// method = new GetMethod(url); +// responseCode = client.executeMethod(method); +// s_logger.info("disable user response code: " + responseCode); +// if (responseCode == 200) { +// InputStream input = method.getResponseBodyAsStream(); +// Element el = queryAsyncJobResult(server, input); +// s_logger +// .info("Disabled user successfully"); +// } else { +// s_logger.error("disable user failed with error code: " + responseCode + ". Following URL was sent: " + url); +// return responseCode; +// } +// } + + // ----------------------------- + // DELETE USER + // ----------------------------- + { + url = server + "?command=deleteUser&id=" + userId; + client = new HttpClient(); + method = new GetMethod(url); + responseCode = client.executeMethod(method); + s_logger.info("delete user response code: " + responseCode); + if (responseCode == 200) { + InputStream input = method.getResponseBodyAsStream(); + Element el = queryAsyncJobResult(server, input); + s_logger + .info("Deleted user successfully"); + } else { + s_logger.error("delete user failed with error code: " + responseCode + ". Following URL was sent: " + url); + return responseCode; + } + } + return responseCode; + } + + private static int executeEventsAndBilling(String server, String developerServer) + throws HttpException, IOException { + // test steps: + // - get all the events in the system for all users in the system + // - generate all the usage records in the system + // - get all the usage records in the system + + // ----------------------------- + // GET EVENTS + // ----------------------------- + String url =server+"?command=listEvents&page=1&account=" + _account.get(); + + s_logger.info("Getting events for the account " + _account.get()); + HttpClient client = new HttpClient(); + HttpMethod method = new GetMethod(url); + int responseCode = client.executeMethod(method); + s_logger.info("get events response code: " + responseCode); + if (responseCode == 200) { + InputStream is = method.getResponseBodyAsStream(); + Map> eventDescriptions = getMultipleValuesFromXML( + is, new String[] { "description" }); + List descriptionText = eventDescriptions.get("description"); + if (descriptionText == null) { + s_logger.info("no events retrieved..."); + } else { + for (String text : descriptionText) { + s_logger.info("event: " + text); + } + } + } else { + s_logger.error("list events failed with error code: " + responseCode + ". Following URL was sent: " + url); + + return responseCode; + } + return responseCode; + } + + + private static int executeStop(String server, String developerServer, + String username) throws HttpException, IOException { + // test steps: + // - get userId for the given username + // - list virtual machines for the user + // - stop all virtual machines + // - get ip addresses for the user + // - release ip addresses + + // ----------------------------- + // GET USER + // ----------------------------- + String userId = _userId.get().toString(); + String encodedUserId = URLEncoder.encode(userId, "UTF-8"); + + String url = server + "?command=listUsers&id=" + encodedUserId; + s_logger.info("Stopping resources for user: " + username); + HttpClient client = new HttpClient(); + HttpMethod method = new GetMethod(url); + int responseCode = client.executeMethod(method); + s_logger.info("get user response code: " + responseCode); + if (responseCode == 200) { + InputStream is = method.getResponseBodyAsStream(); + Map userIdValues = getSingleValueFromXML(is, + new String[] { "id" }); + String userIdStr = userIdValues.get("id"); + if (userIdStr != null) { + userId = userIdStr; + if (userId == null) { + s_logger + .error("get user failed to retrieve a valid user id, aborting depolyment test" + ". Following URL was sent: " + url); + return -1; + } + } + } else { + s_logger.error("get user failed with error code: " + responseCode + ". Following URL was sent: " + url); + return responseCode; + } + + { + // ---------------------------------- + // LIST VIRTUAL MACHINES + // ---------------------------------- + String encodedApiKey = URLEncoder.encode(_apiKey.get(), "UTF-8"); + String requestToSign = "apikey=" + encodedApiKey + + "&command=listVirtualMachines"; + requestToSign = requestToSign.toLowerCase(); + String signature = signRequest(requestToSign, _secretKey.get()); + String encodedSignature = URLEncoder.encode(signature, "UTF-8"); + + url = developerServer + "?command=listVirtualMachines&apikey=" + encodedApiKey + "&signature=" + + encodedSignature; + + s_logger.info("Listing all virtual machines for the user with url " + url); + String[] vmIds = null; + client = new HttpClient(); + method = new GetMethod(url); + responseCode = client.executeMethod(method); + s_logger.info("list virtual machines response code: " + + responseCode); + if (responseCode == 200) { + InputStream is = method.getResponseBodyAsStream(); + Map> vmIdValues = getMultipleValuesFromXML( + is, new String[] { "id" }); + if (vmIdValues.containsKey("id")) { + List vmIdList = vmIdValues.get("id"); + if (vmIdList != null) { + vmIds = new String[vmIdList.size()]; + vmIdList.toArray(vmIds); + String vmIdLogStr = ""; + if ((vmIds != null) && (vmIds.length > 0)) { + vmIdLogStr = vmIds[0]; + for (int i = 1; i < vmIds.length; i++) { + vmIdLogStr = vmIdLogStr + "," + vmIds[i]; + } + } + s_logger.info("got virtual machine ids: " + vmIdLogStr); + } + } + + + } else { + s_logger.error("list virtual machines test failed with error code: " + responseCode + ". Following URL was sent: " + url); + return responseCode; + } + + + // ---------------------------------- + // STOP/DESTROY VIRTUAL MACHINES + // ---------------------------------- + if (vmIds != null) { + for (String vmId : vmIds) { + requestToSign = "apikey=" + encodedApiKey + "&command=stopVirtualMachine&id=" + vmId; + requestToSign = requestToSign.toLowerCase(); + signature = signRequest(requestToSign, _secretKey.get()); + encodedSignature = URLEncoder.encode(signature, "UTF-8"); + + url = developerServer + "?command=stopVirtualMachine&id=" + vmId + "&apikey=" + + encodedApiKey + "&signature=" + encodedSignature; + client = new HttpClient(); + method = new GetMethod(url); + responseCode = client.executeMethod(method); + s_logger.info("StopVirtualMachine" + " [" + vmId + "] response code: " + + responseCode); + if (responseCode == 200) { + InputStream input = method.getResponseBodyAsStream(); + Element el = queryAsyncJobResult(server, input); + Map success = getSingleValueFromXML(el, + new String[] { "success" }); + s_logger.info("StopVirtualMachine..success? " + + success.get("success")); + } else { + s_logger.error("Stop virtual machine test failed with error code: " + responseCode + ". Following URL was sent: " + url); + return responseCode; + } + } + } + +// { +// url = server + "?command=deleteUser&id=" + userId; +// client = new HttpClient(); +// method = new GetMethod(url); +// responseCode = client.executeMethod(method); +// s_logger.info("delete user response code: " + responseCode); +// if (responseCode == 200) { +// InputStream input = method.getResponseBodyAsStream(); +// Element el = queryAsyncJobResult(server, input); +// s_logger +// .info("Deleted user successfully"); +// } else { +// s_logger.error("delete user failed with error code: " + responseCode + ". Following URL was sent: " + url); +// return responseCode; +// } +// } + + + } + + _linuxIP.set(""); + _linuxVmId.set(""); + _linuxPassword.set(""); + _windowsIP.set(""); + _secretKey.set(""); + _apiKey.set(""); + _userId.set(Long.parseLong("0")); + _account.set(""); + _domainRouterId.set(""); + return responseCode; + } + + public static String signRequest(String request, String key) { + try { + Mac mac = Mac.getInstance("HmacSHA1"); + SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), + "HmacSHA1"); + mac.init(keySpec); + mac.update(request.getBytes()); + byte[] encryptedBytes = mac.doFinal(); + return Base64.encodeBytes(encryptedBytes); + } catch (Exception ex) { + s_logger.error("unable to sign request", ex); + } + return null; + } + + private static String sshWinTest(String host) { + if (host == null) { + s_logger + .info("Did not receive a host back from test, ignoring win ssh test"); + return null; + } + + // We will retry 5 times before quitting + int retry = 1; + + while (true) { + try { + if (retry > 0) { + s_logger.info("Retry attempt : " + retry + + " ...sleeping 300 seconds before next attempt. Account is " + _account.get()); + Thread.sleep(300000); + } + + s_logger.info("Attempting to SSH into windows host " + host + + " with retry attempt: " + retry + " for account " + _account.get()); + + Connection conn = new Connection(host); + conn.connect(null, 60000, 60000); + + s_logger.info("User " + _account.get() + " ssHed successfully into windows host " + host); + boolean success = false; + boolean isAuthenticated = conn.authenticateWithPassword( + "Administrator", "password"); + if (isAuthenticated == false) { + return "Authentication failed"; + } + else { + s_logger.info("Authentication is successfull"); + } + + try { + SCPClient scp = new SCPClient(conn); + scp.put("wget.exe", "wget.exe", "C:\\Users\\Administrator", "0777"); + s_logger.info("Successfully put wget.exe file"); + } catch (Exception ex) { + s_logger.error("Unable to put wget.exe " + ex); + } + + if (conn == null ){ + s_logger.error("Connection is null"); + } + Session sess = conn.openSession(); + + s_logger.info("User + " + _account.get() + " executing : wget http://192.168.1.250/dump.bin"); + sess + .execCommand("wget http://192.168.1.250/dump.bin && dir dump.bin"); + + InputStream stdout = sess.getStdout(); + InputStream stderr = sess.getStderr(); + + byte[] buffer = new byte[8192]; + while (true) { + if ((stdout.available() == 0) && (stderr.available() == 0)) { + int conditions = sess.waitForCondition( + ChannelCondition.STDOUT_DATA + | ChannelCondition.STDERR_DATA + | ChannelCondition.EOF, 120000); + + if ((conditions & ChannelCondition.TIMEOUT) != 0) { + s_logger + .info("Timeout while waiting for data from peer."); + return null; + } + + if ((conditions & ChannelCondition.EOF) != 0) { + if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) == 0) { + break; + } + } + } + + while (stdout.available() > 0) { + success = true; + int len = stdout.read(buffer); + if (len > 0) // this check is somewhat paranoid + s_logger.info(new String(buffer, 0, len)); + } + + while (stderr.available() > 0) { + /* int len = */stderr.read(buffer); + } + } + sess.close(); + conn.close(); + + if (success) { + Thread.sleep(120000); + return null; + } else { + retry++; + if (retry == MAX_RETRY_WIN) { + return "SSH Windows Network test fail for account " + _account.get(); + } + } + } catch (Exception e) { + s_logger.error(e); + retry++; + if (retry == MAX_RETRY_WIN) { + return "SSH Windows Network test fail with error " + + e.getMessage(); + } + } + } + } + + private static String sshTest(String host, String password) { + int i = 0; + if (host == null) { + s_logger + .info("Did not receive a host back from test, ignoring ssh test"); + return null; + } + + if (password == null){ + s_logger.info("Did not receive a password back from test, ignoring ssh test"); + return null; + } + + // We will retry 5 times before quitting + String result = null; + int retry = 0; + + while (true) { + try { + if (retry > 0) { + s_logger.info("Retry attempt : " + retry + + " ...sleeping 120 seconds before next attempt. Account is " + _account.get()); + Thread.sleep(120000); + } + + s_logger.info("Attempting to SSH into linux host " + host + + " with retry attempt: " + retry + ". Account is " + _account.get()); + + Connection conn = new Connection(host); + conn.connect(null, 60000, 60000); + + s_logger.info("User + " + _account.get() + " ssHed successfully into linux host " + host); + + boolean isAuthenticated = conn.authenticateWithPassword("root", + password); + + if (isAuthenticated == false) { + s_logger.info("Authentication failed for root with password" + password); + return "Authentication failed"; + + } + + boolean success = false; + String linuxCommand = null; + + if (i % 10 == 0) + linuxCommand = "rm -rf *; wget http://192.168.1.250/dump.bin && ls -al dump.bin"; + else + linuxCommand = "wget http://192.168.1.250/dump.bin && ls -al dump.bin"; + + Session sess = conn.openSession(); + s_logger.info("User " + _account.get() + " executing : " + linuxCommand); + sess.execCommand(linuxCommand); + + InputStream stdout = sess.getStdout(); + InputStream stderr = sess.getStderr(); + + + byte[] buffer = new byte[8192]; + while (true) { + if ((stdout.available() == 0) && (stderr.available() == 0)) { + int conditions = sess.waitForCondition( + ChannelCondition.STDOUT_DATA + | ChannelCondition.STDERR_DATA + | ChannelCondition.EOF, 120000); + + if ((conditions & ChannelCondition.TIMEOUT) != 0) { + s_logger + .info("Timeout while waiting for data from peer."); + return null; + } + + if ((conditions & ChannelCondition.EOF) != 0) { + if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) == 0) { + break; + } + } + } + + while (stdout.available() > 0) { + success = true; + int len = stdout.read(buffer); + if (len > 0) // this check is somewhat paranoid + s_logger.info(new String(buffer, 0, len)); + } + + while (stderr.available() > 0) { + /* int len = */stderr.read(buffer); + } + } + + sess.close(); + conn.close(); + + if (!success) { + retry++; + if (retry == MAX_RETRY_LINUX) { + result = "SSH Linux Network test fail"; + } + } + + return result; + } catch (Exception e) { + retry++; + s_logger.error("SSH Linux Network test fail with error"); + if (retry == MAX_RETRY_LINUX) { + return "SSH Linux Network test fail with error " + + e.getMessage(); + } + } + i++; + } + } + + public static String createMD5Password(String password) { + MessageDigest md5; + + try { + md5 = MessageDigest.getInstance("MD5"); + } catch (NoSuchAlgorithmException e) { + throw new CloudRuntimeException("Error", e); + } + + md5.reset(); + BigInteger pwInt = new BigInteger(1, md5.digest(password.getBytes())); + + // make sure our MD5 hash value is 32 digits long... + StringBuffer sb = new StringBuffer(); + String pwStr = pwInt.toString(16); + int padding = 32 - pwStr.length(); + for (int i = 0; i < padding; i++) { + sb.append('0'); + } + sb.append(pwStr); + return sb.toString(); + } + + + public static Element queryAsyncJobResult (String host, InputStream inputStream) { + Element returnBody = null; + + Map values = getSingleValueFromXML(inputStream, + new String[] { "jobid" }); + String jobId = values.get("jobid"); + + if (jobId == null) { + s_logger.error("Unable to get a jobId"); + return null; + } + + //s_logger.info("Job id is " + jobId); + String resultUrl = host + "?command=queryAsyncJobResult&jobid=" + jobId; + HttpClient client = new HttpClient(); + HttpMethod method = new GetMethod(resultUrl); + while (true) { + try { + client.executeMethod(method); + //s_logger.info("Method is executed successfully. Following url was sent " + resultUrl); + InputStream is = method.getResponseBodyAsStream(); + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + Document doc = builder.parse(is); + returnBody = doc.getDocumentElement(); + doc.getDocumentElement().normalize(); + Element jobStatusTag = (Element) returnBody.getElementsByTagName("jobstatus").item(0); + String jobStatus = jobStatusTag.getTextContent(); + if(jobStatus.equals("0")) { + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + } + } else { + break; + } + + } catch (Exception ex) { + s_logger.error(ex); + } + } + return returnBody; + } + +} diff --git a/test/src/com/cloud/test/stress/WgetTest.java b/test/src/com/cloud/test/stress/WgetTest.java index 276fe228c8c..28e74081493 100644 --- a/test/src/com/cloud/test/stress/WgetTest.java +++ b/test/src/com/cloud/test/stress/WgetTest.java @@ -10,148 +10,148 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.test.stress; - -import java.io.InputStream; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; - -import org.apache.log4j.Logger; - -import com.trilead.ssh2.ChannelCondition; -import com.trilead.ssh2.Connection; -import com.trilead.ssh2.Session; - -public class WgetTest { - - public static int MAX_RETRY_LINUX = 1; - public static final Logger s_logger = Logger.getLogger(WgetTest.class.getName()); - public static String host = ""; - public static String password = "rs-ccb35ea5"; - - - - public static void main (String[] args) { - - // Parameters - List argsList = Arrays.asList(args); - Iterator iter = argsList.iterator(); - while (iter.hasNext()) { - String arg = iter.next(); - // host - if (arg.equals("-h")) { - host = iter.next(); - } - //password - - if (arg.equals("-p")) { - password = iter.next(); - } - - } - - int i = 0; - if (host == null || host.equals("")) { - s_logger - .info("Did not receive a host back from test, ignoring ssh test"); - System.exit(2); - } - - if (password == null){ - s_logger.info("Did not receive a password back from test, ignoring ssh test"); - System.exit(2); - } - int retry = 0; - - try { - if (retry > 0) { - s_logger.info("Retry attempt : " + retry - + " ...sleeping 120 seconds before next attempt"); - Thread.sleep(120000); - } - - s_logger.info("Attempting to SSH into linux host " + host - + " with retry attempt: " + retry); - - Connection conn = new Connection(host); - conn.connect(null, 60000, 60000); - - s_logger.info("User + ssHed successfully into linux host " + host); - - boolean isAuthenticated = conn.authenticateWithPassword("root", - password); - - if (isAuthenticated == false) { - s_logger.info("Authentication failed for root with password" + password); - System.exit(2); - } - - boolean success = false; - String linuxCommand = null; - - if (i % 10 == 0) - linuxCommand = "rm -rf *; wget http://192.168.1.250/dump.bin && ls -al dump.bin"; - else - linuxCommand = "wget http://192.168.1.250/dump.bin && ls -al dump.bin"; - - Session sess = conn.openSession(); - sess.execCommand(linuxCommand); - - InputStream stdout = sess.getStdout(); - InputStream stderr = sess.getStderr(); - - - byte[] buffer = new byte[8192]; - while (true) { - if ((stdout.available() == 0) && (stderr.available() == 0)) { - int conditions = sess.waitForCondition( - ChannelCondition.STDOUT_DATA - | ChannelCondition.STDERR_DATA - | ChannelCondition.EOF, 120000); - - if ((conditions & ChannelCondition.TIMEOUT) != 0) { - s_logger - .info("Timeout while waiting for data from peer."); - System.exit(2); - } - - if ((conditions & ChannelCondition.EOF) != 0) { - if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) == 0) { - break; - } - } - } - - while (stdout.available() > 0) { - success = true; - int len = stdout.read(buffer); - if (len > 0) // this check is somewhat paranoid - s_logger.info(new String(buffer, 0, len)); - } - - while (stderr.available() > 0) { - /* int len = */stderr.read(buffer); - } - } - - sess.close(); - conn.close(); - - if (!success) { - retry++; - if (retry == MAX_RETRY_LINUX) { - System.exit(2); - } - } - } catch (Exception e) { - retry++; - s_logger.error("SSH Linux Network test fail with error"); - if (retry == MAX_RETRY_LINUX) { - s_logger.error("Ssh test failed"); - System.exit(2); - } - } - } - -} +package com.cloud.test.stress; + +import java.io.InputStream; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; + +import org.apache.log4j.Logger; + +import com.trilead.ssh2.ChannelCondition; +import com.trilead.ssh2.Connection; +import com.trilead.ssh2.Session; + +public class WgetTest { + + public static int MAX_RETRY_LINUX = 1; + public static final Logger s_logger = Logger.getLogger(WgetTest.class.getName()); + public static String host = ""; + public static String password = "rs-ccb35ea5"; + + + + public static void main (String[] args) { + + // Parameters + List argsList = Arrays.asList(args); + Iterator iter = argsList.iterator(); + while (iter.hasNext()) { + String arg = iter.next(); + // host + if (arg.equals("-h")) { + host = iter.next(); + } + //password + + if (arg.equals("-p")) { + password = iter.next(); + } + + } + + int i = 0; + if (host == null || host.equals("")) { + s_logger + .info("Did not receive a host back from test, ignoring ssh test"); + System.exit(2); + } + + if (password == null){ + s_logger.info("Did not receive a password back from test, ignoring ssh test"); + System.exit(2); + } + int retry = 0; + + try { + if (retry > 0) { + s_logger.info("Retry attempt : " + retry + + " ...sleeping 120 seconds before next attempt"); + Thread.sleep(120000); + } + + s_logger.info("Attempting to SSH into linux host " + host + + " with retry attempt: " + retry); + + Connection conn = new Connection(host); + conn.connect(null, 60000, 60000); + + s_logger.info("User + ssHed successfully into linux host " + host); + + boolean isAuthenticated = conn.authenticateWithPassword("root", + password); + + if (isAuthenticated == false) { + s_logger.info("Authentication failed for root with password" + password); + System.exit(2); + } + + boolean success = false; + String linuxCommand = null; + + if (i % 10 == 0) + linuxCommand = "rm -rf *; wget http://192.168.1.250/dump.bin && ls -al dump.bin"; + else + linuxCommand = "wget http://192.168.1.250/dump.bin && ls -al dump.bin"; + + Session sess = conn.openSession(); + sess.execCommand(linuxCommand); + + InputStream stdout = sess.getStdout(); + InputStream stderr = sess.getStderr(); + + + byte[] buffer = new byte[8192]; + while (true) { + if ((stdout.available() == 0) && (stderr.available() == 0)) { + int conditions = sess.waitForCondition( + ChannelCondition.STDOUT_DATA + | ChannelCondition.STDERR_DATA + | ChannelCondition.EOF, 120000); + + if ((conditions & ChannelCondition.TIMEOUT) != 0) { + s_logger + .info("Timeout while waiting for data from peer."); + System.exit(2); + } + + if ((conditions & ChannelCondition.EOF) != 0) { + if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) == 0) { + break; + } + } + } + + while (stdout.available() > 0) { + success = true; + int len = stdout.read(buffer); + if (len > 0) // this check is somewhat paranoid + s_logger.info(new String(buffer, 0, len)); + } + + while (stderr.available() > 0) { + /* int len = */stderr.read(buffer); + } + } + + sess.close(); + conn.close(); + + if (!success) { + retry++; + if (retry == MAX_RETRY_LINUX) { + System.exit(2); + } + } + } catch (Exception e) { + retry++; + s_logger.error("SSH Linux Network test fail with error"); + if (retry == MAX_RETRY_LINUX) { + s_logger.error("Ssh test failed"); + System.exit(2); + } + } + } + +} diff --git a/test/src/com/cloud/test/ui/AddAndDeleteAISO.java b/test/src/com/cloud/test/ui/AddAndDeleteAISO.java index 7e6dff151fa..90634728f3c 100644 --- a/test/src/com/cloud/test/ui/AddAndDeleteAISO.java +++ b/test/src/com/cloud/test/ui/AddAndDeleteAISO.java @@ -10,104 +10,104 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.test.ui; - -import org.junit.Test; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import com.cloud.test.ui.AbstractSeleniumTestCase; -import com.thoughtworks.selenium.SeleniumException; - -public class AddAndDeleteAISO extends AbstractSeleniumTestCase { - - @Test - public void testAddAndDeleteISO() throws Exception { - try { - selenium.open("/client/"); - selenium.type("account_username", "admin"); - selenium.type("account_password", "password"); - selenium.click("loginbutton"); - Thread.sleep(3000); - assertTrue(selenium.isTextPresent("admin")); - selenium.click("//div[@id='leftmenu_templates']/div"); - selenium.click("//div[@id='leftmenu_submenu_my_iso']/div/div[2]"); - Thread.sleep(3000); - selenium.click("label"); - - selenium.type("add_iso_name", "abc"); - selenium.type("add_iso_display_text", "abc"); - String iso_url = System.getProperty("add_iso_url", "http://10.91.28.6/ISO/Fedora-11-i386-DVD.iso"); - selenium.type("add_iso_url", iso_url); - String iso_zone = System.getProperty("add_iso_zone", "All Zones"); - selenium.select("add_iso_zone", "label="+iso_zone); - String iso_os_type = System.getProperty("add_iso_os_type", "Fedora 11"); - selenium.select("add_iso_os_type", "label="+iso_os_type); - selenium.click("//div[28]/div[11]/button[1]"); - Thread.sleep(3000); - int i=1; - try - { - for(;;i++) - { - System.out.println("i= "+i); - selenium.click("//div[" +i+ "]/div/div[2]/span/span"); - } - } - catch(Exception ex) { - } - - for (int second = 0;; second++) { - if (second >= 60) fail("timeout"); - try { if (selenium.isVisible("//div[@id='after_action_info_container_on_top']")) break; } catch (Exception e) {} - Thread.sleep(10000); - } - - assertTrue(selenium.isTextPresent("Adding succeeded")); - Thread.sleep(3000); - int status=1; - while(!selenium.isTextPresent("Ready")) - { - for(int j =1;j<=i;j++) - - { - if (selenium.isTextPresent("Ready")) - { - status=0; - break; - } - selenium.click("//div["+j+"]/div/div[2]/span/span"); - } - if(status==0){ - break; - } - else - { - selenium.click("//div[@id='leftmenu_submenu_featured_iso']/div/div[2]"); - Thread.sleep(3000); - selenium.click("//div[@id='leftmenu_submenu_my_iso']/div/div[2]"); - Thread.sleep(3000); - } - - } - selenium.click("link=Delete ISO"); - selenium.click("//div[28]/div[11]/button[1]"); - for (int second = 0;; second++) { - if (second >= 60) fail("timeout"); - try { if (selenium.isVisible("after_action_info_container_on_top")) break; } catch (Exception e) {} - Thread.sleep(1000); - } - - assertTrue(selenium.isTextPresent("Delete ISO action succeeded")); - selenium.click("main_logout"); - selenium.waitForPageToLoad("30000"); - assertTrue(selenium.isTextPresent("Welcome to Management Console")); - - } catch (SeleniumException ex) { - - System.err.println(ex.getMessage()); - fail(ex.getMessage()); - - throw ex; - } - } +package com.cloud.test.ui; + +import org.junit.Test; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import com.cloud.test.ui.AbstractSeleniumTestCase; +import com.thoughtworks.selenium.SeleniumException; + +public class AddAndDeleteAISO extends AbstractSeleniumTestCase { + + @Test + public void testAddAndDeleteISO() throws Exception { + try { + selenium.open("/client/"); + selenium.type("account_username", "admin"); + selenium.type("account_password", "password"); + selenium.click("loginbutton"); + Thread.sleep(3000); + assertTrue(selenium.isTextPresent("admin")); + selenium.click("//div[@id='leftmenu_templates']/div"); + selenium.click("//div[@id='leftmenu_submenu_my_iso']/div/div[2]"); + Thread.sleep(3000); + selenium.click("label"); + + selenium.type("add_iso_name", "abc"); + selenium.type("add_iso_display_text", "abc"); + String iso_url = System.getProperty("add_iso_url", "http://10.91.28.6/ISO/Fedora-11-i386-DVD.iso"); + selenium.type("add_iso_url", iso_url); + String iso_zone = System.getProperty("add_iso_zone", "All Zones"); + selenium.select("add_iso_zone", "label="+iso_zone); + String iso_os_type = System.getProperty("add_iso_os_type", "Fedora 11"); + selenium.select("add_iso_os_type", "label="+iso_os_type); + selenium.click("//div[28]/div[11]/button[1]"); + Thread.sleep(3000); + int i=1; + try + { + for(;;i++) + { + System.out.println("i= "+i); + selenium.click("//div[" +i+ "]/div/div[2]/span/span"); + } + } + catch(Exception ex) { + } + + for (int second = 0;; second++) { + if (second >= 60) fail("timeout"); + try { if (selenium.isVisible("//div[@id='after_action_info_container_on_top']")) break; } catch (Exception e) {} + Thread.sleep(10000); + } + + assertTrue(selenium.isTextPresent("Adding succeeded")); + Thread.sleep(3000); + int status=1; + while(!selenium.isTextPresent("Ready")) + { + for(int j =1;j<=i;j++) + + { + if (selenium.isTextPresent("Ready")) + { + status=0; + break; + } + selenium.click("//div["+j+"]/div/div[2]/span/span"); + } + if(status==0){ + break; + } + else + { + selenium.click("//div[@id='leftmenu_submenu_featured_iso']/div/div[2]"); + Thread.sleep(3000); + selenium.click("//div[@id='leftmenu_submenu_my_iso']/div/div[2]"); + Thread.sleep(3000); + } + + } + selenium.click("link=Delete ISO"); + selenium.click("//div[28]/div[11]/button[1]"); + for (int second = 0;; second++) { + if (second >= 60) fail("timeout"); + try { if (selenium.isVisible("after_action_info_container_on_top")) break; } catch (Exception e) {} + Thread.sleep(1000); + } + + assertTrue(selenium.isTextPresent("Delete ISO action succeeded")); + selenium.click("main_logout"); + selenium.waitForPageToLoad("30000"); + assertTrue(selenium.isTextPresent("Welcome to Management Console")); + + } catch (SeleniumException ex) { + + System.err.println(ex.getMessage()); + fail(ex.getMessage()); + + throw ex; + } + } } \ No newline at end of file diff --git a/test/src/com/cloud/test/ui/AddAndDeleteATemplate.java b/test/src/com/cloud/test/ui/AddAndDeleteATemplate.java index d03b788cf49..7046bdef585 100644 --- a/test/src/com/cloud/test/ui/AddAndDeleteATemplate.java +++ b/test/src/com/cloud/test/ui/AddAndDeleteATemplate.java @@ -10,102 +10,102 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.test.ui; - -import org.junit.Test; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import com.cloud.test.ui.AbstractSeleniumTestCase; -import com.thoughtworks.selenium.SeleniumException; - -public class AddAndDeleteATemplate extends AbstractSeleniumTestCase { - - @Test - public void testAddAndDeleteTemplate() throws Exception { - try { - selenium.open("/client/"); - selenium.type("account_username", "admin"); - selenium.type("account_password", "password"); - selenium.click("loginbutton"); - Thread.sleep(3000); - assertTrue(selenium.isTextPresent("admin")); - selenium.click("//div[@id='leftmenu_templates']/div"); - selenium.click("//div[@id='leftmenu_submenu_my_template']/div/div[2]"); - Thread.sleep(3000); - selenium.click("label"); - selenium.type("add_template_name", "abc"); - selenium.type("add_template_display_text", "abc"); - String template_url = System.getProperty("add_template_url", "http://10.91.28.6/templates/centos53-x86_64/latest/f59f18fb-ae94-4f97-afd2-f84755767aca.vhd.bz2"); - selenium.type("add_template_url", template_url); - String template_zone = System.getProperty("add_template_zone", "All Zones"); - selenium.select("add_template_zone", "label="+template_zone); - String template_os_type = System.getProperty("add_template_os_type", "CentOS 5.3 (32-bit)"); - selenium.select("add_template_os_type", "label="+template_os_type); - selenium.click("//div[28]/div[11]/button[1]"); - Thread.sleep(3000); - int i=1; - try - { - for(;;i++) - { - System.out.println("i= "+i); - selenium.click("//div[" +i+ "]/div/div[2]/span/span"); - } - } - catch(Exception ex) { - } - - for (int second = 0;; second++) { - if (second >= 60) fail("timeout"); - try { if (selenium.isVisible("//div[@id='after_action_info_container_on_top']")) break; } catch (Exception e) {} - Thread.sleep(10000); - } - - assertTrue(selenium.isTextPresent("Adding succeeded")); - Thread.sleep(3000); - int status=1; - while(!selenium.isTextPresent("Ready")) - { - for(int j =1;j<=i;j++) - - { - if (selenium.isTextPresent("Ready")) - { - status=0; - break; - } - selenium.click("//div["+j+"]/div/div[2]/span/span"); - } - if(status==0){ - break; - } - else - { - selenium.click("//div[@id='leftmenu_submenu_featured_template']/div/div[2]"); - Thread.sleep(3000); - selenium.click("//div[@id='leftmenu_submenu_my_template']/div/div[2]"); - Thread.sleep(3000); - } - - } - selenium.click("link=Delete Template"); - selenium.click("//div[28]/div[11]/button[1]"); - for (int second = 0;; second++) { - if (second >= 60) fail("timeout"); - try { if (selenium.isVisible("after_action_info_container_on_top")) break; } catch (Exception e) {} - Thread.sleep(1000); - } - - assertTrue(selenium.isTextPresent("Delete Template action succeeded")); - selenium.click("main_logout"); - selenium.waitForPageToLoad("30000"); - assertTrue(selenium.isTextPresent("Welcome to Management Console")); - } catch (SeleniumException ex) { - - System.err.println(ex.getMessage()); - fail(ex.getMessage()); - - throw ex; - } - } +package com.cloud.test.ui; + +import org.junit.Test; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import com.cloud.test.ui.AbstractSeleniumTestCase; +import com.thoughtworks.selenium.SeleniumException; + +public class AddAndDeleteATemplate extends AbstractSeleniumTestCase { + + @Test + public void testAddAndDeleteTemplate() throws Exception { + try { + selenium.open("/client/"); + selenium.type("account_username", "admin"); + selenium.type("account_password", "password"); + selenium.click("loginbutton"); + Thread.sleep(3000); + assertTrue(selenium.isTextPresent("admin")); + selenium.click("//div[@id='leftmenu_templates']/div"); + selenium.click("//div[@id='leftmenu_submenu_my_template']/div/div[2]"); + Thread.sleep(3000); + selenium.click("label"); + selenium.type("add_template_name", "abc"); + selenium.type("add_template_display_text", "abc"); + String template_url = System.getProperty("add_template_url", "http://10.91.28.6/templates/centos53-x86_64/latest/f59f18fb-ae94-4f97-afd2-f84755767aca.vhd.bz2"); + selenium.type("add_template_url", template_url); + String template_zone = System.getProperty("add_template_zone", "All Zones"); + selenium.select("add_template_zone", "label="+template_zone); + String template_os_type = System.getProperty("add_template_os_type", "CentOS 5.3 (32-bit)"); + selenium.select("add_template_os_type", "label="+template_os_type); + selenium.click("//div[28]/div[11]/button[1]"); + Thread.sleep(3000); + int i=1; + try + { + for(;;i++) + { + System.out.println("i= "+i); + selenium.click("//div[" +i+ "]/div/div[2]/span/span"); + } + } + catch(Exception ex) { + } + + for (int second = 0;; second++) { + if (second >= 60) fail("timeout"); + try { if (selenium.isVisible("//div[@id='after_action_info_container_on_top']")) break; } catch (Exception e) {} + Thread.sleep(10000); + } + + assertTrue(selenium.isTextPresent("Adding succeeded")); + Thread.sleep(3000); + int status=1; + while(!selenium.isTextPresent("Ready")) + { + for(int j =1;j<=i;j++) + + { + if (selenium.isTextPresent("Ready")) + { + status=0; + break; + } + selenium.click("//div["+j+"]/div/div[2]/span/span"); + } + if(status==0){ + break; + } + else + { + selenium.click("//div[@id='leftmenu_submenu_featured_template']/div/div[2]"); + Thread.sleep(3000); + selenium.click("//div[@id='leftmenu_submenu_my_template']/div/div[2]"); + Thread.sleep(3000); + } + + } + selenium.click("link=Delete Template"); + selenium.click("//div[28]/div[11]/button[1]"); + for (int second = 0;; second++) { + if (second >= 60) fail("timeout"); + try { if (selenium.isVisible("after_action_info_container_on_top")) break; } catch (Exception e) {} + Thread.sleep(1000); + } + + assertTrue(selenium.isTextPresent("Delete Template action succeeded")); + selenium.click("main_logout"); + selenium.waitForPageToLoad("30000"); + assertTrue(selenium.isTextPresent("Welcome to Management Console")); + } catch (SeleniumException ex) { + + System.err.println(ex.getMessage()); + fail(ex.getMessage()); + + throw ex; + } + } } \ No newline at end of file diff --git a/test/src/com/cloud/test/utils/ConsoleProxy.java b/test/src/com/cloud/test/utils/ConsoleProxy.java index 925195edad9..cd4741c67ee 100644 --- a/test/src/com/cloud/test/utils/ConsoleProxy.java +++ b/test/src/com/cloud/test/utils/ConsoleProxy.java @@ -10,101 +10,101 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.test.utils; - -import java.io.BufferedReader; -import java.io.IOException; - -import org.apache.log4j.Logger; - +package com.cloud.test.utils; + +import java.io.BufferedReader; +import java.io.IOException; + +import org.apache.log4j.Logger; + import com.cloud.utils.script.OutputInterpreter; import com.cloud.utils.script.Script; - -public class ConsoleProxy implements Runnable { - public static String proxyIp; - private String command; - private int connectionsMade; - private long responseTime; - public static final Logger s_logger = Logger.getLogger(ConsoleProxy.class - .getClass()); - - public ConsoleProxy(String port, String sid, String host) { - this.command = "https://" + proxyIp - + ".realhostip.com:8000/getscreen?w=100&h=75&host=" + host - + "&port=" + port + "&sid=" + sid; - s_logger.info("Command for a console proxy is " + this.command); - this.connectionsMade=0; - this.responseTime=0; - } - - public int getConnectionsMade() { - return this.connectionsMade; - } - - public long getResponseTime() { - return this.responseTime; - } - - public void run() { - while (true){ - - Script myScript = new Script("wget"); - myScript.add(command); - myScript.execute(); - long begin = System.currentTimeMillis(); - wgetInt process = new wgetInt(); - String response = myScript.execute(process); - long end = process.getEnd(); - if (response!=null){ - s_logger.info("Content lenght is incorrect: "+response); - } - - long duration = (end - begin); - this.connectionsMade++; - this.responseTime=this.responseTime+duration; - try{ - Thread.sleep(1000); - }catch (InterruptedException e){ - - } - - } - } - - public class wgetInt extends OutputInterpreter { - private long end; - - public long getEnd() { - return end; - } - - public void setEnd(long end) { - this.end = end; - } - - @Override - public String interpret(BufferedReader reader) throws IOException { - // TODO Auto-generated method stub - end = System.currentTimeMillis(); - String status = null; - String line = null; - while ((line = reader.readLine()) != null) { - int index = line.indexOf("Length:"); - if (index == -1) { - continue; - } - else{ - int index1 = line.indexOf("Length: 1827"); - if (index1 == -1) { - return status; - } - else - status=line; - } - - } - return status; - } - - } -} + +public class ConsoleProxy implements Runnable { + public static String proxyIp; + private String command; + private int connectionsMade; + private long responseTime; + public static final Logger s_logger = Logger.getLogger(ConsoleProxy.class + .getClass()); + + public ConsoleProxy(String port, String sid, String host) { + this.command = "https://" + proxyIp + + ".realhostip.com:8000/getscreen?w=100&h=75&host=" + host + + "&port=" + port + "&sid=" + sid; + s_logger.info("Command for a console proxy is " + this.command); + this.connectionsMade=0; + this.responseTime=0; + } + + public int getConnectionsMade() { + return this.connectionsMade; + } + + public long getResponseTime() { + return this.responseTime; + } + + public void run() { + while (true){ + + Script myScript = new Script("wget"); + myScript.add(command); + myScript.execute(); + long begin = System.currentTimeMillis(); + wgetInt process = new wgetInt(); + String response = myScript.execute(process); + long end = process.getEnd(); + if (response!=null){ + s_logger.info("Content lenght is incorrect: "+response); + } + + long duration = (end - begin); + this.connectionsMade++; + this.responseTime=this.responseTime+duration; + try{ + Thread.sleep(1000); + }catch (InterruptedException e){ + + } + + } + } + + public class wgetInt extends OutputInterpreter { + private long end; + + public long getEnd() { + return end; + } + + public void setEnd(long end) { + this.end = end; + } + + @Override + public String interpret(BufferedReader reader) throws IOException { + // TODO Auto-generated method stub + end = System.currentTimeMillis(); + String status = null; + String line = null; + while ((line = reader.readLine()) != null) { + int index = line.indexOf("Length:"); + if (index == -1) { + continue; + } + else{ + int index1 = line.indexOf("Length: 1827"); + if (index1 == -1) { + return status; + } + else + status=line; + } + + } + return status; + } + + } +} diff --git a/test/src/com/cloud/test/utils/IpSqlGenerator.java b/test/src/com/cloud/test/utils/IpSqlGenerator.java index 31f3b311598..1a90c20b6ee 100644 --- a/test/src/com/cloud/test/utils/IpSqlGenerator.java +++ b/test/src/com/cloud/test/utils/IpSqlGenerator.java @@ -10,75 +10,75 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.test.utils; - -import java.io.DataOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.util.StringTokenizer; - -public class IpSqlGenerator { - public static void main (String[] args) { - try { - if (args.length != 5) { - System.out.println("Usage -- generate-ip.sh "); - System.out.println("Example -- generate-ip.sh public 192.168.1.1 192.168.1.255 1 1"); - System.out.println(" will generate ips ranging from public ips 192.168.1.1 to 192.168.1.255 for dc 1 and pod 1"); - return; - } - - String type = args[0]; - - StringTokenizer st = new StringTokenizer(args[1], "."); - int ipS1 = Integer.parseInt(st.nextToken()); - int ipS2 = Integer.parseInt(st.nextToken()); - int ipS3 = Integer.parseInt(st.nextToken()); - int ipS4 = Integer.parseInt(st.nextToken()); - - st = new StringTokenizer(args[2], "."); - int ipE1 = Integer.parseInt(st.nextToken()); - int ipE2 = Integer.parseInt(st.nextToken()); - int ipE3 = Integer.parseInt(st.nextToken()); - int ipE4 = Integer.parseInt(st.nextToken()); - - String dcId = args[3]; - String podId = args[4]; - - if (type.equals("private")) { - FileOutputStream fs = new FileOutputStream(new File("private-ips.sql")); - DataOutputStream out = new DataOutputStream(fs); - for (int i = ipS1; i <= ipE1; i++) { - for (int j = ipS2; j <= ipE2; j++) { - for (int k = ipS3; k <= ipE3; k++) { - for (int l = ipS4; l <= ipE4; l++) { - out.writeBytes("INSERT INTO `vmops`.`dc_ip_address_alloc` (ip_address, data_center_id, pod_id) VALUES ('" - + i + "." + j + "." + k + "." + l + "'," + dcId + "," + podId + ");\r\n"); - } - } - } - } - out.writeBytes("\r\n"); - out.flush(); - out.close(); - } else { - FileOutputStream fs = new FileOutputStream(new File("public-ips.sql")); - DataOutputStream out = new DataOutputStream(fs); - for (int i = ipS1; i <= ipE1; i++) { - for (int j = ipS2; j <= ipE2; j++) { - for (int k = ipS3; k <= ipE3; k++) { - for (int l = ipS4; l <= ipE4; l++) { - out.writeBytes("INSERT INTO `vmops`.`user_ip_address` (ip_address, data_center_id) VALUES ('" - + i + "." + j + "." + k + "." + l + "'," + dcId + ");\r\n"); - } - } - } - } - out.writeBytes("\r\n"); - out.flush(); - out.close(); - } - } catch (Exception e) { - - } - } -} +package com.cloud.test.utils; + +import java.io.DataOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.util.StringTokenizer; + +public class IpSqlGenerator { + public static void main (String[] args) { + try { + if (args.length != 5) { + System.out.println("Usage -- generate-ip.sh "); + System.out.println("Example -- generate-ip.sh public 192.168.1.1 192.168.1.255 1 1"); + System.out.println(" will generate ips ranging from public ips 192.168.1.1 to 192.168.1.255 for dc 1 and pod 1"); + return; + } + + String type = args[0]; + + StringTokenizer st = new StringTokenizer(args[1], "."); + int ipS1 = Integer.parseInt(st.nextToken()); + int ipS2 = Integer.parseInt(st.nextToken()); + int ipS3 = Integer.parseInt(st.nextToken()); + int ipS4 = Integer.parseInt(st.nextToken()); + + st = new StringTokenizer(args[2], "."); + int ipE1 = Integer.parseInt(st.nextToken()); + int ipE2 = Integer.parseInt(st.nextToken()); + int ipE3 = Integer.parseInt(st.nextToken()); + int ipE4 = Integer.parseInt(st.nextToken()); + + String dcId = args[3]; + String podId = args[4]; + + if (type.equals("private")) { + FileOutputStream fs = new FileOutputStream(new File("private-ips.sql")); + DataOutputStream out = new DataOutputStream(fs); + for (int i = ipS1; i <= ipE1; i++) { + for (int j = ipS2; j <= ipE2; j++) { + for (int k = ipS3; k <= ipE3; k++) { + for (int l = ipS4; l <= ipE4; l++) { + out.writeBytes("INSERT INTO `vmops`.`dc_ip_address_alloc` (ip_address, data_center_id, pod_id) VALUES ('" + + i + "." + j + "." + k + "." + l + "'," + dcId + "," + podId + ");\r\n"); + } + } + } + } + out.writeBytes("\r\n"); + out.flush(); + out.close(); + } else { + FileOutputStream fs = new FileOutputStream(new File("public-ips.sql")); + DataOutputStream out = new DataOutputStream(fs); + for (int i = ipS1; i <= ipE1; i++) { + for (int j = ipS2; j <= ipE2; j++) { + for (int k = ipS3; k <= ipE3; k++) { + for (int l = ipS4; l <= ipE4; l++) { + out.writeBytes("INSERT INTO `vmops`.`user_ip_address` (ip_address, data_center_id) VALUES ('" + + i + "." + j + "." + k + "." + l + "'," + dcId + ");\r\n"); + } + } + } + } + out.writeBytes("\r\n"); + out.flush(); + out.close(); + } + } catch (Exception e) { + + } + } +} diff --git a/test/src/com/cloud/test/utils/ProxyLoadTemp.java b/test/src/com/cloud/test/utils/ProxyLoadTemp.java index ff166a82de4..da72ed0ab1f 100644 --- a/test/src/com/cloud/test/utils/ProxyLoadTemp.java +++ b/test/src/com/cloud/test/utils/ProxyLoadTemp.java @@ -10,108 +10,108 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.test.utils; - -import java.io.BufferedReader; -import java.io.FileReader; -import java.util.ArrayList; - -import org.apache.log4j.Logger; - - - - -public class ProxyLoadTemp { - public static final Logger s_logger= Logger.getLogger(ProxyLoadTemp.class.getClass()); - public static int numThreads=0; - public static ArrayList proxyList = new ArrayList(); - public static long begin; - public static long end; - public static long sum=0; - - public ProxyLoadTemp(){ - } - - public static void main (String[] args){ - begin= System.currentTimeMillis(); - Runtime.getRuntime().addShutdownHook(new ShutdownThread(new ProxyLoadTemp())); - ConsoleProxy.proxyIp="172-16-1-101"; - - try - { - BufferedReader consoleInput = new BufferedReader(new FileReader("console.input")); - boolean eof = false; - s_logger.info("Started reading file"); - while (!eof){ - String line = consoleInput.readLine(); - s_logger.info("Line is "+line); - if (line == null){ - s_logger.info("Line "+numThreads+" is null"); - eof=true; - } - else{ - String[] result=null; - try - { - s_logger.info("Starting parsing line "+line); - result= parseLine(line, "[,]"); - s_logger.info("Line retrieved from the file is "+result[0]+" "+result[1]+" "+result[2]); - ConsoleProxy proxy = new ConsoleProxy(result[0], result[1], result[2]); - proxyList.add(proxy); - new Thread(proxy).start(); - numThreads++; - - } - catch (Exception ex){ - s_logger.warn(ex); - } - } - - } - }catch(Exception e){ - s_logger.warn(e); - } - - } - - public static class ShutdownThread extends Thread { - ProxyLoadTemp temp; - public ShutdownThread(ProxyLoadTemp temp) { - this.temp = temp; - } - public void run() { - s_logger.info("Program was running in "+numThreads+" threads"); - - for (int j=0; j proxyList = new ArrayList(); + public static long begin; + public static long end; + public static long sum=0; + + public ProxyLoadTemp(){ + } + + public static void main (String[] args){ + begin= System.currentTimeMillis(); + Runtime.getRuntime().addShutdownHook(new ShutdownThread(new ProxyLoadTemp())); + ConsoleProxy.proxyIp="172-16-1-101"; + + try + { + BufferedReader consoleInput = new BufferedReader(new FileReader("console.input")); + boolean eof = false; + s_logger.info("Started reading file"); + while (!eof){ + String line = consoleInput.readLine(); + s_logger.info("Line is "+line); + if (line == null){ + s_logger.info("Line "+numThreads+" is null"); + eof=true; + } + else{ + String[] result=null; + try + { + s_logger.info("Starting parsing line "+line); + result= parseLine(line, "[,]"); + s_logger.info("Line retrieved from the file is "+result[0]+" "+result[1]+" "+result[2]); + ConsoleProxy proxy = new ConsoleProxy(result[0], result[1], result[2]); + proxyList.add(proxy); + new Thread(proxy).start(); + numThreads++; + + } + catch (Exception ex){ + s_logger.warn(ex); + } + } + + } + }catch(Exception e){ + s_logger.warn(e); + } + + } + + public static class ShutdownThread extends Thread { + ProxyLoadTemp temp; + public ShutdownThread(ProxyLoadTemp temp) { + this.temp = temp; + } + public void run() { + s_logger.info("Program was running in "+numThreads+" threads"); + + for (int j=0; j argsList = Arrays.asList(args); - Iterator iter = argsList.iterator(); - while (iter.hasNext()) { - String arg = iter.next(); - if (arg.equals("-a")) { - apikey = iter.next(); - - } - if (arg.equals("-u")) { - url = iter.next(); - } - - if (arg.equals("-s")) { - secretkey = iter.next(); - } - } - - - if (url == null) { - System.out.println("Please specify url with -u option. Example: -u \"command=listZones&id=1\""); - System.exit(1); - } - - if (apikey == null) { - System.out.println("Please specify apikey with -a option"); - System.exit(1); - } - - if (secretkey == null) { - System.out.println("Please specify secretkey with -s option"); - System.exit(1); - } - - TreeMap param = new TreeMap(); - - String temp = ""; - param.put("apikey", apikey); - - StringTokenizer str1 = new StringTokenizer (url, "&"); - while(str1.hasMoreTokens()) { - String newEl = str1.nextToken(); - StringTokenizer str2 = new StringTokenizer(newEl, "="); - String name = str2.nextToken(); - String value= str2.nextToken(); - param.put(name, value); - } - - //sort url hash map by key - Set c = param.entrySet(); - Iterator it = c.iterator(); - while (it.hasNext()) { - Map.Entry me = (Map.Entry)it.next(); - String key = (String) me.getKey(); - String value = (String) me.getValue(); - try { - temp = temp + key + "=" + URLEncoder.encode(value, "UTF-8") + "&"; - } catch (Exception ex) { - System.out.println("Unable to set parameter " + value + " for the command " + param.get("command")); - } - - } - temp = temp.substring(0, temp.length()-1 ); - String requestToSign = temp.toLowerCase(); - System.out.println("After sorting: " + requestToSign); - String signature = UtilsForTest.signRequest(requestToSign, secretkey); - System.out.println("After Base64 encoding: " + signature); - String encodedSignature = ""; - try { - encodedSignature = URLEncoder.encode(signature, "UTF-8"); - } catch (Exception ex) { - System.out.println(ex); + +public class SignRequest { + public static String url; + public static String apikey; + public static String secretkey; + public static String command; + + + public static void main (String[] args) { + // Parameters + List argsList = Arrays.asList(args); + Iterator iter = argsList.iterator(); + while (iter.hasNext()) { + String arg = iter.next(); + if (arg.equals("-a")) { + apikey = iter.next(); + + } + if (arg.equals("-u")) { + url = iter.next(); + } + + if (arg.equals("-s")) { + secretkey = iter.next(); + } } - System.out.println("After UTF8 encoding: " + encodedSignature); + + + if (url == null) { + System.out.println("Please specify url with -u option. Example: -u \"command=listZones&id=1\""); + System.exit(1); + } + + if (apikey == null) { + System.out.println("Please specify apikey with -a option"); + System.exit(1); + } + + if (secretkey == null) { + System.out.println("Please specify secretkey with -s option"); + System.exit(1); + } + + TreeMap param = new TreeMap(); + + String temp = ""; + param.put("apikey", apikey); + + StringTokenizer str1 = new StringTokenizer (url, "&"); + while(str1.hasMoreTokens()) { + String newEl = str1.nextToken(); + StringTokenizer str2 = new StringTokenizer(newEl, "="); + String name = str2.nextToken(); + String value= str2.nextToken(); + param.put(name, value); + } + + //sort url hash map by key + Set c = param.entrySet(); + Iterator it = c.iterator(); + while (it.hasNext()) { + Map.Entry me = (Map.Entry)it.next(); + String key = (String) me.getKey(); + String value = (String) me.getValue(); + try { + temp = temp + key + "=" + URLEncoder.encode(value, "UTF-8") + "&"; + } catch (Exception ex) { + System.out.println("Unable to set parameter " + value + " for the command " + param.get("command")); + } + + } + temp = temp.substring(0, temp.length()-1 ); + String requestToSign = temp.toLowerCase(); + System.out.println("After sorting: " + requestToSign); + String signature = UtilsForTest.signRequest(requestToSign, secretkey); + System.out.println("After Base64 encoding: " + signature); + String encodedSignature = ""; + try { + encodedSignature = URLEncoder.encode(signature, "UTF-8"); + } catch (Exception ex) { + System.out.println(ex); + } + System.out.println("After UTF8 encoding: " + encodedSignature); String url = temp + "&signature=" + encodedSignature; - System.out.println("After sort and add signature: " + url); - - } -} + System.out.println("After sort and add signature: " + url); + + } +} diff --git a/test/src/com/cloud/test/utils/SqlDataGenerator.java b/test/src/com/cloud/test/utils/SqlDataGenerator.java index efa9b58fccb..5060cd8dc09 100644 --- a/test/src/com/cloud/test/utils/SqlDataGenerator.java +++ b/test/src/com/cloud/test/utils/SqlDataGenerator.java @@ -10,35 +10,35 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.test.utils; - -import java.io.DataOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.util.Formatter; - -public class SqlDataGenerator { - public static void main (String[] args) { - try { - FileOutputStream fs = new FileOutputStream(new File("out.txt")); - - DataOutputStream out = new DataOutputStream(fs); - - for (int i = 20; i < 171; i++) { - out.writeBytes("INSERT INTO `vmops`.`dc_ip_address_alloc` (ip_address, data_center_id, pod_id) VALUES ('192.168.2."+i+"',1,1);\r\n"); - } - out.writeBytes("\r\n"); - for (int i = 1; i < 10000; i++) { - StringBuilder imagePath = new StringBuilder(); - Formatter formatter = new Formatter(imagePath); - formatter.format("%04x", i); - out.writeBytes("INSERT INTO `vmops`.`dc_vnet_alloc` (vnet, data_center_id) VALUES ('"+imagePath.toString()+"',1);\r\n"); - } - - out.flush(); - out.close(); - } catch (Exception e) { - - } - } -} +package com.cloud.test.utils; + +import java.io.DataOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.util.Formatter; + +public class SqlDataGenerator { + public static void main (String[] args) { + try { + FileOutputStream fs = new FileOutputStream(new File("out.txt")); + + DataOutputStream out = new DataOutputStream(fs); + + for (int i = 20; i < 171; i++) { + out.writeBytes("INSERT INTO `vmops`.`dc_ip_address_alloc` (ip_address, data_center_id, pod_id) VALUES ('192.168.2."+i+"',1,1);\r\n"); + } + out.writeBytes("\r\n"); + for (int i = 1; i < 10000; i++) { + StringBuilder imagePath = new StringBuilder(); + Formatter formatter = new Formatter(imagePath); + formatter.format("%04x", i); + out.writeBytes("INSERT INTO `vmops`.`dc_vnet_alloc` (vnet, data_center_id) VALUES ('"+imagePath.toString()+"',1);\r\n"); + } + + out.flush(); + out.close(); + } catch (Exception e) { + + } + } +} diff --git a/test/src/com/cloud/test/utils/TestClient.java b/test/src/com/cloud/test/utils/TestClient.java index 2086510573a..f2ce4ef1ec8 100644 --- a/test/src/com/cloud/test/utils/TestClient.java +++ b/test/src/com/cloud/test/utils/TestClient.java @@ -10,368 +10,368 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.test.utils; - -import java.io.InputStream; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; -import java.util.Random; - -import org.apache.commons.httpclient.HttpClient; -import org.apache.commons.httpclient.HttpMethod; -import org.apache.commons.httpclient.methods.GetMethod; -import org.apache.log4j.Logger; -import org.apache.log4j.NDC; - -import com.trilead.ssh2.ChannelCondition; -import com.trilead.ssh2.Connection; -import com.trilead.ssh2.SCPClient; -import com.trilead.ssh2.Session; - -public class TestClient { - private static long sleepTime = 180000L; // default 0 - private static boolean cleanUp = true; - public static final Logger s_logger = Logger.getLogger(TestClient.class.getName()); - private static boolean repeat = true; - private static int numOfUsers = 0; - private static String[] users = null; - private static boolean internet = true; - - private static final int MAX_RETRY_LINUX = 5; - private static final int MAX_RETRY_WIN = 10; - - public static void main (String[] args) { - String host = "http://localhost"; - String port = "8080"; - String testUrl = "/client/test"; - int numThreads = 1; - - try { - // Parameters - List argsList = Arrays.asList(args); - Iterator iter = argsList.iterator(); - while (iter.hasNext()) { - String arg = iter.next(); - // host - if (arg.equals("-h")) { - host = "http://" + iter.next(); - } - - if (arg.equals("-p")) { - port = iter.next(); - } - - if (arg.equals("-t")) { - numThreads = Integer.parseInt(iter.next()); - } - - if (arg.equals("-s")) { - sleepTime = Long.parseLong(iter.next()); - } - - if (arg.equals("-c")) { - cleanUp = Boolean.parseBoolean(iter.next()); - if (!cleanUp) sleepTime = 0L; // no need to wait if we don't ever cleanup - } - - if (arg.equals("-r")) { - repeat = Boolean.parseBoolean(iter.next()); - } - - if (arg.equals("-u")) { - numOfUsers = Integer.parseInt(iter.next()); - } - - if (arg.equals("-i")) { - internet = Boolean.parseBoolean(iter.next()); - } - } - - final String server = host+":"+port+testUrl; - s_logger.info("Starting test against server: " + server + " with " + numThreads + " thread(s)"); - if (cleanUp) s_logger.info("Clean up is enabled, each test will wait " + sleepTime + " ms before cleaning up"); - - if (numOfUsers > 0) { - s_logger.info("Pre-generating users for test of size : " + numOfUsers); - users = new String[numOfUsers]; - Random ran = new Random(); - for (int i = 0; i < numOfUsers; i++) { - users[i] = Math.abs(ran.nextInt()) + "-user"; - } - } - - for (int i = 0; i < numThreads; i++) { - new Thread(new Runnable() { - public void run() { - do { - String username = null; - try { - long now = System.currentTimeMillis(); - Random ran = new Random(); - if (users != null) { - username = users[Math.abs(ran.nextInt()) % numOfUsers]; - } else { - username = Math.abs(ran.nextInt())+"-user"; - } - NDC.push(username); - - String url = server+"?email="+username+"&password="+username+"&command=deploy"; - s_logger.info("Launching test for user: " + username + " with url: " + url); - HttpClient client = new HttpClient(); - HttpMethod method = new GetMethod(url); - int responseCode = client.executeMethod(method); - boolean success = false; - String reason = null; - if (responseCode == 200) { - if (internet) { - s_logger.info("Deploy successful...waiting 5 minute before SSH tests"); - Thread.sleep(300000L); // Wait 60 seconds so the linux VM can boot up. - - s_logger.info("Begin Linux SSH test"); - reason = sshTest(method.getResponseHeader("linuxIP").getValue()); - - if (reason == null) { - s_logger.info("Linux SSH test successful"); - s_logger.info("Begin Windows SSH test"); - reason = sshWinTest(method.getResponseHeader("windowsIP").getValue()); - } - } - if (reason == null) { - if (internet) { - s_logger.info("Windows SSH test successful"); - } else { - s_logger.info("deploy test successful....now cleaning up"); - if (cleanUp) { - s_logger.info("Waiting " + sleepTime + " ms before cleaning up vms"); - Thread.sleep(sleepTime); - } else { - success = true; - } - } - if (users == null) { - s_logger.info("Sending cleanup command"); - url = server+"?email="+username+"&password="+username+"&command=cleanup"; - } else { - s_logger.info("Sending stop DomR / destroy VM command"); - url = server+"?email="+username+"&password="+username+"&command=stopDomR"; - } - method = new GetMethod(url); - responseCode = client.executeMethod(method); - if (responseCode == 200) { - success = true; - } else { - reason = method.getStatusText(); - } - } else { - // Just stop but don't destroy the VMs/Routers - s_logger.info("SSH test failed with reason '" + reason + "', stopping VMs"); - url = server+"?email="+username+"&password="+username+"&command=stop"; - responseCode = client.executeMethod(new GetMethod(url)); - } - } else { - // Just stop but don't destroy the VMs/Routers - reason = method.getStatusText(); - s_logger.info("Deploy test failed with reason '" + reason + "', stopping VMs"); - url = server+"?email="+username+"&password="+username+"&command=stop"; - client.executeMethod(new GetMethod(url)); - } - - if (success) { - s_logger.info("***** Completed test for user : " + username + " in " + ((System.currentTimeMillis() - now) / 1000L) + " seconds"); - } else { - s_logger.info("##### FAILED test for user : " + username + " in " + ((System.currentTimeMillis() - now) / 1000L) + " seconds with reason : " + reason); - } - } catch (Exception e) { - s_logger.warn("Error in thread", e); - try { - HttpClient client = new HttpClient(); - String url = server+"?email="+username+"&password="+username+"&command=stop"; - client.executeMethod(new GetMethod(url)); - } catch (Exception e1) { - } - } finally { - NDC.clear(); - } - } while (repeat); - } - }).start(); - } - } catch (Exception e) { - s_logger.error(e); - } - } - - private static String sshWinTest(String host) { - if (host == null) { - s_logger.info("Did not receive a host back from test, ignoring win ssh test"); - return null; - } - - // We will retry 5 times before quitting - int retry = 0; - - while (true) { - try { - if (retry > 0) { - s_logger.info("Retry attempt : " + retry + " ...sleeping 300 seconds before next attempt"); - Thread.sleep(300000); - } - - s_logger.info("Attempting to SSH into windows host " + host + " with retry attempt: " + retry); - - Connection conn = new Connection(host); - conn.connect(null, 60000, 60000); - - s_logger.info("SSHed successfully into windows host " + host); - boolean success = false; - boolean isAuthenticated = conn.authenticateWithPassword("vmops", "vmops"); - if (isAuthenticated == false) { - return "Authentication failed"; - } - SCPClient scp = new SCPClient(conn); - - scp.put("wget.exe", ""); - - Session sess = conn.openSession(); - s_logger.info("Executing : wget http://172.16.0.220/dump.bin"); - sess.execCommand("wget http://172.16.0.220/dump.bin && dir dump.bin"); - - InputStream stdout = sess.getStdout(); - InputStream stderr = sess.getStderr(); - - byte[] buffer = new byte[8192]; - while (true) { - if ((stdout.available() == 0) && (stderr.available() == 0)) { - int conditions = sess.waitForCondition(ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA - | ChannelCondition.EOF, 120000); - - if ((conditions & ChannelCondition.TIMEOUT) != 0) { - s_logger.info("Timeout while waiting for data from peer."); - return null; - } - - if ((conditions & ChannelCondition.EOF) != 0) { - if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) == 0) { - break; - } - } - } - - while (stdout.available() > 0) { - success = true; - int len = stdout.read(buffer); - if (len > 0) // this check is somewhat paranoid - s_logger.info(new String(buffer, 0, len)); - } - - while (stderr.available() > 0) { - int len = stderr.read(buffer); - } - } - sess.close(); - conn.close(); - - if (success) { - return null; - } else { - retry++; - if (retry == MAX_RETRY_WIN) { - return "SSH Windows Network test fail"; - } - } - } catch (Exception e) { - retry++; - if (retry == MAX_RETRY_WIN) { - return "SSH Windows Network test fail with error " + e.getMessage(); - } - } - } - } - - private static String sshTest(String host) { - if (host == null) { - s_logger.info("Did not receive a host back from test, ignoring ssh test"); - return null; - } - - // We will retry 5 times before quitting - int retry = 0; - - while (true) { - try { - if (retry > 0) { - s_logger.info("Retry attempt : " + retry + " ...sleeping 120 seconds before next attempt"); - Thread.sleep(120000); - } - - s_logger.info("Attempting to SSH into linux host " + host + " with retry attempt: " + retry); - - Connection conn = new Connection(host); - conn.connect(null, 60000, 60000); - - s_logger.info("SSHed successfully into linux host " + host); - - boolean isAuthenticated = conn.authenticateWithPassword("root", "password"); - - if (isAuthenticated == false) { - return "Authentication failed"; - } - boolean success = false; - Session sess = conn.openSession(); - s_logger.info("Executing : wget http://172.16.0.220/dump.bin"); - sess.execCommand("wget http://172.16.0.220/dump.bin && ls -al dump.bin"); - - InputStream stdout = sess.getStdout(); - InputStream stderr = sess.getStderr(); - - byte[] buffer = new byte[8192]; - while (true) { - if ((stdout.available() == 0) && (stderr.available() == 0)) { - int conditions = sess.waitForCondition(ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA - | ChannelCondition.EOF, 120000); - - if ((conditions & ChannelCondition.TIMEOUT) != 0) { - s_logger.info("Timeout while waiting for data from peer."); - return null; - } - - if ((conditions & ChannelCondition.EOF) != 0) { - if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) == 0) { - break; - } - } - } - - while (stdout.available() > 0) { - success = true; - int len = stdout.read(buffer); - if (len > 0) // this check is somewhat paranoid - s_logger.info(new String(buffer, 0, len)); - } - - while (stderr.available() > 0) { - int len = stderr.read(buffer); - } - } - - sess.close(); - conn.close(); - - if (success) { - return null; - } else { - retry++; - if (retry == MAX_RETRY_LINUX) { - return "SSH Linux Network test fail"; - } - } - } catch (Exception e) { - retry++; - if (retry == MAX_RETRY_LINUX) { - return "SSH Linux Network test fail with error " + e.getMessage(); - } - } - } - } -} +package com.cloud.test.utils; + +import java.io.InputStream; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.Random; + +import org.apache.commons.httpclient.HttpClient; +import org.apache.commons.httpclient.HttpMethod; +import org.apache.commons.httpclient.methods.GetMethod; +import org.apache.log4j.Logger; +import org.apache.log4j.NDC; + +import com.trilead.ssh2.ChannelCondition; +import com.trilead.ssh2.Connection; +import com.trilead.ssh2.SCPClient; +import com.trilead.ssh2.Session; + +public class TestClient { + private static long sleepTime = 180000L; // default 0 + private static boolean cleanUp = true; + public static final Logger s_logger = Logger.getLogger(TestClient.class.getName()); + private static boolean repeat = true; + private static int numOfUsers = 0; + private static String[] users = null; + private static boolean internet = true; + + private static final int MAX_RETRY_LINUX = 5; + private static final int MAX_RETRY_WIN = 10; + + public static void main (String[] args) { + String host = "http://localhost"; + String port = "8080"; + String testUrl = "/client/test"; + int numThreads = 1; + + try { + // Parameters + List argsList = Arrays.asList(args); + Iterator iter = argsList.iterator(); + while (iter.hasNext()) { + String arg = iter.next(); + // host + if (arg.equals("-h")) { + host = "http://" + iter.next(); + } + + if (arg.equals("-p")) { + port = iter.next(); + } + + if (arg.equals("-t")) { + numThreads = Integer.parseInt(iter.next()); + } + + if (arg.equals("-s")) { + sleepTime = Long.parseLong(iter.next()); + } + + if (arg.equals("-c")) { + cleanUp = Boolean.parseBoolean(iter.next()); + if (!cleanUp) sleepTime = 0L; // no need to wait if we don't ever cleanup + } + + if (arg.equals("-r")) { + repeat = Boolean.parseBoolean(iter.next()); + } + + if (arg.equals("-u")) { + numOfUsers = Integer.parseInt(iter.next()); + } + + if (arg.equals("-i")) { + internet = Boolean.parseBoolean(iter.next()); + } + } + + final String server = host+":"+port+testUrl; + s_logger.info("Starting test against server: " + server + " with " + numThreads + " thread(s)"); + if (cleanUp) s_logger.info("Clean up is enabled, each test will wait " + sleepTime + " ms before cleaning up"); + + if (numOfUsers > 0) { + s_logger.info("Pre-generating users for test of size : " + numOfUsers); + users = new String[numOfUsers]; + Random ran = new Random(); + for (int i = 0; i < numOfUsers; i++) { + users[i] = Math.abs(ran.nextInt()) + "-user"; + } + } + + for (int i = 0; i < numThreads; i++) { + new Thread(new Runnable() { + public void run() { + do { + String username = null; + try { + long now = System.currentTimeMillis(); + Random ran = new Random(); + if (users != null) { + username = users[Math.abs(ran.nextInt()) % numOfUsers]; + } else { + username = Math.abs(ran.nextInt())+"-user"; + } + NDC.push(username); + + String url = server+"?email="+username+"&password="+username+"&command=deploy"; + s_logger.info("Launching test for user: " + username + " with url: " + url); + HttpClient client = new HttpClient(); + HttpMethod method = new GetMethod(url); + int responseCode = client.executeMethod(method); + boolean success = false; + String reason = null; + if (responseCode == 200) { + if (internet) { + s_logger.info("Deploy successful...waiting 5 minute before SSH tests"); + Thread.sleep(300000L); // Wait 60 seconds so the linux VM can boot up. + + s_logger.info("Begin Linux SSH test"); + reason = sshTest(method.getResponseHeader("linuxIP").getValue()); + + if (reason == null) { + s_logger.info("Linux SSH test successful"); + s_logger.info("Begin Windows SSH test"); + reason = sshWinTest(method.getResponseHeader("windowsIP").getValue()); + } + } + if (reason == null) { + if (internet) { + s_logger.info("Windows SSH test successful"); + } else { + s_logger.info("deploy test successful....now cleaning up"); + if (cleanUp) { + s_logger.info("Waiting " + sleepTime + " ms before cleaning up vms"); + Thread.sleep(sleepTime); + } else { + success = true; + } + } + if (users == null) { + s_logger.info("Sending cleanup command"); + url = server+"?email="+username+"&password="+username+"&command=cleanup"; + } else { + s_logger.info("Sending stop DomR / destroy VM command"); + url = server+"?email="+username+"&password="+username+"&command=stopDomR"; + } + method = new GetMethod(url); + responseCode = client.executeMethod(method); + if (responseCode == 200) { + success = true; + } else { + reason = method.getStatusText(); + } + } else { + // Just stop but don't destroy the VMs/Routers + s_logger.info("SSH test failed with reason '" + reason + "', stopping VMs"); + url = server+"?email="+username+"&password="+username+"&command=stop"; + responseCode = client.executeMethod(new GetMethod(url)); + } + } else { + // Just stop but don't destroy the VMs/Routers + reason = method.getStatusText(); + s_logger.info("Deploy test failed with reason '" + reason + "', stopping VMs"); + url = server+"?email="+username+"&password="+username+"&command=stop"; + client.executeMethod(new GetMethod(url)); + } + + if (success) { + s_logger.info("***** Completed test for user : " + username + " in " + ((System.currentTimeMillis() - now) / 1000L) + " seconds"); + } else { + s_logger.info("##### FAILED test for user : " + username + " in " + ((System.currentTimeMillis() - now) / 1000L) + " seconds with reason : " + reason); + } + } catch (Exception e) { + s_logger.warn("Error in thread", e); + try { + HttpClient client = new HttpClient(); + String url = server+"?email="+username+"&password="+username+"&command=stop"; + client.executeMethod(new GetMethod(url)); + } catch (Exception e1) { + } + } finally { + NDC.clear(); + } + } while (repeat); + } + }).start(); + } + } catch (Exception e) { + s_logger.error(e); + } + } + + private static String sshWinTest(String host) { + if (host == null) { + s_logger.info("Did not receive a host back from test, ignoring win ssh test"); + return null; + } + + // We will retry 5 times before quitting + int retry = 0; + + while (true) { + try { + if (retry > 0) { + s_logger.info("Retry attempt : " + retry + " ...sleeping 300 seconds before next attempt"); + Thread.sleep(300000); + } + + s_logger.info("Attempting to SSH into windows host " + host + " with retry attempt: " + retry); + + Connection conn = new Connection(host); + conn.connect(null, 60000, 60000); + + s_logger.info("SSHed successfully into windows host " + host); + boolean success = false; + boolean isAuthenticated = conn.authenticateWithPassword("vmops", "vmops"); + if (isAuthenticated == false) { + return "Authentication failed"; + } + SCPClient scp = new SCPClient(conn); + + scp.put("wget.exe", ""); + + Session sess = conn.openSession(); + s_logger.info("Executing : wget http://172.16.0.220/dump.bin"); + sess.execCommand("wget http://172.16.0.220/dump.bin && dir dump.bin"); + + InputStream stdout = sess.getStdout(); + InputStream stderr = sess.getStderr(); + + byte[] buffer = new byte[8192]; + while (true) { + if ((stdout.available() == 0) && (stderr.available() == 0)) { + int conditions = sess.waitForCondition(ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA + | ChannelCondition.EOF, 120000); + + if ((conditions & ChannelCondition.TIMEOUT) != 0) { + s_logger.info("Timeout while waiting for data from peer."); + return null; + } + + if ((conditions & ChannelCondition.EOF) != 0) { + if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) == 0) { + break; + } + } + } + + while (stdout.available() > 0) { + success = true; + int len = stdout.read(buffer); + if (len > 0) // this check is somewhat paranoid + s_logger.info(new String(buffer, 0, len)); + } + + while (stderr.available() > 0) { + int len = stderr.read(buffer); + } + } + sess.close(); + conn.close(); + + if (success) { + return null; + } else { + retry++; + if (retry == MAX_RETRY_WIN) { + return "SSH Windows Network test fail"; + } + } + } catch (Exception e) { + retry++; + if (retry == MAX_RETRY_WIN) { + return "SSH Windows Network test fail with error " + e.getMessage(); + } + } + } + } + + private static String sshTest(String host) { + if (host == null) { + s_logger.info("Did not receive a host back from test, ignoring ssh test"); + return null; + } + + // We will retry 5 times before quitting + int retry = 0; + + while (true) { + try { + if (retry > 0) { + s_logger.info("Retry attempt : " + retry + " ...sleeping 120 seconds before next attempt"); + Thread.sleep(120000); + } + + s_logger.info("Attempting to SSH into linux host " + host + " with retry attempt: " + retry); + + Connection conn = new Connection(host); + conn.connect(null, 60000, 60000); + + s_logger.info("SSHed successfully into linux host " + host); + + boolean isAuthenticated = conn.authenticateWithPassword("root", "password"); + + if (isAuthenticated == false) { + return "Authentication failed"; + } + boolean success = false; + Session sess = conn.openSession(); + s_logger.info("Executing : wget http://172.16.0.220/dump.bin"); + sess.execCommand("wget http://172.16.0.220/dump.bin && ls -al dump.bin"); + + InputStream stdout = sess.getStdout(); + InputStream stderr = sess.getStderr(); + + byte[] buffer = new byte[8192]; + while (true) { + if ((stdout.available() == 0) && (stderr.available() == 0)) { + int conditions = sess.waitForCondition(ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA + | ChannelCondition.EOF, 120000); + + if ((conditions & ChannelCondition.TIMEOUT) != 0) { + s_logger.info("Timeout while waiting for data from peer."); + return null; + } + + if ((conditions & ChannelCondition.EOF) != 0) { + if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) == 0) { + break; + } + } + } + + while (stdout.available() > 0) { + success = true; + int len = stdout.read(buffer); + if (len > 0) // this check is somewhat paranoid + s_logger.info(new String(buffer, 0, len)); + } + + while (stderr.available() > 0) { + int len = stderr.read(buffer); + } + } + + sess.close(); + conn.close(); + + if (success) { + return null; + } else { + retry++; + if (retry == MAX_RETRY_LINUX) { + return "SSH Linux Network test fail"; + } + } + } catch (Exception e) { + retry++; + if (retry == MAX_RETRY_LINUX) { + return "SSH Linux Network test fail with error " + e.getMessage(); + } + } + } + } +} diff --git a/test/src/com/cloud/test/utils/UtilsForTest.java b/test/src/com/cloud/test/utils/UtilsForTest.java index 4c09b118fc0..a53a1949d72 100644 --- a/test/src/com/cloud/test/utils/UtilsForTest.java +++ b/test/src/com/cloud/test/utils/UtilsForTest.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.test.utils; - +package com.cloud.test.utils; + import java.io.InputStream; import java.math.BigInteger; import java.security.MessageDigest; @@ -33,201 +33,201 @@ import org.w3c.dom.NodeList; import com.cloud.utils.encoding.Base64; import com.cloud.utils.exception.CloudRuntimeException; - -public class UtilsForTest { - - private static DocumentBuilderFactory factory = DocumentBuilderFactory - .newInstance(); - - public static boolean verifyTags (Map params) { - boolean result = true; - for (String value : params.keySet()) { - if (params.get(value) == null) { - result=false; - } - } - return result; - } - - public static boolean verifyTagValues (Map params, Map pattern) { - boolean result = true; - - if (pattern != null) { - for (String value : pattern.keySet()) { - if (!pattern.get(value).equals(params.get(value))) { - result=false; - System.out.println("Tag " + value + " has " + params.get(value) + " while expected value is: " + pattern.get(value)); - } - } - } - return result; - } - - - public static Map parseXML(InputStream is, - String[] tagNames) { - Map returnValues = new HashMap(); - try { - DocumentBuilder docBuilder = factory.newDocumentBuilder(); - Document doc = docBuilder.parse(is); - Element rootElement = doc.getDocumentElement(); - - for (int i = 0; i < tagNames.length; i++) { - NodeList targetNodes = rootElement - .getElementsByTagName(tagNames[i]); - if (targetNodes.getLength() <= 0) { - System.out.println("no " + tagNames[i] - + " tag in the response"); - returnValues.put(tagNames[i], null); - } else { - returnValues.put(tagNames[i], targetNodes.item(0) - .getTextContent()); - } - } - } catch (Exception ex) { + +public class UtilsForTest { + + private static DocumentBuilderFactory factory = DocumentBuilderFactory + .newInstance(); + + public static boolean verifyTags (Map params) { + boolean result = true; + for (String value : params.keySet()) { + if (params.get(value) == null) { + result=false; + } + } + return result; + } + + public static boolean verifyTagValues (Map params, Map pattern) { + boolean result = true; + + if (pattern != null) { + for (String value : pattern.keySet()) { + if (!pattern.get(value).equals(params.get(value))) { + result=false; + System.out.println("Tag " + value + " has " + params.get(value) + " while expected value is: " + pattern.get(value)); + } + } + } + return result; + } + + + public static Map parseXML(InputStream is, + String[] tagNames) { + Map returnValues = new HashMap(); + try { + DocumentBuilder docBuilder = factory.newDocumentBuilder(); + Document doc = docBuilder.parse(is); + Element rootElement = doc.getDocumentElement(); + + for (int i = 0; i < tagNames.length; i++) { + NodeList targetNodes = rootElement + .getElementsByTagName(tagNames[i]); + if (targetNodes.getLength() <= 0) { + System.out.println("no " + tagNames[i] + + " tag in the response"); + returnValues.put(tagNames[i], null); + } else { + returnValues.put(tagNames[i], targetNodes.item(0) + .getTextContent()); + } + } + } catch (Exception ex) { System.out.println("error processing XML"); - ex.printStackTrace(); - } - return returnValues; - } - - - public static ArrayList> parseMulXML (InputStream is, String[] tagNames){ - ArrayList> returnValues = new ArrayList>(); - - try { - DocumentBuilder docBuilder = factory.newDocumentBuilder(); - Document doc = docBuilder.parse(is); - Element rootElement = doc.getDocumentElement(); - for (int i = 0; i < tagNames.length; i++) { - NodeList targetNodes = rootElement - .getElementsByTagName(tagNames[i]); - if (targetNodes.getLength() <= 0) { - System.out.println("no " + tagNames[i] - + " tag in XML response...returning null"); - } else { - for (int j = 0; j < targetNodes.getLength(); j++) { - HashMap valueList = new HashMap (); - Node node = targetNodes.item(j); - //parse child nodes - NodeList child = node.getChildNodes(); - for (int c=0; c getSingleValueFromXML(InputStream is, - String[] tagNames) { - Map returnValues = new HashMap(); - try { - DocumentBuilder docBuilder = factory.newDocumentBuilder(); - Document doc = docBuilder.parse(is); - Element rootElement = doc.getDocumentElement(); - - for (int i = 0; i < tagNames.length; i++) { - NodeList targetNodes = rootElement - .getElementsByTagName(tagNames[i]); - if (targetNodes.getLength() <= 0) { - System.out.println("no " + tagNames[i] - + " tag in XML response...returning null"); - } else { - returnValues.put(tagNames[i], targetNodes.item(0) - .getTextContent()); - } - } - } catch (Exception ex) { + ex.printStackTrace(); + } + return returnValues; + } + + + public static ArrayList> parseMulXML (InputStream is, String[] tagNames){ + ArrayList> returnValues = new ArrayList>(); + + try { + DocumentBuilder docBuilder = factory.newDocumentBuilder(); + Document doc = docBuilder.parse(is); + Element rootElement = doc.getDocumentElement(); + for (int i = 0; i < tagNames.length; i++) { + NodeList targetNodes = rootElement + .getElementsByTagName(tagNames[i]); + if (targetNodes.getLength() <= 0) { + System.out.println("no " + tagNames[i] + + " tag in XML response...returning null"); + } else { + for (int j = 0; j < targetNodes.getLength(); j++) { + HashMap valueList = new HashMap (); + Node node = targetNodes.item(j); + //parse child nodes + NodeList child = node.getChildNodes(); + for (int c=0; c getSingleValueFromXML(InputStream is, + String[] tagNames) { + Map returnValues = new HashMap(); + try { + DocumentBuilder docBuilder = factory.newDocumentBuilder(); + Document doc = docBuilder.parse(is); + Element rootElement = doc.getDocumentElement(); + + for (int i = 0; i < tagNames.length; i++) { + NodeList targetNodes = rootElement + .getElementsByTagName(tagNames[i]); + if (targetNodes.getLength() <= 0) { + System.out.println("no " + tagNames[i] + + " tag in XML response...returning null"); + } else { + returnValues.put(tagNames[i], targetNodes.item(0) + .getTextContent()); + } + } + } catch (Exception ex) { System.out.println("error processing XML"); - ex.printStackTrace(); - } - return returnValues; - } - - - public static Map> getMultipleValuesFromXML( - InputStream is, String[] tagNames) { - Map> returnValues = new HashMap>(); - try { - DocumentBuilder docBuilder = factory.newDocumentBuilder(); - Document doc = docBuilder.parse(is); - Element rootElement = doc.getDocumentElement(); - for (int i = 0; i < tagNames.length; i++) { - NodeList targetNodes = rootElement - .getElementsByTagName(tagNames[i]); - if (targetNodes.getLength() <= 0) { - System.out.println("no " + tagNames[i] - + " tag in XML response...returning null"); - } else { - List valueList = new ArrayList(); - for (int j = 0; j < targetNodes.getLength(); j++) { - Node node = targetNodes.item(j); - valueList.add(node.getTextContent()); - } - returnValues.put(tagNames[i], valueList); - } - } - } catch (Exception ex) { - System.out.println(ex); - } - return returnValues; - } - - - - public static String signRequest(String request, String key) { - try { - Mac mac = Mac.getInstance("HmacSHA1"); - SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), - "HmacSHA1"); - mac.init(keySpec); - mac.update(request.getBytes()); + ex.printStackTrace(); + } + return returnValues; + } + + + public static Map> getMultipleValuesFromXML( + InputStream is, String[] tagNames) { + Map> returnValues = new HashMap>(); + try { + DocumentBuilder docBuilder = factory.newDocumentBuilder(); + Document doc = docBuilder.parse(is); + Element rootElement = doc.getDocumentElement(); + for (int i = 0; i < tagNames.length; i++) { + NodeList targetNodes = rootElement + .getElementsByTagName(tagNames[i]); + if (targetNodes.getLength() <= 0) { + System.out.println("no " + tagNames[i] + + " tag in XML response...returning null"); + } else { + List valueList = new ArrayList(); + for (int j = 0; j < targetNodes.getLength(); j++) { + Node node = targetNodes.item(j); + valueList.add(node.getTextContent()); + } + returnValues.put(tagNames[i], valueList); + } + } + } catch (Exception ex) { + System.out.println(ex); + } + return returnValues; + } + + + + public static String signRequest(String request, String key) { + try { + Mac mac = Mac.getInstance("HmacSHA1"); + SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), + "HmacSHA1"); + mac.init(keySpec); + mac.update(request.getBytes()); byte[] encryptedBytes = mac.doFinal(); - //System.out.println("HmacSHA1 hash: " + encryptedBytes); - return Base64.encodeBytes(encryptedBytes); - } catch (Exception ex) { + //System.out.println("HmacSHA1 hash: " + encryptedBytes); + return Base64.encodeBytes(encryptedBytes); + } catch (Exception ex) { System.out.println("unable to sign request"); - ex.printStackTrace(); - } - return null; - } - -} + ex.printStackTrace(); + } + return null; + } + +}