Updated Branches:
  refs/heads/master 2774b62d6 -> d19688103

Fixing coverity issues related to resource leak on FileInputStream being 
created anonymously

Signed-off-by: Daan Hoogland <[email protected]>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/d1968810
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/d1968810
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/d1968810

Branch: refs/heads/master
Commit: d19688103ba7f7c53c264fb67cb534dd693c95cd
Parents: 2774b62
Author: wilderrodrigues <[email protected]>
Authored: Mon Nov 18 15:35:34 2013 +0100
Committer: Daan Hoogland <[email protected]>
Committed: Wed Nov 27 12:51:44 2013 +0100

----------------------------------------------------------------------
 .../cloud/bridge/service/EC2RestServlet.java    | 46 +++++++-------
 .../service/controller/s3/ServiceProvider.java  | 15 +++--
 .../bridge/service/core/ec2/EC2Engine.java      | 65 +++++++++++---------
 .../com/cloud/cluster/ClusterManagerImpl.java   | 40 ++++++------
 .../com/cloud/consoleproxy/ConsoleProxy.java    | 21 ++++---
 5 files changed, 104 insertions(+), 83 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/d1968810/awsapi/src/com/cloud/bridge/service/EC2RestServlet.java
----------------------------------------------------------------------
diff --git a/awsapi/src/com/cloud/bridge/service/EC2RestServlet.java 
b/awsapi/src/com/cloud/bridge/service/EC2RestServlet.java
index 5c56e9d..fd2919d 100644
--- a/awsapi/src/com/cloud/bridge/service/EC2RestServlet.java
+++ b/awsapi/src/com/cloud/bridge/service/EC2RestServlet.java
@@ -58,6 +58,7 @@ import org.apache.axis2.databinding.ADBBean;
 import org.apache.axis2.databinding.ADBException;
 import org.apache.axis2.databinding.utils.writer.MTOMAwareXMLSerializer;
 import org.apache.commons.codec.binary.Base64;
+import org.apache.commons.io.IOUtils;
 import org.apache.log4j.Logger;
 import org.springframework.stereotype.Component;
 import org.springframework.web.context.support.SpringBeanAutowiringSupport;
@@ -103,7 +104,6 @@ import com.amazon.ec2.RunInstancesResponse;
 import com.amazon.ec2.StartInstancesResponse;
 import com.amazon.ec2.StopInstancesResponse;
 import com.amazon.ec2.TerminateInstancesResponse;
-
 import com.cloud.bridge.model.UserCredentialsVO;
 import com.cloud.bridge.persist.dao.CloudStackUserDaoImpl;
 import com.cloud.bridge.persist.dao.OfferingDaoImpl;
