Replace all tabs, particularly the ones in the comments

This commit is contained in:
Alex Huang 2013-11-21 03:39:58 -08:00
parent 62e9273581
commit e4b22d0fca
134 changed files with 4479 additions and 4477 deletions

View File

@ -65,35 +65,35 @@ public interface SAcl {
*/
//public static OrderedPair <Integer,Integer> getCannedAccessControls ( String aclRequestString, String target );
/* {
if ( aclRequestString.equalsIgnoreCase( "public-read" ))
// All users granted READ access.
return new OrderedPair <Integer,Integer> (PERMISSION_READ,GRANTEE_ALLUSERS);
else if (aclRequestString.equalsIgnoreCase( "public-read-write" ))
// All users granted READ and WRITE access
return new OrderedPair <Integer,Integer> ((PERMISSION_READ | PERMISSION_WRITE),GRANTEE_ALLUSERS);
else if (aclRequestString.equalsIgnoreCase( "authenticated-read" ))
// Authenticated users have READ access
return new OrderedPair <Integer,Integer> (PERMISSION_READ,GRANTEE_AUTHENTICATED);
else if (aclRequestString.equalsIgnoreCase( "private" ))
// Only Owner gets FULL_CONTROL
return new OrderedPair <Integer,Integer> (PERMISSION_FULL,GRANTEE_USER);
else if (aclRequestString.equalsIgnoreCase( "bucket-owner-read" ))
{
// Object Owner gets FULL_CONTROL, Bucket Owner gets READ
if ( target.equalsIgnoreCase( "SBucket" ))
return new OrderedPair <Integer,Integer> (PERMISSION_READ, GRANTEE_USER);
else
return new OrderedPair <Integer,Integer> (PERMISSION_FULL, GRANTEE_USER);
}
else if (aclRequestString.equalsIgnoreCase( "bucket-owner-full-control" ))
{
// Object Owner gets FULL_CONTROL, Bucket Owner gets FULL_CONTROL
// This is equivalent to private when used with PUT Bucket
return new OrderedPair <Integer,Integer> (PERMISSION_FULL,GRANTEE_USER);
}
else throw new UnsupportedException( "Unknown Canned Access Policy: " + aclRequestString + " is not supported" );
}
/* {
if ( aclRequestString.equalsIgnoreCase( "public-read" ))
// All users granted READ access.
return new OrderedPair <Integer,Integer> (PERMISSION_READ,GRANTEE_ALLUSERS);
else if (aclRequestString.equalsIgnoreCase( "public-read-write" ))
// All users granted READ and WRITE access
return new OrderedPair <Integer,Integer> ((PERMISSION_READ | PERMISSION_WRITE),GRANTEE_ALLUSERS);
else if (aclRequestString.equalsIgnoreCase( "authenticated-read" ))
// Authenticated users have READ access
return new OrderedPair <Integer,Integer> (PERMISSION_READ,GRANTEE_AUTHENTICATED);
else if (aclRequestString.equalsIgnoreCase( "private" ))
// Only Owner gets FULL_CONTROL
return new OrderedPair <Integer,Integer> (PERMISSION_FULL,GRANTEE_USER);
else if (aclRequestString.equalsIgnoreCase( "bucket-owner-read" ))
{
// Object Owner gets FULL_CONTROL, Bucket Owner gets READ
if ( target.equalsIgnoreCase( "SBucket" ))
return new OrderedPair <Integer,Integer> (PERMISSION_READ, GRANTEE_USER);
else
return new OrderedPair <Integer,Integer> (PERMISSION_FULL, GRANTEE_USER);
}
else if (aclRequestString.equalsIgnoreCase( "bucket-owner-full-control" ))
{
// Object Owner gets FULL_CONTROL, Bucket Owner gets FULL_CONTROL
// This is equivalent to private when used with PUT Bucket
return new OrderedPair <Integer,Integer> (PERMISSION_FULL,GRANTEE_USER);
}
else throw new UnsupportedException( "Unknown Canned Access Policy: " + aclRequestString + " is not supported" );
}
*/
/** Return a Triple
* < permission1, permission2, symbol >
@ -111,39 +111,39 @@ public interface SAcl {
* @param ownerID - An ID for the owner, if used in place of symbols "A" or "*"
*/
//public static Triple <Integer,Integer,String> getCannedAccessControls ( String aclRequestString, String target, String ownerID );
/* throws UnsupportedException
{
if ( aclRequestString.equalsIgnoreCase( "public-read" ))
/* throws UnsupportedException
{
if ( aclRequestString.equalsIgnoreCase( "public-read" ))
// Owner gets FULL_CONTROL and the anonymous principal (the 'A' symbol here) is granted READ access.
return new Triple <Integer, Integer, String> (PERMISSION_FULL, PERMISSION_READ,"A");
else if (aclRequestString.equalsIgnoreCase( "public-read-write" ))
// Owner gets FULL_CONTROL and the anonymous principal (the 'A' symbol here) is granted READ and WRITE access
return new Triple <Integer, Integer, String> (PERMISSION_FULL, (PERMISSION_READ | PERMISSION_WRITE),"A");
else if (aclRequestString.equalsIgnoreCase( "authenticated-read" ))
// Owner gets FULL_CONTROL and ANY principal authenticated as a registered S3 user (the '*' symbol here) is granted READ access
return new Triple <Integer, Integer, String> (PERMISSION_FULL, PERMISSION_READ,"*");
else if (aclRequestString.equalsIgnoreCase( "private" ))
// This is termed the "private" or default ACL, "Owner gets FULL_CONTROL"
return new Triple <Integer, Integer, String> (PERMISSION_FULL, PERMISSION_FULL,null);
else if (aclRequestString.equalsIgnoreCase( "bucket-owner-read" ))
{
// Object Owner gets FULL_CONTROL, Bucket Owner gets READ
// This is equivalent to private when used with PUT Bucket
if ( target.equalsIgnoreCase( "SBucket" ))
return new Triple <Integer, Integer, String> (PERMISSION_FULL,PERMISSION_FULL ,null);
else
return new Triple <Integer, Integer, String> (PERMISSION_FULL,PERMISSION_READ,ownerID);
}
else if (aclRequestString.equalsIgnoreCase( "bucket-owner-full-control" ))
{
// Object Owner gets FULL_CONTROL, Bucket Owner gets FULL_CONTROL
// This is equivalent to private when used with PUT Bucket
if ( target.equalsIgnoreCase( "SBucket" ))
return new Triple <Integer, Integer, String> (PERMISSION_FULL, PERMISSION_FULL, null);
else
return new Triple <Integer, Integer, String> (PERMISSION_FULL,PERMISSION_FULL, ownerID);
}
else throw new UnsupportedException( "Unknown Canned Access Policy: " + aclRequestString + " is not supported" );
}
return new Triple <Integer, Integer, String> (PERMISSION_FULL, PERMISSION_READ,"A");
else if (aclRequestString.equalsIgnoreCase( "public-read-write" ))
// Owner gets FULL_CONTROL and the anonymous principal (the 'A' symbol here) is granted READ and WRITE access
return new Triple <Integer, Integer, String> (PERMISSION_FULL, (PERMISSION_READ | PERMISSION_WRITE),"A");
else if (aclRequestString.equalsIgnoreCase( "authenticated-read" ))
// Owner gets FULL_CONTROL and ANY principal authenticated as a registered S3 user (the '*' symbol here) is granted READ access
return new Triple <Integer, Integer, String> (PERMISSION_FULL, PERMISSION_READ,"*");
else if (aclRequestString.equalsIgnoreCase( "private" ))
// This is termed the "private" or default ACL, "Owner gets FULL_CONTROL"
return new Triple <Integer, Integer, String> (PERMISSION_FULL, PERMISSION_FULL,null);
else if (aclRequestString.equalsIgnoreCase( "bucket-owner-read" ))
{
// Object Owner gets FULL_CONTROL, Bucket Owner gets READ
// This is equivalent to private when used with PUT Bucket
if ( target.equalsIgnoreCase( "SBucket" ))
return new Triple <Integer, Integer, String> (PERMISSION_FULL,PERMISSION_FULL ,null);
else
return new Triple <Integer, Integer, String> (PERMISSION_FULL,PERMISSION_READ,ownerID);
}
else if (aclRequestString.equalsIgnoreCase( "bucket-owner-full-control" ))
{
// Object Owner gets FULL_CONTROL, Bucket Owner gets FULL_CONTROL
// This is equivalent to private when used with PUT Bucket
if ( target.equalsIgnoreCase( "SBucket" ))
return new Triple <Integer, Integer, String> (PERMISSION_FULL, PERMISSION_FULL, null);
else
return new Triple <Integer, Integer, String> (PERMISSION_FULL,PERMISSION_FULL, ownerID);
}
else throw new UnsupportedException( "Unknown Canned Access Policy: " + aclRequestString + " is not supported" );
}
*/
}

View File

@ -37,91 +37,91 @@ public interface SBucket {
public static final int VERSIONING_ENABLED = 1;
public static final int VERSIONING_SUSPENDED = 2;
/* private Long id;
private String name;
private String ownerCanonicalId;
private SHost shost;
private Date createTime;
private int versioningStatus;
private Set<SObject> objectsInBucket = new HashSet<SObject>();
public SBucket() {
versioningStatus = VERSIONING_NULL;
}
public Long getId() {
return id;
}
/* private Long id;
private String name;
private String ownerCanonicalId;
private SHost shost;
private Date createTime;
private int versioningStatus;
private Set<SObject> objectsInBucket = new HashSet<SObject>();
public SBucket() {
versioningStatus = VERSIONING_NULL;
}
public Long getId() {
return id;
}
private void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getOwnerCanonicalId() {
return ownerCanonicalId;
}
public void setOwnerCanonicalId(String ownerCanonicalId) {
this.ownerCanonicalId = ownerCanonicalId;
}
public SHost getShost() {
return shost;
}
public void setShost(SHost shost) {
this.shost = shost;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public int getVersioningStatus() {
return versioningStatus;
}
public void setVersioningStatus( int versioningStatus ) {
this.versioningStatus = versioningStatus;
}
public Set<SObject> getObjectsInBucket() {
return objectsInBucket;
}
private void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getOwnerCanonicalId() {
return ownerCanonicalId;
}
public void setOwnerCanonicalId(String ownerCanonicalId) {
this.ownerCanonicalId = ownerCanonicalId;
}
public SHost getShost() {
return shost;
}
public void setShost(SHost shost) {
this.shost = shost;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public int getVersioningStatus() {
return versioningStatus;
}
public void setVersioningStatus( int versioningStatus ) {
this.versioningStatus = versioningStatus;
}
public Set<SObject> getObjectsInBucket() {
return objectsInBucket;
}
public void setObjectsInBucket(Set<SObject> objectsInBucket) {
this.objectsInBucket = objectsInBucket;
}
@Override
public boolean equals(Object other) {
if(this == other)
return true;
if(!(other instanceof SBucket))
return false;
return getName().equals(((SBucket)other).getName());
}
@Override
public int hashCode() {
return getName().hashCode();
}*/
public void setObjectsInBucket(Set<SObject> objectsInBucket) {
this.objectsInBucket = objectsInBucket;
}
@Override
public boolean equals(Object other) {
if(this == other)
return true;
if(!(other instanceof SBucket))
return false;
return getName().equals(((SBucket)other).getName());
}
@Override
public int hashCode() {
return getName().hashCode();
}*/
}

View File

@ -31,90 +31,90 @@ public interface SHost {
STORAGE_HOST_TYPE_NFS, //1
STORAGE_HOST_TYPE_CASTOR //2
}
/* private Long id;
private String host;
private int hostType;
private MHostVO mhost;
private String exportRoot;
private String userOnHost;
private String userPassword;
private Set<SBucket> buckets = new HashSet<SBucket>();
private Set<MHostMount> mounts = new HashSet<MHostMount>();
public SHost() {
}
public Long getId() {
return id;
}
/* private Long id;
private String host;
private int hostType;
private MHostVO mhost;
private String exportRoot;
private String userOnHost;
private String userPassword;
private Set<SBucket> buckets = new HashSet<SBucket>();
private Set<MHostMount> mounts = new HashSet<MHostMount>();
public SHost() {
}
public Long getId() {
return id;
}
private void setId(Long id) {
this.id = id;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getHostType() {
return hostType;
}
private void setId(Long id) {
this.id = id;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getHostType() {
return hostType;
}
public void setHostType(int hostType) {
this.hostType = hostType;
}
public void setHostType(int hostType) {
this.hostType = hostType;
}
public String getExportRoot() {
return exportRoot;
}
public String getExportRoot() {
return exportRoot;
}
public void setExportRoot(String exportRoot) {
this.exportRoot = exportRoot;
}
public void setExportRoot(String exportRoot) {
this.exportRoot = exportRoot;
}
public String getUserOnHost() {
return userOnHost;
}
public void setUserOnHost(String userOnHost) {
this.userOnHost = userOnHost;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
public MHostVO getMhost() {
return mhost;
}
public String getUserOnHost() {
return userOnHost;
}
public void setUserOnHost(String userOnHost) {
this.userOnHost = userOnHost;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
public MHostVO getMhost() {
return mhost;
}
public void setMhost(MHostVO mhost) {
this.mhost = mhost;
}
public void setMhost(MHostVO mhost) {
this.mhost = mhost;
}
public Set<SBucket> getBuckets() {
return buckets;
}
public Set<SBucket> getBuckets() {
return buckets;
}
public void setBuckets(Set<SBucket> buckets) {
this.buckets = buckets;
}
public Set<MHostMount> getMounts() {
return mounts;
}
public void setBuckets(Set<SBucket> buckets) {
this.buckets = buckets;
}
public Set<MHostMount> getMounts() {
return mounts;
}
public void setMounts(Set<MHostMount> mounts) {
this.mounts = mounts;
}*/
public void setMounts(Set<MHostMount> mounts) {
this.mounts = mounts;
}*/
}

View File

