Skip to content

Commit 2974af8

Browse files
Damans227sachindoddagunimprokopchuk
authored
Make worker and API thread pool size configurable (apache#13565)
* Make worker and API thread pool size configurable The AsyncJobManager's API and Worker executor thread pool sizes are currently derived solely from db.cloud.maxActive (maxActive/2 and maxActive*2/3 respectively). This coupling doesn't account for environments with predominantly I/O-bound workers, where threads are held waiting on external responses for extended periods and higher pool sizes may be needed independently of the DB connection count. This adds two global config keys: - api.job.pool.size (default: 50) - work.job.pool.size (default: 50) The actual pool size is Math.max(configured value, db-derived default), preserving existing behavior by default while allowing operators to increase pool sizes when workloads require it. Pool sizes and their derivation are logged at startup for observability. * Replace synthetic pool size tests with real configure() executor assertions The previous unit tests for the api.job.pool.size/work.job.pool.size config keys only re-ran Math.max() on local hardcoded values, or checked ConfigKey plumbing directly, without ever calling AsyncJobManagerImpl.configure() itself. That meant a regression in the actual pool-sizing logic wouldn't have been caught. These tests now invoke configure() directly and assert on the real core pool size of the created _apiJobExecutor/_workerJobExecutor via reflection, with @Before/@after hooks to stub db.properties and reset config/executor state between tests. --------- Co-authored-by: Sachin R <32716246+sachindoddaguni@users.noreply.github.com> Co-authored-by: mprokopchuk <mprokopchuk@apple.com>
1 parent cc2f74f commit 2974af8

2 files changed

Lines changed: 160 additions & 5 deletions

File tree

‎framework/jobs/src/main/java/org/apache/cloudstack/framework/jobs/impl/AsyncJobManagerImpl.java‎

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,10 @@ public class AsyncJobManagerImpl extends ManagerBase implements AsyncJobManager,
125125
Integer.class, "vm.job.lock.timeout", "1800",
126126
"Time in seconds to wait in acquiring lock to submit a vm worker job", false);
127127
private static final ConfigKey<Boolean> HidePassword = new ConfigKey<Boolean>("Advanced", Boolean.class, "log.hide.password", "true", "If set to true, the password is hidden", true, ConfigKey.Scope.Global);
128+
public static final ConfigKey<Integer> ApiJobPoolSize = new ConfigKey<>("Advanced", Integer.class, "api.job.pool.size", "50",
129+
"Minimum size of the API job executor thread pool. Actual size is the max of this value and db.cloud.maxActive / 2.", false, ConfigKey.Scope.Global);
130+
public static final ConfigKey<Integer> WorkJobPoolSize = new ConfigKey<>("Advanced", Integer.class, "work.job.pool.size", "50",
131+
"Minimum size of the Worker job executor thread pool. Actual size is the max of this value and db.cloud.maxActive * 2 / 3.", false, ConfigKey.Scope.Global);
128132

129133