@@ -203,12 +203,16 @@ public class EC2RestServlet extends HttpServlet {
         if (null != propertiesFile) {
             logger.info("Use EC2 properties file: " + 
propertiesFile.getAbsolutePath());
             EC2Prop = new Properties();
+            FileInputStream ec2PropFile = null;
             try {
-                EC2Prop.load(new FileInputStream(propertiesFile));
+                ec2PropFile = new FileInputStream(propertiesFile);
+                EC2Prop.load(ec2PropFile);
             } catch (FileNotFoundException e) {
                 logger.warn("Unable to open properties file: " + 
propertiesFile.getAbsolutePath(), e);
             } catch (IOException e) {
                 logger.warn("Unable to read properties file: " + 
propertiesFile.getAbsolutePath(), e);
+            } finally {
+                IOUtils.closeQuietly(ec2PropFile);
             }
             String keystore = EC2Prop.getProperty("keystore");
             keystorePassword = EC2Prop.getProperty("keystorePass");
@@ -492,7 +496,7 @@ public class EC2RestServlet extends HttpServlet {
                 response.sendError(530, "Missing cert parameter");
                 return;
             }
-//            logger.debug( "SetCertificate cert: [" + certificate[0] + "]" );
+            // logger.debug( "SetCertificate cert: [" + certificate[0] + "]" );
 
             String[] accessKey = request.getParameterValues("AWSAccessKeyId");
             if (null == accessKey || 0 == accessKey.length) {
@@ -578,12 +582,12 @@ public class EC2RestServlet extends HttpServlet {
                  credentialDao.setCertificateId( accessKey[0], null );
 
                  */txn = TransactionLegacy.open(TransactionLegacy.AWSAPI_DB);
-                UserCredentialsVO user = ucDao.getByAccessKey(accessKey[0]);
-                user.setCertUniqueId(null);
-                ucDao.update(user.getId(), user);
-                response.setStatus(200);
-                endResponse(response, "User certificate deleted successfully");
-                txn.commit();
+                 UserCredentialsVO user = ucDao.getByAccessKey(accessKey[0]);
+                 user.setCertUniqueId(null);
+                 ucDao.update(user.getId(), user);
+                 response.setStatus(200);
+                 endResponse(response, "User certificate deleted 
successfully");
+                 txn.commit();
             } else
                 response.setStatus(404);
 
@@ -830,7 +834,7 @@ public class EC2RestServlet extends HttpServlet {
 
         // -> execute the request
         RevokeSecurityGroupIngressResponse EC2response =
-            
EC2SoapServiceImpl.toRevokeSecurityGroupIngressResponse(ServiceProvider.getInstance().getEC2Engine().revokeSecurityGroup(EC2request));
+                
EC2SoapServiceImpl.toRevokeSecurityGroupIngressResponse(ServiceProvider.getInstance().getEC2Engine().revokeSecurityGroup(EC2request));
         serializeResponse(response, EC2response);
     }
 
@@ -915,7 +919,7 @@ public class EC2RestServlet extends HttpServlet {
 
         // -> execute the request
         AuthorizeSecurityGroupIngressResponse EC2response =
-            
EC2SoapServiceImpl.toAuthorizeSecurityGroupIngressResponse(ServiceProvider.getInstance().getEC2Engine().authorizeSecurityGroup(EC2request));
+                
EC2SoapServiceImpl.toAuthorizeSecurityGroupIngressResponse(ServiceProvider.getInstance().getEC2Engine().authorizeSecurityGroup(EC2request));
         serializeResponse(response, EC2response);
     }
 
@@ -1012,7 +1016,7 @@ public class EC2RestServlet extends HttpServlet {
 
         // -> execute the request
         CreateSecurityGroupResponse EC2response =
-            
EC2SoapServiceImpl.toCreateSecurityGroupResponse(ServiceProvider.getInstance().getEC2Engine().createSecurityGroup(groupName,
 groupDescription));
+                
EC2SoapServiceImpl.toCreateSecurityGroupResponse(ServiceProvider.getInstance().getEC2Engine().createSecurityGroup(groupName,
 groupDescription));
         serializeResponse(response, EC2response);
     }
 
@@ -1028,7 +1032,7 @@ public class EC2RestServlet extends HttpServlet {
 
         // -> execute the request
         DeleteSecurityGroupResponse EC2response =
-            
EC2SoapServiceImpl.toDeleteSecurityGroupResponse(ServiceProvider.getInstance().getEC2Engine().deleteSecurityGroup(groupName));
+                
EC2SoapServiceImpl.toDeleteSecurityGroupResponse(ServiceProvider.getInstance().getEC2Engine().deleteSecurityGroup(groupName));
         serializeResponse(response, EC2response);
     }
 
@@ -1166,7 +1170,7 @@ public class EC2RestServlet extends HttpServlet {
 
         // -> execute the request
         ModifyImageAttributeResponse EC2response =
-            
EC2SoapServiceImpl.toModifyImageAttributeResponse(ServiceProvider.getInstance().getEC2Engine().modifyImageAttribute(ec2request));
+                
EC2SoapServiceImpl.toModifyImageAttributeResponse(ServiceProvider.getInstance().getEC2Engine().modifyImageAttribute(ec2request));
         serializeResponse(response, EC2response);
     }
 
@@ -1231,7 +1235,7 @@ public class EC2RestServlet extends HttpServlet {
 
         // -> execute the request
         ResetImageAttributeResponse EC2response =
-            
EC2SoapServiceImpl.toResetImageAttributeResponse(ServiceProvider.getInstance().getEC2Engine().modifyImageAttribute(ec2request));
+                
EC2SoapServiceImpl.toResetImageAttributeResponse(ServiceProvider.getInstance().getEC2Engine().modifyImageAttribute(ec2request));
         serializeResponse(response, EC2response);
     }
 
@@ -1443,7 +1447,7 @@ public class EC2RestServlet extends HttpServlet {
 
         // -> execute the request
         DescribeAvailabilityZonesResponse EC2response =
-            
EC2SoapServiceImpl.toDescribeAvailabilityZonesResponse(ServiceProvider.getInstance().getEC2Engine().describeAvailabilityZones(EC2request));
+                
EC2SoapServiceImpl.toDescribeAvailabilityZonesResponse(ServiceProvider.getInstance().getEC2Engine().describeAvailabilityZones(EC2request));
         serializeResponse(response, EC2response);
     }
 
@@ -1499,7 +1503,7 @@ public class EC2RestServlet extends HttpServlet {
         }
 
         DescribeImageAttributeResponse EC2response =
-            
EC2SoapServiceImpl.toDescribeImageAttributeResponse(ServiceProvider.getInstance().getEC2Engine().describeImageAttribute(ec2request));
+                
EC2SoapServiceImpl.toDescribeImageAttributeResponse(ServiceProvider.getInstance().getEC2Engine().describeImageAttribute(ec2request));
         serializeResponse(response, EC2response);
     }
 
@@ -1677,7 +1681,7 @@ public class EC2RestServlet extends HttpServlet {
 
         // -> execute the request
         DescribeInstanceAttributeResponse EC2response =
-            
EC2SoapServiceImpl.toDescribeInstanceAttributeResponse(ServiceProvider.getInstance().getEC2Engine().describeInstances(EC2request));
+                
EC2SoapServiceImpl.toDescribeInstanceAttributeResponse(ServiceProvider.getInstance().getEC2Engine().describeInstances(EC2request));
         serializeResponse(response, EC2response);
     }
 
@@ -1707,7 +1711,7 @@ public class EC2RestServlet extends HttpServlet {
 
         // -> execute the request
         ModifyInstanceAttributeResponse EC2response =
-            
EC2SoapServiceImpl.toModifyInstanceAttributeResponse(ServiceProvider.getInstance().getEC2Engine().modifyInstanceAttribute(ec2Request));
+                
EC2SoapServiceImpl.toModifyInstanceAttributeResponse(ServiceProvider.getInstance().getEC2Engine().modifyInstanceAttribute(ec2Request));
         serializeResponse(response, EC2response);
     }
 
@@ -1766,7 +1770,7 @@ public class EC2RestServlet extends HttpServlet {
         // -> execute the request
         EC2Engine engine = ServiceProvider.getInstance().getEC2Engine();
         DescribeVolumesResponse EC2response =
-            
EC2SoapServiceImpl.toDescribeVolumesResponse(ServiceProvider.getInstance().getEC2Engine().describeVolumes(EC2request),
 engine);
+                
EC2SoapServiceImpl.toDescribeVolumesResponse(ServiceProvider.getInstance().getEC2Engine().describeVolumes(EC2request),
 engine);
         serializeResponse(response, EC2response);
     }
 
@@ -1988,7 +1992,7 @@ public class EC2RestServlet extends HttpServlet {
      * parameter to see if the signature has expired and if so the request 
fails.
      */
     private boolean authenticateRequest(HttpServletRequest request, 
HttpServletResponse response) throws SignatureException, IOException, 
InstantiationException,
-        IllegalAccessException, ClassNotFoundException, SQLException, 
ParseException {
+    IllegalAccessException, ClassNotFoundException, SQLException, 
ParseException {
         String cloudSecretKey = null;
         String cloudAccessKey = null;
         String signature = null;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/d1968810/awsapi/src/com/cloud/bridge/service/controller/s3/ServiceProvider.java
----------------------------------------------------------------------
diff --git 
a/awsapi/src/com/cloud/bridge/service/controller/s3/ServiceProvider.java 
b/awsapi/src/com/cloud/bridge/service/controller/s3/ServiceProvider.java
index deb886f..e00408e 100644
--- a/awsapi/src/com/cloud/bridge/service/controller/s3/ServiceProvider.java
+++ b/awsapi/src/com/cloud/bridge/service/controller/s3/ServiceProvider.java
@@ -34,15 +34,14 @@ import javax.annotation.PostConstruct;
 import javax.inject.Inject;
 
 import org.apache.axis2.AxisFault;
+import org.apache.cloudstack.managed.context.ManagedContextTimerTask;
+import org.apache.commons.io.IOUtils;
 import org.apache.log4j.Logger;
 import org.apache.log4j.xml.DOMConfigurator;
 import org.springframework.stereotype.Component;
 
 import com.amazon.ec2.AmazonEC2SkeletonInterface;
 import com.amazon.s3.AmazonS3SkeletonInterface;
-
-import org.apache.cloudstack.managed.context.ManagedContextTimerTask;
-
 import com.cloud.bridge.model.MHostVO;
 import com.cloud.bridge.model.SHost;
 import com.cloud.bridge.model.SHostVO;
@@ -111,8 +110,8 @@ public class ServiceProvider extends ManagerBase {
         instance = this;
     }
 
+    @Override
     public boolean configure(String name, Map<String, Object> params) throws 
ConfigurationException {
-
         initialize();
         return true;
     }
@@ -122,7 +121,7 @@ public class ServiceProvider extends ManagerBase {
         long mhostId = 0;
         if (mhost != null)
             mhostId = mhost.getId() != null ? mhost.getId().longValue() : 0L;
-        return mhostId;
+            return mhostId;
     }
 
     /**
@@ -268,12 +267,16 @@ public class ServiceProvider extends ManagerBase {
         File propertiesFile = 
ConfigurationHelper.findConfigurationFile("cloud-bridge.properties");
         properties = new Properties();
         if (propertiesFile != null) {
+            FileInputStream startProps = null;
             try {
-                properties.load(new FileInputStream(propertiesFile));
+                startProps = new FileInputStream(propertiesFile);
+                properties.load(startProps);
             } catch (FileNotFoundException e) {
                 logger.warn("Unable to open properties file: " + 
propertiesFile.getAbsolutePath(), e);
             } catch (IOException e) {
                 logger.warn("Unable to read properties file: " + 
propertiesFile.getAbsolutePath(), e);
+            } finally {
+                IOUtils.closeQuietly(startProps);
             }
 
             logger.info("Use startup properties file: " + 
propertiesFile.getAbsolutePath());

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/d1968810/awsapi/src/com/cloud/bridge/service/core/ec2/EC2Engine.java
----------------------------------------------------------------------
diff --git a/awsapi/src/com/cloud/bridge/service/core/ec2/EC2Engine.java 
b/awsapi/src/com/cloud/bridge/service/core/ec2/EC2Engine.java
index 59abca0..ccac674 100644
--- a/awsapi/src/com/cloud/bridge/service/core/ec2/EC2Engine.java
+++ b/awsapi/src/com/cloud/bridge/service/core/ec2/EC2Engine.java
@@ -35,6 +35,7 @@ import javax.inject.Inject;
 import javax.naming.ConfigurationException;
 import javax.xml.parsers.ParserConfigurationException;
 
+import org.apache.commons.io.IOUtils;
 import org.apache.log4j.Logger;
 import org.springframework.stereotype.Component;
 import org.xml.sax.SAXException;
@@ -122,12 +123,18 @@ public class EC2Engine extends ManagerBase {
         if (null != propertiesFile) {
             logger.info("Use EC2 properties file: " + 
propertiesFile.getAbsolutePath());
             Properties EC2Prop = new Properties();
+            FileInputStream ec2PropFile = null;
             try {
                 EC2Prop.load(new FileInputStream(propertiesFile));
+                ec2PropFile = new FileInputStream( propertiesFile );
+                EC2Prop.load(ec2PropFile);
+
             } catch (FileNotFoundException e) {
                 logger.warn("Unable to open properties file: " + 
propertiesFile.getAbsolutePath(), e);
             } catch (IOException e) {
                 logger.warn("Unable to read properties file: " + 
propertiesFile.getAbsolutePath(), e);
+            } finally {
+                IOUtils.closeQuietly(ec2PropFile);
             }
             managementServer = EC2Prop.getProperty("managementServer");
             cloudAPIPort = EC2Prop.getProperty("cloudAPIPort", null);
@@ -364,12 +371,12 @@ public class EC2Engine extends ManagerBase {
                 CloudStackSecurityGroup resp = null;
                 if (ipPerm.getProtocol().equalsIgnoreCase("icmp")) {
                     resp =
-                        getApi().authorizeSecurityGroupIngress(null, 
constructList(ipPerm.getIpRangeSet()), null, null, ipPerm.getIcmpCode(), 
ipPerm.getIcmpType(),
-                            ipPerm.getProtocol(), null, request.getName(), 
null, secGroupList);
+                            getApi().authorizeSecurityGroupIngress(null, 
constructList(ipPerm.getIpRangeSet()), null, null, ipPerm.getIcmpCode(), 
ipPerm.getIcmpType(),
+                                    ipPerm.getProtocol(), null, 
request.getName(), null, secGroupList);
                 } else {
                     resp =
-                        getApi().authorizeSecurityGroupIngress(null, 
constructList(ipPerm.getIpRangeSet()), null, ipPerm.getToPort().longValue(), 
null, null,
-                            ipPerm.getProtocol(), null, request.getName(), 
ipPerm.getFromPort().longValue(), secGroupList);
+                            getApi().authorizeSecurityGroupIngress(null, 
constructList(ipPerm.getIpRangeSet()), null, ipPerm.getToPort().longValue(), 
null, null,
+                                    ipPerm.getProtocol(), null, 
request.getName(), ipPerm.getFromPort().longValue(), secGroupList);
                 }
                 if (resp != null) {
                     List<CloudStackIngressRule> ingressRules = 
resp.getIngressRules();
@@ -808,7 +815,7 @@ public class EC2Engine extends ManagerBase {
             CloudStackIpAddress cloudIp = cloudIps.get(0);
 
             List<CloudStackUserVm> vmList =
-                getApi().listVirtualMachines(null, null, true, null, null, 
null, null, request.getInstanceId(), null, null, null, null, null, null, null, 
null, null);
+                    getApi().listVirtualMachines(null, null, true, null, null, 
null, null, request.getInstanceId(), null, null, null, null, null, null, null, 
null, null);
             if (vmList == null || vmList.size() == 0) {
                 throw new Exception("Instance not found");
             }
@@ -863,7 +870,7 @@ public class EC2Engine extends ManagerBase {
 
             CloudStackZone zone = findZone();
             //CloudStackNetwork net = findNetwork(zone);
-//            CloudStackIpAddress resp = getApi().associateIpAddress(null, 
null, null, "0036952d-48df-4422-9fd0-94b0885e18cb");
+            //CloudStackIpAddress resp = getApi().associateIpAddress(null, 
null, null, "0036952d-48df-4422-9fd0-94b0885e18cb");
             CloudStackIpAddress resp = 
getApi().associateIpAddress(zone.getId(), caller.getName(), 
caller.getDomainId(), null);
             ec2Address.setAssociatedInstanceId(resp.getId());
 
@@ -965,8 +972,8 @@ public class EC2Engine extends ManagerBase {
             String osTypeId = imageSet[0].getOsTypeId();
 
             CloudStackTemplate resp =
-                getApi().createTemplate((request.getDescription() == null ? "" 
: request.getDescription()), request.getName(), osTypeId, null, null, null, 
null, null,
-                    null, volumeId);
+                    getApi().createTemplate((request.getDescription() == null 
? "" : request.getDescription()), request.getName(), osTypeId, null, null, 
null, null, null,
+                            null, volumeId);
             if (resp == null || resp.getId() == null) {
                 throw new Exception("Image couldn't be created");
             }
@@ -996,9 +1003,9 @@ public class EC2Engine extends ManagerBase {
         EC2CreateImageResponse image = new EC2CreateImageResponse();
         try {
             List<CloudStackTemplate> templates =
-                getApi().registerTemplate((request.getDescription() == null ? 
request.getName() : request.getDescription()), request.getFormat(),
-                    request.getHypervisor(), request.getName(), 
toOSTypeId(request.getOsTypeName()), request.getLocation(), 
toZoneId(request.getZoneName(), null), null,
-                    null, null, null, null, null, null, null, null);
+                    getApi().registerTemplate((request.getDescription() == 
null ? request.getName() : request.getDescription()), request.getFormat(),
+                            request.getHypervisor(), request.getName(), 
toOSTypeId(request.getOsTypeName()), request.getLocation(), 
toZoneId(request.getZoneName(), null), null,
+                            null, null, null, null, null, null, null, null);
             if (templates != null) {
                 // technically we will only ever register a single template...
                 for (CloudStackTemplate template : templates) {
@@ -1217,13 +1224,13 @@ public class EC2Engine extends ManagerBase {
                     throw new EC2ServiceException(ServerError.InternalError, 
"No Customize Disk Offering Found");
             }
 
-//            // -> no volume name is given in the Amazon request but is 
required in the cloud API
+            // -> no volume name is given in the Amazon request but is 
required in the cloud API
             CloudStackVolume vol =
-                getApi().createVolume(UUID.randomUUID().toString(), null, 
diskOfferingId, null, size, snapshotId, toZoneId(request.getZoneName(), null));
+                    getApi().createVolume(UUID.randomUUID().toString(), null, 
diskOfferingId, null, size, snapshotId, toZoneId(request.getZoneName(), null));
             if (vol != null) {
                 resp.setAttached(vol.getAttached());
                 resp.setCreated(vol.getCreated());
-//                resp.setDevice();
+                //resp.setDevice();
                 resp.setDeviceId(vol.getDeviceId());
                 resp.setHypervisor(vol.getHypervisor());
                 resp.setId(vol.getId());
@@ -1442,8 +1449,8 @@ public class EC2Engine extends ManagerBase {
             for (int i = 0; i < createInstances; i++) {
                 try {
                     CloudStackUserVm resp =
-                        getApi().deployVirtualMachine(svcOffering.getId(), 
request.getTemplateId(), zoneId, null, null, null, null, null, null, null,
-                            request.getKeyName(), null, null, groupIds, 
groupNames, request.getSize().longValue(), request.getUserData());
+                            getApi().deployVirtualMachine(svcOffering.getId(), 
request.getTemplateId(), zoneId, null, null, null, null, null, null, null,
+                                    request.getKeyName(), null, null, 
groupIds, groupNames, request.getSize().longValue(), request.getUserData());
                     EC2Instance vm = new EC2Instance();
                     vm.setId(resp.getId().toString());
                     vm.setName(resp.getName());
@@ -1666,7 +1673,7 @@ public class EC2Engine extends ManagerBase {
      * @param ifs - filter out unwanted instances
      */
     private EC2DescribeInstancesResponse listVirtualMachines(String[] 
virtualMachineIds, EC2InstanceFilterSet ifs, List<CloudStackKeyValue> 
resourceTags)
-        throws Exception {
+            throws Exception {
         EC2DescribeInstancesResponse instances = new 
EC2DescribeInstancesResponse();
 
         if (null == virtualMachineIds || 0 == virtualMachineIds.length) {
@@ -1690,7 +1697,7 @@ public class EC2Engine extends ManagerBase {
      * @param instanceId - if interested in volumes for a specific instance, 
null if instance is not important
      */
     private EC2DescribeVolumesResponse listVolumes(String volumeId, String 
instanceId, EC2DescribeVolumesResponse volumes, List<CloudStackKeyValue> 
resourceTagSet)
-        throws Exception {
+            throws Exception {
 
         List<CloudStackVolume> vols = getApi().listVolumes(null, null, null, 
volumeId, null, null, null, null, null, instanceId, null, resourceTagSet);
         if (vols != null && vols.size() > 0) {
@@ -1881,11 +1888,11 @@ public class EC2Engine extends ManagerBase {
      *         EC2Instance objects loaded.
      */
     private EC2DescribeInstancesResponse lookupInstances(String instanceId, 
EC2DescribeInstancesResponse instances, List<CloudStackKeyValue> resourceTagSet)
-        throws Exception {
+            throws Exception {
 
         String instId = instanceId != null ? instanceId : null;
         List<CloudStackUserVm> vms =
-            getApi().listVirtualMachines(null, null, true, null, null, null, 
null, instId, null, null, null, null, null, null, null, null, resourceTagSet);
+                getApi().listVirtualMachines(null, null, true, null, null, 
null, null, instId, null, null, null, null, null, null, null, null, 
resourceTagSet);
 
         if (vms != null && vms.size() > 0) {
             for (CloudStackUserVm cloudVm : vms) {
@@ -2301,7 +2308,7 @@ public class EC2Engine extends ManagerBase {
      */
     private CloudStackNetwork createDefaultGuestNetwork(String zoneId, 
CloudStackNetworkOffering offering, CloudStackAccount owner) throws Exception {
         return getApi().createNetwork(owner.getName() + "-network", 
owner.getName() + "-network", offering.getId(), zoneId, owner.getName(), 
owner.getDomainId(), true,
-            null, null, null, null, null, null, null, null);
+                null, null, null, null, null, null, null, null);
     }
 
     /**
@@ -2688,8 +2695,8 @@ public class EC2Engine extends ManagerBase {
                 if (errorMessage.contains("Object vm_instance(uuid:") && 
errorMessage.contains(") does not exist")) {
                     throw new 
EC2ServiceException(ClientError.InvalidInstanceID_NotFound, "Specified Instance 
ID does not exist");
                 } else if (errorMessage.contains("Unable to find security 
group by name") || errorMessage.contains("Unable to find security group") ||
-                    (errorMessage.contains("Object security_group(uuid:") && 
errorMessage.contains(") does not exist")) ||
-                    errorMessage.contains("Unable to find group by name ")) {
+                        (errorMessage.contains("Object security_group(uuid:") 
&& errorMessage.contains(") does not exist")) ||
+                        errorMessage.contains("Unable to find group by name 
")) {
                     throw new 
EC2ServiceException(ClientError.InvalidGroup_NotFound, "Specified Security 
Group does not exist");
                 } else if (errorMessage.contains("Invalid port numbers")) {
                     throw new 
EC2ServiceException(ClientError.InvalidPermission_Malformed, "Specified Port 
value is invalid");
@@ -2708,7 +2715,7 @@ public class EC2Engine extends ManagerBase {
                 } else if (errorMessage.contains("Object snapshots(uuid:") && 
errorMessage.contains(") does not exist")) {
                     throw new 
EC2ServiceException(ClientError.InvalidSnapshot_NotFound, "Specified Snapshot 
ID doesn't exist");
                 } else if ((errorMessage.contains("A key pair with name '") && 
errorMessage.contains("' does not exist")) ||
-                    (errorMessage.contains("A key pair with name '") && 
errorMessage.contains("' was not found"))) {
+                        (errorMessage.contains("A key pair with name '") && 
errorMessage.contains("' was not found"))) {
                     throw new 
EC2ServiceException(ClientError.InvalidKeyPair_NotFound, "Specified Key pair 
name is invalid");
                 } else if (errorMessage.contains("A key pair with name '") && 
errorMessage.contains("' already exists")) {
                     throw new 
EC2ServiceException(ClientError.InvalidKeyPair_Duplicate, "Specified Key pair 
already exists");
@@ -2735,7 +2742,7 @@ public class EC2Engine extends ManagerBase {
                 } else if (errorMessage.contains("Unable to find tags by 
parameters specified")) {
                     throw new 
EC2ServiceException(ClientError.InvalidParameterValue, "Specified resourceTag 
for the specified resourceId doesn't exist");
                 } else if (errorMessage.contains("Failed to enable static nat 
for the ip address with specified ipId "
-                    + "as vm with specified vmId is already associated with 
specified currentIp")) {
+                        + "as vm with specified vmId is already associated 
with specified currentIp")) {
                     throw new 
EC2ServiceException(ClientError.InvalidParameterValue, "Specified publicIp is 
already associated to the specified VM");
                 } else if (errorMessage.contains("Specified IP address id is 
not associated with any vm Id")) {
                     throw new 
EC2ServiceException(ClientError.InvalidParameterValue, "Specified publicIp is 
not associated to any VM");
@@ -2783,7 +2790,7 @@ public class EC2Engine extends ManagerBase {
                     throw new 
EC2ServiceException(ClientError.InvalidAMIID_NotFound, "Specified ImageId is 
unavailable");
                 } else if (errorMessage.contains("cannot stop VM") && 
errorMessage.contains("when it is in state Starting")) {
                     throw new 
EC2ServiceException(ClientError.IncorrectInstanceState,
-                        "Unable to stop. One or more of the specified 
instances is in an incorrect state 'pending'");
+                            "Unable to stop. One or more of the specified 
instances is in an incorrect state 'pending'");
                 } else if (errorMessage.contains("Failed to authorize security 
group ingress rule(s)")) {
                     throw new 
EC2ServiceException(ClientError.InvalidParameterValue, "Specified Ip-permission 
is invalid" + " or the Ip-permission already exists");
                 } else if (errorMessage.contains("Failed to reboot vm 
instance")) {
@@ -2798,7 +2805,7 @@ public class EC2Engine extends ManagerBase {
                     throw new 
EC2ServiceException(ClientError.VolumeLimitExceeded, "You have reached the 
limit on the number of volumes that can be created");
                 } else if (errorMessage.contains("Maximum number of resources 
of type 'public_ip' for account") && errorMessage.contains("has been 
exceeded")) {
                     throw new 
EC2ServiceException(ClientError.AddressLimitExceeded,
-                        "You have reached the limit on the number of elastic 
ip addresses your account can have");
+                            "You have reached the limit on the number of 
elastic ip addresses your account can have");
                 } else if (errorMessage.contains("Unable to apply save 
userdata entry on router")) {
                     throw new 
EC2ServiceException(ClientError.InvalidParameterValue, "The value supplied for 
parameter UserData is invalid");
                 } else {
@@ -2846,7 +2853,7 @@ public class EC2Engine extends ManagerBase {
                 throw new EC2ServiceException(ServerError.InternalError, 
"Unable to start the instance that was stopped during image creation");
             } else if (errorMessage.contains("One or more of instanceIds 
specified is in stopped state")) {
                 throw new 
EC2ServiceException(ClientError.IncorrectInstanceState,
-                    "Unable to reboot. One or more of the specified instances 
is in an incorrect state 'stopped'");
+                        "Unable to reboot. One or more of the specified 
instances is in an incorrect state 'stopped'");
             } else if (errorMessage.contains("Specified ipAddress doesn't 
exist")) {
                 throw new 
EC2ServiceException(ClientError.InvalidParameterValue, "Specified publicIp 
doesn't exist");
             } else if (errorMessage.contains("Min Count is greater than the 
number of instances left to allocate")) {
@@ -2865,7 +2872,7 @@ public class EC2Engine extends ManagerBase {
                 throw new 
EC2ServiceException(ClientError.InvalidInstanceID_NotFound, "One or more of the 
specified instanceId not found");
             } else if (errorMessage.contains("Cannot modify, instance should 
be in stopped state")) {
                 throw new 
EC2ServiceException(ClientError.IncorrectInstanceState,
-                    "Unable to modify instance attribute. Specified instance 
is not in the correct state 'stopped'");
+                        "Unable to modify instance attribute. Specified 
instance is not in the correct state 'stopped'");
             } else {
                 throw new EC2ServiceException(ServerError.InternalError, "An 
unexpected error occured");
             }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/d1968810/framework/cluster/src/com/cloud/cluster/ClusterManagerImpl.java
----------------------------------------------------------------------
diff --git a/framework/cluster/src/com/cloud/cluster/ClusterManagerImpl.java 
b/framework/cluster/src/com/cloud/cluster/ClusterManagerImpl.java
index 3e7138f..1058da3 100644
--- a/framework/cluster/src/com/cloud/cluster/ClusterManagerImpl.java
+++ b/framework/cluster/src/com/cloud/cluster/ClusterManagerImpl.java
@@ -40,13 +40,12 @@ import javax.ejb.Local;
 import javax.inject.Inject;
 import javax.naming.ConfigurationException;
 
-import org.apache.log4j.Logger;
-
 import org.apache.cloudstack.framework.config.ConfigDepot;
 import org.apache.cloudstack.framework.config.ConfigKey;
 import org.apache.cloudstack.framework.config.Configurable;
 import org.apache.cloudstack.managed.context.ManagedContextRunnable;
 import org.apache.cloudstack.utils.identity.ManagementServerNode;
+import org.apache.log4j.Logger;
 
 import com.cloud.cluster.dao.ManagementServerHostDao;
 import com.cloud.cluster.dao.ManagementServerHostPeerDao;
@@ -256,15 +255,15 @@ public class ClusterManagerImpl extends ManagerBase 
implements ClusterManager, C
                         try {
                             if (s_logger.isDebugEnabled()) {
                                 s_logger.debug("Cluster PDU " + 
getSelfPeerName() + " -> " + pdu.getDestPeer() + ". agent: " + pdu.getAgentId() 
+ ", pdu seq: " +
-                                    pdu.getSequenceId() + ", pdu ack seq: " + 
pdu.getAckSequenceId() + ", json: " + pdu.getJsonPackage());
+                                        pdu.getSequenceId() + ", pdu ack seq: 
" + pdu.getAckSequenceId() + ", json: " + pdu.getJsonPackage());
                             }
 
                             long startTick = System.currentTimeMillis();
                             String strResult = peerService.execute(pdu);
                             if (s_logger.isDebugEnabled()) {
                                 s_logger.debug("Cluster PDU " + 
getSelfPeerName() + " -> " + pdu.getDestPeer() + " completed. time: " +
-                                    (System.currentTimeMillis() - startTick) + 
"ms. agent: " + pdu.getAgentId() + ", pdu seq: " + pdu.getSequenceId() +
-                                    ", pdu ack seq: " + pdu.getAckSequenceId() 
+ ", json: " + pdu.getJsonPackage());
+                                        (System.currentTimeMillis() - 
startTick) + "ms. agent: " + pdu.getAgentId() + ", pdu seq: " + 
pdu.getSequenceId() +
+                                        ", pdu ack seq: " + 
pdu.getAckSequenceId() + ", json: " + pdu.getJsonPackage());
                             }
 
                             if ("true".equals(strResult))
@@ -274,7 +273,7 @@ public class ClusterManagerImpl extends ManagerBase 
implements ClusterManager, C
                             invalidatePeerService(pdu.getDestPeer());
                             if (s_logger.isInfoEnabled()) {
                                 s_logger.info("Exception on remote execution, 
peer: " + pdu.getDestPeer() + ", iteration: " + i + ", exception message :" +
-                                    e.getMessage());
+                                        e.getMessage());
                             }
                         }
                     }
@@ -564,7 +563,7 @@ public class ClusterManagerImpl extends ManagerBase 
implements ClusterManager, C
                         if (profiler.getDuration() >= 
HeartbeatInterval.value()) {
                             if (s_logger.isDebugEnabled())
                                 s_logger.debug("Management server heartbeat 
takes too long to finish. profiler: " + profiler.toString() + ", 
profilerHeartbeatUpdate: " +
-                                    profilerHeartbeatUpdate.toString() + ", 
profilerPeerScan: " + profilerPeerScan.toString());
+                                        profilerHeartbeatUpdate.toString() + 
", profilerPeerScan: " + profilerPeerScan.toString());
                         }
                     }
 
@@ -625,8 +624,10 @@ public class ClusterManagerImpl extends ManagerBase 
implements ClusterManager, C
         if (_heartbeatConnection != null) {
             Connection conn = TransactionLegacy.getStandaloneConnection();
             if (conn != null) {
-                
_heartbeatConnection.reset(TransactionLegacy.getStandaloneConnection());
+                _heartbeatConnection.reset(conn);
             }
+            // The stand-alone connection does not have to be closed here 
because there will be another reference to it.
+            // As a matter of fact, it will be assigned to the connection 
instance variable in the ConnectionConcierge class.
         }
     }
 
@@ -720,7 +721,7 @@ public class ClusterManagerImpl extends ManagerBase 
implements ClusterManager, C
                     }
                 }
             }
-                break;
+            break;
 
             case nodeRemoved: {
                 List<ManagementServerHostVO> l = msg.getNodes();
@@ -730,11 +731,10 @@ public class ClusterManagerImpl extends ManagerBase 
implements ClusterManager, C
                     }
                 }
             }
-                break;
+            break;
 
             default:
                 break;
-
         }
     }
 
@@ -772,7 +772,7 @@ public class ClusterManagerImpl extends ManagerBase 
implements ClusterManager, C
                 s_logger.info("Found " + inactiveList.size() + " inactive 
management server node based on timestamp");
                 for (ManagementServerHostVO host : inactiveList)
                     s_logger.info("management server node msid: " + 
host.getMsid() + ", name: " + host.getName() + ", service ip: " + 
host.getServiceIP() +
-                        ", version: " + host.getVersion());
+                            ", version: " + host.getVersion());
             }
 
             List<ManagementServerHostVO> downHostList = new 
ArrayList<ManagementServerHostVO>();
@@ -810,7 +810,7 @@ public class ClusterManagerImpl extends ManagerBase 
implements ClusterManager, C
 
             if (_mshostPeerDao.countStateSeenInPeers(_mshostId, _runId, 
ManagementServerHost.State.Down) > 0) {
                 String msg =
-                    "We have detected that at least one management server peer 
reports that this management server is down, perform active fencing to avoid 
split-brain situation";
+                        "We have detected that at least one management server 
peer reports that this management server is down, perform active fencing to 
avoid split-brain situation";
                 s_logger.error(msg);
                 throw new ActiveFencingException(msg);
             }
@@ -831,7 +831,7 @@ public class ClusterManagerImpl extends ManagerBase 
implements ClusterManager, C
                         if (entry.getKey().longValue() != 
_mshostId.longValue()) {
                             if (s_logger.isDebugEnabled()) {
                                 s_logger.debug("Detected management node left 
because of invalidated session, id:" + entry.getKey() + ", nodeIP:" +
-                                    entry.getValue().getServiceIP());
+                                        entry.getValue().getServiceIP());
                             }
                             invalidatedNodeList.add(entry.getValue());
                         }
@@ -918,8 +918,8 @@ public class ClusterManagerImpl extends ManagerBase 
implements ClusterManager, C
         if (profiler.getDuration() >= HeartbeatInterval.value()) {
             if (s_logger.isDebugEnabled())
                 s_logger.debug("Peer scan takes too long to finish. profiler: 
" + profiler.toString() + ", profilerQueryActiveList: " +
-                    profilerQueryActiveList.toString() + ", 
profilerSyncClusterInfo: " + profilerSyncClusterInfo.toString() + ", 
profilerInvalidatedNodeList: " +
-                    profilerInvalidatedNodeList.toString() + ", 
profilerRemovedList: " + profilerRemovedList.toString());
+                        profilerQueryActiveList.toString() + ", 
profilerSyncClusterInfo: " + profilerSyncClusterInfo.toString() + ", 
profilerInvalidatedNodeList: " +
+                        profilerInvalidatedNodeList.toString() + ", 
profilerRemovedList: " + profilerRemovedList.toString());
         }
     }
 
@@ -970,7 +970,7 @@ public class ClusterManagerImpl extends ManagerBase 
implements ClusterManager, C
                     }
 
                     _mshostDao.update(mshost.getId(), getCurrentRunId(), 
NetUtils.getHostName(), version, _clusterNodeIP, 
_currentServiceAdapter.getServicePort(),
-                        DateUtil.currentGMTTime());
+                            DateUtil.currentGMTTime());
                 }
 
                 return mshost;
@@ -1165,19 +1165,19 @@ public class ClusterManagerImpl extends ManagerBase 
implements ClusterManager, C
                         throw new ConfigurationException(msg);
                     } else {
                         String msg =
-                            "Detected another management node with localhost 
IP is considered as running in DB, however it is not pingable, we will continue 
cluster initialization with this management server node";
+                                "Detected another management node with 
localhost IP is considered as running in DB, however it is not pingable, we 
will continue cluster initialization with this management server node";
                         s_logger.info(msg);
                     }
                 } else {
                     if (pingManagementNode(peer.getMsid())) {
                         String msg =
-                            "Detected that another management node with the 
same IP " + peer.getServiceIP() +
+                                "Detected that another management node with 
the same IP " + peer.getServiceIP() +
                                 " is already running, please check your 
cluster configuration";
                         s_logger.error(msg);
                         throw new ConfigurationException(msg);
                     } else {
                         String msg =
-                            "Detected that another management node with the 
same IP " + peer.getServiceIP() +
+                                "Detected that another management node with 
the same IP " + peer.getServiceIP() +
                                 " is considered as running in DB, however it 
is not pingable, we will continue cluster initialization with this management 
server node";
                         s_logger.info(msg);
                     }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/d1968810/services/console-proxy/server/src/com/cloud/consoleproxy/ConsoleProxy.java
----------------------------------------------------------------------
diff --git 
a/services/console-proxy/server/src/com/cloud/consoleproxy/ConsoleProxy.java 
b/services/console-proxy/server/src/com/cloud/consoleproxy/ConsoleProxy.java
index 0d28e09..e52a751 100644
--- a/services/console-proxy/server/src/com/cloud/consoleproxy/ConsoleProxy.java
+++ b/services/console-proxy/server/src/com/cloud/consoleproxy/ConsoleProxy.java
@@ -19,6 +19,7 @@ package com.cloud.consoleproxy;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileNotFoundException;
+import java.io.IOException;
 import java.io.InputStream;
 import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.Method;
@@ -35,11 +36,10 @@ import java.util.concurrent.Executor;
 import org.apache.commons.codec.binary.Base64;
 import org.apache.log4j.xml.DOMConfigurator;
 
-import com.google.gson.Gson;
-import com.sun.net.httpserver.HttpServer;
-
 import com.cloud.consoleproxy.util.Logger;
 import com.cloud.utils.PropertiesUtil;
+import com.google.gson.Gson;
+import com.sun.net.httpserver.HttpServer;
 
 /**
  *
@@ -195,8 +195,8 @@ public class ConsoleProxy {
             Object result;
             try {
                 result =
-                    authMethod.invoke(ConsoleProxy.context, 
param.getClientHostAddress(), String.valueOf(param.getClientHostPort()), 
param.getClientTag(),
-                        param.getClientHostPassword(), param.getTicket(), new 
Boolean(reauthentication));
+                        authMethod.invoke(ConsoleProxy.context, 
param.getClientHostAddress(), String.valueOf(param.getClientHostPort()), 
param.getClientTag(),
+                                param.getClientHostPassword(), 
param.getTicket(), new Boolean(reauthentication));
             } catch (IllegalAccessException e) {
                 s_logger.error("Unable to invoke authenticateConsoleAccess due 
to IllegalAccessException" + " for vm: " + param.getClientTag(), e);
                 authResult.setSuccess(false);
@@ -387,6 +387,12 @@ public class ConsoleProxy {
                 conf.load(confs);
             } catch (Exception e) {
                 s_logger.error(e.toString(), e);
+            } finally {
+                try {
+                    confs.close();
+                }  catch (IOException ioex) {
+                    s_logger.error(ioex.toString(), ioex);
+                }
             }
         }
         start(conf);
@@ -411,7 +417,7 @@ public class ConsoleProxy {
                 viewer.initClient(param);
             } else if 
(!param.getClientHostPassword().equals(viewer.getClientHostPassword())) {
                 s_logger.warn("Bad sid detected(VNC port may be reused). sid 
in session: " + viewer.getClientHostPassword() + ", sid in request: " +
-                    param.getClientHostPassword());
+                        param.getClientHostPassword());
                 viewer.initClient(param);
             }
         }
@@ -450,10 +456,11 @@ public class ConsoleProxy {
                 }
 
                 if (param.getClientHostPassword() == null || 
param.getClientHostPassword().isEmpty() ||
-                    
!param.getClientHostPassword().equals(viewer.getClientHostPassword()))
+                        
!param.getClientHostPassword().equals(viewer.getClientHostPassword()))
                     throw new AuthenticationException("Cannot use the existing 
viewer " + viewer + ": bad sid");
 
                 if (!viewer.isFrontEndAlive()) {
+
                     authenticationExternally(param);
                     viewer.initClient(param);
                     reportLoadChange = true;

Reply via email to