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 ); //public static OrderedPair <Integer,Integer> getCannedAccessControls ( String aclRequestString, String target );
/* { /* {
if ( aclRequestString.equalsIgnoreCase( "public-read" )) if ( aclRequestString.equalsIgnoreCase( "public-read" ))
// All users granted READ access. // All users granted READ access.
return new OrderedPair <Integer,Integer> (PERMISSION_READ,GRANTEE_ALLUSERS); return new OrderedPair <Integer,Integer> (PERMISSION_READ,GRANTEE_ALLUSERS);
else if (aclRequestString.equalsIgnoreCase( "public-read-write" )) else if (aclRequestString.equalsIgnoreCase( "public-read-write" ))
// All users granted READ and WRITE access // All users granted READ and WRITE access
return new OrderedPair <Integer,Integer> ((PERMISSION_READ | PERMISSION_WRITE),GRANTEE_ALLUSERS); return new OrderedPair <Integer,Integer> ((PERMISSION_READ | PERMISSION_WRITE),GRANTEE_ALLUSERS);
else if (aclRequestString.equalsIgnoreCase( "authenticated-read" )) else if (aclRequestString.equalsIgnoreCase( "authenticated-read" ))
// Authenticated users have READ access // Authenticated users have READ access
return new OrderedPair <Integer,Integer> (PERMISSION_READ,GRANTEE_AUTHENTICATED); return new OrderedPair <Integer,Integer> (PERMISSION_READ,GRANTEE_AUTHENTICATED);
else if (aclRequestString.equalsIgnoreCase( "private" )) else if (aclRequestString.equalsIgnoreCase( "private" ))
// Only Owner gets FULL_CONTROL // Only Owner gets FULL_CONTROL
return new OrderedPair <Integer,Integer> (PERMISSION_FULL,GRANTEE_USER); return new OrderedPair <Integer,Integer> (PERMISSION_FULL,GRANTEE_USER);
else if (aclRequestString.equalsIgnoreCase( "bucket-owner-read" )) else if (aclRequestString.equalsIgnoreCase( "bucket-owner-read" ))
{ {
// Object Owner gets FULL_CONTROL, Bucket Owner gets READ // Object Owner gets FULL_CONTROL, Bucket Owner gets READ
if ( target.equalsIgnoreCase( "SBucket" )) if ( target.equalsIgnoreCase( "SBucket" ))
return new OrderedPair <Integer,Integer> (PERMISSION_READ, GRANTEE_USER); return new OrderedPair <Integer,Integer> (PERMISSION_READ, GRANTEE_USER);
else else
return new OrderedPair <Integer,Integer> (PERMISSION_FULL, GRANTEE_USER); return new OrderedPair <Integer,Integer> (PERMISSION_FULL, GRANTEE_USER);
} }
else if (aclRequestString.equalsIgnoreCase( "bucket-owner-full-control" )) else if (aclRequestString.equalsIgnoreCase( "bucket-owner-full-control" ))
{ {
// Object Owner gets FULL_CONTROL, Bucket Owner gets FULL_CONTROL // Object Owner gets FULL_CONTROL, Bucket Owner gets FULL_CONTROL
// This is equivalent to private when used with PUT Bucket // This is equivalent to private when used with PUT Bucket
return new OrderedPair <Integer,Integer> (PERMISSION_FULL,GRANTEE_USER); return new OrderedPair <Integer,Integer> (PERMISSION_FULL,GRANTEE_USER);
} }
else throw new UnsupportedException( "Unknown Canned Access Policy: " + aclRequestString + " is not supported" ); else throw new UnsupportedException( "Unknown Canned Access Policy: " + aclRequestString + " is not supported" );
} }
*/ */
/** Return a Triple /** Return a Triple
* < permission1, permission2, symbol > * < 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 "*" * @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 ); //public static Triple <Integer,Integer,String> getCannedAccessControls ( String aclRequestString, String target, String ownerID );
/* throws UnsupportedException /* throws UnsupportedException
{ {
if ( aclRequestString.equalsIgnoreCase( "public-read" )) if ( aclRequestString.equalsIgnoreCase( "public-read" ))
// Owner gets FULL_CONTROL and the anonymous principal (the 'A' symbol here) is granted READ access. // 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"); return new Triple <Integer, Integer, String> (PERMISSION_FULL, PERMISSION_READ,"A");
else if (aclRequestString.equalsIgnoreCase( "public-read-write" )) 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 // 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"); return new Triple <Integer, Integer, String> (PERMISSION_FULL, (PERMISSION_READ | PERMISSION_WRITE),"A");
else if (aclRequestString.equalsIgnoreCase( "authenticated-read" )) 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 // 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,"*"); return new Triple <Integer, Integer, String> (PERMISSION_FULL, PERMISSION_READ,"*");
else if (aclRequestString.equalsIgnoreCase( "private" )) else if (aclRequestString.equalsIgnoreCase( "private" ))
// This is termed the "private" or default ACL, "Owner gets FULL_CONTROL" // This is termed the "private" or default ACL, "Owner gets FULL_CONTROL"
return new Triple <Integer, Integer, String> (PERMISSION_FULL, PERMISSION_FULL,null); return new Triple <Integer, Integer, String> (PERMISSION_FULL, PERMISSION_FULL,null);
else if (aclRequestString.equalsIgnoreCase( "bucket-owner-read" )) else if (aclRequestString.equalsIgnoreCase( "bucket-owner-read" ))
{ {
// Object Owner gets FULL_CONTROL, Bucket Owner gets READ // Object Owner gets FULL_CONTROL, Bucket Owner gets READ
// This is equivalent to private when used with PUT Bucket // This is equivalent to private when used with PUT Bucket
if ( target.equalsIgnoreCase( "SBucket" )) if ( target.equalsIgnoreCase( "SBucket" ))
return new Triple <Integer, Integer, String> (PERMISSION_FULL,PERMISSION_FULL ,null); return new Triple <Integer, Integer, String> (PERMISSION_FULL,PERMISSION_FULL ,null);
else else
return new Triple <Integer, Integer, String> (PERMISSION_FULL,PERMISSION_READ,ownerID); return new Triple <Integer, Integer, String> (PERMISSION_FULL,PERMISSION_READ,ownerID);
} }
else if (aclRequestString.equalsIgnoreCase( "bucket-owner-full-control" )) else if (aclRequestString.equalsIgnoreCase( "bucket-owner-full-control" ))
{ {
// Object Owner gets FULL_CONTROL, Bucket Owner gets FULL_CONTROL // Object Owner gets FULL_CONTROL, Bucket Owner gets FULL_CONTROL
// This is equivalent to private when used with PUT Bucket // This is equivalent to private when used with PUT Bucket
if ( target.equalsIgnoreCase( "SBucket" )) if ( target.equalsIgnoreCase( "SBucket" ))
return new Triple <Integer, Integer, String> (PERMISSION_FULL, PERMISSION_FULL, null); return new Triple <Integer, Integer, String> (PERMISSION_FULL, PERMISSION_FULL, null);
else else
return new Triple <Integer, Integer, String> (PERMISSION_FULL,PERMISSION_FULL, ownerID); return new Triple <Integer, Integer, String> (PERMISSION_FULL,PERMISSION_FULL, ownerID);
} }
else throw new UnsupportedException( "Unknown Canned Access Policy: " + aclRequestString + " is not supported" ); 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_ENABLED = 1;
public static final int VERSIONING_SUSPENDED = 2; public static final int VERSIONING_SUSPENDED = 2;
/* private Long id; /* private Long id;
private String name; private String name;
private String ownerCanonicalId; private String ownerCanonicalId;
private SHost shost; private SHost shost;
private Date createTime; private Date createTime;
private int versioningStatus; private int versioningStatus;
private Set<SObject> objectsInBucket = new HashSet<SObject>(); private Set<SObject> objectsInBucket = new HashSet<SObject>();
public SBucket() { public SBucket() {
versioningStatus = VERSIONING_NULL; versioningStatus = VERSIONING_NULL;
} }
public Long getId() { public Long getId() {
return id; return id;
} }
private void setId(Long id) { private void setId(Long id) {
this.id = id; this.id = id;
} }
public String getName() { public String getName() {
return name; return name;
} }
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
public String getOwnerCanonicalId() { public String getOwnerCanonicalId() {
return ownerCanonicalId; return ownerCanonicalId;
} }
public void setOwnerCanonicalId(String ownerCanonicalId) { public void setOwnerCanonicalId(String ownerCanonicalId) {
this.ownerCanonicalId = ownerCanonicalId; this.ownerCanonicalId = ownerCanonicalId;
} }
public SHost getShost() { public SHost getShost() {
return shost; return shost;
} }
public void setShost(SHost shost) { public void setShost(SHost shost) {
this.shost = shost; this.shost = shost;
} }
public Date getCreateTime() { public Date getCreateTime() {
return createTime; return createTime;
} }
public void setCreateTime(Date createTime) { public void setCreateTime(Date createTime) {
this.createTime = createTime; this.createTime = createTime;
} }
public int getVersioningStatus() { public int getVersioningStatus() {
return versioningStatus; return versioningStatus;
} }
public void setVersioningStatus( int versioningStatus ) { public void setVersioningStatus( int versioningStatus ) {
this.versioningStatus = versioningStatus; this.versioningStatus = versioningStatus;
} }
public Set<SObject> getObjectsInBucket() { public Set<SObject> getObjectsInBucket() {
return objectsInBucket; return objectsInBucket;
} }
public void setObjectsInBucket(Set<SObject> objectsInBucket) { public void setObjectsInBucket(Set<SObject> objectsInBucket) {
this.objectsInBucket = objectsInBucket; this.objectsInBucket = objectsInBucket;
} }
@Override @Override
public boolean equals(Object other) { public boolean equals(Object other) {
if(this == other) if(this == other)
return true; return true;
if(!(other instanceof SBucket)) if(!(other instanceof SBucket))
return false; return false;
return getName().equals(((SBucket)other).getName()); return getName().equals(((SBucket)other).getName());
} }
@Override @Override
public int hashCode() { public int hashCode() {
return getName().hashCode(); return getName().hashCode();
}*/ }*/
} }

View File

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

View File