@ -54,7 +54,7 @@ public class SObjectVO {
private int nextSequence;
@Column(name = "DeletionMark")
private String deletionMark; // This must also a unique ID to give to the REST client
private String deletionMark; // This must also a unique ID to give to the REST client
@Column(name = "CreateTime")
@Temporal(value = TemporalType.TIMESTAMP)

View File

@ -492,7 +492,7 @@ public class EC2RestServlet extends HttpServlet {
response.sendError(530, "Missing cert parameter");
return;
}
// logger.debug( "SetCertificate cert: [" + certificate[0] + "]" );
// logger.debug( "SetCertificate cert: [" + certificate[0] + "]" );
String[] accessKey = request.getParameterValues("AWSAccessKeyId");
if (null == accessKey || 0 == accessKey.length) {
@ -574,7 +574,7 @@ public class EC2RestServlet extends HttpServlet {
certStore.store(fsOut, keystorePassword.toCharArray());
// -> dis-associate the cert's uniqueId with the Cloud API keys
/* UserCredentialsDao credentialDao = new UserCredentialsDao();
/* UserCredentialsDao credentialDao = new UserCredentialsDao();
credentialDao.setCertificateId( accessKey[0], null );
*/txn = TransactionLegacy.open(TransactionLegacy.AWSAPI_DB);

View File

@ -749,7 +749,7 @@ public class EC2SoapServiceImpl implements AmazonEC2SkeletonInterface {
/**
* ec2-run-instances
*
*
* @param runInstances
*
* @see <a href="http://docs.amazonwebservices.com/AWSEC2/2010-11-15/APIReference/index.html?ApiReference-query-RunInstances.html">RunInstances</a>
@ -885,7 +885,7 @@ public class EC2SoapServiceImpl implements AmazonEC2SkeletonInterface {
/**
* @param modifyInstanceAttribute
* @return
* @return
*/
public static ModifyInstanceAttributeResponse toModifyInstanceAttributeResponse(Boolean status) {
ModifyInstanceAttributeResponse miat = new ModifyInstanceAttributeResponse();
@ -1453,7 +1453,7 @@ public class EC2SoapServiceImpl implements AmazonEC2SkeletonInterface {
Calendar cal = inst.getCreated();
if (null == cal) {
cal = Calendar.getInstance();
// cal.set( 1970, 1, 1 );
// cal.set( 1970, 1, 1 );
}
param7.setLaunchTime(cal);
@ -1924,7 +1924,7 @@ public class EC2SoapServiceImpl implements AmazonEC2SkeletonInterface {
Calendar cal = EC2RestAuth.parseDateString(engineResponse.getCreated());
if (null == cal) {
cal = Calendar.getInstance();
// cal.set( 1970, 1, 1 );
// cal.set( 1970, 1, 1 );
}
param1.setCreateTime(cal);
@ -1974,7 +1974,7 @@ public class EC2SoapServiceImpl implements AmazonEC2SkeletonInterface {
param3.setStatus("error");
param3.setProgress("0%");
}
// param3.setStatus( snap.getState());
// param3.setStatus( snap.getState());
String ownerId = snap.getDomainId() + ":" + snap.getAccountName();

View File

@ -392,7 +392,7 @@ public class S3RestServlet extends HttpServlet {
return new S3BucketAction(); // for ListAllMyBuckets
}
// Because there is a leading / at position 0 of pathInfo, now subtract this to process the remainder
// Because there is a leading / at position 0 of pathInfo, now subtract this to process the remainder
pathInfo = pathInfo.substring(1);
if (ServiceProvider.getInstance().getUseSubDomain())

View File

@ -893,7 +893,7 @@ public class S3BucketAction implements ServletAction {
public void executePutBucketWebsite(HttpServletRequest request, HttpServletResponse response) throws IOException {
// TODO -- LoPri - Undertake checks on Put Bucket Website
// Tested using configuration <Directory /Users/john1/S3-Mount>\nAllowOverride FileInfo AuthConfig Limit...</Directory> in httpd.conf
// Need some way of using AllowOverride to allow use of .htaccess and then pushing .httaccess file to bucket subdirectory of mount point
// Need some way of using AllowOverride to allow use of .htaccess and then pushing .httaccess file to bucket subdirectory of mount point
// Currently has noop effect in the sense that a running apachectl process sees the directory contents without further action
response.setStatus(200);
}

View File

@ -599,7 +599,7 @@ public class S3ObjectAction implements ServletAction {
//System.out.println( oneLine.length() + " body data: " + oneLine );
temp.append(oneLine);
}
// else System.out.println( oneLine.length() + " preamble: " + oneLine );
// else System.out.println( oneLine.length() + " preamble: " + oneLine );
}
// [B] Authenticate the POST request after we have all the headers

View File

@ -81,7 +81,7 @@ public class ServiceProvider extends ManagerBase {
private final Timer timer = new Timer();
private MHostVO mhost;
private Properties properties;
private boolean useSubDomain = false; // use DNS sub domain for bucket name
private boolean useSubDomain = false; // use DNS sub domain for bucket name
private String serviceEndpoint = null;
private String multipartDir = null; // illegal bucket name used as a folder for storing multiparts
private String masterDomain = ".s3.amazonaws.com";

View File

@ -861,7 +861,7 @@ public class EC2Engine extends ManagerBase {
CloudStackZone zone = findZone();
//CloudStackNetwork net = findNetwork(zone);
// CloudStackIpAddress resp = getApi().associateIpAddress(null, null, null, "0036952d-48df-4422-9fd0-94b0885e18cb");
// CloudStackIpAddress resp = getApi().associateIpAddress(null, null, null, "0036952d-48df-4422-9fd0-94b0885e18cb");
CloudStackIpAddress resp = getApi().associateIpAddress(zone.getId(), caller.getName(), caller.getDomainId(), null);
ec2Address.setAssociatedInstanceId(resp.getId());
@ -1213,12 +1213,12 @@ public class EC2Engine extends ManagerBase {
throw new EC2ServiceException(ServerError.InternalError, "No Customize Disk Offering Found");
}
// // -> no volume name is given in the Amazon request but is required in the cloud API
// // -> no volume name is given in the Amazon request but is required in the cloud API
CloudStackVolume vol = getApi().createVolume(UUID.randomUUID().toString(), null, diskOfferingId, null, size, snapshotId, toZoneId(request.getZoneName(), null));
if (vol != null) {
resp.setAttached(vol.getAttached());
resp.setCreated(vol.getCreated());
// resp.setDevice();
// resp.setDevice();
resp.setDeviceId(vol.getDeviceId());
resp.setHypervisor(vol.getHypervisor());
resp.setId(vol.getId());

View File

@ -29,7 +29,7 @@ public class EC2RunInstances {
private String keyName;
private int maxCount;
private int minCount;
private Integer size; // <- in gigs
private Integer size; // <- in gigs
private List<String> groupIdSet;
private List<String> groupNameSet;

View File

@ -50,7 +50,7 @@ public class EC2VolumeFilterSet {
filterTypes.put("tag-key", "string");
filterTypes.put("tag-value", "string");
filterTypes.put("volume-id", "string");
// filterTypes.put( "tag:*", "null" );
// filterTypes.put( "tag:*", "null" );
}
public void addFilter(EC2Filter param) {

View File

@ -120,7 +120,7 @@ public class S3Engine {
static SAclDao s_saclDao;
static BucketPolicyDao s_bPolicy;
private final int LOCK_ACQUIRING_TIMEOUT_SECONDS = 10; // ten seconds
private final int LOCK_ACQUIRING_TIMEOUT_SECONDS = 10; // ten seconds
private final Map<Integer, S3BucketAdapter> bucketAdapters = new HashMap<Integer, S3BucketAdapter>();
@ -775,7 +775,7 @@ public class S3Engine {
if (bucket == null)
throw new NoSuchObjectException("Bucket " + bucketName + " does not exist");
// Is the caller allowed to write the object?
// Is the caller allowed to write the object?
// The allocObjectItem checks for the bucket policy PutObject permissions
OrderedPair<SObjectVO, SObjectItemVO> object_objectitem_pair = allocObjectItem(bucket, key, meta, acl, null);
OrderedPair<SHostVO, String> host_storagelocation_pair = getBucketStorageHost(bucket);
@ -1028,7 +1028,7 @@ public class S3Engine {
return response;
}
// [D] Return the contents of the object inline
// [D] Return the contents of the object inline
// -> extract the meta data that corresponds the specific versioned item
List<SMetaVO> itemMetaData = metaDao.getByTarget("SObjectItem", item.getId());
@ -1137,7 +1137,7 @@ public class S3Engine {
response.setResultDescription("<VersionId>" + wantVersion + "</VersionId>");
}
}
} else { // If versioning is off then we do delete the null object
} else { // If versioning is off then we do delete the null object
S3PolicyContext context = new S3PolicyContext(PolicyActions.DeleteObject, bucketName);
context.setKeyName(nameKey);
verifyAccess(context, "SBucket", sbucket.getId(), SAcl.PERMISSION_WRITE);
@ -1540,7 +1540,7 @@ public class S3Engine {
* Note that canned policies can be set when the object's contents are set
*/
public void setCannedAccessControls(String cannedAccessPolicy, String target, long objectId, SBucketVO bucket) {
// Find the permission and symbol for the principal corresponding to the requested cannedAccessPolicy
// Find the permission and symbol for the principal corresponding to the requested cannedAccessPolicy
Triple<Integer, Integer, String> permission_permission_symbol_triple = SAclVO.getCannedAccessControls(cannedAccessPolicy, target, bucket.getOwnerCanonicalId());
if (null == permission_permission_symbol_triple.getThird())
setSingleAcl(target, objectId, permission_permission_symbol_triple.getFirst());
@ -1672,7 +1672,7 @@ public class S3Engine {
if (hasPermission(s_saclDao.listGrants(target, targetId, "*"), requestedPermission))
return;
}
// No privileges implies that no access is allowed in the case of an anonymous user
// No privileges implies that no access is allowed in the case of an anonymous user
throw new PermissionDeniedException("Access Denied - ACLs do not give user the required permission");
}

View File

@ -31,8 +31,8 @@ import com.cloud.bridge.service.exception.UnsupportedException;
* canonicalUserID
*/
public class S3Grant {
private int grantee; // SAcl.GRANTEE_USER etc
private int permission; // SAcl.PERMISSION_READ etc
private int grantee; // SAcl.GRANTEE_USER etc
private int permission; // SAcl.PERMISSION_READ etc
private String canonicalUserID;
public S3Grant() {

View File

@ -68,7 +68,7 @@ public class EC2RestAuth {
} catch (Exception e) {
}
// -> the time zone is GMT if not defined
// -> the time zone is GMT if not defined
try {
formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
cal.setTime(formatter.parse(created));

View File

@ -32,8 +32,8 @@ import com.google.gson.JsonPrimitive;
* JsonAccessor provides the functionality to allow navigating JSON object graph using simple expressions,
* for example, following property access expressions are all valid ones
*
* rootobj.level1obj[1].property
* this[0].level1obj[1].property
* rootobj.level1obj[1].property
* this[0].level1obj[1].property
*
*/
public class JsonAccessor {
@ -132,9 +132,9 @@ public class JsonAccessor {
/*
* Return
* -1 : property expression can not be resolved
* 0 : match to a null JSON object
* 1+ : matched, for array element, the count of the elements inside the array
* -1 : property expression can not be resolved
* 0 : match to a null JSON object
* 1+ : matched, for array element, the count of the elements inside the array
*/
public int getMatchCount(String propPath) {
JsonElement jsonElement = tryEval(propPath);

View File

@ -42,8 +42,8 @@ public class CloudStackClient {
private String _serviceUrl;
private long _pollIntervalMs = 2000; // 1 second polling interval
private long _pollTimeoutMs = 600000; // 10 minutes polling timeout
private long _pollIntervalMs = 2000; // 1 second polling interval
private long _pollTimeoutMs = 600000; // 10 minutes polling timeout
public CloudStackClient(String serviceRootUrl) {
assert (serviceRootUrl != null);

View File

@ -1014,54 +1014,54 @@ public class VirtualRoutingResource implements Manager {
}
// protected Answer execute(final SetFirewallRuleCommand cmd) {
// String args;
// if(cmd.getProtocol().toLowerCase().equals(NetUtils.NAT_PROTO)){
// //1:1 NAT needs instanceip;publicip;domrip;op
// if(cmd.isCreate()) {
// String args;
// if(cmd.getProtocol().toLowerCase().equals(NetUtils.NAT_PROTO)){
// //1:1 NAT needs instanceip;publicip;domrip;op
// if(cmd.isCreate()) {
// args = "-A";
// } else {
// args = "-D";
// }
//
// args += " -l " + cmd.getPublicIpAddress();
// args += " -i " + cmd.getRouterIpAddress();
// args += " -r " + cmd.getPrivateIpAddress();
// args += " -G " + cmd.getProtocol();
// }else{
// if (cmd.isEnable()) {
// args = "-A";
// } else {
// args = "-D";
// }
// args += " -l " + cmd.getPublicIpAddress();
// args += " -i " + cmd.getRouterIpAddress();
// args += " -r " + cmd.getPrivateIpAddress();
// args += " -G " + cmd.getProtocol();
// }else{
// if (cmd.isEnable()) {
// args = "-A";
// } else {
// args = "-D";
// }
//
// args += " -P " + cmd.getProtocol().toLowerCase();
// args += " -l " + cmd.getPublicIpAddress();
// args += " -p " + cmd.getPublicPort();
// args += " -n " + cmd.getRouterName();
// args += " -i " + cmd.getRouterIpAddress();
// args += " -r " + cmd.getPrivateIpAddress();
// args += " -d " + cmd.getPrivatePort();
// args += " -N " + cmd.getVlanNetmask();
// args += " -P " + cmd.getProtocol().toLowerCase();
// args += " -l " + cmd.getPublicIpAddress();
// args += " -p " + cmd.getPublicPort();
// args += " -n " + cmd.getRouterName();
// args += " -i " + cmd.getRouterIpAddress();
// args += " -r " + cmd.getPrivateIpAddress();
// args += " -d " + cmd.getPrivatePort();
// args += " -N " + cmd.getVlanNetmask();
//
// String oldPrivateIP = cmd.getOldPrivateIP();
// String oldPrivatePort = cmd.getOldPrivatePort();
// String oldPrivateIP = cmd.getOldPrivateIP();
// String oldPrivatePort = cmd.getOldPrivatePort();
//
// if (oldPrivateIP != null) {
// args += " -w " + oldPrivateIP;
// }
// if (oldPrivateIP != null) {
// args += " -w " + oldPrivateIP;
// }
//
// if (oldPrivatePort != null) {
// args += " -x " + oldPrivatePort;
// }
// }
// if (oldPrivatePort != null) {
// args += " -x " + oldPrivatePort;
// }
// }
//
// final Script command = new Script(_firewallPath, _timeout, s_logger);
// String [] argsArray = args.split(" ");
// for (String param : argsArray) {
// command.add(param);
// }
// String result = command.execute();
// return new Answer(cmd, result == null, result);
// final Script command = new Script(_firewallPath, _timeout, s_logger);
// String [] argsArray = args.split(" ");
// for (String param : argsArray) {
// command.add(param);
// }
// String result = command.execute();
// return new Answer(cmd, result == null, result);
// }
protected String getDefaultScriptsDir() {

View File

@ -108,7 +108,7 @@ public abstract class ServerResourceBase implements ServerResource {
}
}
// } catch (final SocketException e) {
// s_logger.warn("Error looking at " + nicName, e);
// s_logger.warn("Error looking at " + nicName, e);
// }
s_logger.debug("Skipping nic " + nicName);
}

View File

@ -130,7 +130,7 @@ public class SerializerHelper {
}
}
//else
// l.add(new Pair<String, Object>(paramName, ""));
// l.add(new Pair<String, Object>(paramName, ""));
} catch (IllegalArgumentException e) {
s_logger.error("Illegal argument exception when calling POJO " + o.getClass().getName() + " get method for property: " + propName);

View File

@ -271,7 +271,7 @@ public class Connection
public XmlRpcClientConfigImpl getConfig()
{
return config;
return config;
}
private XmlRpcClient getClientFromURL(URL url)
{

View File

@ -29,8 +29,8 @@ public final class Marshalling {
o instanceof Double ||
o instanceof Date) {
return o;
} else if (o instanceof Long) {
return o.toString();
} else if (o instanceof Long) {
return o.toString();
} else if (o instanceof Map) {
Map<Object, Object> result = new HashMap<Object, Object>();
Map m = (Map)o;
@ -46,14 +46,14 @@ public final class Marshalling {
result.add(toXMLRPC(e));
}
return result;
} else if (o instanceof XenAPIObject) {
return ((XenAPIObject) o).toWireString();
} else if (o instanceof Enum) {
return o.toString();
}else if (o == null){
return "";
} else if (o instanceof XenAPIObject) {
return ((XenAPIObject) o).toWireString();
} else if (o instanceof Enum) {
return o.toString();
}else if (o == null){
return "";
} else {
throw new RuntimeException ("=============don't know how to marshall:({[" + o + "]})");
throw new RuntimeException ("=============don't know how to marshall:({[" + o + "]})");
}
}
}

View File

@ -14,5 +14,5 @@ package com.xensource.xenapi;
public abstract class XenAPIObject
{
public abstract String toWireString();
public abstract String toWireString();
}

View File

@ -119,8 +119,8 @@ public interface ConfigurationManager {
// * @return newly created disk offering
// */
// DiskOfferingVO createDiskOffering(Long domainId, String name, String description, Long numGibibytes, String tags, boolean isCustomized,
// boolean localStorageRequired, boolean isDisplayOfferingEnabled, Boolean isCustomizedIops, Long minIops, Long maxIops,
// Long bytesReadRate, Long bytesWriteRate, Long iopsReadRate, Long iopsWriteRate);
// boolean localStorageRequired, boolean isDisplayOfferingEnabled, Boolean isCustomizedIops, Long minIops, Long maxIops,
// Long bytesReadRate, Long bytesWriteRate, Long iopsReadRate, Long iopsWriteRate);
/**
* Creates a new pod

View File

@ -142,7 +142,7 @@ public class EngineHostVO implements EngineHost, Identity {
private String hypervisorVersion;
@Column(name = "update_count", updatable = true, nullable = false)
protected long updated; // This field should be updated everytime the state is updated. There's no set method in the vo object because it is done with in the dao code.
protected long updated; // This field should be updated everytime the state is updated. There's no set method in the vo object because it is done with in the dao code.
@Column(name = "uuid")
private String uuid;

View File

@ -146,13 +146,13 @@ public class CapacityDaoImpl extends GenericDaoBase<CapacityVO, Long> implements
*
* */
private static final String LIST_CLUSTERS_CROSSING_THRESHOLD = "SELECT clusterList.cluster_id "
+ "FROM ( SELECT cluster.cluster_id cluster_id, ( (sum(cluster.used) + sum(cluster.reserved) + ?)/sum(cluster.total) ) ratio, cluster.configValue value "
+ "FROM ( SELECT capacity.cluster_id cluster_id, capacity.used_capacity used, capacity.reserved_capacity reserved, capacity.total_capacity * overcommit.value total, "
+ "FROM ( SELECT cluster.cluster_id cluster_id, ( (sum(cluster.used) + sum(cluster.reserved) + ?)/sum(cluster.total) ) ratio, cluster.configValue value "
+ "FROM ( SELECT capacity.cluster_id cluster_id, capacity.used_capacity used, capacity.reserved_capacity reserved, capacity.total_capacity * overcommit.value total, "
+ "CASE (SELECT count(*) FROM `cloud`.`cluster_details` details WHERE details.cluster_id = capacity.cluster_id AND details.name = ? ) "
+ "WHEN 1 THEN ( CASE WHEN (SELECT details.value FROM `cloud`.`cluster_details` details WHERE details.cluster_id = capacity.cluster_id AND details.name = ?) is NULL "
+ "WHEN 1 THEN ( CASE WHEN (SELECT details.value FROM `cloud`.`cluster_details` details WHERE details.cluster_id = capacity.cluster_id AND details.name = ?) is NULL "
+ "THEN (SELECT config.value FROM `cloud`.`configuration` config WHERE config.name = ?)"
+ "ELSE (SELECT details.value FROM `cloud`.`cluster_details` details WHERE details.cluster_id = capacity.cluster_id AND details.name = ? ) END )"
+ "ELSE ( SELECT config.value FROM `cloud`.`configuration` config WHERE config.name = ?) "
+ "ELSE ( SELECT config.value FROM `cloud`.`configuration` config WHERE config.name = ?) "
+ "END configValue "
+ "FROM `cloud`.`op_host_capacity` capacity INNER JOIN `cloud`.`cluster_details` overcommit ON overcommit.cluster_id = capacity.cluster_id "
+ "WHERE capacity.data_center_id = ? AND capacity.capacity_type = ? AND capacity.total_capacity > 0 AND overcommit.name = ?) cluster "

View File

@ -287,11 +287,11 @@ public class VlanDaoImpl extends GenericDaoBase<VlanVO, Long> implements VlanDao
}
return null;
// String ipAddress = _ipAddressDao.assignIpAddress(accountId, domainId, vlan.getId(), false).getAddress();
// if (ipAddress == null) {
// return null;
// }
// return new Pair<String, VlanVO>(ipAddress, vlan);
// String ipAddress = _ipAddressDao.assignIpAddress(accountId, domainId, vlan.getId(), false).getAddress();
// if (ipAddress == null) {
// return null;
// }
// return new Pair<String, VlanVO>(ipAddress, vlan);
}

View File

@ -138,7 +138,7 @@ public class HostVO implements Host {
private String hypervisorVersion;
@Column(name = "update_count", updatable = true, nullable = false)
protected long updated; // This field should be updated everytime the state is updated. There's no set method in the vo object because it is done with in the dao code.
protected long updated; // This field should be updated everytime the state is updated. There's no set method in the vo object because it is done with in the dao code.
@Column(name = "uuid")
private String uuid;

View File

@ -44,7 +44,7 @@ public interface PortProfileDao extends GenericDao<PortProfileVO, Long> {
* List<PortProfileVO> listByVlanId(int vlanId);
*
* List all uplink portprofiles (these represent physical ports).
* List<PortProfileVO> listAllUplinkPortProfiles(); // we may have to provide some filter, like clusterId or zoneId or something.
* List<PortProfileVO> listAllUplinkPortProfiles(); // we may have to provide some filter, like clusterId or zoneId or something.
*
*/
}

View File

@ -118,7 +118,7 @@ public class VMInstanceVO implements VirtualMachine, FiniteStateObject<State, Vi
private boolean limitCpuUse;
@Column(name = "update_count", updatable = true, nullable = false)
protected long updated; // This field should be updated everytime the state is updated. There's no set method in the vo object because it is done with in the dao code.
protected long updated; // This field should be updated everytime the state is updated. There's no set method in the vo object because it is done with in the dao code.
@Column(name = GenericDao.CREATED_COLUMN)
protected Date created;

View File

@ -46,7 +46,7 @@ public class ConsoleProxyDaoImpl extends GenericDaoBase<ConsoleProxyVO, Long> im
//
// query SQL for returnning console proxy assignment info as following
// proxy vm id, count of assignment
// proxy vm id, count of assignment
//
private static final String PROXY_ASSIGNMENT_MATRIX = "SELECT c.id, count(runningVm.id) AS count "
+ " FROM console_proxy AS c LEFT JOIN vm_instance AS i ON c.id=i.id LEFT JOIN"

View File

@ -117,7 +117,7 @@ public class VMEntityVO implements VirtualMachine, FiniteStateObject<State, Virt
private boolean limitCpuUse;
@Column(name = "update_count", updatable = true, nullable = false)
protected long updated; // This field should be updated everytime the state is updated. There's no set method in the vo object because it is done with in the dao code.
protected long updated; // This field should be updated everytime the state is updated. There's no set method in the vo object because it is done with in the dao code.
@Column(name = GenericDao.CREATED_COLUMN)
protected Date created;

View File

@ -35,7 +35,7 @@ public class ClusterServiceServletAdapter extends AdapterBase implements Cluster
private static final Logger s_logger = Logger.getLogger(ClusterServiceServletAdapter.class);
private static final int DEFAULT_SERVICE_PORT = 9090;
private static final int DEFAULT_REQUEST_TIMEOUT = 300; // 300 seconds
private static final int DEFAULT_REQUEST_TIMEOUT = 300; // 300 seconds
@Inject
private ClusterManager _manager;

View File

@ -31,16 +31,16 @@ import com.cloud.utils.Profiler;
//
// Example of using dynamic named locks
//
// GlobalLock lock = GlobalLock.getInternLock("some table name" + rowId);
//
// if(lock.lock()) {
// try {
// do something
// } finally {
// lock.unlock();
// }
// }
// lock.releaseRef();
// GlobalLock lock = GlobalLock.getInternLock("some table name" + rowId);
//
// if(lock.lock()) {
// try {
// do something
// } finally {
// lock.unlock();
// }
// }
// lock.releaseRef();
//
public class GlobalLock {
protected final static Logger s_logger = Logger.getLogger(GlobalLock.class);

View File

@ -49,12 +49,12 @@ public class TransactionContextBuilderTest {
DbAnnotatedBase base = ComponentContext.inject(new DbAnnotatedBase());
base.MethodWithClassDbAnnotated();
/*
Map<String, DbAnnotatedBase> components = ComponentContext.getApplicationContext().getBeansOfType(DbAnnotatedBase.class);
for(Map.Entry<String, DbAnnotatedBase> entry : components.entrySet()) {
System.out.println(entry.getKey());
entry.getValue().MethodWithClassDbAnnotated();
}
/*
Map<String, DbAnnotatedBase> components = ComponentContext.getApplicationContext().getBeansOfType(DbAnnotatedBase.class);
for(Map.Entry<String, DbAnnotatedBase> entry : components.entrySet()) {
System.out.println(entry.getKey());
entry.getValue().MethodWithClassDbAnnotated();
}
*/
for (DbAnnotatedBase entry : _list) {
entry.MethodWithClassDbAnnotated();

View File

@ -26,7 +26,7 @@ public class AsyncCallFuture<T> implements Future<T>, AsyncCompletionCallback<T>
Object _completed = new Object();
boolean _done = false;
T _resultObject; // we will store a copy of the result object
T _resultObject; // we will store a copy of the result object
public AsyncCallFuture() {
}

View File

@ -35,7 +35,7 @@ public class RpcProviderImpl implements RpcProvider {
private TransportProvider _transportProvider;
private String _transportAddress;
private RpcTransportEndpoint _transportEndpoint = new RpcTransportEndpoint(); // transport attachment at RPC layer
private RpcTransportEndpoint _transportEndpoint = new RpcTransportEndpoint(); // transport attachment at RPC layer
private MessageSerializer _messageSerializer;
private List<RpcServiceEndpoint> _serviceEndpoints = new ArrayList<RpcServiceEndpoint>();

View File

@ -21,10 +21,10 @@ package org.apache.cloudstack.framework.rpc;
public interface RpcServiceEndpoint {
/*
* @return
* true call has been handled
* false can not find the call handler
* true call has been handled
* false can not find the call handler
* @throws
* RpcException, exception when
* RpcException, exception when
*/
boolean onCallReceive(RpcServerCall call);
}

View File

@ -26,13 +26,13 @@ public class AsyncSampleListenerStyleCaller {
public void MethodThatWillCallAsyncMethod() {
String vol = new String();
/* _ds.createVolume(vol,
new AsyncCompletionCallback<String>() {
@Override
public void complete(String resultObject) {
// TODO Auto-generated method stub
}
});*/
/* _ds.createVolume(vol,
new AsyncCompletionCallback<String>() {
@Override
public void complete(String resultObject) {
// TODO Auto-generated method stub
}
});*/
}
}

View File

@ -32,7 +32,7 @@ public class ClientOnlyEventDrivenStyle {
String cmd = new String();
RpcCallbackDispatcher<ClientOnlyEventDrivenStyle> callbackDispatcher = RpcCallbackDispatcher.create(this);
callbackDispatcher.setCallback(callbackDispatcher.getTarget().OnAsyncCallRpcServiceCallback(null, null));
_rpcProvider.newCall("host-2").setCommand("TestCommand").setCommandArg(cmd).setTimeout(10000).setCallbackDispatcher(callbackDispatcher).setContext("Context Object") // save context object for callback handler
_rpcProvider.newCall("host-2").setCommand("TestCommand").setCommandArg(cmd).setTimeout(10000).setCallbackDispatcher(callbackDispatcher).setContext("Context Object") // save context object for callback handler
.apply();
}

View File

@ -20,8 +20,8 @@ import com.cloud.utils.component.Adapter;
//
// We extend it from Adapter interface for
// 1) getName()/setName()
// 2) Confirming to general adapter pattern used across CloudStack
// 1) getName()/setName()
// 2) Confirming to general adapter pattern used across CloudStack
//
public interface AsyncJobDispatcher extends Adapter {
void runJob(AsyncJob job);

View File

@ -75,7 +75,7 @@ public interface AsyncJobManager extends Manager {
*
* @param jobId upper job that is going to wait the completion of a down-level job
* @param joinJobId down-level job
* @Param wakeupHandler wake-up handler
* @Param wakeupHandler wake-up handler
* @Param wakeupDispatcher wake-up dispatcher
* @param wakeupTopicsOnMessageBus
* @param wakeupIntervalInMilliSeconds
@ -97,11 +97,11 @@ public interface AsyncJobManager extends Manager {
*
* @param joinJobId down-level job for upper level job to join with
* @param joinStatus AsyncJobConstants status code to indicate success or failure of the
* down-level job
* down-level job
* @param joinResult object-stream serialized result object
* this is primarily used by down-level job to pass error exception objects
* for legacy code to work. To help pass exception object easier, we use
* object-stream based serialization instead of GSON
* this is primarily used by down-level job to pass error exception objects
* for legacy code to work. To help pass exception object easier, we use
* object-stream based serialization instead of GSON
*/
void completeJoin(long joinJobId, JobInfo.Status joinStatus, String joinResult);
@ -118,7 +118,7 @@ public interface AsyncJobManager extends Manager {
* @param timeoutInMiliseconds time out to break out the whole wait process
* @param predicate
* @return true, predicate condition is satisfied
* false, wait is timed out
* false, wait is timed out
*/
boolean waitAndCheck(AsyncJob job, String[] wakupTopicsOnMessageBus, long checkIntervalInMilliSeconds, long timeoutInMiliseconds, Predicate predicate);

View File

@ -38,10 +38,10 @@ public interface AsyncJobJoinMapDao extends GenericDao<AsyncJobJoinMapVO, Long>
void completeJoin(long joinJobId, JobInfo.Status joinStatus, String joinResult, long completeMsid);
// List<Long> wakeupScan();
// List<Long> wakeupScan();
List<Long> findJobsToWake(long joinedJobId);
List<Long> findJobsToWakeBetween(Date cutDate);
// List<Long> wakeupByJoinedJobCompletion(long joinedJobId);
// List<Long> wakeupByJoinedJobCompletion(long joinedJobId);
}

View File

@ -82,7 +82,7 @@ public class AsyncJobJoinMapDaoImpl extends GenericDaoBase<AsyncJobJoinMapVO, Lo
record.setJoinMsid(joinMsid);
record.setJoinStatus(JobInfo.Status.IN_PROGRESS);
record.setSyncSourceId(syncSourceId);
record.setWakeupInterval(wakeupIntervalMs / 1000); // convert millisecond to second
record.setWakeupInterval(wakeupIntervalMs / 1000); // convert millisecond to second
record.setWakeupHandler(wakeupHandler);
record.setWakeupDispatcher(wakeupDispatcher);
if (wakeupHandler != null) {
@ -149,63 +149,63 @@ public class AsyncJobJoinMapDaoImpl extends GenericDaoBase<AsyncJobJoinMapVO, Lo
update(ub, sc, null);
}
// @Override
// @Override
// public List<Long> wakeupScan() {
// List<Long> standaloneList = new ArrayList<Long>();
// List<Long> standaloneList = new ArrayList<Long>();
//
// Date cutDate = DateUtil.currentGMTTime();
// Date cutDate = DateUtil.currentGMTTime();
//
// TransactionLegacy txn = TransactionLegacy.currentTxn();
// TransactionLegacy txn = TransactionLegacy.currentTxn();
// PreparedStatement pstmt = null;
// try {
// txn.start();
// txn.start();
//
// //
// // performance sensitive processing, do it in plain SQL
// //
// String sql = "UPDATE async_job SET job_pending_signals=? WHERE id IN " +
// "(SELECT job_id FROM async_job_join_map WHERE next_wakeup < ? AND expiration > ?)";
// pstmt = txn.prepareStatement(sql);
// pstmt.setInt(1, AsyncJob.Constants.SIGNAL_MASK_WAKEUP);
// pstmt.setString(2, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate));
// pstmt.setString(3, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate));
// pstmt.executeUpdate();
// pstmt.close();
// //
// // performance sensitive processing, do it in plain SQL
// //
// String sql = "UPDATE async_job SET job_pending_signals=? WHERE id IN " +
// "(SELECT job_id FROM async_job_join_map WHERE next_wakeup < ? AND expiration > ?)";
// pstmt = txn.prepareStatement(sql);
// pstmt.setInt(1, AsyncJob.Constants.SIGNAL_MASK_WAKEUP);
// pstmt.setString(2, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate));
// pstmt.setString(3, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate));
// pstmt.executeUpdate();
// pstmt.close();
//
// sql = "UPDATE sync_queue_item SET queue_proc_msid=NULL, queue_proc_number=NULL WHERE content_id IN " +
// "(SELECT job_id FROM async_job_join_map WHERE next_wakeup < ? AND expiration > ?)";
// pstmt = txn.prepareStatement(sql);
// pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate));
// pstmt.setString(2, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate));
// pstmt.executeUpdate();
// pstmt.close();
// sql = "UPDATE sync_queue_item SET queue_proc_msid=NULL, queue_proc_number=NULL WHERE content_id IN " +
// "(SELECT job_id FROM async_job_join_map WHERE next_wakeup < ? AND expiration > ?)";
// pstmt = txn.prepareStatement(sql);
// pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate));
// pstmt.setString(2, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate));
// pstmt.executeUpdate();
// pstmt.close();
//
// sql = "SELECT job_id FROM async_job_join_map WHERE next_wakeup < ? AND expiration > ? AND job_id NOT IN (SELECT content_id FROM sync_queue_item)";
// pstmt = txn.prepareStatement(sql);
// pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate));
// pstmt.setString(2, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate));
// ResultSet rs = pstmt.executeQuery();
// while(rs.next()) {
// standaloneList.add(rs.getLong(1));
// }
// rs.close();
// pstmt.close();
// sql = "SELECT job_id FROM async_job_join_map WHERE next_wakeup < ? AND expiration > ? AND job_id NOT IN (SELECT content_id FROM sync_queue_item)";
// pstmt = txn.prepareStatement(sql);
// pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate));
// pstmt.setString(2, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate));
// ResultSet rs = pstmt.executeQuery();
// while(rs.next()) {
// standaloneList.add(rs.getLong(1));
// }
// rs.close();
// pstmt.close();
//
// // update for next wake-up
// sql = "UPDATE async_job_join_map SET next_wakeup=DATE_ADD(next_wakeup, INTERVAL wakeup_interval SECOND) WHERE next_wakeup < ? AND expiration > ?";
// pstmt = txn.prepareStatement(sql);
// pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate));
// pstmt.setString(2, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate));
// pstmt.executeUpdate();
// pstmt.close();
// // update for next wake-up
// sql = "UPDATE async_job_join_map SET next_wakeup=DATE_ADD(next_wakeup, INTERVAL wakeup_interval SECOND) WHERE next_wakeup < ? AND expiration > ?";
// pstmt = txn.prepareStatement(sql);
// pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate));
// pstmt.setString(2, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate));
// pstmt.executeUpdate();
// pstmt.close();
//
// txn.commit();
// } catch (SQLException e) {
// s_logger.error("Unexpected exception", e);
// }
// txn.commit();
// } catch (SQLException e) {
// s_logger.error("Unexpected exception", e);
// }
//
// return standaloneList;
// }
// }
@Override
public List<Long> findJobsToWake(long joinedJobId) {

View File

@ -86,12 +86,12 @@ public class AsyncJobManagerImpl extends ManagerBase implements AsyncJobManager,
private static final Logger s_logger = Logger.getLogger(AsyncJobManagerImpl.class);
private static final int ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_COOPERATION = 3; // 3 seconds
private static final int ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_SYNC = 60; // 60 seconds
private static final int ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_COOPERATION = 3; // 3 seconds
private static final int ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_SYNC = 60; // 60 seconds
private static final int MAX_ONETIME_SCHEDULE_SIZE = 50;
private static final int HEARTBEAT_INTERVAL = 2000;
private static final int GC_INTERVAL = 10000; // 10 seconds
private static final int GC_INTERVAL = 10000; // 10 seconds
@Inject
private SyncQueueItemDao _queueItemDao;
@ -357,38 +357,38 @@ public class AsyncJobManagerImpl extends ManagerBase implements AsyncJobManager,
// I removed the temporary solution already. I think my changes should fix the deadlock.
/*
------------------------
LATEST DETECTED DEADLOCK
------------------------
130625 20:03:10
*** (1) TRANSACTION:
TRANSACTION 0 98087127, ACTIVE 0 sec, process no 1489, OS thread id 139837829175040 fetching rows, thread declared inside InnoDB 494
mysql tables in use 2, locked 1
LOCK WAIT 3 lock struct(s), heap size 368, 2 row lock(s), undo log entries 1
MySQL thread id 28408, query id 368571321 localhost 127.0.0.1 cloud preparing
UPDATE async_job SET job_pending_signals=1 WHERE id IN (SELECT job_id FROM async_job_join_map WHERE join_job_id = 9)
*** (1) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 0 page no 1275 n bits 80 index `PRIMARY` of table `cloud`.`async_job` trx id 0 98087127 lock_mode X locks rec but not gap waiting
Record lock, heap no 9 PHYSICAL RECORD: n_fields 26; compact format; info bits 0
0: len 8; hex 0000000000000008; asc ;; 1: len 6; hex 000005d8b0d8; asc ;; 2: len 7; hex 00000009270110; asc ' ;; 3: len 8; hex 0000000000000002; asc ;; 4: len 8; hex 0000000000000002; asc ;; 5: SQL NULL; 6: SQL NULL; 7: len 30; hex 6f72672e6170616368652e636c6f7564737461636b2e6170692e636f6d6d; asc org.apache.cloudstack.api.comm;...(truncated); 8: len 30; hex 7b226964223a2232222c22706879736963616c6e6574776f726b6964223a; asc {"id":"2","physicalnetworkid":;...(truncated); 9: len 4; hex 80000000; asc ;; 10: len 4; hex 80000001; asc ;; 11: len 4; hex 80000000; asc ;; 12: len 4; hex 80000000; asc ;; 13: len 30; hex 6f72672e6170616368652e636c6f7564737461636b2e6170692e72657370; asc org.apache.cloudstack.api.resp;...(truncated); 14: len 8; hex 80001a6f7bb0d0a8; asc o{ ;; 15: len 8; hex 80001a6f7bb0d0a8; asc o{ ;; 16: len 8; hex 8000124f06cfd5b6; asc O ;; 17: len 8; hex 8000124f06cfd5b6; asc O ;; 18: SQL NULL; 19: SQL NULL; 20: len 30; hex 66376466396532362d323139622d346338652d393231332d393766653636; asc f7df9e26-219b-4c8e-9213-97fe66;...(truncated); 21: len 30; hex 36623238306364362d663436652d343563322d383833642d333863616439; asc 6b280cd6-f46e-45c2-883d-38cad9;...(truncated); 22: SQL NULL; 23: len 21; hex 4170694173796e634a6f6244697370617463686572; asc ApiAsyncJobDispatcher;; 24: SQL NULL; 25: len 4; hex 80000000; asc ;;
------------------------
LATEST DETECTED DEADLOCK
------------------------
130625 20:03:10
*** (1) TRANSACTION:
TRANSACTION 0 98087127, ACTIVE 0 sec, process no 1489, OS thread id 139837829175040 fetching rows, thread declared inside InnoDB 494
mysql tables in use 2, locked 1
LOCK WAIT 3 lock struct(s), heap size 368, 2 row lock(s), undo log entries 1
MySQL thread id 28408, query id 368571321 localhost 127.0.0.1 cloud preparing
UPDATE async_job SET job_pending_signals=1 WHERE id IN (SELECT job_id FROM async_job_join_map WHERE join_job_id = 9)
*** (1) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 0 page no 1275 n bits 80 index `PRIMARY` of table `cloud`.`async_job` trx id 0 98087127 lock_mode X locks rec but not gap waiting
Record lock, heap no 9 PHYSICAL RECORD: n_fields 26; compact format; info bits 0
0: len 8; hex 0000000000000008; asc ;; 1: len 6; hex 000005d8b0d8; asc ;; 2: len 7; hex 00000009270110; asc ' ;; 3: len 8; hex 0000000000000002; asc ;; 4: len 8; hex 0000000000000002; asc ;; 5: SQL NULL; 6: SQL NULL; 7: len 30; hex 6f72672e6170616368652e636c6f7564737461636b2e6170692e636f6d6d; asc org.apache.cloudstack.api.comm;...(truncated); 8: len 30; hex 7b226964223a2232222c22706879736963616c6e6574776f726b6964223a; asc {"id":"2","physicalnetworkid":;...(truncated); 9: len 4; hex 80000000; asc ;; 10: len 4; hex 80000001; asc ;; 11: len 4; hex 80000000; asc ;; 12: len 4; hex 80000000; asc ;; 13: len 30; hex 6f72672e6170616368652e636c6f7564737461636b2e6170692e72657370; asc org.apache.cloudstack.api.resp;...(truncated); 14: len 8; hex 80001a6f7bb0d0a8; asc o{ ;; 15: len 8; hex 80001a6f7bb0d0a8; asc o{ ;; 16: len 8; hex 8000124f06cfd5b6; asc O ;; 17: len 8; hex 8000124f06cfd5b6; asc O ;; 18: SQL NULL; 19: SQL NULL; 20: len 30; hex 66376466396532362d323139622d346338652d393231332d393766653636; asc f7df9e26-219b-4c8e-9213-97fe66;...(truncated); 21: len 30; hex 36623238306364362d663436652d343563322d383833642d333863616439; asc 6b280cd6-f46e-45c2-883d-38cad9;...(truncated); 22: SQL NULL; 23: len 21; hex 4170694173796e634a6f6244697370617463686572; asc ApiAsyncJobDispatcher;; 24: SQL NULL; 25: len 4; hex 80000000; asc ;;
*** (2) TRANSACTION:
TRANSACTION 0 98087128, ACTIVE 0 sec, process no 1489, OS thread id 139837671909120 fetching rows, thread declared inside InnoDB 492
mysql tables in use 2, locked 1
3 lock struct(s), heap size 368, 2 row lock(s), undo log entries 1
MySQL thread id 28406, query id 368571323 localhost 127.0.0.1 cloud preparing
UPDATE async_job SET job_pending_signals=1 WHERE id IN (SELECT job_id FROM async_job_join_map WHERE join_job_id = 8)
*** (2) HOLDS THE LOCK(S):
RECORD LOCKS space id 0 page no 1275 n bits 80 index `PRIMARY` of table `cloud`.`async_job` trx id 0 98087128 lock_mode X locks rec but not gap
Record lock, heap no 9 PHYSICAL RECORD: n_fields 26; compact format; info bits 0
0: len 8; hex 0000000000000008; asc ;; 1: len 6; hex 000005d8b0d8; asc ;; 2: len 7; hex 00000009270110; asc ' ;; 3: len 8; hex 0000000000000002; asc ;; 4: len 8; hex 0000000000000002; asc ;; 5: SQL NULL; 6: SQL NULL; 7: len 30; hex 6f72672e6170616368652e636c6f7564737461636b2e6170692e636f6d6d; asc org.apache.cloudstack.api.comm;...(truncated); 8: len 30; hex 7b226964223a2232222c22706879736963616c6e6574776f726b6964223a; asc {"id":"2","physicalnetworkid":;...(truncated); 9: len 4; hex 80000000; asc ;; 10: len 4; hex 80000001; asc ;; 11: len 4; hex 80000000; asc ;; 12: len 4; hex 80000000; asc ;; 13: len 30; hex 6f72672e6170616368652e636c6f7564737461636b2e6170692e72657370; asc org.apache.cloudstack.api.resp;...(truncated); 14: len 8; hex 80001a6f7bb0d0a8; asc o{ ;; 15: len 8; hex 80001a6f7bb0d0a8; asc o{ ;; 16: len 8; hex 8000124f06cfd5b6; asc O ;; 17: len 8; hex 8000124f06cfd5b6; asc O ;; 18: SQL NULL; 19: SQL NULL; 20: len 30; hex 66376466396532362d323139622d346338652d393231332d393766653636; asc f7df9e26-219b-4c8e-9213-97fe66;...(truncated); 21: len 30; hex 36623238306364362d663436652d343563322d383833642d333863616439; asc 6b280cd6-f46e-45c2-883d-38cad9;...(truncated); 22: SQL NULL; 23: len 21; hex 4170694173796e634a6f6244697370617463686572; asc ApiAsyncJobDispatcher;; 24: SQL NULL; 25: len 4; hex 80000000; asc ;;
*** (2) TRANSACTION:
TRANSACTION 0 98087128, ACTIVE 0 sec, process no 1489, OS thread id 139837671909120 fetching rows, thread declared inside InnoDB 492
mysql tables in use 2, locked 1
3 lock struct(s), heap size 368, 2 row lock(s), undo log entries 1
MySQL thread id 28406, query id 368571323 localhost 127.0.0.1 cloud preparing
UPDATE async_job SET job_pending_signals=1 WHERE id IN (SELECT job_id FROM async_job_join_map WHERE join_job_id = 8)
*** (2) HOLDS THE LOCK(S):
RECORD LOCKS space id 0 page no 1275 n bits 80 index `PRIMARY` of table `cloud`.`async_job` trx id 0 98087128 lock_mode X locks rec but not gap
Record lock, heap no 9 PHYSICAL RECORD: n_fields 26; compact format; info bits 0
0: len 8; hex 0000000000000008; asc ;; 1: len 6; hex 000005d8b0d8; asc ;; 2: len 7; hex 00000009270110; asc ' ;; 3: len 8; hex 0000000000000002; asc ;; 4: len 8; hex 0000000000000002; asc ;; 5: SQL NULL; 6: SQL NULL; 7: len 30; hex 6f72672e6170616368652e636c6f7564737461636b2e6170692e636f6d6d; asc org.apache.cloudstack.api.comm;...(truncated); 8: len 30; hex 7b226964223a2232222c22706879736963616c6e6574776f726b6964223a; asc {"id":"2","physicalnetworkid":;...(truncated); 9: len 4; hex 80000000; asc ;; 10: len 4; hex 80000001; asc ;; 11: len 4; hex 80000000; asc ;; 12: len 4; hex 80000000; asc ;; 13: len 30; hex 6f72672e6170616368652e636c6f7564737461636b2e6170692e72657370; asc org.apache.cloudstack.api.resp;...(truncated); 14: len 8; hex 80001a6f7bb0d0a8; asc o{ ;; 15: len 8; hex 80001a6f7bb0d0a8; asc o{ ;; 16: len 8; hex 8000124f06cfd5b6; asc O ;; 17: len 8; hex 8000124f06cfd5b6; asc O ;; 18: SQL NULL; 19: SQL NULL; 20: len 30; hex 66376466396532362d323139622d346338652d393231332d393766653636; asc f7df9e26-219b-4c8e-9213-97fe66;...(truncated); 21: len 30; hex 36623238306364362d663436652d343563322d383833642d333863616439; asc 6b280cd6-f46e-45c2-883d-38cad9;...(truncated); 22: SQL NULL; 23: len 21; hex 4170694173796e634a6f6244697370617463686572; asc ApiAsyncJobDispatcher;; 24: SQL NULL; 25: len 4; hex 80000000; asc ;;
*** (2) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 0 page no 1275 n bits 80 index `PRIMARY` of table `cloud`.`async_job` trx id 0 98087128 lock_mode X locks rec but not gap waiting
Record lock, heap no 10 PHYSICAL RECORD: n_fields 26; compact format; info bits 0
0: len 8; hex 0000000000000009; asc ;; 1: len 6; hex 000005d8b0d7; asc ;; 2: len 7; hex 00000009280110; asc ( ;; 3: len 8; hex 0000000000000002; asc ;; 4: len 8; hex 0000000000000002; asc ;; 5: SQL NULL; 6: SQL NULL; 7: len 30; hex 6f72672e6170616368652e636c6f7564737461636b2e6170692e636f6d6d; asc org.apache.cloudstack.api.comm;...(truncated); 8: len 30; hex 7b226964223a2233222c22706879736963616c6e6574776f726b6964223a; asc {"id":"3","physicalnetworkid":;...(truncated); 9: len 4; hex 80000000; asc ;; 10: len 4; hex 80000001; asc ;; 11: len 4; hex 80000000; asc ;; 12: len 4; hex 80000000; asc ;; 13: len 30; hex 6f72672e6170616368652e636c6f7564737461636b2e6170692e72657370; asc org.apache.cloudstack.api.resp;...(truncated); 14: len 8; hex 80001a6f7bb0d0a8; asc o{ ;; 15: len 8; hex 80001a6f7bb0d0a8; asc o{ ;; 16: len 8; hex 8000124f06cfd5b6; asc O ;; 17: len 8; hex 8000124f06cfd5b6; asc O ;; 18: SQL NULL; 19: SQL NULL; 20: len 30; hex 62313065306432342d336233352d343663622d386361622d623933623562; asc b10e0d24-3b35-46cb-8cab-b93b5b;...(truncated); 21: len 30; hex 39353664383563632d383336622d346663612d623738622d646238343739; asc 956d85cc-836b-4fca-b78b-db8479;...(truncated); 22: SQL NULL; 23: len 21; hex 4170694173796e634a6f6244697370617463686572; asc ApiAsyncJobDispatcher;; 24: SQL NULL; 25: len 4; hex 80000000; asc ;;
*** (2) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 0 page no 1275 n bits 80 index `PRIMARY` of table `cloud`.`async_job` trx id 0 98087128 lock_mode X locks rec but not gap waiting
Record lock, heap no 10 PHYSICAL RECORD: n_fields 26; compact format; info bits 0
0: len 8; hex 0000000000000009; asc ;; 1: len 6; hex 000005d8b0d7; asc ;; 2: len 7; hex 00000009280110; asc ( ;; 3: len 8; hex 0000000000000002; asc ;; 4: len 8; hex 0000000000000002; asc ;; 5: SQL NULL; 6: SQL NULL; 7: len 30; hex 6f72672e6170616368652e636c6f7564737461636b2e6170692e636f6d6d; asc org.apache.cloudstack.api.comm;...(truncated); 8: len 30; hex 7b226964223a2233222c22706879736963616c6e6574776f726b6964223a; asc {"id":"3","physicalnetworkid":;...(truncated); 9: len 4; hex 80000000; asc ;; 10: len 4; hex 80000001; asc ;; 11: len 4; hex 80000000; asc ;; 12: len 4; hex 80000000; asc ;; 13: len 30; hex 6f72672e6170616368652e636c6f7564737461636b2e6170692e72657370; asc org.apache.cloudstack.api.resp;...(truncated); 14: len 8; hex 80001a6f7bb0d0a8; asc o{ ;; 15: len 8; hex 80001a6f7bb0d0a8; asc o{ ;; 16: len 8; hex 8000124f06cfd5b6; asc O ;; 17: len 8; hex 8000124f06cfd5b6; asc O ;; 18: SQL NULL; 19: SQL NULL; 20: len 30; hex 62313065306432342d336233352d343663622d386361622d623933623562; asc b10e0d24-3b35-46cb-8cab-b93b5b;...(truncated); 21: len 30; hex 39353664383563632d383336622d346663612d623738622d646238343739; asc 956d85cc-836b-4fca-b78b-db8479;...(truncated); 22: SQL NULL; 23: len 21; hex 4170694173796e634a6f6244697370617463686572; asc ApiAsyncJobDispatcher;; 24: SQL NULL; 25: len 4; hex 80000000; asc ;;
*** WE ROLL BACK TRANSACTION (2)
*** WE ROLL BACK TRANSACTION (2)
*/
_joinMapDao.completeJoin(joinJobId, joinStatus, joinResult, getMsid());

View File

@ -972,7 +972,7 @@ public class NetappManagerImpl extends ManagerBase implements NetappManager {
s_logger.warn("Unable to associate LUN ", uhe);
throw new ServerException("Unable to associate LUN", uhe);
} catch (NaAPIFailedException naf) {
if (naf.getErrno() == 9008) { //initiator group already contains node
if (naf.getErrno() == 9008) { //initiator group already contains node
return returnVal;
}
s_logger.warn("Unable to associate LUN ", naf);

View File

@ -77,7 +77,7 @@ public class BaremetalDnsmasqResource extends BaremetalDhcpResourceBase {
/*
String prepareCmd = String.format("sh /usr/bin/prepare_dnsmasq.sh %1$s %2$s %3$s", _gateway, _dns, _ip);
if (!SSHCmdHelper.sshExecuteCmd(sshConnection, prepareCmd)) {
throw new ConfigurationException("prepare dnsmasq at " + _ip + " failed");
throw new ConfigurationException("prepare dnsmasq at " + _ip + " failed");
}
*/

View File

@ -294,7 +294,7 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S
@Override
public final PingCommand getCurrentStatus(final long id) {
// TODO, need to report VM states on host
// TODO, need to report VM states on host
PingCommand pingCmd = new PingRoutingCommand(getType(), id, null, null);
if (s_logger.isDebugEnabled()) {

View File

@ -194,7 +194,7 @@ public class HypervDirectConnectResourceTest {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Assert.assertTrue(
"Need to put a sample working virtual disk at "
+ testVolWorks.getPath(), testVolWorks.exists());

View File

@ -262,10 +262,10 @@ public class OvmResourceBase implements ServerResource, HypervisorResource {
/*
try {
_canBridgeFirewall = canBridgeFirewall();
_canBridgeFirewall = canBridgeFirewall();
} catch (XmlRpcException e) {
s_logger.error("Failed to detect whether the host supports security groups.", e);
_canBridgeFirewall = false;
s_logger.error("Failed to detect whether the host supports security groups.", e);
_canBridgeFirewall = false;
}
*/

View File

@ -29,11 +29,11 @@ public class Test {
public static void main(String[] args) {
try {
/*Connection c = new Connection("192.168.105.155", "oracle", "password");
Utils util = new UtilsImpl(c);
Utils util = new UtilsImpl(c);
Storage storage = new StorageImpl(c);
String[] res = util.listDir("/etc", 1);
for (String s : res) {
System.out.println(s);
System.out.println(s);
}
@ -51,7 +51,7 @@ public class Test {
System.out.println(pool.getAgentVersion());
String[] srs = storage.listSr();
for (int i=0; i<srs.length; i++) {
System.out.println(srs[i]);
System.out.println(srs[i]);
}
String spuuid = storage.createSp(StorageType.OVSSPNFS, "192.168.110.232:/export/frank/nfs");
System.out.println(spuuid);
@ -95,11 +95,11 @@ public class Test {
//OvmHost.Details d = Coder.fromJson(txt, OvmHost.Details.class);
//OvmHost.Details d = OvmHost.getDetails(c);
//System.out.println(Coder.toJson(d));
// OvmStoragePool.Details pool = new OvmStoragePool.Details();
// pool.path = "192.168.110.232:/export/frank/ovs";
// pool.type = OvmStoragePool.NFS;
// pool.uuid = "123";
// System.out.println(pool.toJson());
// OvmStoragePool.Details pool = new OvmStoragePool.Details();
// pool.path = "192.168.110.232:/export/frank/ovs";
// pool.type = OvmStoragePool.NFS;
// pool.uuid = "123";
// System.out.println(pool.toJson());
String cmd = null;
System.out.println(args.length);
@ -169,12 +169,12 @@ public class Test {
l.add("4b4d8951-f0b6-36c5-b4f3-a82ff2611c65");
System.out.println(Coder.toJson(l));
// Map<String, String> res = OvmHost.getPerformanceStats(c, "xenbr0");
// System.out.println(res.toString());
// String stxt = "{\"vifs\": [{\"bridge\": \"xenbr0\", \"mac\": \"00:16:3E:5C:B1:D1\", \"type\": \"netfront\"}], \"powerState\": \"RUNNING\", \"disks\": [], \"cpuNum\": 1, \"memory\": 536870912, \"rootDisk\": {\"path\": \"/var/ovs/mount/60D0985974CA425AAF5D01A1F161CC8B/running_pool/MyTest/System.img\", \"type\": \"w\"}}";
// OvmVm.Details ddd = Coder.fromJson(stxt, OvmVm.Details.class);
// System.out.println(ddd.vifs.size());
// System.out.println(ddd.rootDisk.path);
// Map<String, String> res = OvmHost.getPerformanceStats(c, "xenbr0");
// System.out.println(res.toString());
// String stxt = "{\"vifs\": [{\"bridge\": \"xenbr0\", \"mac\": \"00:16:3E:5C:B1:D1\", \"type\": \"netfront\"}], \"powerState\": \"RUNNING\", \"disks\": [], \"cpuNum\": 1, \"memory\": 536870912, \"rootDisk\": {\"path\": \"/var/ovs/mount/60D0985974CA425AAF5D01A1F161CC8B/running_pool/MyTest/System.img\", \"type\": \"w\"}}";
// OvmVm.Details ddd = Coder.fromJson(stxt, OvmVm.Details.class);
// System.out.println(ddd.vifs.size());
// System.out.println(ddd.rootDisk.path);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();

View File

@ -65,14 +65,14 @@ public class VmwareCleanupMaid {
_vmName = vmName;
}
// @Override
// public int cleanup(CheckPointManager checkPointMgr) {
//
// // save a check-point in case we crash at current run so that we won't lose it
// _checkPoint = checkPointMgr.pushCheckPoint(new VmwareCleanupMaid(_vCenterAddress, _dcMorValue, _vmName));
// addLeftOverVM(this);
// return 0;
// }
// @Override
// public int cleanup(CheckPointManager checkPointMgr) {
//
// // save a check-point in case we crash at current run so that we won't lose it
// _checkPoint = checkPointMgr.pushCheckPoint(new VmwareCleanupMaid(_vCenterAddress, _dcMorValue, _vmName));
// addLeftOverVM(this);
// return 0;
// }
public String getCleanupProcedure() {
return null;
@ -134,7 +134,7 @@ public class VmwareCleanupMaid {
} catch (Throwable e) {
s_logger.warn("Unable to destroy left over dummy VM " + cleanupMaid.getVmName());
} finally {
// FIXME mgr.popCleanupCheckpoint(cleanupMaid.getCheckPoint());
// FIXME mgr.popCleanupCheckpoint(cleanupMaid.getCheckPoint());
}
}

View File

@ -131,8 +131,8 @@ import com.cloud.vm.DomainRouterVO;
public class VmwareManagerImpl extends ManagerBase implements VmwareManager, VmwareStorageMount, Listener, VmwareDatacenterService {
private static final Logger s_logger = Logger.getLogger(VmwareManagerImpl.class);
private static final int STARTUP_DELAY = 60000; // 60 seconds
private static final long DEFAULT_HOST_SCAN_INTERVAL = 600000; // every 10 minutes
private static final int STARTUP_DELAY = 60000; // 60 seconds
private static final long DEFAULT_HOST_SCAN_INTERVAL = 600000; // every 10 minutes
private long _hostScanInterval = DEFAULT_HOST_SCAN_INTERVAL;
int _timeout;
@ -190,7 +190,7 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
String _managemetPortGroupName;
String _defaultSystemVmNicAdapterType = VirtualEthernetCardType.E1000.toString();
String _recycleHungWorker = "false";
long _hungWorkerTimeout = 7200000; // 2 hour
long _hungWorkerTimeout = 7200000; // 2 hour
int _additionalPortRangeStart;
int _additionalPortRangeSize;
int _routerExtraPublicNics = 2;
@ -472,7 +472,7 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
hostSpec.setUserName(userName);
hostSpec.setPassword(password);
hostSpec.setHostName(host);
hostSpec.setForce(true); // forcely take over the host
hostSpec.setForce(true); // forcely take over the host
ManagedObjectReference morTask = serviceContext.getService().addHostTask(morCluster, hostSpec, true, null, null);
boolean taskResult = vclient.waitForTask(morTask);
@ -600,9 +600,9 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
// there are pending tasks on the subject VM
/*
if(System.currentTimeMillis() - startTick > _hungWorkerTimeout) {
if(s_logger.isInfoEnabled())
s_logger.info("Worker VM expired, seconds elapsed: " + (System.currentTimeMillis() - startTick) / 1000);
return true;
if(s_logger.isInfoEnabled())
s_logger.info("Worker VM expired, seconds elapsed: " + (System.currentTimeMillis() - startTick) / 1000);
return true;
}
*/
return false;

View File

@ -116,7 +116,7 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
Script command = new Script(false, "tar", 0, s_logger);
command.setWorkDir(path);
command.add("-cf", name + ".ova");
command.add(name + ".ovf"); // OVF file should be the first file in OVA archive
command.add(name + ".ovf"); // OVF file should be the first file in OVA archive
command.add(name + "-disk0.vmdk");
s_logger.info("Package OVA with commmand: " + command.toString());
@ -214,7 +214,7 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
Script command = new Script(false, "tar", 0, s_logger);
command.setWorkDir(installFullPath);
command.add("-cf", volumeUuid + ".ova");
command.add(volumeUuid + ".ovf"); // OVF file should be the first file in OVA archive
command.add(volumeUuid + ".ovf"); // OVF file should be the first file in OVA archive
command.add(volumeUuid + "-disk0.vmdk");
command.execute();

View File

@ -313,9 +313,9 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
protected String _name;
protected final long _ops_timeout = 900000; // 15 minutes time out to time
protected final long _ops_timeout = 900000; // 15 minutes time out to time
protected final int _shutdown_waitMs = 300000; // wait up to 5 minutes for shutdown
protected final int _shutdown_waitMs = 300000; // wait up to 5 minutes for shutdown
@Inject
protected VolumeOrchestrationService volMgr;

View File

@ -44,7 +44,7 @@ public interface CiscoNexusVSMDeviceDao extends GenericDao<CiscoNexusVSMDeviceVO
/**
* Return a list of VSM devices that use the same VLAN for no matter what interface. Unlikely, but oh well.
* @param vlanId
* - Needs to filter results by the invoker's account Id. So we may end up adding another param
* - Needs to filter results by the invoker's account Id. So we may end up adding another param
* or may query it in the function.
* @return
*/
@ -67,44 +67,44 @@ public interface CiscoNexusVSMDeviceDao extends GenericDao<CiscoNexusVSMDeviceVO
* Below is a big list of other functions that we may need, but will declare/define/implement once we implement
* the functions above. Pasting those below to not lose track of them.
*
* ListbyZoneId()
- Lists all VSMs in the specified zone.
* ListbyZoneId()
- Lists all VSMs in the specified zone.
ListbyAccountId()
- Lists all VSMs owned by the specified Account.
- Lists all VSMs owned by the specified Account.
ListbyStorageVLAN(vlanId)
- Lists all VSMs whose storage VLAN matches the specified VLAN.
- Filters results by the invoker's account Id.
- Lists all VSMs whose storage VLAN matches the specified VLAN.
- Filters results by the invoker's account Id.
ListbyControlVLAN(vlanId)
- Lists all VSMs whose control VLAN matches the specified VLAN.
- Filters results by the invoker's account Id.
- Lists all VSMs whose control VLAN matches the specified VLAN.
- Filters results by the invoker's account Id.
ListbyPacketVLAN(vlanId)
- Lists all VSMs whose Packet VLAN matches the specified VLAN.
- Filters results by the invoker's account Id.
- Lists all VSMs whose Packet VLAN matches the specified VLAN.
- Filters results by the invoker's account Id.
ListbyConfigMode(mode)
- Lists all VSMs which are currently configured in the specified mode (standalone/HA).
- Filters results by the invoker's account Id.
ListbyConfigMode(mode)
- Lists all VSMs which are currently configured in the specified mode (standalone/HA).
- Filters results by the invoker's account Id.
ListbyConfigState(configState)
- Lists all VSMs which are currently configured in the specified state (primary/standby).
- Filters results by the invoker's account Id.
- Lists all VSMs which are currently configured in the specified state (primary/standby).
- Filters results by the invoker's account Id.
ListbyDeviceState(deviceState)
- Lists all VSMs which are currently in the specified device state (enabled/disabled).
- Filters results by the invoker's account Id.
- Lists all VSMs which are currently in the specified device state (enabled/disabled).
- Filters results by the invoker's account Id.
getBySwitchDomainId(domId)
- Retrieves the VSM with the specified switch domain Id. Each VSM has a unique switch domain Id, just like a real physical switch would.
- Filters results by invoker's account id.
- Retrieves the VSM with the specified switch domain Id. Each VSM has a unique switch domain Id, just like a real physical switch would.
- Filters results by invoker's account id.
getbySwitchName(vsmName)
- Retrieves the VSM's VO object by the specified vsmName.
- Retrieves the VSM's VO object by the specified vsmName.
*/
}

View File

@ -171,7 +171,7 @@ public class CiscoNexusVSMElement extends CiscoNexusVSMDeviceManagerImpl impleme
@Override
public List<CiscoNexusVSMDeviceVO> getCiscoNexusVSMs(ListCiscoNexusVSMsCmd cmd) {
// If clusterId is defined, then it takes precedence, and we will return
// the VSM associated with this cluster.
// the VSM associated with this cluster.
Long clusterId = cmd.getClusterId();
Long zoneId = cmd.getZoneId();

View File

@ -311,7 +311,7 @@ public class VmwareStorageProcessor implements StorageProcessor {
throw new Exception("Unable to create a dummy VM for volume creation");
}
String vmdkFilePair[] = VmwareStorageLayoutHelper.getVmdkFilePairDatastorePath(dsMo, null, vmdkName, VmwareStorageLayoutType.CLOUDSTACK_LEGACY, true // we only use the first file in the pair, linked or not will not matter
String vmdkFilePair[] = VmwareStorageLayoutHelper.getVmdkFilePairDatastorePath(dsMo, null, vmdkName, VmwareStorageLayoutType.CLOUDSTACK_LEGACY, true // we only use the first file in the pair, linked or not will not matter
);
String volumeDatastorePath = vmdkFilePair[0];
synchronized (this) {

View File

@ -132,7 +132,7 @@ public class VmwareStorageMotionStrategy implements DataMotionStrategy {
// Migration across cluster needs to be done in three phases.
// 1. Send a migrate command to source resource to initiate migration
// Run validations against target!!
// Run validations against target!!
// 2. Complete the process. Update the volume details.
MigrateWithStorageCommand migrateWithStorageCmd = new MigrateWithStorageCommand(to, volumeToFilerto, destHost.getGuid());
MigrateWithStorageAnswer migrateWithStorageAnswer = (MigrateWithStorageAnswer)agentMgr.send(srcHost.getId(), migrateWithStorageCmd);

View File

@ -591,7 +591,7 @@ public class F5BigIpResource implements ServerResource {
}
}
// Login
// Login
private void login() throws ExecutionException {
try {

View File

@ -74,24 +74,24 @@ import com.cloud.network.IpAddress;
public class ContrailElementImpl extends AdapterBase
implements ContrailElement, IpDeployer, StaticNatServiceProvider {
private static final Map<Service, Map<Capability, String>> _capabilities = InitCapabilities();
private static final Map<Service, Map<Capability, String>> _capabilities = InitCapabilities();
@Inject ContrailManager _manager;
@Inject NicDao _nicDao;
@Inject ServerDBSync _dbSync;
private static final Logger s_logger =
Logger.getLogger(ContrailElement.class);
@Inject ContrailManager _manager;
@Inject NicDao _nicDao;
@Inject ServerDBSync _dbSync;
private static final Logger s_logger =
Logger.getLogger(ContrailElement.class);
@Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
s_logger.debug("configure");
return true;
s_logger.debug("configure");
return true;
}
// PluggableService
@Override
public List<Class<?>> getCommands() {
List<Class<?>> cmdList = new ArrayList<Class<?>>();
List<Class<?>> cmdList = new ArrayList<Class<?>>();
cmdList.add(CreateServiceInstanceCmd.class);
return cmdList;
}
@ -103,212 +103,212 @@ public class ContrailElementImpl extends AdapterBase
}
private static Map<Service, Map<Capability, String>> InitCapabilities() {
Map<Service, Map<Capability, String>> capabilities = new HashMap<Service, Map<Capability, String>>();
capabilities.put(Service.Connectivity, null);
capabilities.put(Service.Dhcp, new HashMap<Capability, String>());
Map<Service, Map<Capability, String>> capabilities = new HashMap<Service, Map<Capability, String>>();
capabilities.put(Service.Connectivity, null);
capabilities.put(Service.Dhcp, new HashMap<Capability, String>());
capabilities.put(Service.StaticNat, null);
capabilities.put(Service.SourceNat, null);
return capabilities;
return capabilities;
}
@Override
public Map<Service, Map<Capability, String>> getCapabilities() {
return _capabilities;
}
@Override
public Map<Service, Map<Capability, String>> getCapabilities() {
return _capabilities;
}
/**
* Network add/update.
*/
@Override
public boolean implement(Network network, NetworkOffering offering,
DeployDestination dest, ReservationContext context)
throws ConcurrentOperationException, ResourceUnavailableException,
InsufficientCapacityException {
s_logger.debug("NetworkElement implement: " + network.getName() + ", traffic type: " + network.getTrafficType());
if (network.getTrafficType() == TrafficType.Guest) {
s_logger.debug("ignore network " + network.getName());
return true;
}
VirtualNetworkModel vnModel = _manager.getDatabase().lookupVirtualNetwork(network.getUuid(),
_manager.getCanonicalName(network), network.getTrafficType());
if (vnModel == null) {
vnModel = new VirtualNetworkModel(network, network.getUuid(),
_manager.getCanonicalName(network), network.getTrafficType());
vnModel.setProperties(_manager.getModelController(), network);
}
try {
if (!vnModel.verify(_manager.getModelController())) {
vnModel.update(_manager.getModelController());
}
_manager.getDatabase().getVirtualNetworks().add(vnModel);
} catch (Exception ex) {
s_logger.warn("virtual-network update: ", ex);
}
return true;
}
@Override
public boolean prepare(Network network, NicProfile nicProfile,
VirtualMachineProfile vm,
DeployDestination dest, ReservationContext context)
throws ConcurrentOperationException, ResourceUnavailableException,
InsufficientCapacityException {
s_logger.debug("NetworkElement prepare: " + network.getName() + ", traffic type: " + network.getTrafficType());
if (network.getTrafficType() == TrafficType.Guest) {
s_logger.debug("ignore network " + network.getName());
return true;
}
s_logger.debug("network: " + network.getId());
VirtualNetworkModel vnModel = _manager.getDatabase().lookupVirtualNetwork(network.getUuid(),
/**
* Network add/update.
*/
@Override
public boolean implement(Network network, NetworkOffering offering,
DeployDestination dest, ReservationContext context)
throws ConcurrentOperationException, ResourceUnavailableException,
InsufficientCapacityException {
s_logger.debug("NetworkElement implement: " + network.getName() + ", traffic type: " + network.getTrafficType());
if (network.getTrafficType() == TrafficType.Guest) {
s_logger.debug("ignore network " + network.getName());
return true;
}
VirtualNetworkModel vnModel = _manager.getDatabase().lookupVirtualNetwork(network.getUuid(),
_manager.getCanonicalName(network), network.getTrafficType());
if (vnModel == null) {
// There is no notification after a physical network is associated with the VRouter NetworkOffering
// this may be the first time we see this network.
return false;
}
VirtualMachineModel vmModel = _manager.getDatabase().lookupVirtualMachine(vm.getUuid());
if (vmModel == null) {
VMInstanceVO vmVo = (VMInstanceVO) vm.getVirtualMachine();
vmModel = new VirtualMachineModel(vmVo, vm.getUuid());
vmModel.setProperties(_manager.getModelController(), vmVo);
}
if (vnModel == null) {
vnModel = new VirtualNetworkModel(network, network.getUuid(),
_manager.getCanonicalName(network), network.getTrafficType());
vnModel.setProperties(_manager.getModelController(), network);
}
try {
if (!vnModel.verify(_manager.getModelController())) {
vnModel.update(_manager.getModelController());
}
_manager.getDatabase().getVirtualNetworks().add(vnModel);
} catch (Exception ex) {
s_logger.warn("virtual-network update: ", ex);
}
return true;
}
NicVO nic = _nicDao.findById(nicProfile.getId());
assert nic != null;
@Override
public boolean prepare(Network network, NicProfile nicProfile,
VirtualMachineProfile vm,
DeployDestination dest, ReservationContext context)
throws ConcurrentOperationException, ResourceUnavailableException,
InsufficientCapacityException {
VMInterfaceModel vmiModel = vmModel.getVMInterface(nic.getUuid());
if (vmiModel == null) {
vmiModel = new VMInterfaceModel(nic.getUuid());
vmiModel.addToVirtualMachine(vmModel);
s_logger.debug("NetworkElement prepare: " + network.getName() + ", traffic type: " + network.getTrafficType());
if (network.getTrafficType() == TrafficType.Guest) {
s_logger.debug("ignore network " + network.getName());
return true;
}
s_logger.debug("network: " + network.getId());
VirtualNetworkModel vnModel = _manager.getDatabase().lookupVirtualNetwork(network.getUuid(),
_manager.getCanonicalName(network), network.getTrafficType());
if (vnModel == null) {
// There is no notification after a physical network is associated with the VRouter NetworkOffering
// this may be the first time we see this network.
return false;
}
VirtualMachineModel vmModel = _manager.getDatabase().lookupVirtualMachine(vm.getUuid());
if (vmModel == null) {
VMInstanceVO vmVo = (VMInstanceVO) vm.getVirtualMachine();
vmModel = new VirtualMachineModel(vmVo, vm.getUuid());
vmModel.setProperties(_manager.getModelController(), vmVo);
}
NicVO nic = _nicDao.findById(nicProfile.getId());
assert nic != null;
VMInterfaceModel vmiModel = vmModel.getVMInterface(nic.getUuid());
if (vmiModel == null) {
vmiModel = new VMInterfaceModel(nic.getUuid());
vmiModel.addToVirtualMachine(vmModel);
vmiModel.addToVirtualNetwork(vnModel);
}
try {
vmiModel.build(_manager.getModelController(), (VMInstanceVO) vm.getVirtualMachine(), nic);
} catch (IOException ex) {
s_logger.warn("vm interface set", ex);
return false;
}
}
try {
vmiModel.build(_manager.getModelController(), (VMInstanceVO) vm.getVirtualMachine(), nic);
} catch (IOException ex) {
s_logger.warn("vm interface set", ex);
return false;
}
InstanceIpModel ipModel = vmiModel.getInstanceIp();
if (ipModel == null) {
ipModel = new InstanceIpModel(vm.getInstanceName(), nic.getDeviceId());
ipModel.addToVMInterface(vmiModel);
}
ipModel.setAddress(nicProfile.getIp4Address());
InstanceIpModel ipModel = vmiModel.getInstanceIp();
if (ipModel == null) {
ipModel = new InstanceIpModel(vm.getInstanceName(), nic.getDeviceId());
ipModel.addToVMInterface(vmiModel);
}
ipModel.setAddress(nicProfile.getIp4Address());
try {
vmModel.update(_manager.getModelController());
} catch (Exception ex) {
s_logger.warn("virtual-machine-update", ex);
return false;
}
_manager.getDatabase().getVirtualMachines().add(vmModel);
try {
vmModel.update(_manager.getModelController());
} catch (Exception ex) {
s_logger.warn("virtual-machine-update", ex);
return false;
}
_manager.getDatabase().getVirtualMachines().add(vmModel);
return true;
}
return true;
}
@Override
public boolean release(Network network, NicProfile nicProfile,
VirtualMachineProfile vm,
ReservationContext context) throws ConcurrentOperationException,
ResourceUnavailableException {
if (network.getTrafficType() == TrafficType.Guest) {
return true;
} else if (!_manager.isManagedPhysicalNetwork(network)) {
s_logger.debug("release ignore network " + network.getId());
return true;
}
@Override
public boolean release(Network network, NicProfile nicProfile,
VirtualMachineProfile vm,
ReservationContext context) throws ConcurrentOperationException,
ResourceUnavailableException {
if (network.getTrafficType() == TrafficType.Guest) {
return true;
} else if (!_manager.isManagedPhysicalNetwork(network)) {
s_logger.debug("release ignore network " + network.getId());
return true;
}
NicVO nic = _nicDao.findById(nicProfile.getId());
assert nic != null;
NicVO nic = _nicDao.findById(nicProfile.getId());
assert nic != null;
VirtualMachineModel vmModel = _manager.getDatabase().lookupVirtualMachine(vm.getUuid());
if (vmModel == null) {
s_logger.debug("vm " + vm.getInstanceName() + " not in local database");
return true;
}
VMInterfaceModel vmiModel = vmModel.getVMInterface(nic.getUuid());
if (vmiModel != null) {
try {
vmiModel.destroy(_manager.getModelController());
} catch (IOException ex) {
s_logger.warn("virtual-machine-interface delete", ex);
}
vmModel.removeSuccessor(vmiModel);
}
VirtualMachineModel vmModel = _manager.getDatabase().lookupVirtualMachine(vm.getUuid());
if (vmModel == null) {
s_logger.debug("vm " + vm.getInstanceName() + " not in local database");
return true;
}
VMInterfaceModel vmiModel = vmModel.getVMInterface(nic.getUuid());
if (vmiModel != null) {
try {
vmiModel.destroy(_manager.getModelController());
} catch (IOException ex) {
s_logger.warn("virtual-machine-interface delete", ex);
}
vmModel.removeSuccessor(vmiModel);
}
if (!vmModel.hasDescendents()) {
_manager.getDatabase().getVirtualMachines().remove(vmModel);
try {
vmModel.delete(_manager.getModelController());
} catch (IOException e) {
return false;
}
}
if (!vmModel.hasDescendents()) {
_manager.getDatabase().getVirtualMachines().remove(vmModel);
try {
vmModel.delete(_manager.getModelController());
} catch (IOException e) {
return false;
}
}
return true;
}
return true;
}
/**
* Network disable
*/
@Override
public boolean shutdown(Network network, ReservationContext context,
boolean cleanup) throws ConcurrentOperationException,
ResourceUnavailableException {
s_logger.debug("NetworkElement shutdown");
return true;
}
/**
* Network disable
*/
@Override
public boolean shutdown(Network network, ReservationContext context,
boolean cleanup) throws ConcurrentOperationException,
ResourceUnavailableException {
s_logger.debug("NetworkElement shutdown");
return true;
}
/**
* Network delete
*/
@Override
public boolean destroy(Network network, ReservationContext context)
throws ConcurrentOperationException, ResourceUnavailableException {
s_logger.debug("NetworkElement destroy");
return true;
}
/**
* Network delete
*/
@Override
public boolean destroy(Network network, ReservationContext context)
throws ConcurrentOperationException, ResourceUnavailableException {
s_logger.debug("NetworkElement destroy");
return true;
}
@Override
public boolean isReady(PhysicalNetworkServiceProvider provider) {
return true;
}
@Override
public boolean isReady(PhysicalNetworkServiceProvider provider) {
return true;
}
@Override
public boolean shutdownProviderInstances(
PhysicalNetworkServiceProvider provider, ReservationContext context)
throws ConcurrentOperationException, ResourceUnavailableException {
s_logger.debug("NetworkElement shutdown ProviderInstances");
return true;
}
@Override
public boolean shutdownProviderInstances(
PhysicalNetworkServiceProvider provider, ReservationContext context)
throws ConcurrentOperationException, ResourceUnavailableException {
s_logger.debug("NetworkElement shutdown ProviderInstances");
return true;
}
@Override
public boolean canEnableIndividualServices() {
return true;
}
@Override
public boolean canEnableIndividualServices() {
return true;
}
@Override
public boolean verifyServicesCombination(Set<Service> services) {
// TODO Auto-generated method stub
s_logger.debug("NetworkElement verifyServices");
s_logger.debug("Services: " + services);
return true;
}
@Override
public boolean verifyServicesCombination(Set<Service> services) {
// TODO Auto-generated method stub
s_logger.debug("NetworkElement verifyServices");
s_logger.debug("Services: " + services);
return true;
}
@Override
public IpDeployer getIpDeployer(Network network) {
return this;
return this;
}
@Override

View File

@ -76,7 +76,7 @@ public class ContrailGuru extends AdapterBase implements NetworkGuru {
@Override
public String getName() {
return "ContrailGuru";
return "ContrailGuru";
}
@Override

View File

@ -650,17 +650,17 @@ public class ContrailManagerImpl extends ManagerBase implements ContrailManager
@Override
public void createPublicNetworks() {
List<TrafficType> types = new ArrayList<TrafficType>(Arrays.asList(TrafficType.Public));
List<NetworkVO> dbNets = findJuniperManagedNetworks(types);
if (dbNets == null) {
return;
}
for (NetworkVO net: dbNets) {
VirtualNetworkModel vnModel = _database.lookupVirtualNetwork(net.getUuid(), getCanonicalName(net),
TrafficType.Public);
if (vnModel != null) {
continue;
}
List<TrafficType> types = new ArrayList<TrafficType>(Arrays.asList(TrafficType.Public));
List<NetworkVO> dbNets = findJuniperManagedNetworks(types);
if (dbNets == null) {
return;
}
for (NetworkVO net: dbNets) {
VirtualNetworkModel vnModel = _database.lookupVirtualNetwork(net.getUuid(), getCanonicalName(net),
TrafficType.Public);
if (vnModel != null) {
continue;
}
vnModel = new VirtualNetworkModel(net, net.getUuid(), getCanonicalName(net), net.getTrafficType());
vnModel.build(_controller, net);
try {
@ -678,7 +678,7 @@ public class ContrailManagerImpl extends ManagerBase implements ContrailManager
Map<String, String> providerMap = new HashMap<String, String>();
providerMap.put(Service.Connectivity.getName(), Provider.JuniperContrail.getName());
_networksDao.update(net.getId(), net, providerMap);
}
}
}
public boolean createFloatingIp(PublicIpAddress ip) {

View File

@ -531,12 +531,12 @@ public class IntegrationTestConfiguration {
AffinityGroupService mock = Mockito.mock(AffinityGroupService.class);
try {
final AffinityGroupVO gmock = new AffinityGroupVO("grp1", "grp-type", "affinity group", 1, AccountVO.ACCOUNT_ID_SYSTEM, ControlledEntity.ACLType.Account);
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
_affinityGroupDao.persist(gmock);
}
});
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
_affinityGroupDao.persist(gmock);
}
});
Mockito.when(mock.createAffinityGroupInternal(Mockito.any(String.class), Mockito.any(Long.class), Mockito.any(String.class), Mockito.any(String.class), Mockito.any(String.class))).thenReturn(gmock);
} catch (Exception e) {
e.printStackTrace();

View File

@ -67,14 +67,14 @@ public class MockAccountManager extends ManagerBase implements AccountManager {
private static final Logger s_logger =
Logger.getLogger(MockAccountManager.class);
@Inject AccountDao _accountDao;
@Inject AccountDao _accountDao;
@Inject ResourceCountDao _resourceCountDao;
@Inject AccountJoinDao _accountJoinDao;
@Inject UserDao _userDao;
UserVO _systemUser;
AccountVO _systemAccount;
@Inject UserDao _userDao;
UserVO _systemUser;
AccountVO _systemAccount;
@Override
public boolean configure(final String name, final Map<String, Object> params) throws ConfigurationException {
@ -335,38 +335,38 @@ public class MockAccountManager extends ManagerBase implements AccountManager {
return null;
}
@Override
public Account getActiveAccountById(long accountId) {
// TODO Auto-generated method stub
return null;
}
@Override
public Account getActiveAccountById(long accountId) {
// TODO Auto-generated method stub
return null;
}
@Override
public Account getAccount(long accountId) {
@Override
public Account getAccount(long accountId) {
return _systemAccount;
}
}
@Override
public Account createAccount(String accountName, short accountType,
Long domainId, String networkDomain, Map<String, String> details,
String uuid) {
final AccountVO account = new AccountVO(accountName, domainId, networkDomain, accountType, uuid);
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
@Override
public Account createAccount(String accountName, short accountType,
Long domainId, String networkDomain, Map<String, String> details,
String uuid) {
final AccountVO account = new AccountVO(accountName, domainId, networkDomain, accountType, uuid);
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
_accountDao.persist(account);
_resourceCountDao.createResourceCounts(account.getId(), ResourceLimit.ResourceOwnerType.Account);
}
});
_accountDao.persist(account);
_resourceCountDao.createResourceCounts(account.getId(), ResourceLimit.ResourceOwnerType.Account);
}
});
return account;
}
}
@Override
public void logoutUser(long userId) {
// TODO Auto-generated method stub
}
@Override
public void logoutUser(long userId) {
// TODO Auto-generated method stub
}
}

View File

@ -122,7 +122,7 @@ public class PublicNetworkTest extends TestCase {
@Test
public void testPublicNetwork() throws IOException {
DataCenter zone = _server.getZone();
DataCenter zone = _server.getZone();
List<NetworkVO> networks = _networksDao.listByZoneAndTrafficType(zone.getId(), TrafficType.Public);
assertNotNull(networks);
assertFalse(networks.isEmpty());

View File

@ -41,7 +41,7 @@ public class TestDbSetup {
public static void startMysqlServer(int port, String startMysqlScript) throws Exception {
try {
String cwd = new java.io.File(".").getCanonicalPath();
String cwd = new java.io.File(".").getCanonicalPath();
Runtime r = Runtime.getRuntime();
String script = startMysqlScript;
if (script == null) {

View File

@ -3209,7 +3209,7 @@ public class JuniperSrxResource implements ServerResource {
}
/*
* Usage
* Usage
*/
private ExternalNetworkResourceUsageAnswer getUsageAnswer(ExternalNetworkResourceUsageCommand cmd) throws ExecutionException {

View File

@ -36,7 +36,7 @@ import org.apache.cloudstack.api.response.ExternalFirewallResponse;
@APICommand(name = "listExternalFirewalls", description="List external firewall appliances.", responseObject = ExternalFirewallResponse.class)
public class ListExternalFirewallsCmd extends BaseListCmd {
public static final Logger s_logger = Logger.getLogger(ListServiceOfferingsCmd.class.getName());
public static final Logger s_logger = Logger.getLogger(ListServiceOfferingsCmd.class.getName());
private static final String s_name = "listexternalfirewallsresponse";
/////////////////////////////////////////////////////
@ -70,15 +70,15 @@ public class ListExternalFirewallsCmd extends BaseListCmd {
@Override
public void execute(){
List<? extends Host> externalFirewalls = _paElementService.listExternalFirewalls(this);
List<? extends Host> externalFirewalls = _paElementService.listExternalFirewalls(this);
ListResponse<ExternalFirewallResponse> listResponse = new ListResponse<ExternalFirewallResponse>();
List<ExternalFirewallResponse> responses = new ArrayList<ExternalFirewallResponse>();
for (Host externalFirewall : externalFirewalls) {
ExternalFirewallResponse response = _paElementService.createExternalFirewallResponse(externalFirewall);
response.setObjectName("externalfirewall");
response.setResponseName(getCommandName());
responses.add(response);
ExternalFirewallResponse response = _paElementService.createExternalFirewallResponse(externalFirewall);
response.setObjectName("externalfirewall");
response.setResponseName(getCommandName());
responses.add(response);
}
listResponse.setResponses(responses);

View File

@ -96,12 +96,12 @@ import java.io.StringWriter;
public class MockablePaloAltoResource extends PaloAltoResource {
private HashMap<String, String> context;
public void setMockContext(HashMap<String, String> context) {
this.context = context;
}
private HashMap<String, String> context;
public void setMockContext(HashMap<String, String> context) {
this.context = context;
}
/* Fake the calls to the Palo Alto API */
/* Fake the calls to the Palo Alto API */
protected String request(PaloAltoMethod method, Map<String, String> params) throws ExecutionException {
if (method != PaloAltoMethod.GET && method != PaloAltoMethod.POST) {
throw new ExecutionException("Invalid http method used to access the Palo Alto API.");
@ -116,8 +116,8 @@ public class MockablePaloAltoResource extends PaloAltoResource {
// 'config' requests
if (params.containsKey("type") && params.get("type").equals("config") && params.containsKey("action")) {
// action = 'get'
if (params.get("action").equals("get")) {
// action = 'get'
if (params.get("action").equals("get")) {
// get interface for type
// | public_using_ethernet
if (params.get("xpath").equals("/config/devices/entry/network/interface/ethernet/entry[@name='ethernet1/1']")) {
@ -146,7 +146,7 @@ public class MockablePaloAltoResource extends PaloAltoResource {
}
}
// get public interface IP | has_public_interface
// get public interface IP | has_public_interface
if (params.get("xpath").equals("/config/devices/entry/network/interface/ethernet/entry[@name='ethernet1/1']/layer3/units/entry[@name='ethernet1/1.9999']/ip/entry[@name='192.168.80.102/32']")) {
if (context.containsKey("has_public_interface") && context.get("has_public_interface").equals("true")) {
response = "<response status=\"success\" code=\"19\"><result total-count=\"1\" count=\"1\"><entry name=\"192.168.80.102/32\" admin=\"admin\" time=\"2013/07/05 13:02:37\"/></result></response>";
@ -169,7 +169,7 @@ public class MockablePaloAltoResource extends PaloAltoResource {
response = "<response status=\"success\" code=\"19\"><result total-count=\"1\" count=\"1\"><entry name=\"10.3.96.1/20\"/></result></response>";
}
// get source nat | has_src_nat_rule
// get source nat | has_src_nat_rule
if (params.get("xpath").equals("/config/devices/entry/vsys/entry[@name='vsys1']/rulebase/nat/rules/entry[@name='src_nat.3954']")) {
if (context.containsKey("has_src_nat_rule") && context.get("has_src_nat_rule").equals("true")) {
response = "<response status=\"success\" code=\"19\"><result total-count=\"1\" count=\"1\"><entry name=\"src_nat.3954\" admin=\"admin\" time=\"2013/07/05 13:02:38\"><to admin=\"admin\" time=\"2013/07/05 13:02:38\"><member admin=\"admin\" time=\"2013/07/05 13:02:38\">untrust</member></to><from><member>trust</member></from><source><member>10.5.80.1/20</member></source><destination><member>any</member></destination><service>any</service><nat-type>ipv4</nat-type><to-interface>ethernet1/1.9999</to-interface><source-translation><dynamic-ip-and-port><interface-address><ip>192.168.80.102/32</ip><interface>ethernet1/1.9999</interface></interface-address></dynamic-ip-and-port></source-translation></entry></result></response>";
@ -241,10 +241,10 @@ public class MockablePaloAltoResource extends PaloAltoResource {
}
}
}
}
// action = 'set'
if (params.get("action").equals("set")) {
// action = 'set'
if (params.get("action").equals("set")) {
// set management profile
if (params.get("xpath").equals("/config/devices/entry/network/profiles/interface-management-profile/entry[@name='Ping']")) {
response = "<response status=\"success\" code=\"20\"><msg>command succeeded</msg></response>";
@ -324,10 +324,10 @@ public class MockablePaloAltoResource extends PaloAltoResource {
response = "<response status=\"success\" code=\"20\"><msg>command succeeded</msg></response>";
context.put("has_service_tcp_80", "true");
}
}
}
// action = 'delete'
if (params.get("action").equals("delete")) {
// action = 'delete'
if (params.get("action").equals("delete")) {
// remove egress firewall rule
if (params.get("xpath").equals("/config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='policy_0']")) {
response = "<response status=\"success\" code=\"20\"><msg>command succeeded</msg></response>";
@ -396,24 +396,24 @@ public class MockablePaloAltoResource extends PaloAltoResource {
context.remove("has_private_interface");
}
}
}
} // end 'config'
// 'op' requests
if (params.containsKey("type") && params.get("type").equals("op")) {
// check if there are pending changes
if (params.get("cmd").equals("<check><pending-changes></pending-changes></check>")) {
// check if there are pending changes
if (params.get("cmd").equals("<check><pending-changes></pending-changes></check>")) {
if (context.containsKey("firewall_has_pending_changes") && context.get("firewall_has_pending_changes").equals("true")) {
response = "<response status=\"success\"><result>yes</result></response>";
} else {
response = "<response status=\"success\"><result>no</result></response>";
}
}
}
// add a config lock
if (params.get("cmd").equals("<request><config-lock><add></add></config-lock></request>")) {
// add a config lock
if (params.get("cmd").equals("<request><config-lock><add></add></config-lock></request>")) {
response = "<response status=\"success\"><result>Successfully acquired lock. Other administrators will not be able to modify configuration for scope shared until lock is released</result></response>";
}
}
// check job status
if (params.get("cmd").equals("<show><jobs><id>1</id></jobs></show>")) {
@ -424,23 +424,23 @@ public class MockablePaloAltoResource extends PaloAltoResource {
}
}
// load from running config
if (params.get("cmd").equals("<load><config><from>running-config.xml</from></config></load>")) {
// load from running config
if (params.get("cmd").equals("<load><config><from>running-config.xml</from></config></load>")) {
response = "<response status=\"success\"><result><msg><line>Config loaded from running-config.xml</line></msg></result></response>";
}
}
// remove config lock
if (params.get("cmd").equals("<request><config-lock><remove></remove></config-lock></request>")) {
// remove config lock
if (params.get("cmd").equals("<request><config-lock><remove></remove></config-lock></request>")) {
response = "<response status=\"success\"><result>Config lock released for scope shared</result></response>";
}
}
} // end 'op'
// 'commit' requests
if (params.containsKey("type") && params.get("type").equals("commit")) {
// cmd = '<commit></commit>'
if (params.get("cmd").equals("<commit></commit>")) {
// cmd = '<commit></commit>'
if (params.get("cmd").equals("<commit></commit>")) {
response = "<response status=\"success\" code=\"19\"><result><msg><line>Commit job enqueued with jobid 1</line></msg><job>1</job></result></response>";
}
}
} // end 'commit'

View File

@ -106,8 +106,8 @@ import javax.xml.transform.Source;
import java.io.StringWriter;
public class PaloAltoResourceTest {
// configuration data
private String _test_name = "PaloAltoTestDevice";
// configuration data
private String _test_name = "PaloAltoTestDevice";
private String _test_zoneId = "TestZone";
private String _test_ip = "192.168.80.2";
private String _test_username = "admin";
@ -118,101 +118,101 @@ public class PaloAltoResourceTest {
private String _test_privateZone = "trust";
private String _test_virtualRouter = "default";
MockablePaloAltoResource _resource;
Map<String, Object> _resource_params;
HashMap<String, String> _context;
@Before
public void setUp() {
_resource = new MockablePaloAltoResource();
_resource_params = new HashMap<String, Object>(); // params to be passed to configure()
_resource_params.put("name", _test_name);
_resource_params.put("zoneId", _test_zoneId);
_resource_params.put("ip", _test_ip);
_resource_params.put("username", _test_username);
_resource_params.put("password", _test_password);
_resource_params.put("publicinterface", _test_publicInterface);
_resource_params.put("privateinterface", _test_privateInterface);
_resource_params.put("publicnetwork", _test_publicZone);
_resource_params.put("privatenetwork", _test_privateZone);
_resource_params.put("pavr", _test_virtualRouter);
_resource_params.put("guid", "aaaaa-bbbbb-ccccc");
MockablePaloAltoResource _resource;
Map<String, Object> _resource_params;
HashMap<String, String> _context;
@Before
public void setUp() {
_resource = new MockablePaloAltoResource();
_resource_params = new HashMap<String, Object>(); // params to be passed to configure()
_resource_params.put("name", _test_name);
_resource_params.put("zoneId", _test_zoneId);
_resource_params.put("ip", _test_ip);
_resource_params.put("username", _test_username);
_resource_params.put("password", _test_password);
_resource_params.put("publicinterface", _test_publicInterface);
_resource_params.put("privateinterface", _test_privateInterface);
_resource_params.put("publicnetwork", _test_publicZone);
_resource_params.put("privatenetwork", _test_privateZone);
_resource_params.put("pavr", _test_virtualRouter);
_resource_params.put("guid", "aaaaa-bbbbb-ccccc");
_context = new HashMap<String, String>(); // global context
_context.put("name", _test_name);
_context.put("zone_id", _test_zoneId);
_context.put("ip", _test_ip);
_context.put("username", _test_username);
_context.put("password", _test_password);
_context.put("public_interface", _test_publicInterface);
_context.put("private_interface", _test_privateInterface);
_context.put("public_zone", _test_publicZone);
_context.put("private_zone", _test_privateZone);
_context.put("pa_vr", _test_virtualRouter);
// --
_context.put("public_using_ethernet", "true");
_context.put("private_using_ethernet", "true");
_context.put("has_management_profile", "true");
_context.put("enable_console_output", "false"); // CHANGE TO "true" TO ENABLE CONSOLE LOGGING OF TESTS
_resource.setMockContext(_context);
}
_context = new HashMap<String, String>(); // global context
_context.put("name", _test_name);
_context.put("zone_id", _test_zoneId);
_context.put("ip", _test_ip);
_context.put("username", _test_username);
_context.put("password", _test_password);
_context.put("public_interface", _test_publicInterface);
_context.put("private_interface", _test_privateInterface);
_context.put("public_zone", _test_publicZone);
_context.put("private_zone", _test_privateZone);
_context.put("pa_vr", _test_virtualRouter);
// --
_context.put("public_using_ethernet", "true");
_context.put("private_using_ethernet", "true");
_context.put("has_management_profile", "true");
_context.put("enable_console_output", "false"); // CHANGE TO "true" TO ENABLE CONSOLE LOGGING OF TESTS
_resource.setMockContext(_context);
}
@Test (expected=ConfigurationException.class)
public void resourceConfigureFailure() throws ConfigurationException {
_resource.configure("PaloAltoResource", new HashMap<String, Object>());
}
@Test
public void resourceConfigureWithoutManagementProfile() throws ConfigurationException {
if (_context.containsKey("enable_console_output") && _context.get("enable_console_output").equals("true")) {
System.out.println("\nTEST: resourceConfigureWithoutManagementProfile");
System.out.println("---------------------------------------------------");
}
@Test (expected=ConfigurationException.class)
public void resourceConfigureFailure() throws ConfigurationException {
_resource.configure("PaloAltoResource", new HashMap<String, Object>());
}
@Test
public void resourceConfigureWithoutManagementProfile() throws ConfigurationException {
if (_context.containsKey("enable_console_output") && _context.get("enable_console_output").equals("true")) {
System.out.println("\nTEST: resourceConfigureWithoutManagementProfile");
System.out.println("---------------------------------------------------");
}
_context.remove("has_management_profile");
_resource.setMockContext(_context);
_resource.configure("PaloAltoResource", _resource_params);
}
_resource.setMockContext(_context);
_resource.configure("PaloAltoResource", _resource_params);
}
@Test
public void resourceConfigureWithManagementProfile() throws ConfigurationException {
if (_context.containsKey("enable_console_output") && _context.get("enable_console_output").equals("true")) {
System.out.println("\nTEST: resourceConfigureWithManagementProfile");
System.out.println("---------------------------------------------------");
}
_resource.configure("PaloAltoResource", _resource_params);
}
@Test
public void resourceConfigureWithManagementProfile() throws ConfigurationException {
if (_context.containsKey("enable_console_output") && _context.get("enable_console_output").equals("true")) {
System.out.println("\nTEST: resourceConfigureWithManagementProfile");
System.out.println("---------------------------------------------------");
}
_resource.configure("PaloAltoResource", _resource_params);
}
@Test (expected=ConfigurationException.class)
public void simulateFirewallNotConfigurable() throws ConfigurationException {
if (_context.containsKey("enable_console_output") && _context.get("enable_console_output").equals("true")) {
System.out.println("\nTEST: simulateFirewallNotConfigurable");
System.out.println("---------------------------------------------------");
}
_context.put("firewall_has_pending_changes", "true");
@Test (expected=ConfigurationException.class)
public void simulateFirewallNotConfigurable() throws ConfigurationException {
if (_context.containsKey("enable_console_output") && _context.get("enable_console_output").equals("true")) {
System.out.println("\nTEST: simulateFirewallNotConfigurable");
System.out.println("---------------------------------------------------");
}
_context.put("firewall_has_pending_changes", "true");
_context.remove("has_management_profile");
_resource.setMockContext(_context);
_resource.configure("PaloAltoResource", _resource_params);
}
_resource.setMockContext(_context);
_resource.configure("PaloAltoResource", _resource_params);
}
@Test (expected=ConfigurationException.class)
public void simulateFirewallCommitFailure() throws ConfigurationException {
if (_context.containsKey("enable_console_output") && _context.get("enable_console_output").equals("true")) {
System.out.println("\nTEST: simulateFirewallCommitFailure");
System.out.println("---------------------------------------------------");
}
_context.put("simulate_commit_failure", "true");
@Test (expected=ConfigurationException.class)
public void simulateFirewallCommitFailure() throws ConfigurationException {
if (_context.containsKey("enable_console_output") && _context.get("enable_console_output").equals("true")) {
System.out.println("\nTEST: simulateFirewallCommitFailure");
System.out.println("---------------------------------------------------");
}
_context.put("simulate_commit_failure", "true");
_context.remove("has_management_profile");
_resource.setMockContext(_context);
_resource.configure("PaloAltoResource", _resource_params);
}
_resource.setMockContext(_context);
_resource.configure("PaloAltoResource", _resource_params);
}
@Test
@Test
public void testInitialize() throws ConfigurationException {
if (_context.containsKey("enable_console_output") && _context.get("enable_console_output").equals("true")) {
System.out.println("\nTEST: testInitialization");
System.out.println("---------------------------------------------------");
}
_resource.configure("PaloAltoResource", _resource_params);
if (_context.containsKey("enable_console_output") && _context.get("enable_console_output").equals("true")) {
System.out.println("\nTEST: testInitialization");
System.out.println("---------------------------------------------------");
}
_resource.configure("PaloAltoResource", _resource_params);
StartupCommand[] sc = _resource.initialize();
assertTrue(sc.length == 1);
@ -221,16 +221,16 @@ public class PaloAltoResourceTest {
assertTrue("TestZone".equals(sc[0].getDataCenter()));
}
@Test // implement public & private interfaces, source nat, guest network
public void implementGuestNetwork() throws ConfigurationException, ExecutionException {
if (_context.containsKey("enable_console_output") && _context.get("enable_console_output").equals("true")) {
System.out.println("\nTEST: implementGuestNetwork");
System.out.println("---------------------------------------------------");
}
_resource.configure("PaloAltoResource", _resource_params);
@Test // implement public & private interfaces, source nat, guest network
public void implementGuestNetwork() throws ConfigurationException, ExecutionException {
if (_context.containsKey("enable_console_output") && _context.get("enable_console_output").equals("true")) {
System.out.println("\nTEST: implementGuestNetwork");
System.out.println("---------------------------------------------------");
}
_resource.configure("PaloAltoResource", _resource_params);
IpAddressTO ip = new IpAddressTO(Long.valueOf("1"), "192.168.80.102", true, false, true, "untagged", null, null, null, 100, false);
IpAddressTO[] ips = new IpAddressTO[1];
IpAddressTO ip = new IpAddressTO(Long.valueOf("1"), "192.168.80.102", true, false, true, "untagged", null, null, null, 100, false);
IpAddressTO[] ips = new IpAddressTO[1];
ips[0] = ip;
IpAssocCommand cmd = new IpAssocCommand(ips);
cmd.setAccessDetail(NetworkElementCommand.GUEST_NETWORK_GATEWAY, "10.3.96.1");
@ -239,23 +239,23 @@ public class PaloAltoResourceTest {
IpAssocAnswer answer = (IpAssocAnswer) _resource.executeRequest(cmd);
assertTrue(answer.getResult());
}
}
@Test // remove public & private interface details, source nat, guest network
public void shutdownGuestNetwork() throws ConfigurationException, ExecutionException {
if (_context.containsKey("enable_console_output") && _context.get("enable_console_output").equals("true")) {
System.out.println("\nTEST: shutdownGuestNetwork");
System.out.println("---------------------------------------------------");
}
_context.put("has_public_interface", "true");
_context.put("has_private_interface", "true");
_context.put("has_src_nat_rule", "true");
_context.put("has_isolation_fw_rule", "true");
_resource.setMockContext(_context);
_resource.configure("PaloAltoResource", _resource_params);
@Test // remove public & private interface details, source nat, guest network
public void shutdownGuestNetwork() throws ConfigurationException, ExecutionException {
if (_context.containsKey("enable_console_output") && _context.get("enable_console_output").equals("true")) {
System.out.println("\nTEST: shutdownGuestNetwork");
System.out.println("---------------------------------------------------");
}
_context.put("has_public_interface", "true");
_context.put("has_private_interface", "true");
_context.put("has_src_nat_rule", "true");
_context.put("has_isolation_fw_rule", "true");
_resource.setMockContext(_context);
_resource.configure("PaloAltoResource", _resource_params);
IpAddressTO ip = new IpAddressTO(Long.valueOf("1"), "192.168.80.102", false, false, true, "untagged", null, null, null, 100, false);
IpAddressTO[] ips = new IpAddressTO[1];
IpAddressTO ip = new IpAddressTO(Long.valueOf("1"), "192.168.80.102", false, false, true, "untagged", null, null, null, 100, false);
IpAddressTO[] ips = new IpAddressTO[1];
ips[0] = ip;
IpAssocCommand cmd = new IpAssocCommand(ips);
cmd.setAccessDetail(NetworkElementCommand.GUEST_NETWORK_GATEWAY, "10.3.96.1");
@ -264,21 +264,21 @@ public class PaloAltoResourceTest {
IpAssocAnswer answer = (IpAssocAnswer) _resource.executeRequest(cmd);
assertTrue(answer.getResult());
}
}
@Test
@Test
public void addIngressFirewallRule() throws ConfigurationException, Exception {
if (_context.containsKey("enable_console_output") && _context.get("enable_console_output").equals("true")) {
System.out.println("\nTEST: addIngressFirewallRule");
System.out.println("---------------------------------------------------");
}
_context.put("has_public_interface", "true");
_context.put("has_private_interface", "true");
_context.put("has_src_nat_rule", "true");
_context.put("has_isolation_fw_rule", "true");
_context.put("has_service_tcp_80", "true");
_resource.setMockContext(_context);
_resource.configure("PaloAltoResource", _resource_params);
if (_context.containsKey("enable_console_output") && _context.get("enable_console_output").equals("true")) {
System.out.println("\nTEST: addIngressFirewallRule");
System.out.println("---------------------------------------------------");
}
_context.put("has_public_interface", "true");
_context.put("has_private_interface", "true");
_context.put("has_src_nat_rule", "true");
_context.put("has_isolation_fw_rule", "true");
_context.put("has_service_tcp_80", "true");
_resource.setMockContext(_context);
_resource.configure("PaloAltoResource", _resource_params);
long vlanId = 3954;
List<FirewallRuleTO> rules = new ArrayList<FirewallRuleTO>();
@ -297,20 +297,20 @@ public class PaloAltoResourceTest {
assertTrue(answer.getResult());
}
@Test
@Test
public void removeIngressFirewallRule() throws ConfigurationException, Exception {
if (_context.containsKey("enable_console_output") && _context.get("enable_console_output").equals("true")) {
System.out.println("\nTEST: removeIngressFirewallRule");
System.out.println("---------------------------------------------------");
}
_context.put("has_public_interface", "true");
_context.put("has_private_interface", "true");
_context.put("has_src_nat_rule", "true");
_context.put("has_isolation_fw_rule", "true");
_context.put("has_service_tcp_80", "true");
_context.put("has_ingress_fw_rule", "true");
_resource.setMockContext(_context);
_resource.configure("PaloAltoResource", _resource_params);
if (_context.containsKey("enable_console_output") && _context.get("enable_console_output").equals("true")) {
System.out.println("\nTEST: removeIngressFirewallRule");
System.out.println("---------------------------------------------------");
}
_context.put("has_public_interface", "true");
_context.put("has_private_interface", "true");
_context.put("has_src_nat_rule", "true");
_context.put("has_isolation_fw_rule", "true");
_context.put("has_service_tcp_80", "true");
_context.put("has_ingress_fw_rule", "true");
_resource.setMockContext(_context);
_resource.configure("PaloAltoResource", _resource_params);
long vlanId = 3954;
List<FirewallRuleTO> rules = new ArrayList<FirewallRuleTO>();
@ -329,17 +329,17 @@ public class PaloAltoResourceTest {
@Test
public void addEgressFirewallRule() throws ConfigurationException, Exception {
if (_context.containsKey("enable_console_output") && _context.get("enable_console_output").equals("true")) {
System.out.println("\nTEST: addEgressFirewallRule");
System.out.println("---------------------------------------------------");
}
_context.put("has_public_interface", "true");
_context.put("has_private_interface", "true");
_context.put("has_src_nat_rule", "true");
_context.put("has_isolation_fw_rule", "true");
_context.put("has_service_tcp_80", "true");
_resource.setMockContext(_context);
_resource.configure("PaloAltoResource", _resource_params);
if (_context.containsKey("enable_console_output") && _context.get("enable_console_output").equals("true")) {
System.out.println("\nTEST: addEgressFirewallRule");
System.out.println("---------------------------------------------------");
}
_context.put("has_public_interface", "true");
_context.put("has_private_interface", "true");
_context.put("has_src_nat_rule", "true");
_context.put("has_isolation_fw_rule", "true");
_context.put("has_service_tcp_80", "true");
_resource.setMockContext(_context);
_resource.configure("PaloAltoResource", _resource_params);
long vlanId = 3954;
List<FirewallRuleTO> rules = new ArrayList<FirewallRuleTO>();
@ -359,20 +359,20 @@ public class PaloAltoResourceTest {
assertTrue(answer.getResult());
}
@Test
@Test
public void removeEgressFirewallRule() throws ConfigurationException, Exception {
if (_context.containsKey("enable_console_output") && _context.get("enable_console_output").equals("true")) {
System.out.println("\nTEST: removeEgressFirewallRule");
System.out.println("---------------------------------------------------");
}
_context.put("has_public_interface", "true");
_context.put("has_private_interface", "true");
_context.put("has_src_nat_rule", "true");
_context.put("has_isolation_fw_rule", "true");
_context.put("has_service_tcp_80", "true");
_context.put("has_egress_fw_rule", "true");
_resource.setMockContext(_context);
_resource.configure("PaloAltoResource", _resource_params);
if (_context.containsKey("enable_console_output") && _context.get("enable_console_output").equals("true")) {
System.out.println("\nTEST: removeEgressFirewallRule");
System.out.println("---------------------------------------------------");
}
_context.put("has_public_interface", "true");
_context.put("has_private_interface", "true");
_context.put("has_src_nat_rule", "true");
_context.put("has_isolation_fw_rule", "true");
_context.put("has_service_tcp_80", "true");
_context.put("has_egress_fw_rule", "true");
_resource.setMockContext(_context);
_resource.configure("PaloAltoResource", _resource_params);
long vlanId = 3954;
List<FirewallRuleTO> rules = new ArrayList<FirewallRuleTO>();
@ -392,17 +392,17 @@ public class PaloAltoResourceTest {
@Test
public void addStaticNatRule() throws ConfigurationException, Exception {
if (_context.containsKey("enable_console_output") && _context.get("enable_console_output").equals("true")) {
System.out.println("\nTEST: addStaticNatRule");
System.out.println("---------------------------------------------------");
}
_context.put("has_public_interface", "true");
_context.put("has_private_interface", "true");
_context.put("has_src_nat_rule", "true");
_context.put("has_isolation_fw_rule", "true");
_context.put("has_service_tcp_80", "true");
_resource.setMockContext(_context);
_resource.configure("PaloAltoResource", _resource_params);
if (_context.containsKey("enable_console_output") && _context.get("enable_console_output").equals("true")) {
System.out.println("\nTEST: addStaticNatRule");
System.out.println("---------------------------------------------------");
}
_context.put("has_public_interface", "true");
_context.put("has_private_interface", "true");
_context.put("has_src_nat_rule", "true");
_context.put("has_isolation_fw_rule", "true");
_context.put("has_service_tcp_80", "true");
_resource.setMockContext(_context);
_resource.configure("PaloAltoResource", _resource_params);
long vlanId = 3954;
List<StaticNatRuleTO> rules = new ArrayList<StaticNatRuleTO>();
@ -420,18 +420,18 @@ public class PaloAltoResourceTest {
@Test
public void removeStaticNatRule() throws ConfigurationException, Exception {
if (_context.containsKey("enable_console_output") && _context.get("enable_console_output").equals("true")) {
System.out.println("\nTEST: removeStaticNatRule");
System.out.println("---------------------------------------------------");
}
_context.put("has_public_interface", "true");
_context.put("has_private_interface", "true");
_context.put("has_src_nat_rule", "true");
_context.put("has_isolation_fw_rule", "true");
_context.put("has_service_tcp_80", "true");
_context.put("has_stc_nat_rule", "true");
_resource.setMockContext(_context);
_resource.configure("PaloAltoResource", _resource_params);
if (_context.containsKey("enable_console_output") && _context.get("enable_console_output").equals("true")) {
System.out.println("\nTEST: removeStaticNatRule");
System.out.println("---------------------------------------------------");
}
_context.put("has_public_interface", "true");
_context.put("has_private_interface", "true");
_context.put("has_src_nat_rule", "true");
_context.put("has_isolation_fw_rule", "true");
_context.put("has_service_tcp_80", "true");
_context.put("has_stc_nat_rule", "true");
_resource.setMockContext(_context);
_resource.configure("PaloAltoResource", _resource_params);
long vlanId = 3954;
List<StaticNatRuleTO> rules = new ArrayList<StaticNatRuleTO>();
@ -449,17 +449,17 @@ public class PaloAltoResourceTest {
@Test
public void addPortForwardingRule() throws ConfigurationException, Exception {
if (_context.containsKey("enable_console_output") && _context.get("enable_console_output").equals("true")) {
System.out.println("\nTEST: addPortForwardingRule");
System.out.println("---------------------------------------------------");
}
_context.put("has_public_interface", "true");
_context.put("has_private_interface", "true");
_context.put("has_src_nat_rule", "true");
_context.put("has_isolation_fw_rule", "true");
_context.put("has_service_tcp_80", "true");
_resource.setMockContext(_context);
_resource.configure("PaloAltoResource", _resource_params);
if (_context.containsKey("enable_console_output") && _context.get("enable_console_output").equals("true")) {
System.out.println("\nTEST: addPortForwardingRule");
System.out.println("---------------------------------------------------");
}
_context.put("has_public_interface", "true");
_context.put("has_private_interface", "true");
_context.put("has_src_nat_rule", "true");
_context.put("has_isolation_fw_rule", "true");
_context.put("has_service_tcp_80", "true");
_resource.setMockContext(_context);
_resource.configure("PaloAltoResource", _resource_params);
long vlanId = 3954;
List<PortForwardingRuleTO> rules = new ArrayList<PortForwardingRuleTO>();
@ -477,18 +477,18 @@ public class PaloAltoResourceTest {
@Test
public void removePortForwardingRule() throws ConfigurationException, Exception {
if (_context.containsKey("enable_console_output") && _context.get("enable_console_output").equals("true")) {
System.out.println("\nTEST: removePortForwardingRule");
System.out.println("---------------------------------------------------");
}
_context.put("has_public_interface", "true");
_context.put("has_private_interface", "true");
_context.put("has_src_nat_rule", "true");
_context.put("has_isolation_fw_rule", "true");
_context.put("has_service_tcp_80", "true");
_context.put("has_dst_nat_rule", "true");
_resource.setMockContext(_context);
_resource.configure("PaloAltoResource", _resource_params);
if (_context.containsKey("enable_console_output") && _context.get("enable_console_output").equals("true")) {
System.out.println("\nTEST: removePortForwardingRule");
System.out.println("---------------------------------------------------");
}
_context.put("has_public_interface", "true");
_context.put("has_private_interface", "true");
_context.put("has_src_nat_rule", "true");
_context.put("has_isolation_fw_rule", "true");
_context.put("has_service_tcp_80", "true");
_context.put("has_dst_nat_rule", "true");
_resource.setMockContext(_context);
_resource.configure("PaloAltoResource", _resource_params);
long vlanId = 3954;
List<PortForwardingRuleTO> rules = new ArrayList<PortForwardingRuleTO>();

View File

@ -445,6 +445,7 @@
<outputDirectory>${basedir}/${cs.target.dir}/classes</outputDirectory>
<testOutputDirectory>${basedir}/${cs.target.dir}/test-classes</testOutputDirectory>
<plugins>
<!--
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
@ -474,6 +475,7 @@
<excludes>**\/target\/,**\/bin\/,**\/*.xml,**\/*.ini,**\/*.sh,**\/*.bat</excludes>
</configuration>
</plugin>
-->
</plugins>
<pluginManagement>
<plugins>

View File

@ -324,7 +324,7 @@ public class AlertManagerImpl extends ManagerBase implements AlertManager, Confi
}
// Calculate CPU and RAM capacities
// get all hosts...even if they are not in 'UP' state
// get all hosts...even if they are not in 'UP' state
List<HostVO> hosts = _resourceMgr.listAllNotInMaintenanceHostsInOneZone(Host.Type.Routing, null);
for (HostVO host : hosts) {
_capacityMgr.updateCapacityForHost(host);

View File

@ -602,7 +602,7 @@ public enum Config {
MigrateWait("Advanced", AgentManager.class, Integer.class, "migratewait", "3600", "Time (in seconds) to wait for VM migrate finish", null),
HAWorkers("Advanced", AgentManager.class, Integer.class, "ha.workers", "5", "Number of ha worker threads.", null),
MountParent("Advanced", ManagementServer.class, String.class, "mount.parent", "/var/cloudstack/mnt", "The mount point on the Management Server for Secondary Storage.", null),
// UpgradeURL("Advanced", ManagementServer.class, String.class, "upgrade.url", "http://example.com:8080/client/agent/update.zip", "The upgrade URL is the URL of the management server that agents will connect to in order to automatically upgrade.", null),
// UpgradeURL("Advanced", ManagementServer.class, String.class, "upgrade.url", "http://example.com:8080/client/agent/update.zip", "The upgrade URL is the URL of the management server that agents will connect to in order to automatically upgrade.", null),
SystemVMUseLocalStorage(
"Advanced",
ManagementServer.class,

View File

@ -23,13 +23,13 @@ public interface ConsoleProxyManager extends Manager, ConsoleProxyService {
public static final int DEFAULT_PROXY_CAPACITY = 50;
public static final int DEFAULT_STANDBY_CAPACITY = 10;
public static final int DEFAULT_PROXY_VM_RAMSIZE = 1024; // 1G
public static final int DEFAULT_PROXY_VM_CPUMHZ = 500; // 500 MHz
public static final int DEFAULT_PROXY_VM_RAMSIZE = 1024; // 1G
public static final int DEFAULT_PROXY_VM_CPUMHZ = 500; // 500 MHz
public static final int DEFAULT_PROXY_CMD_PORT = 8001;
public static final int DEFAULT_PROXY_VNC_PORT = 0;
public static final int DEFAULT_PROXY_URL_PORT = 80;
public static final int DEFAULT_PROXY_SESSION_TIMEOUT = 300000; // 5 minutes
public static final int DEFAULT_PROXY_SESSION_TIMEOUT = 300000; // 5 minutes
public static final String ALERT_SUBJECT = "proxy-alert";
public static final String CERTIFICATE_NAME = "CPVMCertificate";

View File

@ -144,12 +144,12 @@ import com.cloud.vm.dao.VMInstanceDao;
//
// Possible console proxy state transition cases
// Stopped --> Starting -> Running
// HA -> Stopped -> Starting -> Running
// Migrating -> Running (if previous state is Running before it enters into Migrating state
// Migrating -> Stopped (if previous state is not Running before it enters into Migrating state)
// Running -> HA (if agent lost connection)
// Stopped -> Destroyed
// Stopped --> Starting -> Running
// HA -> Stopped -> Starting -> Running
// Migrating -> Running (if previous state is Running before it enters into Migrating state
// Migrating -> Stopped (if previous state is not Running before it enters into Migrating state)
// Running -> HA (if agent lost connection)
// Stopped -> Destroyed
//
// Starting, HA, Migrating, Running state are all counted as "Open" for available capacity calculation
// because sooner or later, it will be driven into Running state

View File

@ -58,7 +58,7 @@ public class RecreatableFencer extends AdapterBase implements FenceBuilder {
for (VolumeVO vol : vols) {
if (!vol.isRecreatable()) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Unable to f ence off volumes that are not recreatable: " + vol);
s_logger.debug("Unable to f ence off volumes that are not recreatable: " + vol);
}
return null;
}

View File

@ -40,7 +40,7 @@ public class PortProfileManagerImpl {
@DB
public PortProfileVO addPortProfile(String portProfName, long vsmId, int vlanId, PortType pType, BindingType bType) {
// In this function, we create a port profile record in the port_profile table.
// In this function, we create a port profile record in the port_profile table.
// First, check if a port profile with the given name already exists. If it does, throw an exception.
if (_portProfileDao.findByName(portProfName) != null) {
@ -63,7 +63,7 @@ public class PortProfileManagerImpl {
// In this function, we create a port profile record in the port_profile table.
// First, check if a port profile with the given name already exists. If it does, throw an exception.
// First, check if a port profile with the given name already exists. If it does, throw an exception.
PortProfileVO portProfileObj;
portProfileObj = _portProfileDao.findByName(portProfName);

View File

@ -63,7 +63,7 @@ public interface VirtualNetworkApplianceManager extends Manager, VirtualNetworkA
"Name of the default router template on LXC.", true, ConfigKey.Scope.Zone, null);
public static final int DEFAULT_ROUTER_VM_RAMSIZE = 128; // 128M
public static final int DEFAULT_ROUTER_CPU_MHZ = 500; // 500 MHz
public static final int DEFAULT_ROUTER_CPU_MHZ = 500; // 500 MHz
public static final boolean USE_POD_VLAN = false;
/**

View File

@ -170,7 +170,7 @@ public class ConsoleProxyPasswordBasedEncryptor {
random.nextBytes(ivBytes);
KeyIVPair keyIvPair = new KeyIVPair("8x/xUBgX0Up+3UEo39dSeG277JhVj31+ElHkN5+EC0Q=", "Y2SUiIN6JXTdKNK/ZMDyVtLB7gAM9MCCiyrP1xd3bSQ=");
//keyIvPair.setKeyBytes(keyBytes);
//keyIvPair.setKeyBytes(keyBytes);
//keyIvPair.setIvBytes(ivBytes);
Gson gson = new GsonBuilder().create();

View File

@ -432,7 +432,7 @@ public class ConsoleProxyServlet extends HttpServlet {
Mac mac = Mac.getInstance("HmacSHA1");
long ts = normalizedHashTime.getTime();
ts = ts / 60000; // round up to 1 minute
ts = ts / 60000; // round up to 1 minute
String secretKey = s_ms.getHashKey();
SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(), "HmacSHA1");

View File

@ -140,18 +140,18 @@ import com.cloud.vm.dao.VMInstanceDao;
//
// Possible secondary storage vm state transition cases
// Creating -> Destroyed
// Creating -> Stopped --> Starting -> Running
// HA -> Stopped -> Starting -> Running
// Migrating -> Running (if previous state is Running before it enters into Migrating state
// Migrating -> Stopped (if previous state is not Running before it enters into Migrating state)
// Running -> HA (if agent lost connection)
// Stopped -> Destroyed
// Creating -> Destroyed
// Creating -> Stopped --> Starting -> Running
// HA -> Stopped -> Starting -> Running
// Migrating -> Running (if previous state is Running before it enters into Migrating state
// Migrating -> Stopped (if previous state is not Running before it enters into Migrating state)
// Running -> HA (if agent lost connection)
// Stopped -> Destroyed
//
// Creating state indicates of record creating and IP address allocation are ready, it is a transient
// state which will soon be switching towards Running if everything goes well.
// Stopped state indicates the readiness of being able to start (has storage and IP resources allocated)
// Starting state can only be entered from Stopped states
// Creating state indicates of record creating and IP address allocation are ready, it is a transient
// state which will soon be switching towards Running if everything goes well.
// Stopped state indicates the readiness of being able to start (has storage and IP resources allocated)
// Starting state can only be entered from Stopped states
//
// Starting, HA, Migrating, Creating and Running state are all counted as "Open" for available capacity calculation
// because sooner or later, it will be driven into Running state
@ -212,7 +212,7 @@ public class SecondaryStorageManagerImpl extends ManagerBase implements Secondar
UserVmDetailsDao _vmDetailsDao;
@Inject
protected ResourceManager _resourceMgr;
//@Inject // TODO this is a very strange usage, a singleton class need to inject itself?
//@Inject // TODO this is a very strange usage, a singleton class need to inject itself?
protected SecondaryStorageVmManager _ssvmMgr;
@Inject
NetworkDao _networkDao;
@ -1286,42 +1286,42 @@ public class SecondaryStorageManagerImpl extends ManagerBase implements Secondar
/*
StartupCommand firstCmd = startup[0];
if (!(firstCmd instanceof StartupStorageCommand)) {
return null;
return null;
}
com.cloud.host.Host.Type type = null;
StartupStorageCommand ssCmd = ((StartupStorageCommand) firstCmd);
if (ssCmd.getHostType() == Host.Type.SecondaryStorageCmdExecutor) {
type = ssCmd.getHostType();
type = ssCmd.getHostType();
} else {
if (ssCmd.getResourceType() == Storage.StorageResourceType.SECONDARY_STORAGE) {
type = Host.Type.SecondaryStorage;
if (resource != null && resource instanceof DummySecondaryStorageResource) {
host.setResource(null);
}
} else if (ssCmd.getResourceType() == Storage.StorageResourceType.LOCAL_SECONDARY_STORAGE) {
type = Host.Type.LocalSecondaryStorage;
} else {
type = Host.Type.Storage;
}
if (ssCmd.getResourceType() == Storage.StorageResourceType.SECONDARY_STORAGE) {
type = Host.Type.SecondaryStorage;
if (resource != null && resource instanceof DummySecondaryStorageResource) {
host.setResource(null);
}
} else if (ssCmd.getResourceType() == Storage.StorageResourceType.LOCAL_SECONDARY_STORAGE) {
type = Host.Type.LocalSecondaryStorage;
} else {
type = Host.Type.Storage;
}
final Map<String, String> hostDetails = ssCmd.getHostDetails();
if (hostDetails != null) {
if (details != null) {
details.putAll(hostDetails);
} else {
details = hostDetails;
}
}
final Map<String, String> hostDetails = ssCmd.getHostDetails();
if (hostDetails != null) {
if (details != null) {
details.putAll(hostDetails);
} else {
details = hostDetails;
}
}
host.setDetails(details);
host.setParent(ssCmd.getParent());
host.setTotalSize(ssCmd.getTotalSize());
host.setHypervisorType(HypervisorType.None);
host.setType(type);
if (ssCmd.getNfsShare() != null) {
host.setStorageUrl(ssCmd.getNfsShare());
}
host.setDetails(details);
host.setParent(ssCmd.getParent());
host.setTotalSize(ssCmd.getTotalSize());
host.setHypervisorType(HypervisorType.None);
host.setType(type);
if (ssCmd.getNfsShare() != null) {
host.setStorageUrl(ssCmd.getNfsShare());
}
}
*/
return null; // no need to handle this event anymore since secondary storage is not in host table anymore.

View File

@ -27,11 +27,11 @@ import com.cloud.vm.SecondaryStorageVmVO;
public interface SecondaryStorageVmManager extends Manager {
public static final int DEFAULT_SS_VM_RAMSIZE = 256; // 256M
public static final int DEFAULT_SS_VM_CPUMHZ = 500; // 500 MHz
public static final int DEFAULT_SS_VM_RAMSIZE = 256; // 256M
public static final int DEFAULT_SS_VM_CPUMHZ = 500; // 500 MHz
public static final int DEFAULT_SS_VM_MTUSIZE = 1500;
public static final int DEFAULT_SS_VM_CAPACITY = 50; // max command execution session per SSVM
public static final int DEFAULT_STANDBY_CAPACITY = 10; // standy capacity to reserve per zone
public static final int DEFAULT_SS_VM_CAPACITY = 50; // max command execution session per SSVM
public static final int DEFAULT_STANDBY_CAPACITY = 10; // standy capacity to reserve per zone
public static final String ALERT_SUBJECT = "secondarystoragevm-alert";

View File

@ -1085,7 +1085,7 @@ public class DatabaseConfig {
} catch (SQLException ex) {
s_logger.error("error creating vm template: " + ex);
} finally {
txn.close();
txn.close();
}
*/
/*
@ -1108,7 +1108,7 @@ public class DatabaseConfig {
} catch (SQLException ex) {
s_logger.error("error creating vm template: " + ex);
} finally {
txn.close();
txn.close();
}
*/
}
@ -1294,7 +1294,7 @@ public class DatabaseConfig {
} catch (SQLException ex) {
s_logger.error("error updating admin user", ex);
} finally {
txn.close();
txn.close();
}
updateSql = "update account set domain_id = 1 where id = 1";
@ -1305,7 +1305,7 @@ public class DatabaseConfig {
} catch (SQLException ex) {
s_logger.error("error updating system user", ex);
} finally {
txn.close();
txn.close();
}
*/
}

View File

@ -568,30 +568,30 @@ public class IPRangeConfig {
"Unable to start DB connection to read guest cidr network. Please contact Cloud Support.");
}
// public static String getGuestIpNetwork() {
// return DatabaseConfig.getDatabaseValueString("SELECT * FROM `cloud`.`configuration` WHERE name = \"guest.ip.network\"", "value",
// "Unable to start DB connection to read guest IP network. Please contact Cloud Support.");
// }
//
// public static String getGuestNetmask() {
// return DatabaseConfig.getDatabaseValueString("SELECT * FROM `cloud`.`configuration` WHERE name = \"guest.netmask\"", "value",
// "Unable to start DB connection to read guest netmask. Please contact Cloud Support.");
// }
// public static String getGuestIpNetwork() {
// return DatabaseConfig.getDatabaseValueString("SELECT * FROM `cloud`.`configuration` WHERE name = \"guest.ip.network\"", "value",
// "Unable to start DB connection to read guest IP network. Please contact Cloud Support.");
// }
//
// public static String getGuestNetmask() {
// return DatabaseConfig.getDatabaseValueString("SELECT * FROM `cloud`.`configuration` WHERE name = \"guest.netmask\"", "value",
// "Unable to start DB connection to read guest netmask. Please contact Cloud Support.");
// }
// public static String getGuestSubnet() {
// String guestIpNetwork = getGuestIpNetwork();
// String guestNetmask = getGuestNetmask();
//
// if (guestIpNetwork == null || guestIpNetwork.isEmpty()) printError("Please enter a valid guest IP network address.");
// if (guestNetmask == null || guestNetmask.isEmpty()) printError("Please enter a valid guest IP network netmask");
//
// return NetUtils.getSubNet(guestIpNetwork, guestNetmask);
// }
// public static String getGuestSubnet() {
// String guestIpNetwork = getGuestIpNetwork();
// String guestNetmask = getGuestNetmask();
//
// if (guestIpNetwork == null || guestIpNetwork.isEmpty()) printError("Please enter a valid guest IP network address.");
// if (guestNetmask == null || guestNetmask.isEmpty()) printError("Please enter a valid guest IP network netmask");
//
// return NetUtils.getSubNet(guestIpNetwork, guestNetmask);
// }
// public static long getGuestCidrSize() {
// String guestNetmask = getGuestNetmask();
// return NetUtils.getCidrSize(guestNetmask);
// }
// public static long getGuestCidrSize() {
// String guestNetmask = getGuestNetmask();
// return NetUtils.getCidrSize(guestNetmask);
// }
public static boolean validCIDR(final String cidr) {
if (cidr == null || cidr.isEmpty()) {

View File

@ -75,7 +75,7 @@ public class PodZoneConfig {
private String checkPodCidrSubnets(long dcId, HashMap<Long, Vector<Object>> currentPodCidrSubnets) {
// DataCenterDao _dcDao = null;
// DataCenterDao _dcDao = null;
// final ComponentLocator locator = ComponentLocator.getLocator("management-server");
// _dcDao = locator.getDao(DataCenterDao.class);
@ -86,7 +86,7 @@ public class PodZoneConfig {
String zoneName = PodZoneConfig.getZoneName(dcId);
//get the guest network cidr and guest netmask from the zone
// DataCenterVO dcVo = _dcDao.findById(dcId);
// DataCenterVO dcVo = _dcDao.findById(dcId);
String guestNetworkCidr = IPRangeConfig.getGuestNetworkCidr(dcId);
@ -236,9 +236,9 @@ public class PodZoneConfig {
String newVlanSubnet = NetUtils.getSubNet(vlanGateway, vlanNetmask);
List<VlanVO> vlans = _vlanDao.findByZone(zoneId);
for (VlanVO vlan : vlans) {
String currentVlanSubnet = NetUtils.getSubNet(vlan.getVlanGateway(), vlan.getVlanNetmask());
if (newVlanSubnet.equals(currentVlanSubnet))
return genReturnList("false", "The VLAN with ID " + vlan.getVlanId() + " in zone " + zone + " has the same subnet. Please specify a different gateway/netmask.");
String currentVlanSubnet = NetUtils.getSubNet(vlan.getVlanGateway(), vlan.getVlanNetmask());
if (newVlanSubnet.equals(currentVlanSubnet))
return genReturnList("false", "The VLAN with ID " + vlan.getVlanId() + " in zone " + zone + " has the same subnet. Please specify a different gateway/netmask.");
}
*/
@ -259,20 +259,20 @@ public class PodZoneConfig {
/*
else {
// Check if a VLAN actually exists in the specified zone
long vlanDbId = getVlanDbId(zone, vlanId);
if (vlanDbId == -1)
return genReturnList("false", "A VLAN with ID " + vlanId + " does not exist in zone " + zone);
// Check if a VLAN actually exists in the specified zone
long vlanDbId = getVlanDbId(zone, vlanId);
if (vlanDbId == -1)
return genReturnList("false", "A VLAN with ID " + vlanId + " does not exist in zone " + zone);
// Check if there are any public IPs that are in the specified vlan.
List<IPAddressVO> ips = _publicIpAddressDao.listByVlanDbId(vlanDbId);
if (ips.size() != 0)
return genReturnList("false", "Please delete all IP addresses that are in VLAN " + vlanId + " before deleting the VLAN.");
// Check if there are any public IPs that are in the specified vlan.
List<IPAddressVO> ips = _publicIpAddressDao.listByVlanDbId(vlanDbId);
if (ips.size() != 0)
return genReturnList("false", "Please delete all IP addresses that are in VLAN " + vlanId + " before deleting the VLAN.");
// Delete the vlan
_vlanDao.delete(vlanDbId);
// Delete the vlan
_vlanDao.delete(vlanDbId);
return genReturnList("true", "Successfully deleted VLAN.");
return genReturnList("true", "Successfully deleted VLAN.");
}
*/
}

View File

@ -74,7 +74,7 @@ public class KeystoreTest extends TestCase {
/*
public void testKeystoreSave() throws Exception {
KeystoreVO ksVo;
KeystoreVO ksVo;
ComponentLocator locator = ComponentLocator.getCurrentLocator();
@ -98,15 +98,15 @@ public class KeystoreTest extends TestCase {
}
public void testStripeKey() throws Exception {
Pattern regex = Pattern.compile("(^[\\-]+[^\\-]+[\\-]+[\\n]?)([^\\-]+)([\\-]+[^\\-]+[\\-]+$)");
Matcher m = regex.matcher("-----BEGIN RSA PRIVATE KEY-----\nMIIEpAIBAAKCAQEAm4bLUORp9oM65GV9XrPrbs+K563DjUR1M8mP1HaE+Y4lX5pk\nvQjC/xoEqSs5pxDDWXAkoexvxij8A4AWcsKU1Q+ep2E+GcytBoz8XINGvgb8cQNn\n/4PlVWKp7j5SDDNCfleYvmiRn8k6P4mxVJOHKzwb/IwQcKghyqAF1w==\n-----END RSA PRIVATE KEY-----");
if(m.find()) {
String content = m.group(2);
assertTrue(content.startsWith("MIIEpAIBAAKCAQE"));
assertTrue(content.endsWith("KghyqAF1w==\n"));
} else {
assertTrue(false);
}
Pattern regex = Pattern.compile("(^[\\-]+[^\\-]+[\\-]+[\\n]?)([^\\-]+)([\\-]+[^\\-]+[\\-]+$)");
Matcher m = regex.matcher("-----BEGIN RSA PRIVATE KEY-----\nMIIEpAIBAAKCAQEAm4bLUORp9oM65GV9XrPrbs+K563DjUR1M8mP1HaE+Y4lX5pk\nvQjC/xoEqSs5pxDDWXAkoexvxij8A4AWcsKU1Q+ep2E+GcytBoz8XINGvgb8cQNn\n/4PlVWKp7j5SDDNCfleYvmiRn8k6P4mxVJOHKzwb/IwQcKghyqAF1w==\n-----END RSA PRIVATE KEY-----");
if(m.find()) {
String content = m.group(2);
assertTrue(content.startsWith("MIIEpAIBAAKCAQE"));
assertTrue(content.endsWith("KghyqAF1w==\n"));
} else {
assertTrue(false);
}
}
public void testKeystoreManager() throws Exception {
@ -122,10 +122,10 @@ public class KeystoreTest extends TestCase {
assertTrue(ksBits != null);
try {
KeyStore ks = CertificateHelper.loadKeystore(ksBits, "vmops.com");
assertTrue(ks != null);
KeyStore ks = CertificateHelper.loadKeystore(ksBits, "vmops.com");
assertTrue(ks != null);
} catch(Exception e) {
assertTrue(false);
assertTrue(false);
}
KeystoreDao ksDao = locator.getDao(KeystoreDao.class);
@ -137,18 +137,18 @@ public class KeystoreTest extends TestCase {
UserVmResponse vm = new UserVmResponse();
vm.setId(Long.toString(3L));
/*
vm.setAccountName("admin");
vm.setName("i-2-3-KY");
vm.setDisplayName("i-2-3-KY");
vm.setDomainId(1L);
vm.setDomainName("ROOT");
vm.setCreated(new Date());
vm.setState("Running");
vm.setZoneId(1L);
vm.setZoneName("KY");
vm.setHostId(1L);
vm.setAccountName("admin");
vm.setName("i-2-3-KY");
vm.setDisplayName("i-2-3-KY");
vm.setDomainId(1L);
vm.setDomainName("ROOT");
vm.setCreated(new Date());
vm.setState("Running");
vm.setZoneId(1L);
vm.setZoneName("KY");
vm.setHostId(1L);
vm.setObjectName("virtualmachine");
vm.setObjectName("virtualmachine");
*/
String result = ApiSerializerHelper.toSerializedString(vm);
// String result = "org.apache.cloudstack.api.response.UserVmResponse/virtualmachine/{\"id\":{\"_tableName\":\"vm_instance\",\"_value\":3},\"name\":\"i-2-3-KY\",\"displayname\":\"i-2-3-KY\",\"account\":\"admin\",\"projectid\":{\"_tableName\":\"projects\"},\"domainid\":{\"_tableName\":\"domain\",\"_value\":1},\"domain\":\"ROOT\",\"created\":\"2011-11-02T21:54:07-0700\",\"state\":\"Running\",\"haenable\":false,\"groupid\":{\"_tableName\":\"instance_group\"},\"zoneid\":{\"_tableName\":\"data_center\",\"_value\":1},\"zonename\":\"KY\",\"hostid\":{\"_tableName\":\"host\",\"_value\":1},\"hostname\":\"xenserver-basic\",\"templateid\":{\"_tableName\":\"vm_template\",\"_value\":2},\"templatename\":\"CentOS 5.3(64-bit) no GUI (XenServer)\",\"templatedisplaytext\":\"CentOS 5.3(64-bit) no GUI (XenServer)\",\"passwordenabled\":false,\"isoid\":{\"_tableName\":\"vm_template\"},\"serviceofferingid\":{\"_tableName\":\"disk_offering\",\"_value\":7},\"serviceofferingname\":\"Small Instance\",\"cpunumber\":1,\"cpuspeed\":500,\"memory\":512,\"guestosid\":{\"_tableName\":\"guest_os\",\"_value\":12},\"rootdeviceid\":0,\"rootdevicetype\":\"NetworkFilesystem\",\"securitygroup\":[],\"jobid\":{\"_tableName\":\"async_job\"},\"nic\":[{\"id\":7,\"networkid\":200,\"netmask\":\"255.255.255.0\",\"gateway\":\"10.1.1.1\",\"ipaddress\":\"10.1.1.116\",\"isolationuri\":\"vlan://1699\",\"broadcasturi\":\"vlan://1699\",\"traffictype\":\"Guest\",\"type\":\"Virtual\",\"isdefault\":true,\"macaddress\":\"02:00:39:a7:00:01\"}],\"hypervisor\":\"XenServer\"}";

View File

@ -23,34 +23,34 @@ import org.junit.Test;
public class RemoteAccessVpnTest {
private final static Logger s_logger = Logger.getLogger(RemoteAccessVpnTest.class);
// private static void addDaos(MockComponentLocator locator) {
// locator.addDao("AccountDao", AccountDaoImpl.class);
// locator.addDao("VpnUserDao", VpnUserDaoImpl.class);
// locator.addDao("FirewallRulesDao", FirewallRulesDaoImpl.class);
// locator.addDao("IPAddressDao", IPAddressDaoImpl.class);
// locator.addDao("DomainDao", DomainDaoImpl.class);
// locator.addDao("UsageEventDao", UsageEventDaoImpl.class);
// locator.addDao("RemoteAccessVpnDao", RemoteAccessVpnDaoImpl.class);
// locator.addDao("ConfigurationDao", ConfigurationDaoImpl.class);
// private static void addDaos(MockComponentLocator locator) {
// locator.addDao("AccountDao", AccountDaoImpl.class);
// locator.addDao("VpnUserDao", VpnUserDaoImpl.class);
// locator.addDao("FirewallRulesDao", FirewallRulesDaoImpl.class);
// locator.addDao("IPAddressDao", IPAddressDaoImpl.class);
// locator.addDao("DomainDao", DomainDaoImpl.class);
// locator.addDao("UsageEventDao", UsageEventDaoImpl.class);
// locator.addDao("RemoteAccessVpnDao", RemoteAccessVpnDaoImpl.class);
// locator.addDao("ConfigurationDao", ConfigurationDaoImpl.class);
//
// }
//
// private static void addManagers(MockComponentLocator locator) {
// locator.addManager("AccountManager", MockAccountManagerImpl.class);
// locator.addManager("DomainManager", MockDomainManagerImpl.class);
// locator.addManager("NetworkManager", MockNetworkManagerImpl.class);
// locator.addManager("NetworkModel", MockNetworkModelImpl.class);
// locator.addManager("RulesManager", MockRulesManagerImpl.class);
// locator.addManager("FirewallManager", MockFirewallManagerImpl.class);
// }
// }
//
// private static void addManagers(MockComponentLocator locator) {
// locator.addManager("AccountManager", MockAccountManagerImpl.class);
// locator.addManager("DomainManager", MockDomainManagerImpl.class);
// locator.addManager("NetworkManager", MockNetworkManagerImpl.class);
// locator.addManager("NetworkModel", MockNetworkModelImpl.class);
// locator.addManager("RulesManager", MockRulesManagerImpl.class);
// locator.addManager("FirewallManager", MockFirewallManagerImpl.class);
// }
// @Before
// public void setUp() {
// locator = new MockComponentLocator("management-server");
// addDaos(locator);
// addManagers(locator);
// s_logger.info("Finished setUp");
// }
// @Before
// public void setUp() {
// locator = new MockComponentLocator("management-server");
// addDaos(locator);
// addManagers(locator);
// s_logger.info("Finished setUp");
// }
@After
public void tearDown() throws Exception {
@ -58,19 +58,19 @@ public class RemoteAccessVpnTest {
@Test
public void testInjected() throws Exception {
// List<Pair<String, Class<? extends RemoteAccessVPNServiceProvider>>> list =
// new ArrayList<Pair<String, Class<? extends RemoteAccessVPNServiceProvider>>>();
// list.add(new Pair<String, Class<? extends RemoteAccessVPNServiceProvider>>("RemoteAccessVPNServiceProvider", MockRemoteAccessVPNServiceProvider.class));
// locator.addAdapterChain(RemoteAccessVPNServiceProvider.class, list);
// s_logger.info("Finished add adapter");
// locator.makeActive(new DefaultInterceptorLibrary());
// s_logger.info("Finished make active");
// RemoteAccessVpnManagerImpl vpnMgr = ComponentLocator.inject(RemoteAccessVpnManagerImpl.class);
// s_logger.info("Finished inject");
// Assert.assertTrue(vpnMgr.configure("RemoteAccessVpnMgr",new HashMap<String, Object>()) );
// Assert.assertTrue(vpnMgr.start());
// int numProviders = vpnMgr.getRemoteAccessVPNServiceProviders().size();
// Assert.assertTrue(numProviders > 0);
// List<Pair<String, Class<? extends RemoteAccessVPNServiceProvider>>> list =
// new ArrayList<Pair<String, Class<? extends RemoteAccessVPNServiceProvider>>>();
// list.add(new Pair<String, Class<? extends RemoteAccessVPNServiceProvider>>("RemoteAccessVPNServiceProvider", MockRemoteAccessVPNServiceProvider.class));
// locator.addAdapterChain(RemoteAccessVPNServiceProvider.class, list);
// s_logger.info("Finished add adapter");
// locator.makeActive(new DefaultInterceptorLibrary());
// s_logger.info("Finished make active");
// RemoteAccessVpnManagerImpl vpnMgr = ComponentLocator.inject(RemoteAccessVpnManagerImpl.class);
// s_logger.info("Finished inject");
// Assert.assertTrue(vpnMgr.configure("RemoteAccessVpnMgr",new HashMap<String, Object>()) );
// Assert.assertTrue(vpnMgr.start());
// int numProviders = vpnMgr.getRemoteAccessVPNServiceProviders().size();
// Assert.assertTrue(numProviders > 0);
}
}

View File

@ -41,157 +41,157 @@ public class MockServer implements Runnable {
protected boolean verbose = System.getProperty("rdpclient.MockServer.debug", "false").equals("true");
public MockServer(Packet packets[]) {
this.packets = packets;
this.packets = packets;
}
public void start() throws IOException {
serverSocket = new ServerSocket(0);
serverSocket = new ServerSocket(0);
shutdown = false;
exception = null;
shutdowned = false;
shutdown = false;
exception = null;
shutdowned = false;
new Thread(this).start();
new Thread(this).start();
}
public void run() {
try {
Socket socket = serverSocket.accept();
try {
Socket socket = serverSocket.accept();
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
try {
for (int i = 0; i < packets.length && !shutdown; i++) {
try {
for (int i = 0; i < packets.length && !shutdown; i++) {
Packet packet = packets[i];
switch (packet.type) {
case CLIENT: {
// Read client data and compare it with mock data
// (unless "ignore" option is set)
byte actualData[] = new byte[packet.data.length];
int actualDataLength = is.read(actualData);
Packet packet = packets[i];
switch (packet.type) {
case CLIENT: {
// Read client data and compare it with mock data
// (unless "ignore" option is set)
byte actualData[] = new byte[packet.data.length];
int actualDataLength = is.read(actualData);
if (verbose)
System.out.println("[" + this + "] INFO: Data is read: {" + Arrays.toString(Arrays.copyOf(actualData, actualDataLength)) + "}.");
if (verbose)
System.out.println("[" + this + "] INFO: Data is read: {" + Arrays.toString(Arrays.copyOf(actualData, actualDataLength)) + "}.");
if (!packet.ignore) {
// Compare actual data with expected data
if (actualDataLength != packet.data.length) {
throw new AssertionError("Actual length of client request for packet #" + (i + 1) + " (\"" + packet.id + "\")"
+ " does not match length of expected client request. Actual length: " + actualDataLength + ", expected legnth: "
+ packet.data.length + ".");
}
if (!packet.ignore) {
// Compare actual data with expected data
if (actualDataLength != packet.data.length) {
throw new AssertionError("Actual length of client request for packet #" + (i + 1) + " (\"" + packet.id + "\")"
+ " does not match length of expected client request. Actual length: " + actualDataLength + ", expected legnth: "
+ packet.data.length + ".");
}
for (int j = 0; j < packet.data.length; j++) {
for (int j = 0; j < packet.data.length; j++) {
if (packet.data[j] != actualData[j]) {
throw new AssertionError("Actual byte #" + (j + 1) + " of client request for packet #" + (i + 1) + " (\"" + packet.id
+ "\")" + " does not match corresponding byte of expected client request. Actual byte: " + actualData[j]
+ ", expected byte: " + packet.data[j] + ".");
}
}
}
break;
}
case SERVER: {
// Send mock data to client
os.write(packet.data);
if (packet.data[j] != actualData[j]) {
throw new AssertionError("Actual byte #" + (j + 1) + " of client request for packet #" + (i + 1) + " (\"" + packet.id
+ "\")" + " does not match corresponding byte of expected client request. Actual byte: " + actualData[j]
+ ", expected byte: " + packet.data[j] + ".");
}
}
}
break;
}
case SERVER: {
// Send mock data to client
os.write(packet.data);
if (verbose)
System.out.println("[" + this + "] INFO: Data is written: {" + Arrays.toString(packet.data) + "}.");
if (verbose)
System.out.println("[" + this + "] INFO: Data is written: {" + Arrays.toString(packet.data) + "}.");
break;
}
case UPGRADE_TO_SSL: {
// Attach SSL context to socket
break;
}
case UPGRADE_TO_SSL: {
// Attach SSL context to socket
final SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(socket, null, serverSocket.getLocalPort(), true);
sslSocket.setEnabledCipherSuites(sslSocket.getSupportedCipherSuites());
sslSocket.setUseClientMode(false);
sslSocket.startHandshake();
is = sslSocket.getInputStream();
os = sslSocket.getOutputStream();
final SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(socket, null, serverSocket.getLocalPort(), true);
sslSocket.setEnabledCipherSuites(sslSocket.getSupportedCipherSuites());
sslSocket.setUseClientMode(false);
sslSocket.startHandshake();
is = sslSocket.getInputStream();
os = sslSocket.getOutputStream();
break;
}
default:
throw new RuntimeException("Unknown packet type: " + packet.type);
}
break;
}
default:
throw new RuntimeException("Unknown packet type: " + packet.type);
}
}
} finally {
try {
is.close();
} catch (Throwable e) {
}
try {
os.close();
} catch (Throwable e) {
}
try {
socket.close();
} catch (Throwable e) {
}
try {
serverSocket.close();
} catch (Throwable e) {
}
}
} catch (Throwable e) {
System.err.println("Error in mock server: " + e.getMessage());
e.printStackTrace(System.err);
exception = e;
}
shutdowned = true;
if (verbose)
System.out.println("[" + this + "] INFO: Mock server shutdowned.");
}
} finally {
try {
is.close();
} catch (Throwable e) {
}
try {
os.close();
} catch (Throwable e) {
}
try {
socket.close();
} catch (Throwable e) {
}
try {
serverSocket.close();
} catch (Throwable e) {
}
}
} catch (Throwable e) {
System.err.println("Error in mock server: " + e.getMessage());
e.printStackTrace(System.err);
exception = e;
}
shutdowned = true;
if (verbose)
System.out.println("[" + this + "] INFO: Mock server shutdowned.");
}
public void shutdown() {
shutdown = true;
shutdown = true;
}
public InetSocketAddress getAddress() {
return (InetSocketAddress) serverSocket.getLocalSocketAddress();
return (InetSocketAddress) serverSocket.getLocalSocketAddress();
}
public Throwable getException() {
return exception;
return exception;
}
public static class Packet {
public static enum PacketType {
SERVER, CLIENT, UPGRADE_TO_SSL;
}
public static enum PacketType {
SERVER, CLIENT, UPGRADE_TO_SSL;
}
public String id = "";
public String id = "";
public Packet() {
}
public Packet() {
}
public Packet(String id) {
this.id = id;
}
public Packet(String id) {
this.id = id;
}
public PacketType type;
public PacketType type;
public boolean ignore = false;
public boolean ignore = false;
public byte data[];
public byte data[];
}
public boolean isShutdowned() {
return shutdowned;
return shutdowned;
}
public void waitUntilShutdowned(long timeToWaitMiliseconds) throws InterruptedException {
long deadline = System.currentTimeMillis() + timeToWaitMiliseconds;
while (!shutdowned && System.currentTimeMillis() < deadline) {
Thread.sleep(10);
}
long deadline = System.currentTimeMillis() + timeToWaitMiliseconds;
while (!shutdowned && System.currentTimeMillis() < deadline) {
Thread.sleep(10);
}
}
}

View File

@ -36,154 +36,154 @@ public class MockServerTest extends TestCase {
public void testIsMockServerCanRespond() throws Exception {
final byte[] mockClientData = new byte[] { 0x01, 0x02, 0x03 };
final byte[] mockServerData = new byte[] { 0x03, 0x02, 0x01 };
final byte[] mockClientData = new byte[] { 0x01, 0x02, 0x03 };
final byte[] mockServerData = new byte[] { 0x03, 0x02, 0x01 };
MockServer server = new MockServer(new Packet[] { new Packet("Client hello") {
{
type = CLIENT;
data = mockClientData;
}
}, new Packet("Server hello") {
{
type = SERVER;
data = mockServerData;
}
} });
MockServer server = new MockServer(new Packet[] { new Packet("Client hello") {
{
type = CLIENT;
data = mockClientData;
}
}, new Packet("Server hello") {
{
type = SERVER;
data = mockServerData;
}
} });
server.start();
server.start();
// Connect to server and send and receive mock data
// Connect to server and send and receive mock data
Socket socket = SocketFactory.getDefault().createSocket();
try {
socket.connect(server.getAddress());
Socket socket = SocketFactory.getDefault().createSocket();
try {
socket.connect(server.getAddress());
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
// Write mock data to server
os.write(mockClientData);
// Write mock data to server
os.write(mockClientData);
// Read data from server
byte actualData[] = new byte[mockServerData.length];
int actualDataLength = is.read(actualData);
// Read data from server
byte actualData[] = new byte[mockServerData.length];
int actualDataLength = is.read(actualData);
// Compare mock data with actual data
assertEquals("Unexpected length of actual data read from server.", mockServerData.length, actualDataLength);
// Compare mock data with actual data
assertEquals("Unexpected length of actual data read from server.", mockServerData.length, actualDataLength);
for (int i = 0; i < actualDataLength; i++) {
assertEquals("Unexpected byte #" + i + " in response", mockServerData[i], actualData[i]);
}
for (int i = 0; i < actualDataLength; i++) {
assertEquals("Unexpected byte #" + i + " in response", mockServerData[i], actualData[i]);
}
server.waitUntilShutdowned(1 * 1000 /* up to 1 second */);
server.waitUntilShutdowned(1 * 1000 /* up to 1 second */);
assertNull("Unexpected exception at mock server side.", server.getException());
assertTrue("Server is not shutdowned at after conversation.", server.isShutdowned());
assertNull("Unexpected exception at mock server side.", server.getException());
assertTrue("Server is not shutdowned at after conversation.", server.isShutdowned());
} finally {
socket.close();
}
} finally {
socket.close();
}
}
public void testIsMockServerCanUpgradeConnectionToSsl() throws Exception {
final byte[] mockClientData1 = new byte[] { 0x01, 0x02, 0x03 };
final byte[] mockServerData1 = new byte[] { 0x03, 0x02, 0x01 };
final byte[] mockClientData1 = new byte[] { 0x01, 0x02, 0x03 };
final byte[] mockServerData1 = new byte[] { 0x03, 0x02, 0x01 };
final byte[] mockClientData2 = new byte[] { 0x02, 0x04, 0x02, 0x03 };
final byte[] mockServerData2 = new byte[] { 0x02, 0x02, 0x01, 0x04 };
final byte[] mockClientData2 = new byte[] { 0x02, 0x04, 0x02, 0x03 };
final byte[] mockServerData2 = new byte[] { 0x02, 0x02, 0x01, 0x04 };
MockServer server = new MockServer(new Packet[] { new Packet("Client hello") {
{
type = CLIENT;
data = mockClientData1;
}
}, new Packet("Server hello") {
{
type = SERVER;
data = mockServerData1;
}
}, new Packet("Upgrade connection to SSL") {
{
type = UPGRADE_TO_SSL;
}
}, new Packet("Client data over SSL") {
{
type = CLIENT;
data = mockClientData2;
}
}, new Packet("Server data over SSL") {
{
type = SERVER;
data = mockServerData2;
}
} });
MockServer server = new MockServer(new Packet[] { new Packet("Client hello") {
{
type = CLIENT;
data = mockClientData1;
}
}, new Packet("Server hello") {
{
type = SERVER;
data = mockServerData1;
}
}, new Packet("Upgrade connection to SSL") {
{
type = UPGRADE_TO_SSL;
}
}, new Packet("Client data over SSL") {
{
type = CLIENT;
data = mockClientData2;
}
}, new Packet("Server data over SSL") {
{
type = SERVER;
data = mockServerData2;
}
} });
server.start();
server.start();
// Connect to server and send and receive mock data
// Connect to server and send and receive mock data
Socket socket = SocketFactory.getDefault().createSocket();
try {
InetSocketAddress address = server.getAddress();
socket.connect(address);
Socket socket = SocketFactory.getDefault().createSocket();
try {
InetSocketAddress address = server.getAddress();
socket.connect(address);
// Send hello data over plain connection
{
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
// Send hello data over plain connection
{
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
// Write mock data to server
os.write(mockClientData1);
// Write mock data to server
os.write(mockClientData1);
// Read data from server
byte actualData[] = new byte[mockServerData1.length];
int actualDataLength = is.read(actualData);
// Read data from server
byte actualData[] = new byte[mockServerData1.length];
int actualDataLength = is.read(actualData);
// Compare mock data with actual data
assertEquals("Unexpected length of actual data read from server.", mockServerData1.length, actualDataLength);
// Compare mock data with actual data
assertEquals("Unexpected length of actual data read from server.", mockServerData1.length, actualDataLength);
for (int i = 0; i < actualDataLength; i++) {
assertEquals("Unexpected byte #" + i + " in response", mockServerData1[i], actualData[i]);
}
}
for (int i = 0; i < actualDataLength; i++) {
assertEquals("Unexpected byte #" + i + " in response", mockServerData1[i], actualData[i]);
}
}
// Upgrade connection to SSL and send mock data
{
//System.setProperty("javax.net.debug", "ssl");
// Upgrade connection to SSL and send mock data
{
//System.setProperty("javax.net.debug", "ssl");
final SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(socket, address.getHostName(), address.getPort(), true);
sslSocket.setEnabledCipherSuites(sslSocket.getSupportedCipherSuites());
sslSocket.startHandshake();
final SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(socket, address.getHostName(), address.getPort(), true);
sslSocket.setEnabledCipherSuites(sslSocket.getSupportedCipherSuites());
sslSocket.startHandshake();
InputStream is = sslSocket.getInputStream();
OutputStream os = sslSocket.getOutputStream();
InputStream is = sslSocket.getInputStream();
OutputStream os = sslSocket.getOutputStream();
// Write mock data to server
os.write(mockClientData2);
// Write mock data to server
os.write(mockClientData2);
// Read data from server
byte actualData[] = new byte[mockServerData2.length];
int actualDataLength = is.read(actualData);
// Read data from server
byte actualData[] = new byte[mockServerData2.length];
int actualDataLength = is.read(actualData);
// Compare mock data with actual data
assertEquals("Unexpected length of actual data read from server.", mockServerData2.length, actualDataLength);
// Compare mock data with actual data
assertEquals("Unexpected length of actual data read from server.", mockServerData2.length, actualDataLength);
for (int i = 0; i < actualDataLength; i++) {
assertEquals("Unexpected byte #" + i + " in response", mockServerData2[i], actualData[i]);
}
for (int i = 0; i < actualDataLength; i++) {
assertEquals("Unexpected byte #" + i + " in response", mockServerData2[i], actualData[i]);
}
}
}
server.waitUntilShutdowned(1 * 1000 /* up to 1 second */);
server.waitUntilShutdowned(1 * 1000 /* up to 1 second */);
assertNull("Unexpected exception at mock server side.", server.getException());
assertTrue("Server is not shutdowned at after conversation.", server.isShutdowned());
} finally {
socket.close();
}
assertNull("Unexpected exception at mock server side.", server.getException());
assertTrue("Server is not shutdowned at after conversation.", server.isShutdowned());
} finally {
socket.close();
}
}
}

View File

@ -176,7 +176,7 @@ public class ConsoleProxyPasswordBasedEncryptor {
random.nextBytes(ivBytes);
KeyIVPair keyIvPair = new KeyIVPair("8x/xUBgX0Up+3UEo39dSeG277JhVj31+ElHkN5+EC0Q=", "Y2SUiIN6JXTdKNK/ZMDyVtLB7gAM9MCCiyrP1xd3bSQ=");
//keyIvPair.setKeyBytes(keyBytes);
//keyIvPair.setKeyBytes(keyBytes);
//keyIvPair.setIvBytes(ivBytes);
Gson gson = new GsonBuilder().create();

View File

@ -43,7 +43,7 @@ public interface DownloadManager extends Manager {
* @param url the url from where to download from
* @param hvm whether the template is a hardware virtual machine
* @param accountId the accountId of the iso owner (null if public iso)
* @param descr description of the template
* @param descr description of the template
* @param user username used for authentication to the server
* @param password password used for authentication to the server
* @param maxDownloadSizeInBytes (optional) max download size for the template, in bytes.

View File

@ -611,21 +611,21 @@ public class UploadManagerImpl extends ManagerBase implements UploadManager {
command = new Script("/bin/bash", s_logger);
command.add("-c");
command.add("iptables -D INPUT -i " + intf + " -p tcp -m state --state NEW -m tcp --dport " + port + " -j DROP;" +
"iptables -D INPUT -i " + intf + " -p tcp -m state --state NEW -m tcp --dport " + port + " -j HTTP;" +
"iptables -D INPUT -i " + intf + " -p tcp -m state --state NEW -m tcp --dport " + "443" + " -j DROP;" +
"iptables -D INPUT -i " + intf + " -p tcp -m state --state NEW -m tcp --dport " + "443" + " -j HTTP;" +
"iptables -F HTTP;" +
"iptables -X HTTP;" +
"iptables -N HTTP;" +
"iptables -I INPUT -i " + intf + " -p tcp -m state --state NEW -m tcp --dport " + port + " -j DROP;" +
"iptables -I INPUT -i " + intf + " -p tcp -m state --state NEW -m tcp --dport " + "443" + " -j DROP;" +
"iptables -I INPUT -i " + intf + " -p tcp -m state --state NEW -m tcp --dport " + port + " -j HTTP;" +
"iptables -D INPUT -i " + intf + " -p tcp -m state --state NEW -m tcp --dport " + port + " -j HTTP;" +
"iptables -D INPUT -i " + intf + " -p tcp -m state --state NEW -m tcp --dport " + "443" + " -j DROP;" +
"iptables -D INPUT -i " + intf + " -p tcp -m state --state NEW -m tcp --dport " + "443" + " -j HTTP;" +
"iptables -F HTTP;" +
"iptables -X HTTP;" +
"iptables -N HTTP;" +
"iptables -I INPUT -i " + intf + " -p tcp -m state --state NEW -m tcp --dport " + port + " -j DROP;" +
"iptables -I INPUT -i " + intf + " -p tcp -m state --state NEW -m tcp --dport " + "443" + " -j DROP;" +
"iptables -I INPUT -i " + intf + " -p tcp -m state --state NEW -m tcp --dport " + port + " -j HTTP;" +
"iptables -I INPUT -i " + intf + " -p tcp -m state --state NEW -m tcp --dport " + "443" + " -j HTTP;");
result = command.execute();
if (result != null) {
s_logger.warn("Error in opening up httpd port err=" + result );
return false;
s_logger.warn("Error in opening up httpd port err=" + result );
return false;
}*/
command = new Script("/bin/bash", s_logger);

View File

@ -27,102 +27,102 @@ 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 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<String> argsList = Arrays.asList(args);
Iterator<String> 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<numThreads; i++){
new Thread(new Runnable() {
public void run() {
try{
public static void main (String[] args){
List<String> argsList = Arrays.asList(args);
Iterator<String> 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<numThreads; i++){
new Thread(new Runnable() {
public void run() {
try{
String username = null;
String singlePrivateIp=null;
Random ran = new Random();
username = Math.abs(ran.nextInt())+ "-user";
//Create User
User myUser = new User(username,username, server, developerServer);
try{
myUser.launchUser();
myUser.registerUser();
}catch (Exception e){
s_logger.warn("Error code: ", e);
}
if (myUser.getUserId()!=null){
s_logger.info("User "+myUser.getUserName()+" was created successfully, starting VM creation");
//create VMs for the user
for (int i=0; i<numVM; i++){
//Create a new VM, add it to the list of user's VMs
VirtualMachine myVM = new VirtualMachine(myUser.getUserId());
myVM.deployVM(zoneId, serviceOfferingId, templateId, myUser.getDeveloperServer(), myUser.getApiKey(), myUser.getSecretKey());
myUser.getVirtualMachines().add(myVM);
singlePrivateIp=myVM.getPrivateIp();
if (singlePrivateIp!=null){
s_logger.info("VM with private Ip "+singlePrivateIp+" was successfully created");
}
else{
s_logger.info("Problems with VM creation for a user"+myUser.getUserName());
s_logger.info("Deployment failed");
break;
}
}
s_logger.info("Deployment done..."+numVM+" VMs were created.");
}
String username = null;
String singlePrivateIp=null;
Random ran = new Random();
username = Math.abs(ran.nextInt())+ "-user";
//Create User
User myUser = new User(username,username, server, developerServer);
try{
myUser.launchUser();
myUser.registerUser();
}catch (Exception e){
s_logger.warn("Error code: ", e);
}
if (myUser.getUserId()!=null){
s_logger.info("User "+myUser.getUserName()+" was created successfully, starting VM creation");
//create VMs for the user
for (int i=0; i<numVM; i++){
//Create a new VM, add it to the list of user's VMs
VirtualMachine myVM = new VirtualMachine(myUser.getUserId());
myVM.deployVM(zoneId, serviceOfferingId, templateId, myUser.getDeveloperServer(), myUser.getApiKey(), myUser.getSecretKey());
myUser.getVirtualMachines().add(myVM);
singlePrivateIp=myVM.getPrivateIp();
if (singlePrivateIp!=null){
s_logger.info("VM with private Ip "+singlePrivateIp+" was successfully created");
}
else{
s_logger.info("Problems with VM creation for a user"+myUser.getUserName());
s_logger.info("Deployment failed");
break;
}
}
s_logger.info("Deployment done..."+numVM+" VMs were created.");
}
}catch (Exception e){
s_logger.error(e);
}
}
}).start();
}
}
}catch (Exception e){
s_logger.error(e);
}
}
}).start();
}
}
}

View File

@ -36,7 +36,7 @@ import com.cloud.test.stress.TestClientWithAPI;
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;
@ -49,161 +49,161 @@ private static final int _developerPort=8080;
public static void main (String[] args){
List<String> argsList = Arrays.asList(args);
Iterator<String> 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<numThreads; i++){
new Thread(new Runnable() {
public void run() {
try{
public static void main (String[] args){
List<String> argsList = Arrays.asList(args);
Iterator<String> 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<numThreads; i++){
new Thread(new Runnable() {
public void run() {
try{
String username = null;
String singlePrivateIp=null;
String singlePublicIp=null;
Random ran = new Random();
username = Math.abs(ran.nextInt())+ "-user";
//Create User
User myUser = new User(username,username, server, developerServer);
try{
myUser.launchUser();
myUser.registerUser();
}catch (Exception e){
s_logger.warn("Error code: ", e);
}
if (myUser.getUserId()!=null){
s_logger.info("User "+myUser.getUserName()+" was created successfully, starting VM creation");
//create VMs for the user
for (int i=0; i<numVM; i++){
//Create a new VM, add it to the list of user's VMs
VirtualMachine myVM = new VirtualMachine(myUser.getUserId());
myVM.deployVM(_zoneId, _serviceOfferingId, _templateId, myUser.getDeveloperServer(), myUser.getApiKey(), myUser.getSecretKey());
myUser.getVirtualMachines().add(myVM);
singlePrivateIp=myVM.getPrivateIp();
if (singlePrivateIp!=null){
s_logger.info("VM with private Ip "+singlePrivateIp+" was successfully created");
}
else{
s_logger.info("Problems with VM creation for a user"+myUser.getUserName());
break;
}
//get public IP address for the User
myUser.retrievePublicIp(_zoneId);
singlePublicIp=myUser.getPublicIp().get(myUser.getPublicIp().size()-1);
if (singlePublicIp!=null){
s_logger.info("Successfully got public Ip "+singlePublicIp+" for user "+myUser.getUserName());
}
else{
s_logger.info("Problems with getting public Ip address for user"+myUser.getUserName());
break;
}
//create ForwardProxy rules for user's VMs
int responseCode = CreateForwardingRule(myUser, singlePrivateIp, singlePublicIp, "22", "22");
if (responseCode==500)
break;
}
s_logger.info("Deployment successful..."+numVM+" VMs were created. Waiting for 5 min before performance test");
Thread.sleep(300000L); // Wait
//Start performance test for the user
s_logger.info("Starting performance test for Guest network that has "+myUser.getPublicIp().size()+" public IP addresses");
for (int j=0; j<myUser.getPublicIp().size(); j++){
s_logger.info("Starting test for user which has "+myUser.getVirtualMachines().size()+" vms. Public IP for the user is "+myUser.getPublicIp().get(j)+" , number of retries is "+_retry+" , private IP address of the machine is"+myUser.getVirtualMachines().get(j).getPrivateIp());
guestNetwork myNetwork =new guestNetwork(myUser.getPublicIp().get(j), _retry);
myNetwork.setVirtualMachines(myUser.getVirtualMachines());
new Thread(myNetwork).start();
}
}
}catch (Exception e){
s_logger.error(e);
}
}
}).start();
}
}
String username = null;
String singlePrivateIp=null;
String singlePublicIp=null;
Random ran = new Random();
username = Math.abs(ran.nextInt())+ "-user";
//Create User
User myUser = new User(username,username, server, developerServer);
try{
myUser.launchUser();
myUser.registerUser();
}catch (Exception e){
s_logger.warn("Error code: ", e);
}
if (myUser.getUserId()!=null){
s_logger.info("User "+myUser.getUserName()+" was created successfully, starting VM creation");
//create VMs for the user
for (int i=0; i<numVM; i++){
//Create a new VM, add it to the list of user's VMs
VirtualMachine myVM = new VirtualMachine(myUser.getUserId());
myVM.deployVM(_zoneId, _serviceOfferingId, _templateId, myUser.getDeveloperServer(), myUser.getApiKey(), myUser.getSecretKey());
myUser.getVirtualMachines().add(myVM);
singlePrivateIp=myVM.getPrivateIp();
if (singlePrivateIp!=null){
s_logger.info("VM with private Ip "+singlePrivateIp+" was successfully created");
}
else{
s_logger.info("Problems with VM creation for a user"+myUser.getUserName());
break;
}
//get public IP address for the User
myUser.retrievePublicIp(_zoneId);
singlePublicIp=myUser.getPublicIp().get(myUser.getPublicIp().size()-1);
if (singlePublicIp!=null){
s_logger.info("Successfully got public Ip "+singlePublicIp+" for user "+myUser.getUserName());
}
else{
s_logger.info("Problems with getting public Ip address for user"+myUser.getUserName());
break;
}
//create ForwardProxy rules for user's VMs
int responseCode = CreateForwardingRule(myUser, singlePrivateIp, singlePublicIp, "22", "22");
if (responseCode==500)
break;
}
s_logger.info("Deployment successful..."+numVM+" VMs were created. Waiting for 5 min before performance test");
Thread.sleep(300000L); // Wait
//Start performance test for the user
s_logger.info("Starting performance test for Guest network that has "+myUser.getPublicIp().size()+" public IP addresses");
for (int j=0; j<myUser.getPublicIp().size(); j++){
s_logger.info("Starting test for user which has "+myUser.getVirtualMachines().size()+" vms. Public IP for the user is "+myUser.getPublicIp().get(j)+" , number of retries is "+_retry+" , private IP address of the machine is"+myUser.getVirtualMachines().get(j).getPrivateIp());
guestNetwork myNetwork =new guestNetwork(myUser.getPublicIp().get(j), _retry);
myNetwork.setVirtualMachines(myUser.getVirtualMachines());
new Thread(myNetwork).start();
}
}
}catch (Exception e){
s_logger.error(e);
}
}
}).start();
}
}
private static int CreateForwardingRule(User myUser, String privateIp, String publicIp, String publicPort, String privatePort) throws IOException{
String encodedPrivateIp=URLEncoder.encode(""+privateIp, "UTF-8");
String encodedPublicIp=URLEncoder.encode(""+publicIp, "UTF-8");
String encodedPrivatePort=URLEncoder.encode(""+privatePort, "UTF-8");
String encodedPublicPort=URLEncoder.encode(""+publicPort, "UTF-8");
String encodedApiKey = URLEncoder.encode(myUser.getApiKey(), "UTF-8");
int responseCode=500;
String requestToSign = "apiKey=" + encodedApiKey
+ "&command=createOrUpdateIpForwardingRule&privateIp="
+ encodedPrivateIp + "&privatePort=" + encodedPrivatePort
+ "&protocol=tcp&publicIp="
+ encodedPublicIp + "&publicPort="+encodedPublicPort;
requestToSign = requestToSign.toLowerCase();
s_logger.info("Request to sign is "+requestToSign);
String signature = TestClientWithAPI.signRequest(requestToSign, myUser.getSecretKey());
String encodedSignature = URLEncoder.encode(signature, "UTF-8");
private static int CreateForwardingRule(User myUser, String privateIp, String publicIp, String publicPort, String privatePort) throws IOException{
String encodedPrivateIp=URLEncoder.encode(""+privateIp, "UTF-8");
String encodedPublicIp=URLEncoder.encode(""+publicIp, "UTF-8");
String encodedPrivatePort=URLEncoder.encode(""+privatePort, "UTF-8");
String encodedPublicPort=URLEncoder.encode(""+publicPort, "UTF-8");
String encodedApiKey = URLEncoder.encode(myUser.getApiKey(), "UTF-8");
int responseCode=500;
String requestToSign = "apiKey=" + encodedApiKey
+ "&command=createOrUpdateIpForwardingRule&privateIp="
+ encodedPrivateIp + "&privatePort=" + encodedPrivatePort
+ "&protocol=tcp&publicIp="
+ encodedPublicIp + "&publicPort="+encodedPublicPort;
requestToSign = requestToSign.toLowerCase();
s_logger.info("Request to sign is "+requestToSign);
String signature = TestClientWithAPI.signRequest(requestToSign, myUser.getSecretKey());
String encodedSignature = URLEncoder.encode(signature, "UTF-8");
String url = myUser.getDeveloperServer() + "?command=createOrUpdateIpForwardingRule"
+ "&publicIp=" + encodedPublicIp
+ "&publicPort="+encodedPublicPort+"&privateIp=" + encodedPrivateIp
+ "&privatePort=" + encodedPrivatePort + "&protocol=tcp&apiKey=" + encodedApiKey
+ "&signature=" + encodedSignature;
s_logger.info("Trying to create IP forwarding rule: "+url);
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod(url);
responseCode = client.executeMethod(method);
s_logger.info("create ip forwarding rule response code: "
+ responseCode);
if (responseCode == 200) {
s_logger.info("The rule is created successfully");
} else if (responseCode == 500) {
InputStream is = method.getResponseBodyAsStream();
Map<String, String> 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;
}
String url = myUser.getDeveloperServer() + "?command=createOrUpdateIpForwardingRule"
+ "&publicIp=" + encodedPublicIp
+ "&publicPort="+encodedPublicPort+"&privateIp=" + encodedPrivateIp
+ "&privatePort=" + encodedPrivatePort + "&protocol=tcp&apiKey=" + encodedApiKey
+ "&signature=" + encodedSignature;
s_logger.info("Trying to create IP forwarding rule: "+url);
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod(url);
responseCode = client.executeMethod(method);
s_logger.info("create ip forwarding rule response code: "
+ responseCode);
if (responseCode == 200) {
s_logger.info("The rule is created successfully");
} else if (responseCode == 500) {
InputStream is = method.getResponseBodyAsStream();
Map<String, String> 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;
}
}

View File

@ -32,207 +32,207 @@ import com.cloud.test.stress.TestClientWithAPI;
public class User {
public static final Logger s_logger= Logger.getLogger(User.class.getClass());
private ArrayList<VirtualMachine> virtualMachines;
private ArrayList<String> 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 static final Logger s_logger= Logger.getLogger(User.class.getClass());
private ArrayList<VirtualMachine> virtualMachines;
private ArrayList<String> 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<VirtualMachine>();
this.publicIp = new ArrayList<String>();
}
public ArrayList<VirtualMachine> getVirtualMachines() {
return virtualMachines;
}
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<VirtualMachine>();
this.publicIp = new ArrayList<String>();
}
public ArrayList<VirtualMachine> getVirtualMachines() {
return virtualMachines;
}
public void setVirtualMachines(ArrayList<VirtualMachine> virtualMachines) {
this.virtualMachines = virtualMachines;
}
public void setVirtualMachines(ArrayList<VirtualMachine> virtualMachines) {
this.virtualMachines = virtualMachines;
}
public String getUserId() {
return userId;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public ArrayList<String> getPublicIp() {
return publicIp;
}
public ArrayList<String> getPublicIp() {
return publicIp;
}
public void setPublicIp(ArrayList<String> publicIp) {
this.publicIp = publicIp;
}
public void setPublicIp(ArrayList<String> publicIp) {
this.publicIp = publicIp;
}
public String getServer() {
return server;
}
public String getServer() {
return server;
}
public void setServer(String server) {
this.server = server;
}
public void setServer(String server) {
this.server = server;
}
public String getUserName() {
return userName;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getApiKey() {
return apiKey;
}
public String getApiKey() {
return apiKey;
}
public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
public String getPassword() {
return password;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSecretKey() {
return secretKey;
}
public void setPassword(String password) {
this.password = password;
}
public String getSecretKey() {
return secretKey;
}
public void setSecretKey(String secretKey) {
this.secretKey = secretKey;
}
public void setSecretKey(String secretKey) {
this.secretKey = secretKey;
}
public String getDeveloperServer() {
return developerServer;
}
public String getDeveloperServer() {
return developerServer;
}
public void setDeveloperServer(String developerServer) {
this.developerServer = 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);
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<String, String> 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");
if (responseCode == 200) {
InputStream is = method.getResponseBodyAsStream();
Map<String, String> 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;
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<String, String> 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<String, String> 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<String, String> 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<String, String> 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());
}
}
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod(url);
int responseCode=client.executeMethod(method);
if (responseCode == 200) {
InputStream is = method.getResponseBodyAsStream();
Map<String, String> 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<String, String> 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<String, String> 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<String, String> 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());
}
}
}

View File

@ -32,85 +32,85 @@ 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 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 void setPrivateIp(String privateIp) {
this.privateIp = privateIp;
}
public String getUserId() {
return userId;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = 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{
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<String, String> 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"));
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<String, String> 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<String, String> 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());
}
}
} else if (responseCode == 500) {
InputStream is = method.getResponseBodyAsStream();
Map<String, String> 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());
}
}
}

View File

@ -24,84 +24,84 @@ 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<VirtualMachine> virtualMachines;
private int retryNum;
public guestNetwork(String publicIp, int retryNum){
this.publicIp=publicIp;
this.retryNum=retryNum;
}
public ArrayList<VirtualMachine> getVirtualMachines() {
return virtualMachines;
}
public static final Logger s_logger= Logger.getLogger(guestNetwork.class.getClass());
private String publicIp;
private ArrayList<VirtualMachine> virtualMachines;
private int retryNum;
public guestNetwork(String publicIp, int retryNum){
this.publicIp=publicIp;
this.retryNum=retryNum;
}
public ArrayList<VirtualMachine> getVirtualMachines() {
return virtualMachines;
}
public void setVirtualMachines(ArrayList<VirtualMachine> virtualMachines) {
this.virtualMachines = virtualMachines;
}
public void setVirtualMachines(ArrayList<VirtualMachine> 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);
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);
s_logger.info("SSHed successfully into linux host " + this.publicIp);
boolean isAuthenticated = conn.authenticateWithPassword("root",
"password");
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()) ;
}
}
}
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()) ;
}
}
}
}
}
}

View File

@ -29,103 +29,103 @@ import com.trilead.ssh2.Connection;
import com.trilead.ssh2.Session;
public class ConfigTest extends TestCase{
public static final Logger s_logger = Logger.getLogger(ConfigTest.class.getName());
public ConfigTest(){
this.setClient();
this.setParam(new HashMap<String, String>());
}
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<commandLst.getLength(); i++) {
Node fstNode = commandLst.item(i);
Element fstElmnt = (Element) fstNode;
//new command
ApiCommand api = new ApiCommand(fstElmnt, this.getParam(), this.getCommands());
if (api.getName().equals("rebootManagementServer")) {
s_logger.info("Attempting to SSH into management server " + this.getParam().get("hostip"));
try {
Connection conn = new Connection(this.getParam().get("hostip"));
conn.connect(null, 60000, 60000);
public static final Logger s_logger = Logger.getLogger(ConfigTest.class.getName());
public ConfigTest(){
this.setClient();
this.setParam(new HashMap<String, String>());
}
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<commandLst.getLength(); i++) {
Node fstNode = commandLst.item(i);
Element fstElmnt = (Element) fstNode;
//new command
ApiCommand api = new ApiCommand(fstElmnt, this.getParam(), this.getCommands());
if (api.getName().equals("rebootManagementServer")) {
s_logger.info("Attempting to SSH into management server " + this.getParam().get("hostip"));
try {
Connection conn = new Connection(this.getParam().get("hostip"));
conn.connect(null, 60000, 60000);
s_logger.info("SSHed successfully into management server " + this.getParam().get("hostip"));
s_logger.info("SSHed successfully into management server " + this.getParam().get("hostip"));
boolean isAuthenticated = conn.authenticateWithPassword("root",
"password");
boolean isAuthenticated = conn.authenticateWithPassword("root",
"password");
if (isAuthenticated == false) {
s_logger.info("Authentication failed for root with password");
return false;
}
String restartCommand = "service cloud-management restart; service cloud-usage restart";
Session sess = conn.openSession();
s_logger.info("Executing : " + restartCommand);
sess.execCommand(restartCommand);
Thread.sleep(120000);
sess.close();
conn.close();
} catch (Exception ex) {
s_logger.error(ex);
return false;
}
}
else {
//send a command
api.sendCommand(this.getClient(), null);
//verify the response of the command
if ((api.getResponseType() == ResponseType.ERROR) && (api.getResponseCode() == 200) && (api.getTestCaseInfo() != null)) {
s_logger.error("Test case " + api.getTestCaseInfo() + "failed. Command that was supposed to fail, passed. The command was sent with the following url " + api.getUrl());
error++;
}
else if ((api.getResponseType() != ResponseType.ERROR) && (api.getResponseCode() == 200)) {
//set parameters for the future use
if (api.setParam(this.getParam()) == false) {
s_logger.error("Exiting the test...Command " + api.getName() + " didn't return parameters needed for the future use. The command was sent with url " + api.getUrl());
return false;
}
else {
//verify parameters
if (api.verifyParam() == false)
{
s_logger.error("Command " + api.getName() + " failed. Verification for returned parameters failed. Command was sent with url " + api.getUrl());
error++;
}
else if (api.getTestCaseInfo() != null)
{
s_logger.info("Test case " + api.getTestCaseInfo() + " passed. Command was sent with the url " + api.getUrl());
}
}
}
else if ((api.getResponseType() != ResponseType.ERROR) && (api.getResponseCode() != 200)) {
s_logger.error("Command " + api.getName() + " failed with an error code " + api.getResponseCode() + " . Command was sent with url " + api.getUrl() + " Required: " + api.getRequired());
if (api.getRequired() == true) {
s_logger.info("The command is required for the future use, so exiging");
return false;
}
error++;
}
else if (api.getTestCaseInfo() != null) {
s_logger.info("Test case " + api.getTestCaseInfo() + " passed. Command that was supposed to fail, failed - test passed. Command was sent with url " + api.getUrl());
}
}
}
if (error != 0)
return false;
else
return true;
}
if (isAuthenticated == false) {
s_logger.info("Authentication failed for root with password");
return false;
}
String restartCommand = "service cloud-management restart; service cloud-usage restart";
Session sess = conn.openSession();
s_logger.info("Executing : " + restartCommand);
sess.execCommand(restartCommand);
Thread.sleep(120000);
sess.close();
conn.close();
} catch (Exception ex) {
s_logger.error(ex);
return false;
}
}
else {
//send a command
api.sendCommand(this.getClient(), null);
//verify the response of the command
if ((api.getResponseType() == ResponseType.ERROR) && (api.getResponseCode() == 200) && (api.getTestCaseInfo() != null)) {
s_logger.error("Test case " + api.getTestCaseInfo() + "failed. Command that was supposed to fail, passed. The command was sent with the following url " + api.getUrl());
error++;
}
else if ((api.getResponseType() != ResponseType.ERROR) && (api.getResponseCode() == 200)) {
//set parameters for the future use
if (api.setParam(this.getParam()) == false) {
s_logger.error("Exiting the test...Command " + api.getName() + " didn't return parameters needed for the future use. The command was sent with url " + api.getUrl());
return false;
}
else {
//verify parameters
if (api.verifyParam() == false)
{
s_logger.error("Command " + api.getName() + " failed. Verification for returned parameters failed. Command was sent with url " + api.getUrl());
error++;
}
else if (api.getTestCaseInfo() != null)
{
s_logger.info("Test case " + api.getTestCaseInfo() + " passed. Command was sent with the url " + api.getUrl());
}
}
}
else if ((api.getResponseType() != ResponseType.ERROR) && (api.getResponseCode() != 200)) {
s_logger.error("Command " + api.getName() + " failed with an error code " + api.getResponseCode() + " . Command was sent with url " + api.getUrl() + " Required: " + api.getRequired());
if (api.getRequired() == true) {
s_logger.info("The command is required for the future use, so exiging");
return false;
}
error++;
}
else if (api.getTestCaseInfo() != null) {
s_logger.info("Test case " + api.getTestCaseInfo() + " passed. Command that was supposed to fail, failed - test passed. Command was sent with url " + api.getUrl());
}
}
}
if (error != 0)
return false;
else
return true;
}
}

Some files were not shown because too many files have changed in this diff Show More