3636import java .net .UnknownHostException ;
3737import java .io .OutputStreamWriter ;
3838import java .io .IOException ;
39+ import java .io .InputStream ;
40+ import java .nio .charset .StandardCharsets ;
3941
4042import javax .inject .Inject ;
4143import javax .net .ssl .HttpsURLConnection ;
5759import com .cloud .dc .dao .ClusterDao ;
5860import com .cloud .dc .DataCenterVO ;
5961import com .cloud .dc .dao .DataCenterDao ;
60- import com .cloud .vm .UserVmVO ;
61- import com .cloud .vm .dao .UserVmDao ;
6262import com .cloud .vm .VMInstanceVO ;
6363import com .cloud .vm .dao .VMInstanceDao ;
6464import com .cloud .utils .db .SearchCriteria ;
@@ -100,8 +100,6 @@ public class UsageReporter extends ManagerBase implements ComponentMethodInterce
100100 @ Inject
101101 private DataCenterDao _dataCenterDao ;
102102 @ Inject
103- private UserVmDao _userVmDao ;
104- @ Inject
105103 private VMInstanceDao _vmInstance ;
106104 @ Inject
107105 private VersionDao _versionDao ;
@@ -130,6 +128,9 @@ public boolean start() {
130128 }
131129
132130 private void init (Map <String , String > configs ) {
131+ if (_executor != null ) {
132+ _executor .shutdown ();
133+ }
133134 _executor = Executors .newScheduledThreadPool (1 , new NamedThreadFactory ("UsageReporter" ));
134135
135136 usageReportInterval = NumbersUtil .parseInt (configs .get ("usage.report.interval" ), 7 );
@@ -153,29 +154,37 @@ private void sendReport(String reportUri, String uniqueID, Map<String, Object> r
153154
154155 int http_timeout = 15000 ;
155156
157+ HttpsURLConnection conn = null ;
156158 try {
157159 s_logger .info ("Usage Report will be send to: " + reportUri );
158160 s_logger .debug ("REPORT: " + report );
159161
160162 URL url = new URL (reportUri + "/" + uniqueID );
161163
162- HttpsURLConnection conn = (HttpsURLConnection ) url .openConnection ();
164+ conn = (HttpsURLConnection ) url .openConnection ();
163165 conn .setConnectTimeout (http_timeout );
164166 conn .setReadTimeout (http_timeout );
165167 conn .setRequestMethod ("POST" );
166168 conn .setDoOutput (true );
167169 conn .setRequestProperty ("Content-Type" , "application/json" );
168170 conn .setRequestProperty ("Accept" , "application/json" );
169171
170- OutputStreamWriter osw = new OutputStreamWriter (conn .getOutputStream ());
171- osw .write (report );
172- osw .flush ();
173- osw .close ();
172+ try (OutputStreamWriter osw = new OutputStreamWriter (conn .getOutputStream (), StandardCharsets .UTF_8 )) {
173+ osw .write (report );
174+ }
174175
175176 int resp_code = conn .getResponseCode ();
176177
177- if (resp_code == HttpsURLConnection .HTTP_OK ){
178- s_logger .info ("Usage Report succesfully send to: " + reportUri );
178+ // Consume and close the response stream to allow connection reuse
179+ InputStream responseStream = (resp_code >= 200 && resp_code < 300 )
180+ ? conn .getInputStream () : conn .getErrorStream ();
181+ if (responseStream != null ) {
182+ responseStream .skip (Long .MAX_VALUE );
183+ responseStream .close ();
184+ }
185+
186+ if (resp_code == HttpsURLConnection .HTTP_OK ) {
187+ s_logger .info ("Usage Report successfully sent to: " + reportUri );
179188 } else {
180189 s_logger .warn ("Failed to send Usage Report: " + conn .getResponseMessage ());
181190 }
@@ -185,11 +194,15 @@ private void sendReport(String reportUri, String uniqueID, Map<String, Object> r
185194 } catch (SocketTimeoutException e ) {
186195 s_logger .warn ("Sending Usage Report to " + reportUri + " timed out: " + e .getMessage ());
187196 } catch (MalformedURLException e ) {
188- s_logger .warn (reportUri + " is a invalid URL for sending Usage Report to: " + e .getMessage ());
197+ s_logger .warn (reportUri + " is a invalid URL for sending Usage Report to: " + e .getMessage ());
189198 } catch (ProtocolException e ) {
190199 s_logger .warn ("Sending Usage Report failed due to a invalid protocol: " + e .getMessage ());
191200 } catch (IOException e ) {
192201 s_logger .warn ("Failed to write Usage Report due to a IOException: " + e .getMessage ());
202+ } finally {
203+ if (conn != null ) {
204+ conn .disconnect ();
205+ }
193206 }
194207 }
195208
@@ -201,21 +214,23 @@ private String getUniqueId() {
201214 try {
202215 conn = TransactionLegacy .getStandaloneConnection ();
203216
204- PreparedStatement pstmt = conn .prepareStatement ("SELECT version,updated FROM version ORDER BY id ASC LIMIT 1" );
205- ResultSet rs = pstmt .executeQuery ();
206- if (rs .next ()) {
207- unique = DigestUtils .sha256Hex (rs .getString (1 ) + rs .getString (2 ));
208- } else {
209- s_logger .debug ("No rows found in the version table. Unable to obtain unique ID for this environment" );
217+ try (PreparedStatement pstmt = conn .prepareStatement ("SELECT version,updated FROM version ORDER BY id ASC LIMIT 1" );
218+ ResultSet rs = pstmt .executeQuery ()) {
219+ if (rs .next ()) {
220+ unique = DigestUtils .sha256Hex (rs .getString (1 ) + rs .getString (2 ));
221+ } else {
222+ s_logger .debug ("No rows found in the version table. Unable to obtain unique ID for this environment" );
223+ }
210224 }
211-
212- rs .close ();
213225 } catch (SQLException e ) {
214226 s_logger .debug ("Unable to get the unique ID of this environment: " + e .getMessage ());
215227 } finally {
216- try {
217- conn .close ();
218- } catch (SQLException e ) {
228+ if (conn != null ) {
229+ try {
230+ conn .close ();
231+ } catch (SQLException e ) {
232+ s_logger .debug ("Failed to close database connection: " + e .getMessage ());
233+ }
219234 }
220235 }
221236
@@ -366,28 +381,23 @@ private Map<String, AtomicLongMap> getInstanceReport() {
366381 AtomicLongMap <Object > ha_enabled = AtomicLongMap .create ();
367382 AtomicLongMap <Object > dynamically_scalable = AtomicLongMap .create ();
368383
369- SearchCriteria <HostVO > host_sc = _hostDao .createSearchCriteria ();
370- List <HostVO > hosts = _hostDao .search (host_sc , null );
371- for (HostVO host : hosts ) {
372- List <UserVmVO > vms = _userVmDao .listByLastHostId (host .getId ());
373- for (UserVmVO vm : vms ) {
374- VMInstanceVO vmVO = _vmInstance .findById (vm .getId ());
375-
376- if (vmVO .getHypervisorType () != null ) {
377- hypervisor_type .getAndIncrement (vmVO .getHypervisorType ());
378- }
379-
380- if (vmVO .getState () != null ) {
381- instance_state .getAndIncrement (vmVO .getState ());
382- }
384+ SearchCriteria <VMInstanceVO > vm_sc = _vmInstance .createSearchCriteria ();
385+ List <VMInstanceVO > vms = _vmInstance .search (vm_sc , null );
386+ for (VMInstanceVO vmVO : vms ) {
387+ if (vmVO .getHypervisorType () != null ) {
388+ hypervisor_type .getAndIncrement (vmVO .getHypervisorType ());
389+ }
383390
384- if (vmVO .getType () != null ) {
385- instance_type .getAndIncrement (vmVO .getType ());
386- }
391+ if (vmVO .getState () != null ) {
392+ instance_state .getAndIncrement (vmVO .getState ());
393+ }
387394
388- ha_enabled . getAndIncrement (vmVO .isHaEnabled ());
389- dynamically_scalable .getAndIncrement (vmVO .isDynamicallyScalable ());
395+ if (vmVO .getType () != null ) {
396+ instance_type .getAndIncrement (vmVO .getType ());
390397 }
398+
399+ ha_enabled .getAndIncrement (vmVO .isHaEnabled ());
400+ dynamically_scalable .getAndIncrement (vmVO .isDynamicallyScalable ());
391401 }
392402
393403 instanceMap .put ("hypervisor_type" , hypervisor_type );
@@ -424,7 +434,7 @@ private Map<String, Object> getDiskOfferingReport() {
424434 diskOfferingReport .put ("system_use" , system_use );
425435 diskOfferingReport .put ("provisioning_type" , provisioning_type );
426436 diskOfferingReport .put ("use_local_storage" , use_local_storage );
427- diskOfferingReport .put ("avg_disk_size" , disk_size / offerings .size ());
437+ diskOfferingReport .put ("avg_disk_size" , offerings . isEmpty () ? 0 : disk_size / offerings .size ());
428438
429439 return diskOfferingReport ;
430440 }
@@ -450,7 +460,7 @@ class UsageCollector extends ManagedContextRunnable {
450460 @ Override
451461 protected void runInContext () {
452462 try {
453- s_logger .warn ("UsageReporter is running..." );
463+ s_logger .info ("UsageReporter is running..." );
454464
455465 Map <String , Object > reportMap = new HashMap <String , Object >();
456466
0 commit comments