@ -54,7 +54,7 @@ public class SObjectVO {
private int nextSequence; private int nextSequence;
@Column(name = "DeletionMark") @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") @Column(name = "CreateTime")
@Temporal(value = TemporalType.TIMESTAMP) @Temporal(value = TemporalType.TIMESTAMP)

View File

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

View File

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

View File

@ -392,7 +392,7 @@ public class S3RestServlet extends HttpServlet {
return new S3BucketAction(); // for ListAllMyBuckets 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); pathInfo = pathInfo.substring(1);
if (ServiceProvider.getInstance().getUseSubDomain()) if (ServiceProvider.getInstance().getUseSubDomain())

View File

@ -893,7 +893,7 @@ public class S3BucketAction implements ServletAction {
public void executePutBucketWebsite(HttpServletRequest request, HttpServletResponse response) throws IOException { public void executePutBucketWebsite(HttpServletRequest request, HttpServletResponse response) throws IOException {
// TODO -- LoPri - Undertake checks on Put Bucket Website // TODO -- LoPri - Undertake checks on Put Bucket Website
// Tested using configuration <Directory /Users/john1/S3-Mount>\nAllowOverride FileInfo AuthConfig Limit...</Directory> in httpd.conf // 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 // Currently has noop effect in the sense that a running apachectl process sees the directory contents without further action
response.setStatus(200); response.setStatus(200);
} }

View File

@ -599,7 +599,7 @@ public class S3ObjectAction implements ServletAction {
//System.out.println( oneLine.length() + " body data: " + oneLine ); //System.out.println( oneLine.length() + " body data: " + oneLine );
temp.append(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 // [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 final Timer timer = new Timer();
private MHostVO mhost; private MHostVO mhost;
private Properties properties; 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 serviceEndpoint = null;
private String multipartDir = null; // illegal bucket name used as a folder for storing multiparts private String multipartDir = null; // illegal bucket name used as a folder for storing multiparts
private String masterDomain = ".s3.amazonaws.com"; private String masterDomain = ".s3.amazonaws.com";

View File

@ -861,7 +861,7 @@ public class EC2Engine extends ManagerBase {
CloudStackZone zone = findZone(); CloudStackZone zone = findZone();
//CloudStackNetwork net = findNetwork(zone); //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); CloudStackIpAddress resp = getApi().associateIpAddress(zone.getId(), caller.getName(), caller.getDomainId(), null);
ec2Address.setAssociatedInstanceId(resp.getId()); ec2Address.setAssociatedInstanceId(resp.getId());
@ -1213,12 +1213,12 @@ public class EC2Engine extends ManagerBase {
throw new EC2ServiceException(ServerError.InternalError, "No Customize Disk Offering Found"); 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)); CloudStackVolume vol = getApi().createVolume(UUID.randomUUID().toString(), null, diskOfferingId, null, size, snapshotId, toZoneId(request.getZoneName(), null));
if (vol != null) { if (vol != null) {
resp.setAttached(vol.getAttached()); resp.setAttached(vol.getAttached());
resp.setCreated(vol.getCreated()); resp.setCreated(vol.getCreated());
// resp.setDevice(); // resp.setDevice();
resp.setDeviceId(vol.getDeviceId()); resp.setDeviceId(vol.getDeviceId());
resp.setHypervisor(vol.getHypervisor()); resp.setHypervisor(vol.getHypervisor());
resp.setId(vol.getId()); resp.setId(vol.getId());

View File

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

View File

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

View File

@ -120,7 +120,7 @@ public class S3Engine {
static SAclDao s_saclDao; static SAclDao s_saclDao;
static BucketPolicyDao s_bPolicy; 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>(); private final Map<Integer, S3BucketAdapter> bucketAdapters = new HashMap<Integer, S3BucketAdapter>();
@ -775,7 +775,7 @@ public class S3Engine {
if (bucket == null) if (bucket == null)
throw new NoSuchObjectException("Bucket " + bucketName + " does not exist"); 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 // The allocObjectItem checks for the bucket policy PutObject permissions
OrderedPair<SObjectVO, SObjectItemVO> object_objectitem_pair = allocObjectItem(bucket, key, meta, acl, null); OrderedPair<SObjectVO, SObjectItemVO> object_objectitem_pair = allocObjectItem(bucket, key, meta, acl, null);
OrderedPair<SHostVO, String> host_storagelocation_pair = getBucketStorageHost(bucket); OrderedPair<SHostVO, String> host_storagelocation_pair = getBucketStorageHost(bucket);
@ -1028,7 +1028,7 @@ public class S3Engine {
return response; 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 // -> extract the meta data that corresponds the specific versioned item
List<SMetaVO> itemMetaData = metaDao.getByTarget("SObjectItem", item.getId()); List<SMetaVO> itemMetaData = metaDao.getByTarget("SObjectItem", item.getId());
@ -1137,7 +1137,7 @@ public class S3Engine {
response.setResultDescription("<VersionId>" + wantVersion + "</VersionId>"); 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); S3PolicyContext context = new S3PolicyContext(PolicyActions.DeleteObject, bucketName);
context.setKeyName(nameKey); context.setKeyName(nameKey);
verifyAccess(context, "SBucket", sbucket.getId(), SAcl.PERMISSION_WRITE); 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 * 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) { 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()); Triple<Integer, Integer, String> permission_permission_symbol_triple = SAclVO.getCannedAccessControls(cannedAccessPolicy, target, bucket.getOwnerCanonicalId());
if (null == permission_permission_symbol_triple.getThird()) if (null == permission_permission_symbol_triple.getThird())
setSingleAcl(target, objectId, permission_permission_symbol_triple.getFirst()); setSingleAcl(target, objectId, permission_permission_symbol_triple.getFirst());
@ -1672,7 +1672,7 @@ public class S3Engine {
if (hasPermission(s_saclDao.listGrants(target, targetId, "*"), requestedPermission)) if (hasPermission(s_saclDao.listGrants(target, targetId, "*"), requestedPermission))
return; 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"); 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 * canonicalUserID
*/ */
public class S3Grant { public class S3Grant {
private int grantee; // SAcl.GRANTEE_USER etc private int grantee; // SAcl.GRANTEE_USER etc
private int permission; // SAcl.PERMISSION_READ etc private int permission; // SAcl.PERMISSION_READ etc
private String canonicalUserID; private String canonicalUserID;
public S3Grant() { public S3Grant() {

View File

@ -68,7 +68,7 @@ public class EC2RestAuth {
} catch (Exception e) { } catch (Exception e) {
} }
// -> the time zone is GMT if not defined // -> the time zone is GMT if not defined
try { try {
formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
cal.setTime(formatter.parse(created)); 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, * JsonAccessor provides the functionality to allow navigating JSON object graph using simple expressions,
* for example, following property access expressions are all valid ones * for example, following property access expressions are all valid ones
* *
* rootobj.level1obj[1].property * rootobj.level1obj[1].property
* this[0].level1obj[1].property * this[0].level1obj[1].property
* *
*/ */
public class JsonAccessor { public class JsonAccessor {
@ -132,9 +132,9 @@ public class JsonAccessor {
/* /*
* Return * Return
* -1 : property expression can not be resolved * -1 : property expression can not be resolved
* 0 : match to a null JSON object * 0 : match to a null JSON object
* 1+ : matched, for array element, the count of the elements inside the array * 1+ : matched, for array element, the count of the elements inside the array
*/ */
public int getMatchCount(String propPath) { public int getMatchCount(String propPath) {
JsonElement jsonElement = tryEval(propPath); JsonElement jsonElement = tryEval(propPath);

View File

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

View File

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

View File

@ -108,7 +108,7 @@ public abstract class ServerResourceBase implements ServerResource {
} }
} }
// } catch (final SocketException e) { // } 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); s_logger.debug("Skipping nic " + nicName);
} }

View File

@ -130,7 +130,7 @@ public class SerializerHelper {
} }
} }
//else //else
// l.add(new Pair<String, Object>(paramName, "")); // l.add(new Pair<String, Object>(paramName, ""));
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
s_logger.error("Illegal argument exception when calling POJO " + o.getClass().getName() + " get method for property: " + propName); 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() public XmlRpcClientConfigImpl getConfig()
{ {
return config; return config;
} }
private XmlRpcClient getClientFromURL(URL url) private XmlRpcClient getClientFromURL(URL url)
{ {

View File

@ -29,8 +29,8 @@ public final class Marshalling {
o instanceof Double || o instanceof Double ||
o instanceof Date) { o instanceof Date) {
return o; return o;
} else if (o instanceof Long) { } else if (o instanceof Long) {
return o.toString(); return o.toString();
} else if (o instanceof Map) { } else if (o instanceof Map) {
Map<Object, Object> result = new HashMap<Object, Object>(); Map<Object, Object> result = new HashMap<Object, Object>();
Map m = (Map)o; Map m = (Map)o;
@ -46,14 +46,14 @@ public final class Marshalling {
result.add(toXMLRPC(e)); result.add(toXMLRPC(e));
} }
return result; return result;
} else if (o instanceof XenAPIObject) { } else if (o instanceof XenAPIObject) {
return ((XenAPIObject) o).toWireString(); return ((XenAPIObject) o).toWireString();
} else if (o instanceof Enum) { } else if (o instanceof Enum) {
return o.toString(); return o.toString();
}else if (o == null){ }else if (o == null){
return ""; return "";
} else { } 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 class XenAPIObject
{ {
public abstract String toWireString(); public abstract String toWireString();
} }

View File

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

View File

@ -142,7 +142,7 @@ public class EngineHostVO implements EngineHost, Identity {
private String hypervisorVersion; private String hypervisorVersion;
@Column(name = "update_count", updatable = true, nullable = false) @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") @Column(name = "uuid")
private String 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 " 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 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 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 = ? ) " + "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 = ?)" + "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 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 " + "END configValue "
+ "FROM `cloud`.`op_host_capacity` capacity INNER JOIN `cloud`.`cluster_details` overcommit ON overcommit.cluster_id = capacity.cluster_id " + "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 " + "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; return null;
// String ipAddress = _ipAddressDao.assignIpAddress(accountId, domainId, vlan.getId(), false).getAddress(); // String ipAddress = _ipAddressDao.assignIpAddress(accountId, domainId, vlan.getId(), false).getAddress();
// if (ipAddress == null) { // if (ipAddress == null) {
// return null; // return null;
// } // }
// return new Pair<String, VlanVO>(ipAddress, vlan); // return new Pair<String, VlanVO>(ipAddress, vlan);
} }

View File

@ -138,7 +138,7 @@ public class HostVO implements Host {
private String hypervisorVersion; private String hypervisorVersion;
@Column(name = "update_count", updatable = true, nullable = false) @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") @Column(name = "uuid")
private String uuid; private String uuid;

View File

@ -44,7 +44,7 @@ public interface PortProfileDao extends GenericDao<PortProfileVO, Long> {
* List<PortProfileVO> listByVlanId(int vlanId); * List<PortProfileVO> listByVlanId(int vlanId);
* *
* List all uplink portprofiles (these represent physical ports). * 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; private boolean limitCpuUse;
@Column(name = "update_count", updatable = true, nullable = false) @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) @Column(name = GenericDao.CREATED_COLUMN)
protected Date created; 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 // 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 " 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" + " 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; private boolean limitCpuUse;
@Column(name = "update_count", updatable = true, nullable = false) @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) @Column(name = GenericDao.CREATED_COLUMN)
protected Date created; 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 Logger s_logger = Logger.getLogger(ClusterServiceServletAdapter.class);
private static final int DEFAULT_SERVICE_PORT = 9090; 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 @Inject
private ClusterManager _manager; private ClusterManager _manager;

View File

@ -31,16 +31,16 @@ import com.cloud.utils.Profiler;
// //
// Example of using dynamic named locks // Example of using dynamic named locks
// //
// GlobalLock lock = GlobalLock.getInternLock("some table name" + rowId); // GlobalLock lock = GlobalLock.getInternLock("some table name" + rowId);
// //
// if(lock.lock()) { // if(lock.lock()) {
// try { // try {
// do something // do something
// } finally { // } finally {
// lock.unlock(); // lock.unlock();
// } // }
// } // }
// lock.releaseRef(); // lock.releaseRef();
// //
public class GlobalLock { public class GlobalLock {
protected final static Logger s_logger = Logger.getLogger(GlobalLock.class); 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()); DbAnnotatedBase base = ComponentContext.inject(new DbAnnotatedBase());
base.MethodWithClassDbAnnotated(); base.MethodWithClassDbAnnotated();
/* /*
Map<String, DbAnnotatedBase> components = ComponentContext.getApplicationContext().getBeansOfType(DbAnnotatedBase.class); Map<String, DbAnnotatedBase> components = ComponentContext.getApplicationContext().getBeansOfType(DbAnnotatedBase.class);
for(Map.Entry<String, DbAnnotatedBase> entry : components.entrySet()) { for(Map.Entry<String, DbAnnotatedBase> entry : components.entrySet()) {
System.out.println(entry.getKey()); System.out.println(entry.getKey());
entry.getValue().MethodWithClassDbAnnotated(); entry.getValue().MethodWithClassDbAnnotated();
} }
*/ */
for (DbAnnotatedBase entry : _list) { for (DbAnnotatedBase entry : _list) {
entry.MethodWithClassDbAnnotated(); entry.MethodWithClassDbAnnotated();

View File

@ -26,7 +26,7 @@ public class AsyncCallFuture<T> implements Future<T>, AsyncCompletionCallback<T>
Object _completed = new Object(); Object _completed = new Object();
boolean _done = false; 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() { public AsyncCallFuture() {
} }

View File

@ -35,7 +35,7 @@ public class RpcProviderImpl implements RpcProvider {
private TransportProvider _transportProvider; private TransportProvider _transportProvider;
private String _transportAddress; 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 MessageSerializer _messageSerializer;
private List<RpcServiceEndpoint> _serviceEndpoints = new ArrayList<RpcServiceEndpoint>(); private List<RpcServiceEndpoint> _serviceEndpoints = new ArrayList<RpcServiceEndpoint>();

View File

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

View File

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

View File

@ -32,7 +32,7 @@ public class ClientOnlyEventDrivenStyle {
String cmd = new String(); String cmd = new String();
RpcCallbackDispatcher<ClientOnlyEventDrivenStyle> callbackDispatcher = RpcCallbackDispatcher.create(this); RpcCallbackDispatcher<ClientOnlyEventDrivenStyle> callbackDispatcher = RpcCallbackDispatcher.create(this);
callbackDispatcher.setCallback(callbackDispatcher.getTarget().OnAsyncCallRpcServiceCallback(null, null)); 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(); .apply();
} }

View File

@ -20,8 +20,8 @@ import com.cloud.utils.component.Adapter;
// //
// We extend it from Adapter interface for // We extend it from Adapter interface for
// 1) getName()/setName() // 1) getName()/setName()
// 2) Confirming to general adapter pattern used across CloudStack // 2) Confirming to general adapter pattern used across CloudStack
// //
public interface AsyncJobDispatcher extends Adapter { public interface AsyncJobDispatcher extends Adapter {
void runJob(AsyncJob job); 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 jobId upper job that is going to wait the completion of a down-level job
* @param joinJobId down-level job * @param joinJobId down-level job
* @Param wakeupHandler wake-up handler * @Param wakeupHandler wake-up handler
* @Param wakeupDispatcher wake-up dispatcher * @Param wakeupDispatcher wake-up dispatcher
* @param wakeupTopicsOnMessageBus * @param wakeupTopicsOnMessageBus
* @param wakeupIntervalInMilliSeconds * @param wakeupIntervalInMilliSeconds
@ -97,11 +97,11 @@ public interface AsyncJobManager extends Manager {
* *
* @param joinJobId down-level job for upper level job to join with * @param joinJobId down-level job for upper level job to join with
* @param joinStatus AsyncJobConstants status code to indicate success or failure of the * @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 * @param joinResult object-stream serialized result object
* this is primarily used by down-level job to pass error exception objects * 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 * for legacy code to work. To help pass exception object easier, we use
* object-stream based serialization instead of GSON * object-stream based serialization instead of GSON
*/ */
void completeJoin(long joinJobId, JobInfo.Status joinStatus, String joinResult); 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 timeoutInMiliseconds time out to break out the whole wait process
* @param predicate * @param predicate
* @return true, predicate condition is satisfied * @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); 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); void completeJoin(long joinJobId, JobInfo.Status joinStatus, String joinResult, long completeMsid);
// List<Long> wakeupScan(); // List<Long> wakeupScan();
List<Long> findJobsToWake(long joinedJobId); List<Long> findJobsToWake(long joinedJobId);
List<Long> findJobsToWakeBetween(Date cutDate); 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.setJoinMsid(joinMsid);
record.setJoinStatus(JobInfo.Status.IN_PROGRESS); record.setJoinStatus(JobInfo.Status.IN_PROGRESS);
record.setSyncSourceId(syncSourceId); record.setSyncSourceId(syncSourceId);
record.setWakeupInterval(wakeupIntervalMs / 1000); // convert millisecond to second record.setWakeupInterval(wakeupIntervalMs / 1000); // convert millisecond to second
record.setWakeupHandler(wakeupHandler); record.setWakeupHandler(wakeupHandler);
record.setWakeupDispatcher(wakeupDispatcher); record.setWakeupDispatcher(wakeupDispatcher);
if (wakeupHandler != null) { if (wakeupHandler != null) {
@ -149,63 +149,63 @@ public class AsyncJobJoinMapDaoImpl extends GenericDaoBase<AsyncJobJoinMapVO, Lo
update(ub, sc, null); update(ub, sc, null);
} }
// @Override // @Override
// public List<Long> wakeupScan() { // 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; // PreparedStatement pstmt = null;
// try { // try {
// txn.start(); // txn.start();
// //
// // // //
// // performance sensitive processing, do it in plain SQL // // performance sensitive processing, do it in plain SQL
// // // //
// String sql = "UPDATE async_job SET job_pending_signals=? WHERE id IN " + // 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 > ?)"; // "(SELECT job_id FROM async_job_join_map WHERE next_wakeup < ? AND expiration > ?)";
// pstmt = txn.prepareStatement(sql); // pstmt = txn.prepareStatement(sql);
// pstmt.setInt(1, AsyncJob.Constants.SIGNAL_MASK_WAKEUP); // pstmt.setInt(1, AsyncJob.Constants.SIGNAL_MASK_WAKEUP);
// pstmt.setString(2, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate)); // pstmt.setString(2, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate));
// pstmt.setString(3, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate)); // pstmt.setString(3, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate));
// pstmt.executeUpdate(); // pstmt.executeUpdate();
// pstmt.close(); // pstmt.close();
// //
// sql = "UPDATE sync_queue_item SET queue_proc_msid=NULL, queue_proc_number=NULL WHERE content_id IN " + // 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 > ?)"; // "(SELECT job_id FROM async_job_join_map WHERE next_wakeup < ? AND expiration > ?)";
// pstmt = txn.prepareStatement(sql); // pstmt = txn.prepareStatement(sql);
// pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate)); // pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate));
// pstmt.setString(2, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate)); // pstmt.setString(2, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate));
// pstmt.executeUpdate(); // pstmt.executeUpdate();
// pstmt.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)"; // 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 = txn.prepareStatement(sql);
// pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate)); // pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate));
// pstmt.setString(2, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate)); // pstmt.setString(2, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate));
// ResultSet rs = pstmt.executeQuery(); // ResultSet rs = pstmt.executeQuery();
// while(rs.next()) { // while(rs.next()) {
// standaloneList.add(rs.getLong(1)); // standaloneList.add(rs.getLong(1));
// } // }
// rs.close(); // rs.close();
// pstmt.close(); // pstmt.close();
// //
// // update for next wake-up // // 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 > ?"; // 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 = txn.prepareStatement(sql);
// pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate)); // pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate));
// pstmt.setString(2, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate)); // pstmt.setString(2, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate));
// pstmt.executeUpdate(); // pstmt.executeUpdate();
// pstmt.close(); // pstmt.close();
// //
// txn.commit(); // txn.commit();
// } catch (SQLException e) { // } catch (SQLException e) {
// s_logger.error("Unexpected exception", e); // s_logger.error("Unexpected exception", e);
// } // }
// //
// return standaloneList; // return standaloneList;
// } // }
@Override @Override
public List<Long> findJobsToWake(long joinedJobId) { 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 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_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_SYNC = 60; // 60 seconds
private static final int MAX_ONETIME_SCHEDULE_SIZE = 50; private static final int MAX_ONETIME_SCHEDULE_SIZE = 50;
private static final int HEARTBEAT_INTERVAL = 2000; 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 @Inject
private SyncQueueItemDao _queueItemDao; 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. // I removed the temporary solution already. I think my changes should fix the deadlock.
/* /*
------------------------ ------------------------
LATEST DETECTED DEADLOCK LATEST DETECTED DEADLOCK
------------------------ ------------------------
130625 20:03:10 130625 20:03:10
*** (1) TRANSACTION: *** (1) TRANSACTION:
TRANSACTION 0 98087127, ACTIVE 0 sec, process no 1489, OS thread id 139837829175040 fetching rows, thread declared inside InnoDB 494 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 mysql tables in use 2, locked 1
LOCK WAIT 3 lock struct(s), heap size 368, 2 row lock(s), undo log entries 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 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) 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: *** (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 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 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 ;; 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: *** (2) TRANSACTION:
TRANSACTION 0 98087128, ACTIVE 0 sec, process no 1489, OS thread id 139837671909120 fetching rows, thread declared inside InnoDB 492 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 mysql tables in use 2, locked 1
3 lock struct(s), heap size 368, 2 row lock(s), undo log entries 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 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) 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): *** (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 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 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 ;; 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: *** (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 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 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 ;; 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()); _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); s_logger.warn("Unable to associate LUN ", uhe);
throw new ServerException("Unable to associate LUN", uhe); throw new ServerException("Unable to associate LUN", uhe);
} catch (NaAPIFailedException naf) { } catch (NaAPIFailedException naf) {
if (naf.getErrno() == 9008) { //initiator group already contains node if (naf.getErrno() == 9008) { //initiator group already contains node
return returnVal; return returnVal;
} }
s_logger.warn("Unable to associate LUN ", naf); 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); String prepareCmd = String.format("sh /usr/bin/prepare_dnsmasq.sh %1$s %2$s %3$s", _gateway, _dns, _ip);
if (!SSHCmdHelper.sshExecuteCmd(sshConnection, prepareCmd)) { 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 @Override
public final PingCommand getCurrentStatus(final long id) { 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); PingCommand pingCmd = new PingRoutingCommand(getType(), id, null, null);
if (s_logger.isDebugEnabled()) { if (s_logger.isDebugEnabled()) {

View File

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

View File

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

View File

@ -29,11 +29,11 @@ public class Test {
public static void main(String[] args) { public static void main(String[] args) {
try { try {
/*Connection c = new Connection("192.168.105.155", "oracle", "password"); /*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); Storage storage = new StorageImpl(c);
String[] res = util.listDir("/etc", 1); String[] res = util.listDir("/etc", 1);
for (String s : res) { for (String s : res) {
System.out.println(s); System.out.println(s);
} }
@ -51,7 +51,7 @@ public class Test {
System.out.println(pool.getAgentVersion()); System.out.println(pool.getAgentVersion());
String[] srs = storage.listSr(); String[] srs = storage.listSr();
for (int i=0; i<srs.length; i++) { 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"); String spuuid = storage.createSp(StorageType.OVSSPNFS, "192.168.110.232:/export/frank/nfs");
System.out.println(spuuid); System.out.println(spuuid);
@ -95,11 +95,11 @@ public class Test {
//OvmHost.Details d = Coder.fromJson(txt, OvmHost.Details.class); //OvmHost.Details d = Coder.fromJson(txt, OvmHost.Details.class);
//OvmHost.Details d = OvmHost.getDetails(c); //OvmHost.Details d = OvmHost.getDetails(c);
//System.out.println(Coder.toJson(d)); //System.out.println(Coder.toJson(d));
// OvmStoragePool.Details pool = new OvmStoragePool.Details(); // OvmStoragePool.Details pool = new OvmStoragePool.Details();
// pool.path = "192.168.110.232:/export/frank/ovs"; // pool.path = "192.168.110.232:/export/frank/ovs";
// pool.type = OvmStoragePool.NFS; // pool.type = OvmStoragePool.NFS;
// pool.uuid = "123"; // pool.uuid = "123";
// System.out.println(pool.toJson()); // System.out.println(pool.toJson());
String cmd = null; String cmd = null;
System.out.println(args.length); System.out.println(args.length);
@ -169,12 +169,12 @@ public class Test {
l.add("4b4d8951-f0b6-36c5-b4f3-a82ff2611c65"); l.add("4b4d8951-f0b6-36c5-b4f3-a82ff2611c65");
System.out.println(Coder.toJson(l)); System.out.println(Coder.toJson(l));
// Map<String, String> res = OvmHost.getPerformanceStats(c, "xenbr0"); // Map<String, String> res = OvmHost.getPerformanceStats(c, "xenbr0");
// System.out.println(res.toString()); // 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\"}}"; // 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); // OvmVm.Details ddd = Coder.fromJson(stxt, OvmVm.Details.class);
// System.out.println(ddd.vifs.size()); // System.out.println(ddd.vifs.size());
// System.out.println(ddd.rootDisk.path); // System.out.println(ddd.rootDisk.path);
} catch (Exception e) { } catch (Exception e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();

View File

@ -65,14 +65,14 @@ public class VmwareCleanupMaid {
_vmName = vmName; _vmName = vmName;
} }
// @Override // @Override
// public int cleanup(CheckPointManager checkPointMgr) { // public int cleanup(CheckPointManager checkPointMgr) {
// //
// // save a check-point in case we crash at current run so that we won't lose it // // 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)); // _checkPoint = checkPointMgr.pushCheckPoint(new VmwareCleanupMaid(_vCenterAddress, _dcMorValue, _vmName));
// addLeftOverVM(this); // addLeftOverVM(this);
// return 0; // return 0;
// } // }
public String getCleanupProcedure() { public String getCleanupProcedure() {
return null; return null;
@ -134,7 +134,7 @@ public class VmwareCleanupMaid {
} catch (Throwable e) { } catch (Throwable e) {
s_logger.warn("Unable to destroy left over dummy VM " + cleanupMaid.getVmName()); s_logger.warn("Unable to destroy left over dummy VM " + cleanupMaid.getVmName());
} finally { } 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 { public class VmwareManagerImpl extends ManagerBase implements VmwareManager, VmwareStorageMount, Listener, VmwareDatacenterService {
private static final Logger s_logger = Logger.getLogger(VmwareManagerImpl.class); private static final Logger s_logger = Logger.getLogger(VmwareManagerImpl.class);
private static final int STARTUP_DELAY = 60000; // 60 seconds private static final int STARTUP_DELAY = 60000; // 60 seconds
private static final long DEFAULT_HOST_SCAN_INTERVAL = 600000; // every 10 minutes private static final long DEFAULT_HOST_SCAN_INTERVAL = 600000; // every 10 minutes
private long _hostScanInterval = DEFAULT_HOST_SCAN_INTERVAL; private long _hostScanInterval = DEFAULT_HOST_SCAN_INTERVAL;
int _timeout; int _timeout;
@ -190,7 +190,7 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
String _managemetPortGroupName; String _managemetPortGroupName;
String _defaultSystemVmNicAdapterType = VirtualEthernetCardType.E1000.toString(); String _defaultSystemVmNicAdapterType = VirtualEthernetCardType.E1000.toString();
String _recycleHungWorker = "false"; String _recycleHungWorker = "false";
long _hungWorkerTimeout = 7200000; // 2 hour long _hungWorkerTimeout = 7200000; // 2 hour
int _additionalPortRangeStart; int _additionalPortRangeStart;
int _additionalPortRangeSize; int _additionalPortRangeSize;
int _routerExtraPublicNics = 2; int _routerExtraPublicNics = 2;
@ -472,7 +472,7 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
hostSpec.setUserName(userName); hostSpec.setUserName(userName);
hostSpec.setPassword(password); hostSpec.setPassword(password);
hostSpec.setHostName(host); 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); ManagedObjectReference morTask = serviceContext.getService().addHostTask(morCluster, hostSpec, true, null, null);
boolean taskResult = vclient.waitForTask(morTask); 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 // there are pending tasks on the subject VM
/* /*
if(System.currentTimeMillis() - startTick > _hungWorkerTimeout) { if(System.currentTimeMillis() - startTick > _hungWorkerTimeout) {
if(s_logger.isInfoEnabled()) if(s_logger.isInfoEnabled())
s_logger.info("Worker VM expired, seconds elapsed: " + (System.currentTimeMillis() - startTick) / 1000); s_logger.info("Worker VM expired, seconds elapsed: " + (System.currentTimeMillis() - startTick) / 1000);
return true; return true;
} }
*/ */
return false; return false;

View File

@ -116,7 +116,7 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
Script command = new Script(false, "tar", 0, s_logger); Script command = new Script(false, "tar", 0, s_logger);
command.setWorkDir(path); command.setWorkDir(path);
command.add("-cf", name + ".ova"); 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"); command.add(name + "-disk0.vmdk");
s_logger.info("Package OVA with commmand: " + command.toString()); 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); Script command = new Script(false, "tar", 0, s_logger);
command.setWorkDir(installFullPath); command.setWorkDir(installFullPath);
command.add("-cf", volumeUuid + ".ova"); 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.add(volumeUuid + "-disk0.vmdk");
command.execute(); command.execute();

View File

@ -313,9 +313,9 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
protected String _name; 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 @Inject
protected VolumeOrchestrationService volMgr; 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. * Return a list of VSM devices that use the same VLAN for no matter what interface. Unlikely, but oh well.
* @param vlanId * @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. * or may query it in the function.
* @return * @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 * 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. * the functions above. Pasting those below to not lose track of them.
* *
* ListbyZoneId() * ListbyZoneId()
- Lists all VSMs in the specified zone. - Lists all VSMs in the specified zone.
ListbyAccountId() ListbyAccountId()
- Lists all VSMs owned by the specified Account. - Lists all VSMs owned by the specified Account.
ListbyStorageVLAN(vlanId) ListbyStorageVLAN(vlanId)
- Lists all VSMs whose storage VLAN matches the specified VLAN. - Lists all VSMs whose storage VLAN matches the specified VLAN.
- Filters results by the invoker's account Id. - Filters results by the invoker's account Id.
ListbyControlVLAN(vlanId) ListbyControlVLAN(vlanId)
- Lists all VSMs whose control VLAN matches the specified VLAN. - Lists all VSMs whose control VLAN matches the specified VLAN.
- Filters results by the invoker's account Id. - Filters results by the invoker's account Id.
ListbyPacketVLAN(vlanId) ListbyPacketVLAN(vlanId)
- Lists all VSMs whose Packet VLAN matches the specified VLAN. - Lists all VSMs whose Packet VLAN matches the specified VLAN.
- Filters results by the invoker's account Id. - Filters results by the invoker's account Id.
ListbyConfigMode(mode) ListbyConfigMode(mode)
- Lists all VSMs which are currently configured in the specified mode (standalone/HA). - Lists all VSMs which are currently configured in the specified mode (standalone/HA).
- Filters results by the invoker's account Id. - Filters results by the invoker's account Id.
ListbyConfigState(configState) ListbyConfigState(configState)
- Lists all VSMs which are currently configured in the specified state (primary/standby). - Lists all VSMs which are currently configured in the specified state (primary/standby).
- Filters results by the invoker's account Id. - Filters results by the invoker's account Id.
ListbyDeviceState(deviceState) ListbyDeviceState(deviceState)
- Lists all VSMs which are currently in the specified device state (enabled/disabled). - Lists all VSMs which are currently in the specified device state (enabled/disabled).
- Filters results by the invoker's account Id. - Filters results by the invoker's account Id.
getBySwitchDomainId(domId) 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. - 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. - Filters results by invoker's account id.
getbySwitchName(vsmName) 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 @Override
public List<CiscoNexusVSMDeviceVO> getCiscoNexusVSMs(ListCiscoNexusVSMsCmd cmd) { public List<CiscoNexusVSMDeviceVO> getCiscoNexusVSMs(ListCiscoNexusVSMsCmd cmd) {
// If clusterId is defined, then it takes precedence, and we will return // 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 clusterId = cmd.getClusterId();
Long zoneId = cmd.getZoneId(); 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"); 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]; String volumeDatastorePath = vmdkFilePair[0];
synchronized (this) { synchronized (this) {

View File

@ -132,7 +132,7 @@ public class VmwareStorageMotionStrategy implements DataMotionStrategy {
// Migration across cluster needs to be done in three phases. // Migration across cluster needs to be done in three phases.
// 1. Send a migrate command to source resource to initiate migration // 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. // 2. Complete the process. Update the volume details.
MigrateWithStorageCommand migrateWithStorageCmd = new MigrateWithStorageCommand(to, volumeToFilerto, destHost.getGuid()); MigrateWithStorageCommand migrateWithStorageCmd = new MigrateWithStorageCommand(to, volumeToFilerto, destHost.getGuid());
MigrateWithStorageAnswer migrateWithStorageAnswer = (MigrateWithStorageAnswer)agentMgr.send(srcHost.getId(), migrateWithStorageCmd); 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 { private void login() throws ExecutionException {
try { try {

View File

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

View File

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

View File

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

View File

@ -531,12 +531,12 @@ public class IntegrationTestConfiguration {
AffinityGroupService mock = Mockito.mock(AffinityGroupService.class); AffinityGroupService mock = Mockito.mock(AffinityGroupService.class);
try { try {
final AffinityGroupVO gmock = new AffinityGroupVO("grp1", "grp-type", "affinity group", 1, AccountVO.ACCOUNT_ID_SYSTEM, ControlledEntity.ACLType.Account); final AffinityGroupVO gmock = new AffinityGroupVO("grp1", "grp-type", "affinity group", 1, AccountVO.ACCOUNT_ID_SYSTEM, ControlledEntity.ACLType.Account);
Transaction.execute(new TransactionCallbackNoReturn() { Transaction.execute(new TransactionCallbackNoReturn() {
@Override @Override
public void doInTransactionWithoutResult(TransactionStatus status) { public void doInTransactionWithoutResult(TransactionStatus status) {
_affinityGroupDao.persist(gmock); _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); 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) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();

View File

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

View File

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

View File

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

View File

@ -3209,7 +3209,7 @@ public class JuniperSrxResource implements ServerResource {
} }
/* /*
* Usage * Usage
*/ */
private ExternalNetworkResourceUsageAnswer getUsageAnswer(ExternalNetworkResourceUsageCommand cmd) throws ExecutionException { 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) @APICommand(name = "listExternalFirewalls", description="List external firewall appliances.", responseObject = ExternalFirewallResponse.class)
public class ListExternalFirewallsCmd extends BaseListCmd { 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"; private static final String s_name = "listexternalfirewallsresponse";
///////////////////////////////////////////////////// /////////////////////////////////////////////////////
@ -70,15 +70,15 @@ public class ListExternalFirewallsCmd extends BaseListCmd {
@Override @Override
public void execute(){ public void execute(){
List<? extends Host> externalFirewalls = _paElementService.listExternalFirewalls(this); List<? extends Host> externalFirewalls = _paElementService.listExternalFirewalls(this);
ListResponse<ExternalFirewallResponse> listResponse = new ListResponse<ExternalFirewallResponse>(); ListResponse<ExternalFirewallResponse> listResponse = new ListResponse<ExternalFirewallResponse>();
List<ExternalFirewallResponse> responses = new ArrayList<ExternalFirewallResponse>(); List<ExternalFirewallResponse> responses = new ArrayList<ExternalFirewallResponse>();
for (Host externalFirewall : externalFirewalls) { for (Host externalFirewall : externalFirewalls) {
ExternalFirewallResponse response = _paElementService.createExternalFirewallResponse(externalFirewall); ExternalFirewallResponse response = _paElementService.createExternalFirewallResponse(externalFirewall);
response.setObjectName("externalfirewall"); response.setObjectName("externalfirewall");
response.setResponseName(getCommandName()); response.setResponseName(getCommandName());
responses.add(response); responses.add(response);
} }
listResponse.setResponses(responses); listResponse.setResponses(responses);

View File

@ -96,12 +96,12 @@ import java.io.StringWriter;
public class MockablePaloAltoResource extends PaloAltoResource { public class MockablePaloAltoResource extends PaloAltoResource {
private HashMap<String, String> context; private HashMap<String, String> context;
public void setMockContext(HashMap<String, String> context) { public void setMockContext(HashMap<String, String> context) {
this.context = 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 { protected String request(PaloAltoMethod method, Map<String, String> params) throws ExecutionException {
if (method != PaloAltoMethod.GET && method != PaloAltoMethod.POST) { if (method != PaloAltoMethod.GET && method != PaloAltoMethod.POST) {
throw new ExecutionException("Invalid http method used to access the Palo Alto API."); throw new ExecutionException("Invalid http method used to access the Palo Alto API.");
@ -116,8 +116,8 @@ public class MockablePaloAltoResource extends PaloAltoResource {
// 'config' requests // 'config' requests
if (params.containsKey("type") && params.get("type").equals("config") && params.containsKey("action")) { if (params.containsKey("type") && params.get("type").equals("config") && params.containsKey("action")) {
// action = 'get' // action = 'get'
if (params.get("action").equals("get")) { if (params.get("action").equals("get")) {
// get interface for type // get interface for type
// | public_using_ethernet // | public_using_ethernet
if (params.get("xpath").equals("/config/devices/entry/network/interface/ethernet/entry[@name='ethernet1/1']")) { 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 (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")) { 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>"; 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>"; 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 (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")) { 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>"; 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' // action = 'set'
if (params.get("action").equals("set")) { if (params.get("action").equals("set")) {
// set management profile // set management profile
if (params.get("xpath").equals("/config/devices/entry/network/profiles/interface-management-profile/entry[@name='Ping']")) { 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>"; 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>"; response = "<response status=\"success\" code=\"20\"><msg>command succeeded</msg></response>";
context.put("has_service_tcp_80", "true"); context.put("has_service_tcp_80", "true");
} }
} }
// action = 'delete' // action = 'delete'
if (params.get("action").equals("delete")) { if (params.get("action").equals("delete")) {
// remove egress firewall rule // remove egress firewall rule
if (params.get("xpath").equals("/config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='policy_0']")) { 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>"; 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"); context.remove("has_private_interface");
} }
} }
} // end 'config' } // end 'config'
// 'op' requests // 'op' requests
if (params.containsKey("type") && params.get("type").equals("op")) { if (params.containsKey("type") && params.get("type").equals("op")) {
// check if there are pending changes // check if there are pending changes
if (params.get("cmd").equals("<check><pending-changes></pending-changes></check>")) { 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")) { if (context.containsKey("firewall_has_pending_changes") && context.get("firewall_has_pending_changes").equals("true")) {
response = "<response status=\"success\"><result>yes</result></response>"; response = "<response status=\"success\"><result>yes</result></response>";
} else { } else {
response = "<response status=\"success\"><result>no</result></response>"; response = "<response status=\"success\"><result>no</result></response>";
} }
} }
// add a config lock // add a config lock
if (params.get("cmd").equals("<request><config-lock><add></add></config-lock></request>")) { 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>"; 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 // check job status
if (params.get("cmd").equals("<show><jobs><id>1</id></jobs></show>")) { 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 // load from running config
if (params.get("cmd").equals("<load><config><from>running-config.xml</from></config></load>")) { 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>"; response = "<response status=\"success\"><result><msg><line>Config loaded from running-config.xml</line></msg></result></response>";
} }
// remove config lock // remove config lock
if (params.get("cmd").equals("<request><config-lock><remove></remove></config-lock></request>")) { 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>"; response = "<response status=\"success\"><result>Config lock released for scope shared</result></response>";
} }
} // end 'op' } // end 'op'
// 'commit' requests // 'commit' requests
if (params.containsKey("type") && params.get("type").equals("commit")) { if (params.containsKey("type") && params.get("type").equals("commit")) {
// cmd = '<commit></commit>' // cmd = '<commit></commit>'
if (params.get("cmd").equals("<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>"; response = "<response status=\"success\" code=\"19\"><result><msg><line>Commit job enqueued with jobid 1</line></msg><job>1</job></result></response>";
} }
} // end 'commit' } // end 'commit'

View File

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

View File

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

View File

@ -324,7 +324,7 @@ public class AlertManagerImpl extends ManagerBase implements AlertManager, Confi
} }
// Calculate CPU and RAM capacities // 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); List<HostVO> hosts = _resourceMgr.listAllNotInMaintenanceHostsInOneZone(Host.Type.Routing, null);
for (HostVO host : hosts) { for (HostVO host : hosts) {
_capacityMgr.updateCapacityForHost(host); _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), 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), 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), 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( SystemVMUseLocalStorage(
"Advanced", "Advanced",
ManagementServer.class, 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_PROXY_CAPACITY = 50;
public static final int DEFAULT_STANDBY_CAPACITY = 10; 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_RAMSIZE = 1024; // 1G
public static final int DEFAULT_PROXY_VM_CPUMHZ = 500; // 500 MHz 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_CMD_PORT = 8001;
public static final int DEFAULT_PROXY_VNC_PORT = 0; public static final int DEFAULT_PROXY_VNC_PORT = 0;
public static final int DEFAULT_PROXY_URL_PORT = 80; 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 ALERT_SUBJECT = "proxy-alert";
public static final String CERTIFICATE_NAME = "CPVMCertificate"; 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 // Possible console proxy state transition cases
// Stopped --> Starting -> Running // Stopped --> Starting -> Running
// HA -> Stopped -> Starting -> Running // HA -> Stopped -> Starting -> Running
// Migrating -> Running (if previous state is Running before it enters into Migrating state // 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) // Migrating -> Stopped (if previous state is not Running before it enters into Migrating state)
// Running -> HA (if agent lost connection) // Running -> HA (if agent lost connection)
// Stopped -> Destroyed // Stopped -> Destroyed
// //
// Starting, HA, Migrating, Running state are all counted as "Open" for available capacity calculation // 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 // 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) { for (VolumeVO vol : vols) {
if (!vol.isRecreatable()) { if (!vol.isRecreatable()) {
if (s_logger.isDebugEnabled()) { 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; return null;
} }

View File

@ -40,7 +40,7 @@ public class PortProfileManagerImpl {
@DB @DB
public PortProfileVO addPortProfile(String portProfName, long vsmId, int vlanId, PortType pType, BindingType bType) { 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. // First, check if a port profile with the given name already exists. If it does, throw an exception.
if (_portProfileDao.findByName(portProfName) != null) { 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. // 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; PortProfileVO portProfileObj;
portProfileObj = _portProfileDao.findByName(portProfName); 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); "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_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; public static final boolean USE_POD_VLAN = false;
/** /**

View File

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

View File

@ -432,7 +432,7 @@ public class ConsoleProxyServlet extends HttpServlet {
Mac mac = Mac.getInstance("HmacSHA1"); Mac mac = Mac.getInstance("HmacSHA1");
long ts = normalizedHashTime.getTime(); 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(); String secretKey = s_ms.getHashKey();
SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(), "HmacSHA1"); 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 // Possible secondary storage vm state transition cases
// Creating -> Destroyed // Creating -> Destroyed
// Creating -> Stopped --> Starting -> Running // Creating -> Stopped --> Starting -> Running
// HA -> Stopped -> Starting -> Running // HA -> Stopped -> Starting -> Running
// Migrating -> Running (if previous state is Running before it enters into Migrating state // 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) // Migrating -> Stopped (if previous state is not Running before it enters into Migrating state)
// Running -> HA (if agent lost connection) // Running -> HA (if agent lost connection)
// Stopped -> Destroyed // Stopped -> Destroyed
// //
// Creating state indicates of record creating and IP address allocation are ready, it is a transient // 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. // 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) // 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 state can only be entered from Stopped states
// //
// Starting, HA, Migrating, Creating and Running state are all counted as "Open" for available capacity calculation // 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 // because sooner or later, it will be driven into Running state
@ -212,7 +212,7 @@ public class SecondaryStorageManagerImpl extends ManagerBase implements Secondar
UserVmDetailsDao _vmDetailsDao; UserVmDetailsDao _vmDetailsDao;
@Inject @Inject
protected ResourceManager _resourceMgr; 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; protected SecondaryStorageVmManager _ssvmMgr;
@Inject @Inject
NetworkDao _networkDao; NetworkDao _networkDao;
@ -1286,42 +1286,42 @@ public class SecondaryStorageManagerImpl extends ManagerBase implements Secondar
/* /*
StartupCommand firstCmd = startup[0]; StartupCommand firstCmd = startup[0];
if (!(firstCmd instanceof StartupStorageCommand)) { if (!(firstCmd instanceof StartupStorageCommand)) {
return null; return null;
} }
com.cloud.host.Host.Type type = null; com.cloud.host.Host.Type type = null;
StartupStorageCommand ssCmd = ((StartupStorageCommand) firstCmd); StartupStorageCommand ssCmd = ((StartupStorageCommand) firstCmd);
if (ssCmd.getHostType() == Host.Type.SecondaryStorageCmdExecutor) { if (ssCmd.getHostType() == Host.Type.SecondaryStorageCmdExecutor) {
type = ssCmd.getHostType(); type = ssCmd.getHostType();
} else { } else {
if (ssCmd.getResourceType() == Storage.StorageResourceType.SECONDARY_STORAGE) { if (ssCmd.getResourceType() == Storage.StorageResourceType.SECONDARY_STORAGE) {
type = Host.Type.SecondaryStorage; type = Host.Type.SecondaryStorage;
if (resource != null && resource instanceof DummySecondaryStorageResource) { if (resource != null && resource instanceof DummySecondaryStorageResource) {
host.setResource(null); host.setResource(null);
} }
} else if (ssCmd.getResourceType() == Storage.StorageResourceType.LOCAL_SECONDARY_STORAGE) { } else if (ssCmd.getResourceType() == Storage.StorageResourceType.LOCAL_SECONDARY_STORAGE) {
type = Host.Type.LocalSecondaryStorage; type = Host.Type.LocalSecondaryStorage;
} else { } else {
type = Host.Type.Storage; type = Host.Type.Storage;
} }
final Map<String, String> hostDetails = ssCmd.getHostDetails(); final Map<String, String> hostDetails = ssCmd.getHostDetails();
if (hostDetails != null) { if (hostDetails != null) {
if (details != null) { if (details != null) {
details.putAll(hostDetails); details.putAll(hostDetails);
} else { } else {
details = hostDetails; details = hostDetails;
} }
} }
host.setDetails(details); host.setDetails(details);
host.setParent(ssCmd.getParent()); host.setParent(ssCmd.getParent());
host.setTotalSize(ssCmd.getTotalSize()); host.setTotalSize(ssCmd.getTotalSize());
host.setHypervisorType(HypervisorType.None); host.setHypervisorType(HypervisorType.None);
host.setType(type); host.setType(type);
if (ssCmd.getNfsShare() != null) { if (ssCmd.getNfsShare() != null) {
host.setStorageUrl(ssCmd.getNfsShare()); host.setStorageUrl(ssCmd.getNfsShare());
} }
} }
*/ */
return null; // no need to handle this event anymore since secondary storage is not in host table anymore. 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 interface SecondaryStorageVmManager extends Manager {
public static final int DEFAULT_SS_VM_RAMSIZE = 256; // 256M 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_CPUMHZ = 500; // 500 MHz
public static final int DEFAULT_SS_VM_MTUSIZE = 1500; 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_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_STANDBY_CAPACITY = 10; // standy capacity to reserve per zone
public static final String ALERT_SUBJECT = "secondarystoragevm-alert"; public static final String ALERT_SUBJECT = "secondarystoragevm-alert";

View File

@ -1085,7 +1085,7 @@ public class DatabaseConfig {
} catch (SQLException ex) { } catch (SQLException ex) {
s_logger.error("error creating vm template: " + ex); s_logger.error("error creating vm template: " + ex);
} finally { } finally {
txn.close(); txn.close();
} }
*/ */
/* /*
@ -1108,7 +1108,7 @@ public class DatabaseConfig {
} catch (SQLException ex) { } catch (SQLException ex) {
s_logger.error("error creating vm template: " + ex); s_logger.error("error creating vm template: " + ex);
} finally { } finally {
txn.close(); txn.close();
} }
*/ */
} }
@ -1294,7 +1294,7 @@ public class DatabaseConfig {
} catch (SQLException ex) { } catch (SQLException ex) {
s_logger.error("error updating admin user", ex); s_logger.error("error updating admin user", ex);
} finally { } finally {
txn.close(); txn.close();
} }
updateSql = "update account set domain_id = 1 where id = 1"; updateSql = "update account set domain_id = 1 where id = 1";
@ -1305,7 +1305,7 @@ public class DatabaseConfig {
} catch (SQLException ex) { } catch (SQLException ex) {
s_logger.error("error updating system user", ex); s_logger.error("error updating system user", ex);
} finally { } 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."); "Unable to start DB connection to read guest cidr network. Please contact Cloud Support.");
} }
// public static String getGuestIpNetwork() { // public static String getGuestIpNetwork() {
// return DatabaseConfig.getDatabaseValueString("SELECT * FROM `cloud`.`configuration` WHERE name = \"guest.ip.network\"", "value", // 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."); // "Unable to start DB connection to read guest IP network. Please contact Cloud Support.");
// } // }
// //
// public static String getGuestNetmask() { // public static String getGuestNetmask() {
// return DatabaseConfig.getDatabaseValueString("SELECT * FROM `cloud`.`configuration` WHERE name = \"guest.netmask\"", "value", // 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."); // "Unable to start DB connection to read guest netmask. Please contact Cloud Support.");
// } // }
// public static String getGuestSubnet() { // public static String getGuestSubnet() {
// String guestIpNetwork = getGuestIpNetwork(); // String guestIpNetwork = getGuestIpNetwork();
// String guestNetmask = getGuestNetmask(); // String guestNetmask = getGuestNetmask();
// //
// if (guestIpNetwork == null || guestIpNetwork.isEmpty()) printError("Please enter a valid guest IP network address."); // 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"); // if (guestNetmask == null || guestNetmask.isEmpty()) printError("Please enter a valid guest IP network netmask");
// //
// return NetUtils.getSubNet(guestIpNetwork, guestNetmask); // return NetUtils.getSubNet(guestIpNetwork, guestNetmask);
// } // }
// public static long getGuestCidrSize() { // public static long getGuestCidrSize() {
// String guestNetmask = getGuestNetmask(); // String guestNetmask = getGuestNetmask();
// return NetUtils.getCidrSize(guestNetmask); // return NetUtils.getCidrSize(guestNetmask);
// } // }
public static boolean validCIDR(final String cidr) { public static boolean validCIDR(final String cidr) {
if (cidr == null || cidr.isEmpty()) { if (cidr == null || cidr.isEmpty()) {

View File

@ -75,7 +75,7 @@ public class PodZoneConfig {
private String checkPodCidrSubnets(long dcId, HashMap<Long, Vector<Object>> currentPodCidrSubnets) { private String checkPodCidrSubnets(long dcId, HashMap<Long, Vector<Object>> currentPodCidrSubnets) {
// DataCenterDao _dcDao = null; // DataCenterDao _dcDao = null;
// final ComponentLocator locator = ComponentLocator.getLocator("management-server"); // final ComponentLocator locator = ComponentLocator.getLocator("management-server");
// _dcDao = locator.getDao(DataCenterDao.class); // _dcDao = locator.getDao(DataCenterDao.class);
@ -86,7 +86,7 @@ public class PodZoneConfig {
String zoneName = PodZoneConfig.getZoneName(dcId); String zoneName = PodZoneConfig.getZoneName(dcId);
//get the guest network cidr and guest netmask from the zone //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); String guestNetworkCidr = IPRangeConfig.getGuestNetworkCidr(dcId);
@ -236,9 +236,9 @@ public class PodZoneConfig {
String newVlanSubnet = NetUtils.getSubNet(vlanGateway, vlanNetmask); String newVlanSubnet = NetUtils.getSubNet(vlanGateway, vlanNetmask);
List<VlanVO> vlans = _vlanDao.findByZone(zoneId); List<VlanVO> vlans = _vlanDao.findByZone(zoneId);
for (VlanVO vlan : vlans) { for (VlanVO vlan : vlans) {
String currentVlanSubnet = NetUtils.getSubNet(vlan.getVlanGateway(), vlan.getVlanNetmask()); String currentVlanSubnet = NetUtils.getSubNet(vlan.getVlanGateway(), vlan.getVlanNetmask());
if (newVlanSubnet.equals(currentVlanSubnet)) 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."); 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 { else {
// Check if a VLAN actually exists in the specified zone // Check if a VLAN actually exists in the specified zone
long vlanDbId = getVlanDbId(zone, vlanId); long vlanDbId = getVlanDbId(zone, vlanId);
if (vlanDbId == -1) if (vlanDbId == -1)
return genReturnList("false", "A VLAN with ID " + vlanId + " does not exist in zone " + zone); 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. // Check if there are any public IPs that are in the specified vlan.
List<IPAddressVO> ips = _publicIpAddressDao.listByVlanDbId(vlanDbId); List<IPAddressVO> ips = _publicIpAddressDao.listByVlanDbId(vlanDbId);
if (ips.size() != 0) if (ips.size() != 0)
return genReturnList("false", "Please delete all IP addresses that are in VLAN " + vlanId + " before deleting the VLAN."); return genReturnList("false", "Please delete all IP addresses that are in VLAN " + vlanId + " before deleting the VLAN.");
// Delete the vlan // Delete the vlan
_vlanDao.delete(vlanDbId); _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 { public void testKeystoreSave() throws Exception {
KeystoreVO ksVo; KeystoreVO ksVo;
ComponentLocator locator = ComponentLocator.getCurrentLocator(); ComponentLocator locator = ComponentLocator.getCurrentLocator();
@ -98,15 +98,15 @@ public class KeystoreTest extends TestCase {
} }
public void testStripeKey() throws Exception { public void testStripeKey() throws Exception {
Pattern regex = Pattern.compile("(^[\\-]+[^\\-]+[\\-]+[\\n]?)([^\\-]+)([\\-]+[^\\-]+[\\-]+$)"); 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-----"); 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()) { if(m.find()) {
String content = m.group(2); String content = m.group(2);
assertTrue(content.startsWith("MIIEpAIBAAKCAQE")); assertTrue(content.startsWith("MIIEpAIBAAKCAQE"));
assertTrue(content.endsWith("KghyqAF1w==\n")); assertTrue(content.endsWith("KghyqAF1w==\n"));
} else { } else {
assertTrue(false); assertTrue(false);
} }
} }
public void testKeystoreManager() throws Exception { public void testKeystoreManager() throws Exception {
@ -122,10 +122,10 @@ public class KeystoreTest extends TestCase {
assertTrue(ksBits != null); assertTrue(ksBits != null);
try { try {
KeyStore ks = CertificateHelper.loadKeystore(ksBits, "vmops.com"); KeyStore ks = CertificateHelper.loadKeystore(ksBits, "vmops.com");
assertTrue(ks != null); assertTrue(ks != null);
} catch(Exception e) { } catch(Exception e) {
assertTrue(false); assertTrue(false);
} }
KeystoreDao ksDao = locator.getDao(KeystoreDao.class); KeystoreDao ksDao = locator.getDao(KeystoreDao.class);
@ -137,18 +137,18 @@ public class KeystoreTest extends TestCase {
UserVmResponse vm = new UserVmResponse(); UserVmResponse vm = new UserVmResponse();
vm.setId(Long.toString(3L)); vm.setId(Long.toString(3L));
/* /*
vm.setAccountName("admin"); vm.setAccountName("admin");
vm.setName("i-2-3-KY"); vm.setName("i-2-3-KY");
vm.setDisplayName("i-2-3-KY"); vm.setDisplayName("i-2-3-KY");
vm.setDomainId(1L); vm.setDomainId(1L);
vm.setDomainName("ROOT"); vm.setDomainName("ROOT");
vm.setCreated(new Date()); vm.setCreated(new Date());
vm.setState("Running"); vm.setState("Running");
vm.setZoneId(1L); vm.setZoneId(1L);
vm.setZoneName("KY"); vm.setZoneName("KY");
vm.setHostId(1L); vm.setHostId(1L);
vm.setObjectName("virtualmachine"); vm.setObjectName("virtualmachine");
*/ */
String result = ApiSerializerHelper.toSerializedString(vm); 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\"}"; // 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 { public class RemoteAccessVpnTest {
private final static Logger s_logger = Logger.getLogger(RemoteAccessVpnTest.class); private final static Logger s_logger = Logger.getLogger(RemoteAccessVpnTest.class);
// private static void addDaos(MockComponentLocator locator) { // private static void addDaos(MockComponentLocator locator) {
// locator.addDao("AccountDao", AccountDaoImpl.class); // locator.addDao("AccountDao", AccountDaoImpl.class);
// locator.addDao("VpnUserDao", VpnUserDaoImpl.class); // locator.addDao("VpnUserDao", VpnUserDaoImpl.class);
// locator.addDao("FirewallRulesDao", FirewallRulesDaoImpl.class); // locator.addDao("FirewallRulesDao", FirewallRulesDaoImpl.class);
// locator.addDao("IPAddressDao", IPAddressDaoImpl.class); // locator.addDao("IPAddressDao", IPAddressDaoImpl.class);
// locator.addDao("DomainDao", DomainDaoImpl.class); // locator.addDao("DomainDao", DomainDaoImpl.class);
// locator.addDao("UsageEventDao", UsageEventDaoImpl.class); // locator.addDao("UsageEventDao", UsageEventDaoImpl.class);
// locator.addDao("RemoteAccessVpnDao", RemoteAccessVpnDaoImpl.class); // locator.addDao("RemoteAccessVpnDao", RemoteAccessVpnDaoImpl.class);
// locator.addDao("ConfigurationDao", ConfigurationDaoImpl.class); // locator.addDao("ConfigurationDao", ConfigurationDaoImpl.class);
// //
// } // }
// //
// private static void addManagers(MockComponentLocator locator) { // private static void addManagers(MockComponentLocator locator) {
// locator.addManager("AccountManager", MockAccountManagerImpl.class); // locator.addManager("AccountManager", MockAccountManagerImpl.class);
// locator.addManager("DomainManager", MockDomainManagerImpl.class); // locator.addManager("DomainManager", MockDomainManagerImpl.class);
// locator.addManager("NetworkManager", MockNetworkManagerImpl.class); // locator.addManager("NetworkManager", MockNetworkManagerImpl.class);
// locator.addManager("NetworkModel", MockNetworkModelImpl.class); // locator.addManager("NetworkModel", MockNetworkModelImpl.class);
// locator.addManager("RulesManager", MockRulesManagerImpl.class); // locator.addManager("RulesManager", MockRulesManagerImpl.class);
// locator.addManager("FirewallManager", MockFirewallManagerImpl.class); // locator.addManager("FirewallManager", MockFirewallManagerImpl.class);
// } // }
// @Before // @Before
// public void setUp() { // public void setUp() {
// locator = new MockComponentLocator("management-server"); // locator = new MockComponentLocator("management-server");
// addDaos(locator); // addDaos(locator);
// addManagers(locator); // addManagers(locator);
// s_logger.info("Finished setUp"); // s_logger.info("Finished setUp");
// } // }
@After @After
public void tearDown() throws Exception { public void tearDown() throws Exception {
@ -58,19 +58,19 @@ public class RemoteAccessVpnTest {
@Test @Test
public void testInjected() throws Exception { public void testInjected() throws Exception {
// List<Pair<String, Class<? extends RemoteAccessVPNServiceProvider>>> list = // List<Pair<String, Class<? extends RemoteAccessVPNServiceProvider>>> list =
// new ArrayList<Pair<String, Class<? extends RemoteAccessVPNServiceProvider>>>(); // new ArrayList<Pair<String, Class<? extends RemoteAccessVPNServiceProvider>>>();
// list.add(new Pair<String, Class<? extends RemoteAccessVPNServiceProvider>>("RemoteAccessVPNServiceProvider", MockRemoteAccessVPNServiceProvider.class)); // list.add(new Pair<String, Class<? extends RemoteAccessVPNServiceProvider>>("RemoteAccessVPNServiceProvider", MockRemoteAccessVPNServiceProvider.class));
// locator.addAdapterChain(RemoteAccessVPNServiceProvider.class, list); // locator.addAdapterChain(RemoteAccessVPNServiceProvider.class, list);
// s_logger.info("Finished add adapter"); // s_logger.info("Finished add adapter");
// locator.makeActive(new DefaultInterceptorLibrary()); // locator.makeActive(new DefaultInterceptorLibrary());
// s_logger.info("Finished make active"); // s_logger.info("Finished make active");
// RemoteAccessVpnManagerImpl vpnMgr = ComponentLocator.inject(RemoteAccessVpnManagerImpl.class); // RemoteAccessVpnManagerImpl vpnMgr = ComponentLocator.inject(RemoteAccessVpnManagerImpl.class);
// s_logger.info("Finished inject"); // s_logger.info("Finished inject");
// Assert.assertTrue(vpnMgr.configure("RemoteAccessVpnMgr",new HashMap<String, Object>()) ); // Assert.assertTrue(vpnMgr.configure("RemoteAccessVpnMgr",new HashMap<String, Object>()) );
// Assert.assertTrue(vpnMgr.start()); // Assert.assertTrue(vpnMgr.start());
// int numProviders = vpnMgr.getRemoteAccessVPNServiceProviders().size(); // int numProviders = vpnMgr.getRemoteAccessVPNServiceProviders().size();
// Assert.assertTrue(numProviders > 0); // 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"); protected boolean verbose = System.getProperty("rdpclient.MockServer.debug", "false").equals("true");
public MockServer(Packet packets[]) { public MockServer(Packet packets[]) {
this.packets = packets; this.packets = packets;
} }
public void start() throws IOException { public void start() throws IOException {
serverSocket = new ServerSocket(0); serverSocket = new ServerSocket(0);
shutdown = false; shutdown = false;
exception = null; exception = null;
shutdowned = false; shutdowned = false;
new Thread(this).start(); new Thread(this).start();
} }
public void run() { public void run() {
try { try {
Socket socket = serverSocket.accept(); Socket socket = serverSocket.accept();
InputStream is = socket.getInputStream(); InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream(); OutputStream os = socket.getOutputStream();
try { try {
for (int i = 0; i < packets.length && !shutdown; i++) { for (int i = 0; i < packets.length && !shutdown; i++) {
Packet packet = packets[i]; Packet packet = packets[i];
switch (packet.type) { switch (packet.type) {
case CLIENT: { case CLIENT: {
// Read client data and compare it with mock data // Read client data and compare it with mock data
// (unless "ignore" option is set) // (unless "ignore" option is set)
byte actualData[] = new byte[packet.data.length]; byte actualData[] = new byte[packet.data.length];
int actualDataLength = is.read(actualData); int actualDataLength = is.read(actualData);
if (verbose) if (verbose)
System.out.println("[" + this + "] INFO: Data is read: {" + Arrays.toString(Arrays.copyOf(actualData, actualDataLength)) + "}."); System.out.println("[" + this + "] INFO: Data is read: {" + Arrays.toString(Arrays.copyOf(actualData, actualDataLength)) + "}.");
if (!packet.ignore) { if (!packet.ignore) {
// Compare actual data with expected data // Compare actual data with expected data
if (actualDataLength != packet.data.length) { if (actualDataLength != packet.data.length) {
throw new AssertionError("Actual length of client request for packet #" + (i + 1) + " (\"" + packet.id + "\")" 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: " + " does not match length of expected client request. Actual length: " + actualDataLength + ", expected legnth: "
+ packet.data.length + "."); + 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]) { if (packet.data[j] != actualData[j]) {
throw new AssertionError("Actual byte #" + (j + 1) + " of client request for packet #" + (i + 1) + " (\"" + packet.id 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] + "\")" + " does not match corresponding byte of expected client request. Actual byte: " + actualData[j]
+ ", expected byte: " + packet.data[j] + "."); + ", expected byte: " + packet.data[j] + ".");
} }
} }
} }
break; break;
} }
case SERVER: { case SERVER: {
// Send mock data to client // Send mock data to client
os.write(packet.data); os.write(packet.data);
if (verbose) if (verbose)
System.out.println("[" + this + "] INFO: Data is written: {" + Arrays.toString(packet.data) + "}."); System.out.println("[" + this + "] INFO: Data is written: {" + Arrays.toString(packet.data) + "}.");
break; break;
} }
case UPGRADE_TO_SSL: { case UPGRADE_TO_SSL: {
// Attach SSL context to socket // Attach SSL context to socket
final SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault(); final SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(socket, null, serverSocket.getLocalPort(), true); SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(socket, null, serverSocket.getLocalPort(), true);
sslSocket.setEnabledCipherSuites(sslSocket.getSupportedCipherSuites()); sslSocket.setEnabledCipherSuites(sslSocket.getSupportedCipherSuites());
sslSocket.setUseClientMode(false); sslSocket.setUseClientMode(false);
sslSocket.startHandshake(); sslSocket.startHandshake();
is = sslSocket.getInputStream(); is = sslSocket.getInputStream();
os = sslSocket.getOutputStream(); os = sslSocket.getOutputStream();
break; break;
} }
default: default:
throw new RuntimeException("Unknown packet type: " + packet.type); throw new RuntimeException("Unknown packet type: " + packet.type);
} }
} }
} finally { } finally {
try { try {
is.close(); is.close();
} catch (Throwable e) { } catch (Throwable e) {
} }
try { try {
os.close(); os.close();
} catch (Throwable e) { } catch (Throwable e) {
} }
try { try {
socket.close(); socket.close();
} catch (Throwable e) { } catch (Throwable e) {
} }
try { try {
serverSocket.close(); serverSocket.close();
} catch (Throwable e) { } catch (Throwable e) {
} }
} }
} catch (Throwable e) { } catch (Throwable e) {
System.err.println("Error in mock server: " + e.getMessage()); System.err.println("Error in mock server: " + e.getMessage());
e.printStackTrace(System.err); e.printStackTrace(System.err);
exception = e; exception = e;
} }
shutdowned = true; shutdowned = true;
if (verbose) if (verbose)
System.out.println("[" + this + "] INFO: Mock server shutdowned."); System.out.println("[" + this + "] INFO: Mock server shutdowned.");
} }
public void shutdown() { public void shutdown() {
shutdown = true; shutdown = true;
} }
public InetSocketAddress getAddress() { public InetSocketAddress getAddress() {
return (InetSocketAddress) serverSocket.getLocalSocketAddress(); return (InetSocketAddress) serverSocket.getLocalSocketAddress();
} }
public Throwable getException() { public Throwable getException() {
return exception; return exception;
} }
public static class Packet { public static class Packet {
public static enum PacketType { public static enum PacketType {
SERVER, CLIENT, UPGRADE_TO_SSL; SERVER, CLIENT, UPGRADE_TO_SSL;
} }
public String id = ""; public String id = "";
public Packet() { public Packet() {
} }
public Packet(String id) { public Packet(String id) {
this.id = 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() { public boolean isShutdowned() {
return shutdowned; return shutdowned;
} }
public void waitUntilShutdowned(long timeToWaitMiliseconds) throws InterruptedException { public void waitUntilShutdowned(long timeToWaitMiliseconds) throws InterruptedException {
long deadline = System.currentTimeMillis() + timeToWaitMiliseconds; long deadline = System.currentTimeMillis() + timeToWaitMiliseconds;
while (!shutdowned && System.currentTimeMillis() < deadline) { while (!shutdowned && System.currentTimeMillis() < deadline) {
Thread.sleep(10); Thread.sleep(10);
} }
} }
} }

View File

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

View File

@ -176,7 +176,7 @@ public class ConsoleProxyPasswordBasedEncryptor {
random.nextBytes(ivBytes); random.nextBytes(ivBytes);
KeyIVPair keyIvPair = new KeyIVPair("8x/xUBgX0Up+3UEo39dSeG277JhVj31+ElHkN5+EC0Q=", "Y2SUiIN6JXTdKNK/ZMDyVtLB7gAM9MCCiyrP1xd3bSQ="); KeyIVPair keyIvPair = new KeyIVPair("8x/xUBgX0Up+3UEo39dSeG277JhVj31+ElHkN5+EC0Q=", "Y2SUiIN6JXTdKNK/ZMDyVtLB7gAM9MCCiyrP1xd3bSQ=");
//keyIvPair.setKeyBytes(keyBytes); //keyIvPair.setKeyBytes(keyBytes);
//keyIvPair.setIvBytes(ivBytes); //keyIvPair.setIvBytes(ivBytes);
Gson gson = new GsonBuilder().create(); 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 url the url from where to download from
* @param hvm whether the template is a hardware virtual machine * @param hvm whether the template is a hardware virtual machine
* @param accountId the accountId of the iso owner (null if public iso) * @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 user username used for authentication to the server
* @param password password 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. * @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 = new Script("/bin/bash", s_logger);
command.add("-c"); command.add("-c");
command.add("iptables -D INPUT -i " + intf + " -p tcp -m state --state NEW -m tcp --dport " + port + " -j DROP;" + 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 " + 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 DROP;" +
"iptables -D INPUT -i " + intf + " -p tcp -m state --state NEW -m tcp --dport " + "443" + " -j HTTP;" + "iptables -D INPUT -i " + intf + " -p tcp -m state --state NEW -m tcp --dport " + "443" + " -j HTTP;" +
"iptables -F HTTP;" + "iptables -F HTTP;" +
"iptables -X HTTP;" + "iptables -X HTTP;" +
"iptables -N 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 " + 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 " + "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 " + port + " -j HTTP;" +
"iptables -I INPUT -i " + intf + " -p tcp -m state --state NEW -m tcp --dport " + "443" + " -j HTTP;"); "iptables -I INPUT -i " + intf + " -p tcp -m state --state NEW -m tcp --dport " + "443" + " -j HTTP;");
result = command.execute(); result = command.execute();
if (result != null) { if (result != null) {
s_logger.warn("Error in opening up httpd port err=" + result ); s_logger.warn("Error in opening up httpd port err=" + result );
return false; return false;
}*/ }*/
command = new Script("/bin/bash", s_logger); command = new Script("/bin/bash", s_logger);

View File

@ -27,102 +27,102 @@ import org.apache.log4j.Logger;
public class BuildGuestNetwork { public class BuildGuestNetwork {
public static final Logger s_logger= Logger.getLogger(BuildGuestNetwork.class.getClass()); public static final Logger s_logger= Logger.getLogger(BuildGuestNetwork.class.getClass());
private static final int _apiPort=8096; private static final int _apiPort=8096;
private static final int _developerPort=8080; private static final int _developerPort=8080;
private static final String _apiUrl = "/client/api"; private static final String _apiUrl = "/client/api";
private static int numVM=1; private static int numVM=1;
private static long zoneId=-1L; private static long zoneId=-1L;
private static long templateId=3; private static long templateId=3;
private static long serviceOfferingId=1; private static long serviceOfferingId=1;
public static void main (String[] args){ public static void main (String[] args){
List<String> argsList = Arrays.asList(args); List<String> argsList = Arrays.asList(args);
Iterator<String> iter = argsList.iterator(); Iterator<String> iter = argsList.iterator();
String host = "http://localhost"; String host = "http://localhost";
int numThreads = 1; int numThreads = 1;
while (iter.hasNext()){ while (iter.hasNext()){
String arg = iter.next(); String arg = iter.next();
if (arg.equals("-h")){ if (arg.equals("-h")){
host="http://"+iter.next(); host="http://"+iter.next();
} }
if (arg.equals("-t")){ if (arg.equals("-t")){
numThreads=Integer.parseInt(iter.next()); numThreads=Integer.parseInt(iter.next());
} }
if (arg.equals("-n")){ if (arg.equals("-n")){
numVM=Integer.parseInt(iter.next()); numVM=Integer.parseInt(iter.next());
} }
if (arg.equals("-z")){ if (arg.equals("-z")){
zoneId=Integer.parseInt(iter.next()); zoneId=Integer.parseInt(iter.next());
} }
if (arg.equals("-e")){ if (arg.equals("-e")){
templateId=Integer.parseInt(iter.next()); templateId=Integer.parseInt(iter.next());
} }
if (arg.equals("-s")){ if (arg.equals("-s")){
serviceOfferingId=Integer.parseInt(iter.next()); serviceOfferingId=Integer.parseInt(iter.next());
} }
} }
final String server = host + ":" + _apiPort + "/"; final String server = host + ":" + _apiPort + "/";
final String developerServer = host + ":" + _developerPort + _apiUrl; final String developerServer = host + ":" + _developerPort + _apiUrl;
s_logger.info("Starting test in "+numThreads+" thread(s). Each thread is launching "+numVM+" VMs"); s_logger.info("Starting test in "+numThreads+" thread(s). Each thread is launching "+numVM+" VMs");
for (int i=0; i<numThreads; i++){ for (int i=0; i<numThreads; i++){
new Thread(new Runnable() { new Thread(new Runnable() {
public void run() { public void run() {
try{ try{
String username = null; String username = null;
String singlePrivateIp=null; String singlePrivateIp=null;
Random ran = new Random(); Random ran = new Random();
username = Math.abs(ran.nextInt())+ "-user"; username = Math.abs(ran.nextInt())+ "-user";
//Create User //Create User
User myUser = new User(username,username, server, developerServer); User myUser = new User(username,username, server, developerServer);
try{ try{
myUser.launchUser(); myUser.launchUser();
myUser.registerUser(); myUser.registerUser();
}catch (Exception e){ }catch (Exception e){
s_logger.warn("Error code: ", e); s_logger.warn("Error code: ", e);
} }
if (myUser.getUserId()!=null){ if (myUser.getUserId()!=null){
s_logger.info("User "+myUser.getUserName()+" was created successfully, starting VM creation"); s_logger.info("User "+myUser.getUserName()+" was created successfully, starting VM creation");
//create VMs for the user //create VMs for the user
for (int i=0; i<numVM; i++){ for (int i=0; i<numVM; i++){
//Create a new VM, add it to the list of user's VMs //Create a new VM, add it to the list of user's VMs
VirtualMachine myVM = new VirtualMachine(myUser.getUserId()); VirtualMachine myVM = new VirtualMachine(myUser.getUserId());
myVM.deployVM(zoneId, serviceOfferingId, templateId, myUser.getDeveloperServer(), myUser.getApiKey(), myUser.getSecretKey()); myVM.deployVM(zoneId, serviceOfferingId, templateId, myUser.getDeveloperServer(), myUser.getApiKey(), myUser.getSecretKey());
myUser.getVirtualMachines().add(myVM); myUser.getVirtualMachines().add(myVM);
singlePrivateIp=myVM.getPrivateIp(); singlePrivateIp=myVM.getPrivateIp();
if (singlePrivateIp!=null){ if (singlePrivateIp!=null){
s_logger.info("VM with private Ip "+singlePrivateIp+" was successfully created"); s_logger.info("VM with private Ip "+singlePrivateIp+" was successfully created");
} }
else{ else{
s_logger.info("Problems with VM creation for a user"+myUser.getUserName()); s_logger.info("Problems with VM creation for a user"+myUser.getUserName());
s_logger.info("Deployment failed"); s_logger.info("Deployment failed");
break; break;
} }
} }
s_logger.info("Deployment done..."+numVM+" VMs were created."); s_logger.info("Deployment done..."+numVM+" VMs were created.");
} }
}catch (Exception e){ }catch (Exception e){
s_logger.error(e); s_logger.error(e);
} }
} }
}).start(); }).start();
} }
} }
} }

View File

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

View File

@ -32,207 +32,207 @@ import com.cloud.test.stress.TestClientWithAPI;
public class User { public class User {
public static final Logger s_logger= Logger.getLogger(User.class.getClass()); public static final Logger s_logger= Logger.getLogger(User.class.getClass());
private ArrayList<VirtualMachine> virtualMachines; private ArrayList<VirtualMachine> virtualMachines;
private ArrayList<String> publicIp; private ArrayList<String> publicIp;
private String server; private String server;
private String developerServer; private String developerServer;
private String userName; private String userName;
private String userId; private String userId;
private String apiKey; private String apiKey;
private String secretKey; private String secretKey;
private String password; private String password;
private String encryptedPassword; private String encryptedPassword;
public User(String userName, String password, String server, String developerServer) public User(String userName, String password, String server, String developerServer)
{ {
this.server=server; this.server=server;
this.developerServer=developerServer; this.developerServer=developerServer;
this.userName=userName; this.userName=userName;
this.password=password; this.password=password;
this.virtualMachines = new ArrayList<VirtualMachine>(); this.virtualMachines = new ArrayList<VirtualMachine>();
this.publicIp = new ArrayList<String>(); this.publicIp = new ArrayList<String>();
} }
public ArrayList<VirtualMachine> getVirtualMachines() { public ArrayList<VirtualMachine> getVirtualMachines() {
return virtualMachines; return virtualMachines;
} }
public void setVirtualMachines(ArrayList<VirtualMachine> virtualMachines) { public void setVirtualMachines(ArrayList<VirtualMachine> virtualMachines) {
this.virtualMachines = virtualMachines; this.virtualMachines = virtualMachines;
} }
public String getUserId() { public String getUserId() {
return userId; return userId;
} }
public void setUserId(String userId) { public void setUserId(String userId) {
this.userId = userId; this.userId = userId;
} }
public ArrayList<String> getPublicIp() { public ArrayList<String> getPublicIp() {
return publicIp; return publicIp;
} }
public void setPublicIp(ArrayList<String> publicIp) { public void setPublicIp(ArrayList<String> publicIp) {
this.publicIp = publicIp; this.publicIp = publicIp;
} }
public String getServer() { public String getServer() {
return server; return server;
} }
public void setServer(String server) { public void setServer(String server) {
this.server = server; this.server = server;
} }
public String getUserName() { public String getUserName() {
return userName; return userName;
} }
public void setUserName(String userName) { public void setUserName(String userName) {
this.userName = userName; this.userName = userName;
} }
public String getApiKey() { public String getApiKey() {
return apiKey; return apiKey;
} }
public void setApiKey(String apiKey) { public void setApiKey(String apiKey) {
this.apiKey = apiKey; this.apiKey = apiKey;
} }
public String getPassword() { public String getPassword() {
return password; return password;
} }
public void setPassword(String password) { public void setPassword(String password) {
this.password = password; this.password = password;
} }
public String getSecretKey() { public String getSecretKey() {
return secretKey; return secretKey;
} }
public void setSecretKey(String secretKey) { public void setSecretKey(String secretKey) {
this.secretKey = secretKey; this.secretKey = secretKey;
} }
public String getDeveloperServer() { public String getDeveloperServer() {
return developerServer; return developerServer;
} }
public void setDeveloperServer(String developerServer) { public void setDeveloperServer(String developerServer) {
this.developerServer = developerServer; this.developerServer = developerServer;
} }
public void launchUser() throws IOException { public void launchUser() throws IOException {
String encodedUsername = URLEncoder.encode(this.getUserName(), "UTF-8"); String encodedUsername = URLEncoder.encode(this.getUserName(), "UTF-8");
this.encryptedPassword=TestClientWithAPI.createMD5Password(this.getPassword()); this.encryptedPassword=TestClientWithAPI.createMD5Password(this.getPassword());
String encodedPassword = URLEncoder.encode(this.encryptedPassword, "UTF-8"); String encodedPassword = URLEncoder.encode(this.encryptedPassword, "UTF-8");
String url = this.server + "?command=createUser&username=" + encodedUsername String url = this.server + "?command=createUser&username=" + encodedUsername
+ "&password=" + encodedPassword + "&password=" + encodedPassword
+ "&firstname=Test&lastname=Test&email=alena@vmops.com&domainId=1"; + "&firstname=Test&lastname=Test&email=alena@vmops.com&domainId=1";
String userIdStr=null; String userIdStr=null;
HttpClient client = new HttpClient(); HttpClient client = new HttpClient();
HttpMethod method = new GetMethod(url); HttpMethod method = new GetMethod(url);
int responseCode = client.executeMethod(method); int responseCode = client.executeMethod(method);
if (responseCode == 200) { if (responseCode == 200) {
InputStream is = method.getResponseBodyAsStream(); InputStream is = method.getResponseBodyAsStream();
Map<String, String> userIdValues = TestClientWithAPI.getSingleValueFromXML(is, Map<String, String> userIdValues = TestClientWithAPI.getSingleValueFromXML(is,
new String[] { "id" }); new String[] { "id" });
userIdStr = userIdValues.get("id"); userIdStr = userIdValues.get("id");
if ((userIdStr != null) && (Long.parseLong(userIdStr)!=-1)) { if ((userIdStr != null) && (Long.parseLong(userIdStr)!=-1)) {
this.setUserId(userIdStr); this.setUserId(userIdStr);
} }
} }
} }
public void retrievePublicIp(long zoneId) throws IOException{ public void retrievePublicIp(long zoneId) throws IOException{
String encodedApiKey = URLEncoder.encode(this.apiKey, "UTF-8"); String encodedApiKey = URLEncoder.encode(this.apiKey, "UTF-8");
String encodedZoneId=URLEncoder.encode(""+zoneId,"UTF-8"); String encodedZoneId=URLEncoder.encode(""+zoneId,"UTF-8");
String requestToSign = "apiKey=" + encodedApiKey String requestToSign = "apiKey=" + encodedApiKey
+ "&command=associateIpAddress" + "&zoneId="+encodedZoneId; + "&command=associateIpAddress" + "&zoneId="+encodedZoneId;
requestToSign = requestToSign.toLowerCase(); requestToSign = requestToSign.toLowerCase();
String signature = TestClientWithAPI.signRequest(requestToSign, this.secretKey); String signature = TestClientWithAPI.signRequest(requestToSign, this.secretKey);
String encodedSignature = URLEncoder.encode(signature, "UTF-8"); String encodedSignature = URLEncoder.encode(signature, "UTF-8");
String url = this.developerServer + "?command=associateIpAddress" + "&apiKey=" String url = this.developerServer + "?command=associateIpAddress" + "&apiKey="
+ encodedApiKey + "&zoneId="+encodedZoneId+"&signature=" + encodedApiKey + "&zoneId="+encodedZoneId+"&signature="
+ encodedSignature; + encodedSignature;
HttpClient client = new HttpClient(); HttpClient client = new HttpClient();
HttpMethod method = new GetMethod(url); HttpMethod method = new GetMethod(url);
int responseCode=client.executeMethod(method); int responseCode=client.executeMethod(method);
if (responseCode == 200) { if (responseCode == 200) {
InputStream is = method.getResponseBodyAsStream(); InputStream is = method.getResponseBodyAsStream();
Map<String, String> values = TestClientWithAPI.getSingleValueFromXML(is, Map<String, String> values = TestClientWithAPI.getSingleValueFromXML(is,
new String[] { "ipaddress" }); new String[] { "ipaddress" });
this.getPublicIp().add(values.get("ipaddress")); this.getPublicIp().add(values.get("ipaddress"));
s_logger.info("Ip address is " + values.get("ipaddress")); s_logger.info("Ip address is " + values.get("ipaddress"));
} else if (responseCode == 500) { } else if (responseCode == 500) {
InputStream is = method.getResponseBodyAsStream(); InputStream is = method.getResponseBodyAsStream();
Map<String, String> errorInfo = TestClientWithAPI.getSingleValueFromXML(is, Map<String, String> errorInfo = TestClientWithAPI.getSingleValueFromXML(is,
new String[] { "errorcode", "description" }); new String[] { "errorcode", "description" });
s_logger.error("associate ip test failed with errorCode: " s_logger.error("associate ip test failed with errorCode: "
+ errorInfo.get("errorCode") + " and description: " + errorInfo.get("errorCode") + " and description: "
+ errorInfo.get("description")); + errorInfo.get("description"));
} else { } else {
s_logger.error("internal error processing request: " s_logger.error("internal error processing request: "
+ method.getStatusText()); + method.getStatusText());
} }
} }
public void registerUser()throws HttpException, IOException{ public void registerUser()throws HttpException, IOException{
String encodedUsername = URLEncoder.encode(this.userName, "UTF-8"); String encodedUsername = URLEncoder.encode(this.userName, "UTF-8");
String encodedPassword = URLEncoder.encode(this.password, "UTF-8"); String encodedPassword = URLEncoder.encode(this.password, "UTF-8");
String url = server + "?command=register&username=" + encodedUsername String url = server + "?command=register&username=" + encodedUsername
+ "&domainid=1"; + "&domainid=1";
s_logger.info("registering: " + this.userName+" with url "+url); s_logger.info("registering: " + this.userName+" with url "+url);
HttpClient client = new HttpClient(); HttpClient client = new HttpClient();
HttpMethod method = new GetMethod(url); HttpMethod method = new GetMethod(url);
int responseCode = client.executeMethod(method); int responseCode = client.executeMethod(method);
if (responseCode == 200) { if (responseCode == 200) {
InputStream is = method.getResponseBodyAsStream(); InputStream is = method.getResponseBodyAsStream();
Map<String, String> requestKeyValues = TestClientWithAPI.getSingleValueFromXML(is, Map<String, String> requestKeyValues = TestClientWithAPI.getSingleValueFromXML(is,
new String[] { "apikey", "secretkey" }); new String[] { "apikey", "secretkey" });
this.setApiKey(requestKeyValues.get("apikey")); this.setApiKey(requestKeyValues.get("apikey"));
this.setSecretKey(requestKeyValues.get("secretkey")); this.setSecretKey(requestKeyValues.get("secretkey"));
} else if (responseCode == 500) { } else if (responseCode == 500) {
InputStream is = method.getResponseBodyAsStream(); InputStream is = method.getResponseBodyAsStream();
Map<String, String> errorInfo = TestClientWithAPI.getSingleValueFromXML(is, Map<String, String> errorInfo = TestClientWithAPI.getSingleValueFromXML(is,
new String[] { "errorcode", "description" }); new String[] { "errorcode", "description" });
s_logger.error("registration failed with errorCode: " s_logger.error("registration failed with errorCode: "
+ errorInfo.get("errorCode") + " and description: " + errorInfo.get("errorCode") + " and description: "
+ errorInfo.get("description")); + errorInfo.get("description"));
} else { } else {
s_logger.error("internal error processing request: " s_logger.error("internal error processing request: "
+ method.getStatusText()); + method.getStatusText());
} }
} }
} }

View File

@ -32,85 +32,85 @@ import java.io.IOException;
public class VirtualMachine { public class VirtualMachine {
public static final Logger s_logger= Logger.getLogger(VirtualMachine.class.getClass()); public static final Logger s_logger= Logger.getLogger(VirtualMachine.class.getClass());
private String privateIp; private String privateIp;
private String userId; private String userId;
public VirtualMachine(String userId){ public VirtualMachine(String userId){
this.userId=userId; this.userId=userId;
} }
public String getPrivateIp() { public String getPrivateIp() {
return privateIp; return privateIp;
} }
public void setPrivateIp(String privateIp) { public void setPrivateIp(String privateIp) {
this.privateIp = privateIp; this.privateIp = privateIp;
} }
public String getUserId() { public String getUserId() {
return userId; return userId;
} }
public void setUserId(String userId) { public void setUserId(String userId) {
this.userId = 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 encodedZoneId = URLEncoder.encode("" + zoneId, "UTF-8");
String encodedServiceOfferingId = URLEncoder.encode("" String encodedServiceOfferingId = URLEncoder.encode(""
+ serviceOfferingId, "UTF-8"); + serviceOfferingId, "UTF-8");
String encodedTemplateId = URLEncoder.encode("" + templateId, String encodedTemplateId = URLEncoder.encode("" + templateId,
"UTF-8"); "UTF-8");
String encodedApiKey=URLEncoder.encode(apiKey, "UTF-8"); String encodedApiKey=URLEncoder.encode(apiKey, "UTF-8");
String requestToSign = "apiKey=" + encodedApiKey String requestToSign = "apiKey=" + encodedApiKey
+ "&command=deployVirtualMachine&serviceOfferingId=" + "&command=deployVirtualMachine&serviceOfferingId="
+ encodedServiceOfferingId + "&templateId=" + encodedServiceOfferingId + "&templateId="
+ encodedTemplateId + "&zoneId=" + encodedZoneId; + encodedTemplateId + "&zoneId=" + encodedZoneId;
requestToSign = requestToSign.toLowerCase(); requestToSign = requestToSign.toLowerCase();
String signature = TestClientWithAPI.signRequest(requestToSign, secretKey); String signature = TestClientWithAPI.signRequest(requestToSign, secretKey);
String encodedSignature = URLEncoder.encode(signature, "UTF-8"); String encodedSignature = URLEncoder.encode(signature, "UTF-8");
String url = server + "?command=deployVirtualMachine" String url = server + "?command=deployVirtualMachine"
+ "&zoneId=" + encodedZoneId + "&serviceOfferingId=" + "&zoneId=" + encodedZoneId + "&serviceOfferingId="
+ encodedServiceOfferingId + "&templateId=" + encodedServiceOfferingId + "&templateId="
+ encodedTemplateId + "&apiKey=" + encodedApiKey + encodedTemplateId + "&apiKey=" + encodedApiKey
+ "&signature=" + encodedSignature; + "&signature=" + encodedSignature;
s_logger.info("Sending this request to deploy a VM: "+url); s_logger.info("Sending this request to deploy a VM: "+url);
HttpClient client = new HttpClient(); HttpClient client = new HttpClient();
HttpMethod method = new GetMethod(url); HttpMethod method = new GetMethod(url);
int responseCode = client.executeMethod(method); int responseCode = client.executeMethod(method);
s_logger.info("deploy linux vm response code: " + responseCode); s_logger.info("deploy linux vm response code: " + responseCode);
if (responseCode == 200) { if (responseCode == 200) {
InputStream is = method.getResponseBodyAsStream(); InputStream is = method.getResponseBodyAsStream();
Map<String, String> values = TestClientWithAPI.getSingleValueFromXML(is, Map<String, String> values = TestClientWithAPI.getSingleValueFromXML(is,
new String[] { "id", "ipaddress" }); new String[] { "id", "ipaddress" });
long linuxVMId = Long.parseLong(values.get("id")); long linuxVMId = Long.parseLong(values.get("id"));
s_logger.info("got linux virtual machine id: " + linuxVMId); s_logger.info("got linux virtual machine id: " + linuxVMId);
this.setPrivateIp(values.get("ipaddress")); this.setPrivateIp(values.get("ipaddress"));
} else if (responseCode == 500) { } else if (responseCode == 500) {
InputStream is = method.getResponseBodyAsStream(); InputStream is = method.getResponseBodyAsStream();
Map<String, String> errorInfo = TestClientWithAPI.getSingleValueFromXML(is, Map<String, String> errorInfo = TestClientWithAPI.getSingleValueFromXML(is,
new String[] { "errorcode", "description" }); new String[] { "errorcode", "description" });
s_logger.error("deploy linux vm test failed with errorCode: " s_logger.error("deploy linux vm test failed with errorCode: "
+ errorInfo.get("errorCode") + " and description: " + errorInfo.get("errorCode") + " and description: "
+ errorInfo.get("description")); + errorInfo.get("description"));
} else { } else {
s_logger.error("internal error processing request: " s_logger.error("internal error processing request: "
+ method.getStatusText()); + method.getStatusText());
} }
} }
} }

View File

@ -24,84 +24,84 @@ import com.trilead.ssh2.Session;
public class guestNetwork implements Runnable{ public class guestNetwork implements Runnable{
public static final Logger s_logger= Logger.getLogger(guestNetwork.class.getClass()); public static final Logger s_logger= Logger.getLogger(guestNetwork.class.getClass());
private String publicIp; private String publicIp;
private ArrayList<VirtualMachine> virtualMachines; private ArrayList<VirtualMachine> virtualMachines;
private int retryNum; private int retryNum;
public guestNetwork(String publicIp, int retryNum){ public guestNetwork(String publicIp, int retryNum){
this.publicIp=publicIp; this.publicIp=publicIp;
this.retryNum=retryNum; this.retryNum=retryNum;
} }
public ArrayList<VirtualMachine> getVirtualMachines() { public ArrayList<VirtualMachine> getVirtualMachines() {
return virtualMachines; return virtualMachines;
} }
public void setVirtualMachines(ArrayList<VirtualMachine> virtualMachines) { public void setVirtualMachines(ArrayList<VirtualMachine> virtualMachines) {
this.virtualMachines = virtualMachines; this.virtualMachines = virtualMachines;
} }
public void run(){ public void run(){
NDC.push("Following thread has started"+Thread.currentThread().getName()); NDC.push("Following thread has started"+Thread.currentThread().getName());
int retry = 0; int retry = 0;
//Start copying files between machines in the network //Start copying files between machines in the network
s_logger.info("The size of the array is " + this.virtualMachines.size()); s_logger.info("The size of the array is " + this.virtualMachines.size());
while (true) { while (true) {
try { try {
if (retry > 0) { if (retry > 0) {
s_logger.info("Retry attempt : " + retry s_logger.info("Retry attempt : " + retry
+ " ...sleeping 120 seconds before next attempt"); + " ...sleeping 120 seconds before next attempt");
Thread.sleep(120000); Thread.sleep(120000);
} }
for (VirtualMachine vm: this.virtualMachines ){ for (VirtualMachine vm: this.virtualMachines ){
s_logger.info("Attempting to SSH into linux host " + this.publicIp s_logger.info("Attempting to SSH into linux host " + this.publicIp
+ " with retry attempt: " + retry); + " with retry attempt: " + retry);
Connection conn = new Connection(this.publicIp); Connection conn = new Connection(this.publicIp);
conn.connect(null, 600000, 600000); 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", boolean isAuthenticated = conn.authenticateWithPassword("root",
"password"); "password");
if (isAuthenticated == false) { if (isAuthenticated == false) {
s_logger.info("Authentication failed"); s_logger.info("Authentication failed");
} }
//execute copy command //execute copy command
Session sess = conn.openSession(); Session sess = conn.openSession();
String fileName; String fileName;
Random ran = new Random(); Random ran = new Random();
fileName=Math.abs(ran.nextInt())+"-file"; fileName=Math.abs(ran.nextInt())+"-file";
String copyCommand = new String ("./scpScript "+vm.getPrivateIp()+" "+fileName); String copyCommand = new String ("./scpScript "+vm.getPrivateIp()+" "+fileName);
s_logger.info("Executing " + copyCommand); s_logger.info("Executing " + copyCommand);
sess.execCommand(copyCommand); sess.execCommand(copyCommand);
Thread.sleep(120000); Thread.sleep(120000);
sess.close(); sess.close();
//execute wget command //execute wget command
sess = conn.openSession(); 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"); 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); s_logger.info("Executing " + downloadCommand);
sess.execCommand(downloadCommand); sess.execCommand(downloadCommand);
Thread.sleep(120000); Thread.sleep(120000);
sess.close(); sess.close();
//close the connection //close the connection
conn.close(); conn.close();
} }
}catch (Exception ex) { }catch (Exception ex) {
s_logger.error(ex); s_logger.error(ex);
retry++; retry++;
if (retry == retryNum) { if (retry == retryNum) {
s_logger.info("Performance Guest Network test failed with error " s_logger.info("Performance Guest Network test failed with error "
+ ex.getMessage()) ; + ex.getMessage()) ;
} }
} }
} }
} }
} }

View File

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

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