130134
private static final int ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_COOPERATION = 3; // 3 seconds
@@ -198,7 +202,7 @@ public String getConfigComponentName() {
198202

199203
@Override
200204
public ConfigKey<?>[] getConfigKeys() {
201-
return new ConfigKey<?>[] {JobExpireMinutes, JobCancelThresholdMinutes, VmJobLockTimeout, HidePassword};
205+
return new ConfigKey<?>[] {JobExpireMinutes, JobCancelThresholdMinutes, VmJobLockTimeout, HidePassword, ApiJobPoolSize, WorkJobPoolSize};
202206
}
203207

204208
@Override
@@ -1100,13 +1104,18 @@ public boolean configure(String name, Map<String, Object> params) throws Configu
11001104
final Properties dbProps = DbProperties.getDbProperties();
11011105
final int cloudMaxActive = Integer.parseInt(dbProps.getProperty("db.cloud.maxActive"));
11021106

1103-
int apiPoolSize = cloudMaxActive / 2;
1104-
int workPoolSize = (cloudMaxActive * 2) / 3;
1107+
int defaultApiPoolSize = cloudMaxActive / 2;
1108+
int defaultWorkPoolSize = (cloudMaxActive * 2) / 3;
11051109

1106-
logger.info("Start AsyncJobManager API executor thread pool in size " + apiPoolSize);
1110+
int apiPoolSize = Math.max(ApiJobPoolSize.value(), defaultApiPoolSize);
1111+
int workPoolSize = Math.max(WorkJobPoolSize.value(), defaultWorkPoolSize);
1112+
1113+
logger.info("Start AsyncJobManager API executor thread pool in size " + apiPoolSize +
1114+
" (configured=" + ApiJobPoolSize.value() + ", db.derived=" + defaultApiPoolSize + ", db.cloud.maxActive=" + cloudMaxActive + ")");
11071115
_apiJobExecutor = Executors.newFixedThreadPool(apiPoolSize, new NamedThreadFactory(AsyncJobManager.API_JOB_POOL_THREAD_PREFIX));
11081116

1109-
logger.info("Start AsyncJobManager Work executor thread pool in size " + workPoolSize);
1117+
logger.info("Start AsyncJobManager Work executor thread pool in size " + workPoolSize +
1118+
" (configured=" + WorkJobPoolSize.value() + ", db.derived=" + defaultWorkPoolSize + ", db.cloud.maxActive=" + cloudMaxActive + ")");
11101119
_workerJobExecutor = Executors.newFixedThreadPool(workPoolSize, new NamedThreadFactory(AsyncJobManager.WORK_JOB_POOL_THREAD_PREFIX));
11111120
} catch (final Exception e) {
11121121
throw new ConfigurationException("Unable to load db.properties to configure AsyncJobManagerImpl");

‎framework/jobs/src/test/java/org/apache/cloudstack/framework/jobs/impl/AsyncJobManagerImplTest.java‎

Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,19 +17,30 @@
1717

1818
package org.apache.cloudstack.framework.jobs.impl;
1919

20+
import java.lang.reflect.Field;
21+
import java.util.Properties;
22+
import java.util.concurrent.ExecutorService;
23+
import java.util.concurrent.ThreadPoolExecutor;
24+
2025
import com.cloud.network.Network;
2126
import com.cloud.network.dao.NetworkDao;
2227
import com.cloud.network.dao.NetworkVO;
2328
import com.cloud.storage.Volume;
29+
import com.cloud.utils.db.DbProperties;
2430
import com.cloud.utils.fsm.NoTransitionException;
2531
import com.cloud.vm.VMInstanceVO;
2632
import com.cloud.vm.VirtualMachine;
2733
import com.cloud.vm.VirtualMachineManager;
2834
import com.cloud.vm.dao.VMInstanceDao;
35+
2936
import org.apache.cloudstack.api.ApiCommandResourceType;
3037
import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService;
3138
import org.apache.cloudstack.engine.subsystem.api.storage.VolumeDataFactory;
3239
import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo;
40+
import org.apache.cloudstack.framework.config.ConfigKey;
41+
import org.junit.After;
42+
import org.junit.Assert;
43+
import org.junit.Before;
3344
import org.junit.Test;
3445
import org.junit.runner.RunWith;
3546
import org.mockito.InjectMocks;
@@ -42,6 +53,12 @@
4253

4354
@RunWith(MockitoJUnitRunner.class)
4455
public class AsyncJobManagerImplTest {
56+
57+
// db.cloud.maxActive value preloaded into DbProperties for every test in this class.
58+
// Chosen so the db-derived defaults (4000/2 = 2000 for api, 4000*2/3 = 2666 for worker)
59+
// are non-trivial and easy to reason about vs. the configured minimums under test.
60+
private static final int DB_CLOUD_MAX_ACTIVE = 4000;
61+
4562
@Spy
4663
@InjectMocks
4764
AsyncJobManagerImpl asyncJobManager;
@@ -56,6 +73,30 @@ public class AsyncJobManagerImplTest {
5673
@Mock
5774
NetworkOrchestrationService networkOrchestrationService;
5875

76+
@Before
77+
public void preloadDbProperties() throws Exception {
78+
Properties props = new Properties();
79+
props.setProperty("db.cloud.maxActive", String.valueOf(DB_CLOUD_MAX_ACTIVE));
80+
// Bypass DbProperties' internal "loaded" guard so configure() reads our
81+
// properties instead of trying to load a real db.properties file.
82+
setDbPropertiesStatics(props, true);
83+
}
84+
85+
@After
86+
public void tearDown() throws Exception {
87+
try {
88+
shutdownIfPresent("_apiJobExecutor");
89+
shutdownIfPresent("_workerJobExecutor");
90+
} finally {
91+
// Reset static state even if executor shutdown throws, so we do not
92+
// pollute later test classes with our stubbed ConfigKey values or
93+
// preloaded DbProperties.
94+
resetConfigValue(AsyncJobManagerImpl.ApiJobPoolSize);
95+
resetConfigValue(AsyncJobManagerImpl.WorkJobPoolSize);
96+
setDbPropertiesStatics(new Properties(), false);
97+
}
98+
}
99+
59100
@Test
60101
public void testCleanupVolumeResource() {
61102
AsyncJobVO job = new AsyncJobVO();
@@ -93,4 +134,109 @@ public void testCleanupNetworkResource() throws NoTransitionException {
93134
Mockito.verify(networkOrchestrationService, Mockito.times(1)).stateTransitTo(networkVO,
94135
Network.Event.OperationFailed);
95136
}
137+
138+
@Test
139+
public void configureApiPoolUsesConfiguredValueWhenLargerThanDbDerived() throws Exception {
140+
overrideConfigValue(AsyncJobManagerImpl.ApiJobPoolSize, 3000);
141+
overrideConfigValue(AsyncJobManagerImpl.WorkJobPoolSize, 50);
142+
invokeConfigureAndSwallowPostSetupNpe();
143+
// apiPoolSize = max(3000, 4000/2) = 3000 (configured wins)
144+
Assert.assertEquals(3000, apiPoolCoreSize());
145+
}
146+
147+
@Test
148+
public void configureApiPoolUsesDbDerivedWhenLargerThanConfigured() throws Exception {
149+
overrideConfigValue(AsyncJobManagerImpl.ApiJobPoolSize, 50);
150+
overrideConfigValue(AsyncJobManagerImpl.WorkJobPoolSize, 50);
151+
invokeConfigureAndSwallowPostSetupNpe();
152+
// apiPoolSize = max(50, 4000/2) = 2000 (db-derived wins)
153+
Assert.assertEquals(DB_CLOUD_MAX_ACTIVE / 2, apiPoolCoreSize());
154+
}
155+
156+
@Test
157+
public void configureWorkerPoolUsesTwoThirdsFormula() throws Exception {
158+
overrideConfigValue(AsyncJobManagerImpl.ApiJobPoolSize, 50);
159+
overrideConfigValue(AsyncJobManagerImpl.WorkJobPoolSize, 50);
160+
invokeConfigureAndSwallowPostSetupNpe();
161+
// workPoolSize = max(50, 4000*2/3) = 2666 (db-derived wins)
162+
Assert.assertEquals((DB_CLOUD_MAX_ACTIVE * 2) / 3, workerPoolCoreSize());
163+
}
164+
165+
@Test
166+
public void configureWorkerPoolUsesConfiguredValueWhenLargerThanDbDerived() throws Exception {
167+
overrideConfigValue(AsyncJobManagerImpl.ApiJobPoolSize, 50);
168+
overrideConfigValue(AsyncJobManagerImpl.WorkJobPoolSize, 5000);
169+
invokeConfigureAndSwallowPostSetupNpe();
170+
// workPoolSize = max(5000, 4000*2/3) = 5000 (configured wins)
171+
Assert.assertEquals(5000, workerPoolCoreSize());
172+
}
173+
174+
/**
175+
* Invoke configure() and swallow the NPE it throws when wiring SearchBuilders
176+
* on the un-mocked DAOs after the pool-sizing block. The executors are created
177+
* inside configure()'s try/catch (before the DAO wiring), so pool sizes can
178+
* still be inspected after the failure.
179+
*/
180+
private void invokeConfigureAndSwallowPostSetupNpe() {
181+
try {
182+
asyncJobManager.configure(null, null);
183+
} catch (Exception ignored) {
184+
// expected: DAO wiring after pool-sizing NPEs because we intentionally
185+
// did not mock the DAOs (they are not part of what we are testing).
186+
}
187+
}
188+
189+
private int apiPoolCoreSize() throws Exception {
190+
Object executor = readField("_apiJobExecutor");
191+
Assert.assertNotNull("configure() did not create _apiJobExecutor - has DAO wiring been moved before pool sizing?", executor);
192+
return ((ThreadPoolExecutor) executor).getCorePoolSize();
193+
}
194+
195+
private int workerPoolCoreSize() throws Exception {
196+
Object executor = readField("_workerJobExecutor");
197+
Assert.assertNotNull("configure() did not create _workerJobExecutor - has DAO wiring been moved before pool sizing?", executor);
198+
return ((ThreadPoolExecutor) executor).getCorePoolSize();
199+
}
200+
201+
private Object readField(String name) throws Exception {
202+
Field f = AsyncJobManagerImpl.class.getDeclaredField(name);
203+
f.setAccessible(true);
204+
return f.get(asyncJobManager);
205+
}
206+
207+
private void shutdownIfPresent(String executorFieldName) {
208+
try {
209+
Object executor = readField(executorFieldName);
210+
if (executor instanceof ExecutorService) {
211+
((ExecutorService) executor).shutdownNow();
212+
}
213+
} catch (Exception ignored) {
214+
// never populated by this test - nothing to clean up
215+
}
216+
}
217+
218+
private void overrideConfigValue(final ConfigKey<?> configKey, final Object value) {
219+
try {
220+
Field f = ConfigKey.class.getDeclaredField("_value");
221+
f.setAccessible(true);
222+
f.set(configKey, value);
223+
} catch (IllegalAccessException | NoSuchFieldException e) {
224+
Assert.fail(e.getMessage());
225+
}
226+
}
227+
228+
private void resetConfigValue(final ConfigKey<?> configKey) throws Exception {
229+
Field f = ConfigKey.class.getDeclaredField("_value");
230+
f.setAccessible(true);
231+
f.set(configKey, null);
232+
}
233+
234+
private void setDbPropertiesStatics(Properties props, boolean loaded) throws Exception {
235+
Field propsField = DbProperties.class.getDeclaredField("properties");
236+
Field loadedField = DbProperties.class.getDeclaredField("loaded");
237+
propsField.setAccessible(true);
238+
loadedField.setAccessible(true);
239+
propsField.set(null, props);
240+
loadedField.set(null, loaded);
241+
}
96242
}

0 commit comments

Comments
 (0)