Skip to content

Commit 7d52cd0

Browse files
authored
Fix calculation of the next time that Usage will execute in removeRawUsageRecords (#12518)
* Fix calculation of the next time that Usage will execute in `removeRawUsageRecords` * Address copilot reviews
1 parent aef3df7 commit 7d52cd0

File tree

4 files changed

+230
-51
lines changed

4 files changed

+230
-51
lines changed

server/src/main/java/com/cloud/usage/UsageServiceImpl.java

Lines changed: 32 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@
1717
package com.cloud.usage;
1818

1919
import java.util.ArrayList;
20-
import java.util.Calendar;
2120
import java.util.Date;
2221
import java.util.List;
2322
import java.util.Map;
@@ -35,6 +34,7 @@
3534
import org.apache.cloudstack.usage.Usage;
3635
import org.apache.cloudstack.usage.UsageService;
3736
import org.apache.cloudstack.usage.UsageTypes;
37+
import org.apache.cloudstack.utils.usage.UsageUtils;
3838
import org.apache.commons.lang3.ObjectUtils;
3939
import org.apache.commons.lang3.StringUtils;
4040
import org.jetbrains.annotations.NotNull;
@@ -127,14 +127,25 @@ public class UsageServiceImpl extends ManagerBase implements UsageService, Manag
127127
@Inject
128128
private NetworkOfferingDao _networkOfferingDao;
129129

130+
private TimeZone usageExecutionTimeZone = TimeZone.getTimeZone("GMT");
131+
132+
private static final long REMOVE_RAW_USAGE_RECORDS_WINDOW_IN_MS = 15 * 60 * 1000;
133+
130134
public UsageServiceImpl() {
131135
}
132136

133137
@Override
134138
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
135139
super.configure(name, params);
140+
136141
String timeZoneStr = ObjectUtils.defaultIfNull(_configDao.getValue(Config.UsageAggregationTimezone.toString()), "GMT");
137142
_usageTimezone = TimeZone.getTimeZone(timeZoneStr);
143+
144+
String executionTimeZone = _configDao.getValue(Config.UsageExecutionTimezone.toString());
145+
if (executionTimeZone != null) {
146+
usageExecutionTimeZone = TimeZone.getTimeZone(executionTimeZone);
147+
}
148+
138149
return true;
139150
}
140151

@@ -465,35 +476,28 @@ public TimeZone getUsageTimezone() {
465476
@Override
466477
public boolean removeRawUsageRecords(RemoveRawUsageRecordsCmd cmd) throws InvalidParameterValueException {
467478
Integer interval = cmd.getInterval();
468-
if (interval != null && interval > 0 ) {
469-
String jobExecTime = _configDao.getValue(Config.UsageStatsJobExecTime.toString());
470-
if (jobExecTime != null ) {
471-
String[] segments = jobExecTime.split(":");
472-
if (segments.length == 2) {
473-
String timeZoneStr = _configDao.getValue(Config.UsageExecutionTimezone.toString());
474-
if (timeZoneStr == null) {
475-
timeZoneStr = "GMT";
476-
}
477-
TimeZone tz = TimeZone.getTimeZone(timeZoneStr);
478-
Calendar cal = Calendar.getInstance(tz);
479-
cal.setTime(new Date());
480-
long curTS = cal.getTimeInMillis();
481-
cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(segments[0]));
482-
cal.set(Calendar.MINUTE, Integer.parseInt(segments[1]));
483-
cal.set(Calendar.SECOND, 0);
484-
cal.set(Calendar.MILLISECOND, 0);
485-
long execTS = cal.getTimeInMillis();
486-
logger.debug("Trying to remove old raw cloud_usage records older than " + interval + " day(s), current time=" + curTS + " next job execution time=" + execTS);
487-
// Let's avoid cleanup when job runs and around a 15 min interval
488-
if (Math.abs(curTS - execTS) < 15 * 60 * 1000) {
489-
return false;
490-
}
491-
}
479+
if (interval == null || interval <= 0) {
480+
throw new InvalidParameterValueException("Interval should be greater than 0.");
481+
}
482+
483+
String jobExecTime = _configDao.getValue(Config.UsageStatsJobExecTime.toString());
484+
Date previousJobExecTime = UsageUtils.getPreviousJobExecutionTime(usageExecutionTimeZone, jobExecTime);
485+
Date nextJobExecTime = UsageUtils.getNextJobExecutionTime(usageExecutionTimeZone, jobExecTime);
486+
if (ObjectUtils.allNotNull(previousJobExecTime, nextJobExecTime)) {
487+
logger.debug("Next Usage job is scheduled to execute at [{}]; previous execution was at [{}].",
488+
DateUtil.displayDateInTimezone(usageExecutionTimeZone, nextJobExecTime), DateUtil.displayDateInTimezone(usageExecutionTimeZone, previousJobExecTime));
489+
Date now = new Date();
490+
if (nextJobExecTime.getTime() - now.getTime() < REMOVE_RAW_USAGE_RECORDS_WINDOW_IN_MS) {
491+
logger.info("Not removing any cloud_usage records because the next Usage job is scheduled to execute in less than {} minute(s).", REMOVE_RAW_USAGE_RECORDS_WINDOW_IN_MS / 60000);
492+
return false;
493+
} else if (now.getTime() - previousJobExecTime.getTime() < REMOVE_RAW_USAGE_RECORDS_WINDOW_IN_MS) {
494+
logger.info("Not removing any cloud_usage records because the last Usage job executed in less than {} minute(s) ago.", REMOVE_RAW_USAGE_RECORDS_WINDOW_IN_MS / 60000);
495+
return false;
492496
}
493-
_usageDao.expungeAllOlderThan(interval, ConfigurationManagerImpl.DELETE_QUERY_BATCH_SIZE.value());
494-
} else {
495-
throw new InvalidParameterValueException("Invalid interval value. Interval to remove cloud_usage records should be greater than 0");
496497
}
498+
499+
logger.info("Removing cloud_usage records older than {} day(s).", interval);
500+
_usageDao.expungeAllOlderThan(interval, ConfigurationManagerImpl.DELETE_QUERY_BATCH_SIZE.value());
497501
return true;
498502
}
499503
}

usage/src/main/java/com/cloud/usage/UsageManagerImpl.java

Lines changed: 12 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -198,7 +198,9 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna
198198
private Future _heartbeat = null;
199199
private Future _sanity = null;
200200
private boolean usageSnapshotSelection = false;
201+
201202
private static TimeZone usageAggregationTimeZone = TimeZone.getTimeZone("GMT");
203+
private static TimeZone usageExecutionTimeZone = TimeZone.getTimeZone("GMT");
202204

203205
public UsageManagerImpl() {
204206
}
@@ -253,6 +255,9 @@ public boolean configure(String name, Map<String, Object> params) throws Configu
253255
if (aggregationTimeZone != null && !aggregationTimeZone.isEmpty()) {
254256
usageAggregationTimeZone = TimeZone.getTimeZone(aggregationTimeZone);
255257
}
258+
if (execTimeZone != null) {
259+
usageExecutionTimeZone = TimeZone.getTimeZone(execTimeZone);
260+
}
256261

257262
try {
258263
if ((execTime == null) || (aggregationRange == null)) {
@@ -261,34 +266,18 @@ public boolean configure(String name, Map<String, Object> params) throws Configu
261266
throw new ConfigurationException("Missing configuration values for usage job, usage.stats.job.exec.time = " + execTime +
262267
", usage.stats.job.aggregation.range = " + aggregationRange);
263268
}
264-
String[] execTimeSegments = execTime.split(":");
265-
if (execTimeSegments.length != 2) {
266-
logger.error("Unable to parse usage.stats.job.exec.time");
267-
throw new ConfigurationException("Unable to parse usage.stats.job.exec.time '" + execTime + "'");
268-
}
269-
int hourOfDay = Integer.parseInt(execTimeSegments[0]);
270-
int minutes = Integer.parseInt(execTimeSegments[1]);
271-
272-
Date currentDate = new Date();
273-
_jobExecTime.setTime(currentDate);
274-
275-
_jobExecTime.set(Calendar.HOUR_OF_DAY, hourOfDay);
276-
_jobExecTime.set(Calendar.MINUTE, minutes);
277-
_jobExecTime.set(Calendar.SECOND, 0);
278-
_jobExecTime.set(Calendar.MILLISECOND, 0);
279-
280-
TimeZone jobExecTimeZone = execTimeZone != null ? TimeZone.getTimeZone(execTimeZone) : Calendar.getInstance().getTimeZone();
281-
_jobExecTime.setTimeZone(jobExecTimeZone);
282269

283-
// if the hour to execute the job has already passed, roll the day forward to the next day
284-
if (_jobExecTime.getTime().before(currentDate)) {
285-
_jobExecTime.roll(Calendar.DAY_OF_YEAR, true);
270+
Date nextJobExecTime = UsageUtils.getNextJobExecutionTime(usageExecutionTimeZone, execTime);
271+
if (nextJobExecTime == null) {
272+
throw new ConfigurationException(String.format("Unable to parse configuration 'usage.stats.job.exec.time' value [%s].", execTime));
286273
}
274+
_jobExecTime.setTimeZone(usageExecutionTimeZone);
275+
_jobExecTime.setTime(nextJobExecTime);
287276

288277
logger.info("Usage is configured to execute in time zone [{}], at [{}], each [{}] minutes; the current time in that timezone is [{}] and the " +
289278
"next job is scheduled to execute at [{}]. During its execution, Usage will aggregate stats according to the time zone [{}] defined in global setting [usage.aggregation.timezone].",
290-
jobExecTimeZone.getID(), execTime, aggregationRange, DateUtil.displayDateInTimezone(jobExecTimeZone, currentDate),
291-
DateUtil.displayDateInTimezone(jobExecTimeZone, _jobExecTime.getTime()), usageAggregationTimeZone.getID());
279+
usageExecutionTimeZone.getID(), execTime, aggregationRange, DateUtil.displayDateInTimezone(usageExecutionTimeZone, new Date()),
280+
DateUtil.displayDateInTimezone(usageExecutionTimeZone, _jobExecTime.getTime()), usageAggregationTimeZone.getID());
292281

293282
_aggregationDuration = Integer.parseInt(aggregationRange);
294283
if (_aggregationDuration < UsageUtils.USAGE_AGGREGATION_RANGE_MIN) {

utils/src/main/java/org/apache/cloudstack/utils/usage/UsageUtils.java

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,57 @@
1919

2020
package org.apache.cloudstack.utils.usage;
2121

22+
import com.cloud.utils.DateUtil;
23+
import org.apache.logging.log4j.LogManager;
24+
import org.apache.logging.log4j.Logger;
25+
26+
import java.util.Calendar;
27+
import java.util.Date;
28+
import java.util.TimeZone;
29+
2230
public class UsageUtils {
31+
protected static Logger logger = LogManager.getLogger(UsageUtils.class);
32+
2333
public static final int USAGE_AGGREGATION_RANGE_MIN = 1;
34+
35+
public static Date getNextJobExecutionTime(TimeZone usageTimeZone, String jobExecTimeConfig) {
36+
return getJobExecutionTime(usageTimeZone, jobExecTimeConfig, true);
37+
}
38+
39+
public static Date getPreviousJobExecutionTime(TimeZone usageTimeZone, String jobExecTimeConfig) {
40+
return getJobExecutionTime(usageTimeZone, jobExecTimeConfig, false);
41+
}
42+
43+
protected static Date getJobExecutionTime(TimeZone usageTimeZone, String jobExecTimeConfig, boolean next) {
44+
String[] execTimeSegments = jobExecTimeConfig.split(":");
45+
if (execTimeSegments.length != 2) {
46+
logger.warn("Unable to parse configuration 'usage.stats.job.exec.time'.");
47+
return null;
48+
}
49+
int hourOfDay;
50+
int minutes;
51+
try {
52+
hourOfDay = Integer.parseInt(execTimeSegments[0]);
53+
minutes = Integer.parseInt(execTimeSegments[1]);
54+
} catch (NumberFormatException e) {
55+
logger.warn("Unable to parse configuration 'usage.stats.job.exec.time' due to non-numeric values in [{}].", jobExecTimeConfig, e);
56+
return null;
57+
}
58+
59+
Date currentDate = DateUtil.currentGMTTime();
60+
Calendar jobExecTime = Calendar.getInstance(usageTimeZone);
61+
jobExecTime.setTime(currentDate);
62+
jobExecTime.set(Calendar.HOUR_OF_DAY, hourOfDay);
63+
jobExecTime.set(Calendar.MINUTE, minutes);
64+
jobExecTime.set(Calendar.SECOND, 0);
65+
jobExecTime.set(Calendar.MILLISECOND, 0);
66+
67+
if (next && jobExecTime.getTime().before(currentDate)) {
68+
jobExecTime.add(Calendar.DAY_OF_YEAR, 1);
69+
} else if (!next && jobExecTime.getTime().after(currentDate)) {
70+
jobExecTime.add(Calendar.DAY_OF_YEAR, -1);
71+
}
72+
73+
return jobExecTime.getTime();
74+
}
2475
}
Lines changed: 135 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,135 @@
1+
//
2+
// Licensed to the Apache Software Foundation (ASF) under one
3+
// or more contributor license agreements. See the NOTICE file
4+
// distributed with this work for additional information
5+
// regarding copyright ownership. The ASF licenses this file
6+
// to you under the Apache License, Version 2.0 (the
7+
// "License"); you may not use this file except in compliance
8+
// with the License. You may obtain a copy of the License at
9+
//
10+
// http://www.apache.org/licenses/LICENSE-2.0
11+
//
12+
// Unless required by applicable law or agreed to in writing,
13+
// software distributed under the License is distributed on an
14+
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15+
// KIND, either express or implied. See the License for the
16+
// specific language governing permissions and limitations
17+
// under the License.
18+
//
19+
20+
package org.apache.cloudstack.utils.usage;
21+
22+
import com.cloud.utils.DateUtil;
23+
import junit.framework.TestCase;
24+
import org.junit.Assert;
25+
import org.junit.Test;
26+
import org.junit.runner.RunWith;
27+
import org.mockito.MockedStatic;
28+
import org.mockito.Mockito;
29+
import org.mockito.junit.MockitoJUnitRunner;
30+
31+
import java.util.Date;
32+
import java.util.TimeZone;
33+
34+
@RunWith(MockitoJUnitRunner.class)
35+
public class UsageUtilsTest extends TestCase {
36+
37+
TimeZone usageTimeZone = TimeZone.getTimeZone("GMT-3");
38+
39+
@Test
40+
public void getJobExecutionTimeTestReturnsNullWhenConfigurationValueIsInvalid() {
41+
Date result = UsageUtils.getNextJobExecutionTime(usageTimeZone, "test");
42+
assertNull(result);
43+
}
44+
45+
@Test
46+
public void getJobExecutionTimeTestReturnsExpectedDateWhenNextIsTrueAndExecutionTimeHasNotPassed() {
47+
Date currentDate = new Date();
48+
currentDate.setTime(1724296800000L);
49+
50+
try (MockedStatic<DateUtil> dateUtilMockedStatic = Mockito.mockStatic(DateUtil.class)) {
51+
dateUtilMockedStatic.when(DateUtil::currentGMTTime).thenReturn(currentDate);
52+
53+
Date result = UsageUtils.getJobExecutionTime(usageTimeZone, "00:30", true);
54+
55+
Assert.assertNotNull(result);
56+
Assert.assertEquals(1724297400000L, result.getTime());
57+
}
58+
}
59+
60+
@Test
61+
public void getJobExecutionTimeTestReturnsExpectedDateWhenNextIsTrueAndExecutionTimeHasPassed() {
62+
Date currentDate = new Date();
63+
currentDate.setTime(1724297460000L);
64+
65+
try (MockedStatic<DateUtil> dateUtilMockedStatic = Mockito.mockStatic(DateUtil.class)) {
66+
dateUtilMockedStatic.when(DateUtil::currentGMTTime).thenReturn(currentDate);
67+
68+
Date result = UsageUtils.getJobExecutionTime(usageTimeZone, "00:30", true);
69+
70+
Assert.assertNotNull(result);
71+
Assert.assertEquals(1724383800000L, result.getTime());
72+
}
73+
}
74+
75+
@Test
76+
public void getJobExecutionTimeTestReturnsExpectedDateWhenNextIsFalseAndExecutionTimeHasNotPassed() {
77+
Date currentDate = new Date();
78+
currentDate.setTime(1724296800000L);
79+
80+
try (MockedStatic<DateUtil> dateUtilMockedStatic = Mockito.mockStatic(DateUtil.class)) {
81+
dateUtilMockedStatic.when(DateUtil::currentGMTTime).thenReturn(currentDate);
82+
83+
Date result = UsageUtils.getJobExecutionTime(usageTimeZone, "00:30", false);
84+
85+
Assert.assertNotNull(result);
86+
Assert.assertEquals(1724211000000L, result.getTime());
87+
}
88+
}
89+
90+
@Test
91+
public void getJobExecutionTimeTestReturnsExpectedDateWhenNextIsFalseAndExecutionTimeHasPassed() {
92+
Date currentDate = new Date();
93+
currentDate.setTime(1724297460000L);
94+
95+
try (MockedStatic<DateUtil> dateUtilMockedStatic = Mockito.mockStatic(DateUtil.class)) {
96+
dateUtilMockedStatic.when(DateUtil::currentGMTTime).thenReturn(currentDate);
97+
98+
Date result = UsageUtils.getJobExecutionTime(usageTimeZone, "00:30", false);
99+
100+
Assert.assertNotNull(result);
101+
Assert.assertEquals(1724297400000L, result.getTime());
102+
}
103+
}
104+
105+
@Test
106+
public void getJobExecutionTimeTestReturnsExpectedDateWhenNextExecutionIsOnNextYear() {
107+
Date currentDate = new Date();
108+
currentDate.setTime(1767236340000L);
109+
110+
try (MockedStatic<DateUtil> dateUtilMockedStatic = Mockito.mockStatic(DateUtil.class)) {
111+
dateUtilMockedStatic.when(DateUtil::currentGMTTime).thenReturn(currentDate);
112+
113+
Date result = UsageUtils.getJobExecutionTime(usageTimeZone, "00:00", true);
114+
115+
Assert.assertNotNull(result);
116+
Assert.assertEquals(1767236400000L, result.getTime());
117+
}
118+
}
119+
120+
@Test
121+
public void getJobExecutionTimeTestReturnsExpectedDateWhenPreviousExecutionWasOnPreviousYear() {
122+
Date currentDate = new Date();
123+
currentDate.setTime(1767236460000L);
124+
125+
try (MockedStatic<DateUtil> dateUtilMockedStatic = Mockito.mockStatic(DateUtil.class)) {
126+
dateUtilMockedStatic.when(DateUtil::currentGMTTime).thenReturn(currentDate);
127+
128+
Date result = UsageUtils.getJobExecutionTime(usageTimeZone, "23:59", false);
129+
130+
Assert.assertNotNull(result);
131+
Assert.assertEquals(1767236340000L, result.getTime());
132+
}
133+
}
134+
135+
}

0 commit comments

Comments
 (0)