Skip to content

Commit d334286

Browse files
authored
feature: disable delayed start agent (#283)
1 parent 89f96a7 commit d334286

File tree

8 files changed

+105
-127
lines changed

8 files changed

+105
-127
lines changed

arex-agent-bootstrap/src/main/java/io/arex/agent/bootstrap/constants/ConfigConstants.java

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,6 @@ public class ConfigConstants {
2525
public static final String DURING_WORK = "arex.during.work";
2626
public static final String AGENT_VERSION = "arex.agent.version";
2727
public static final String IP_VALIDATE = "arex.ip.validate";
28-
29-
public static final String ENABLE_REPORT_STATUS = "arex.enable.report.status";
3028
public static final String CURRENT_RATE = "arex.current.rate";
3129
public static final String DECELERATE_CODE = "arex.decelerate.code";
3230
}

arex-agent-core/src/main/java/io/arex/agent/instrumentation/BaseAgentInstaller.java

Lines changed: 22 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -50,19 +50,19 @@ public void install() {
5050
try {
5151
Thread.currentThread().setContextClassLoader(getClassLoader());
5252
Runtime.getRuntime().addShutdownHook(new Thread(ConfigService.INSTANCE::shutdown, "arex-agent-shutdown-hook"));
53-
// Timed load config for agent delay start and dynamic retransform
53+
// Timed load config for dynamic retransform
5454
long delayMinutes = ConfigService.INSTANCE.loadAgentConfig(agentArgs);
55-
if (delayMinutes > 0) {
56-
TimerService.schedule(this::install, delayMinutes, TimeUnit.MINUTES);
57-
timedReportStatus();
58-
}
59-
if (!ConfigManager.INSTANCE.valid()) {
55+
if (!allowStartAgent()) {
6056
ConfigService.INSTANCE.reportStatus();
6157
if (!ConfigManager.FIRST_TRANSFORM.get()) {
62-
LOGGER.warn("[AREX] Agent would not install due to {}.", ConfigManager.INSTANCE.getInvalidReason());
58+
LOGGER.warn("[AREX] Agent would not install due to {}.", getInvalidReason());
6359
}
6460
return;
6561
}
62+
if (delayMinutes > 0) {
63+
TimerService.schedule(this::install, delayMinutes, TimeUnit.MINUTES);
64+
timedReportStatus();
65+
}
6666
initDependentComponents();
6767
transform();
6868
ConfigService.INSTANCE.reportStatus();
@@ -71,13 +71,25 @@ public void install() {
7171
}
7272
}
7373

74+
boolean allowStartAgent() {
75+
if (ConfigManager.INSTANCE.isLocalStorage()) {
76+
return true;
77+
}
78+
return ConfigManager.INSTANCE.checkTargetAddress();
79+
}
80+
81+
String getInvalidReason() {
82+
if (!ConfigManager.INSTANCE.checkTargetAddress()) {
83+
return "response [targetAddress] is not match";
84+
}
85+
86+
return "invalid config";
87+
}
88+
7489
private void timedReportStatus() {
7590
if (reportStatusTask != null) {
7691
return;
7792
}
78-
if (!ConfigManager.INSTANCE.isEnableReportStatus()) {
79-
return;
80-
}
8193
reportStatusTask = TimerService.scheduleAtFixedRate(() -> {
8294
try {
8395
ConfigService.INSTANCE.reportStatus();
Lines changed: 69 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,26 @@
11
package io.arex.agent.instrumentation;
22

3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
import static org.junit.jupiter.api.Assertions.assertFalse;
5+
import static org.junit.jupiter.api.Assertions.assertTrue;
36
import static org.mockito.ArgumentMatchers.any;
47
import static org.mockito.ArgumentMatchers.anyString;
8+
import static org.mockito.ArgumentMatchers.eq;
59
import static org.mockito.Mockito.mockStatic;
610

711
import io.arex.agent.bootstrap.cache.AdviceInjectorCache;
12+
import io.arex.agent.bootstrap.constants.ConfigConstants;
813
import io.arex.agent.bootstrap.util.AdviceClassesCollector;
14+
import io.arex.foundation.config.ConfigManager;
15+
import io.arex.foundation.model.ConfigQueryResponse;
16+
import io.arex.foundation.model.ConfigQueryResponse.ResponseBody;
17+
import io.arex.foundation.model.ConfigQueryResponse.ServiceCollectConfig;
918
import io.arex.foundation.model.HttpClientResponse;
1019
import io.arex.foundation.serializer.JacksonSerializer;
1120
import io.arex.foundation.util.NetUtils;
1221
import io.arex.foundation.util.httpclient.AsyncHttpClientUtil;
22+
import java.lang.instrument.Instrumentation;
1323
import java.util.concurrent.CompletableFuture;
14-
import net.bytebuddy.agent.ByteBuddyAgent;
1524
import net.bytebuddy.agent.builder.ResettableClassFileTransformer;
1625
import org.junit.jupiter.api.AfterAll;
1726
import org.junit.jupiter.api.BeforeAll;
@@ -21,19 +30,28 @@
2130
import org.mockito.Mockito;
2231

2332
class BaseAgentInstallerTest {
24-
33+
static BaseAgentInstaller installer = null;
2534
@BeforeAll
2635
static void beforeAll() {
2736
mockStatic(AdviceInjectorCache.class);
37+
38+
Instrumentation inst = Mockito.mock(Instrumentation.class);
39+
installer = new BaseAgentInstaller(inst, null, null) {
40+
@Override
41+
protected ResettableClassFileTransformer transform() {
42+
return null;
43+
}
44+
};
2845
}
2946

3047
@AfterAll
3148
static void afterAll() {
49+
installer = null;
3250
Mockito.clearAllCaches();
3351
}
3452

3553
@Test
36-
void install() {
54+
void install() throws Throwable {
3755
Mockito.when(AdviceInjectorCache.contains(any())).thenReturn(true);
3856
try (MockedStatic<AsyncHttpClientUtil> ahc = mockStatic(AsyncHttpClientUtil.class);
3957
MockedStatic<NetUtils> netUtils = mockStatic(NetUtils.class);
@@ -42,18 +60,60 @@ void install() {
4260
Mockito.verify(mock, Mockito.times(1)).addClassToLoaderSearch(JacksonSerializer.class);
4361
})) {
4462

63+
// allow start agent = false
4564
netUtils.when(NetUtils::getIpAddress).thenReturn("127.0.0.1");
4665
ahc.when(() -> AsyncHttpClientUtil.postAsyncWithJson(anyString(), anyString(), any())).thenReturn(
4766
CompletableFuture.completedFuture(HttpClientResponse.emptyResponse()));
4867

49-
BaseAgentInstaller installer = new BaseAgentInstaller(ByteBuddyAgent.install(), null, null) {
50-
@Override
51-
protected ResettableClassFileTransformer transform() {
52-
return null;
53-
}
54-
};
5568

5669
installer.install();
70+
71+
// allow start agent = true
72+
netUtils.when(NetUtils::getIpAddress).thenReturn("127.0.0.1");
73+
ConfigQueryResponse configQueryResponse = new ConfigQueryResponse();
74+
ServiceCollectConfig serviceCollectConfig = new ServiceCollectConfig();
75+
serviceCollectConfig.setAllowDayOfWeeks(127);
76+
serviceCollectConfig.setAllowTimeOfDayFrom("00:00");
77+
serviceCollectConfig.setAllowTimeOfDayTo("23:59");
78+
serviceCollectConfig.setSampleRate(1);
79+
80+
ResponseBody responseBody = new ResponseBody();
81+
responseBody.setTargetAddress("127.0.0.1");
82+
responseBody.setServiceCollectConfiguration(serviceCollectConfig);
83+
configQueryResponse.setBody(responseBody);
84+
CompletableFuture<HttpClientResponse> response = CompletableFuture.completedFuture(new HttpClientResponse(200, null, JacksonSerializer.INSTANCE.serialize(configQueryResponse)));
85+
ahc.when(() -> AsyncHttpClientUtil.postAsyncWithJson(anyString(), anyString(), eq(null))).thenReturn(response);
86+
installer.install();
87+
}
88+
}
89+
90+
@Test
91+
void allowStartAgent() {
92+
ConfigManager.INSTANCE.setStorageServiceMode(ConfigConstants.STORAGE_MODE);
93+
assertTrue(installer.allowStartAgent());
94+
95+
try (MockedStatic<NetUtils> netUtils = mockStatic(NetUtils.class)) {
96+
netUtils.when(NetUtils::getIpAddress).thenReturn("172.0.0.3");
97+
98+
ConfigManager.INSTANCE.setStorageServiceMode("not " + ConfigConstants.STORAGE_MODE);
99+
ConfigManager.INSTANCE.setTargetAddress("172.0.0.1");
100+
101+
assertFalse(installer.allowStartAgent());
102+
}
103+
}
104+
105+
@Test
106+
void getInvalidReason() {
107+
try (MockedStatic<NetUtils> netUtils = mockStatic(NetUtils.class)) {
108+
netUtils.when(NetUtils::getIpAddress).thenReturn("172.0.0.3");
109+
110+
ConfigManager.INSTANCE.setTargetAddress("172.0.0.1");
111+
112+
assertEquals("response [targetAddress] is not match", installer.getInvalidReason());
113+
114+
// checkTargetAddress = true
115+
ConfigManager.INSTANCE.setTargetAddress("172.0.0.3");
116+
assertEquals("invalid config", installer.getInvalidReason());
57117
}
58118
}
59119
}

arex-instrumentation-foundation/src/main/java/io/arex/foundation/config/ConfigManager.java

Lines changed: 3 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,6 @@ public class ConfigManager {
4040
public static final AtomicBoolean FIRST_TRANSFORM = new AtomicBoolean(false);
4141
private static final int DEFAULT_RECORDING_RATE = 1;
4242
private boolean enableDebug;
43-
private boolean enableReportStatus;
4443
private String agentVersion;
4544
private String serviceName;
4645
private String storageServiceHost;
@@ -89,19 +88,6 @@ public void setEnableDebug(String enableDebug) {
8988
System.setProperty(ENABLE_DEBUG, enableDebug);
9089
}
9190

92-
public boolean isEnableReportStatus() {
93-
return enableReportStatus;
94-
}
95-
96-
public void setEnableReportStatus(String enableReportStatus) {
97-
if (StringUtil.isEmpty(enableReportStatus)) {
98-
return;
99-
}
100-
101-
this.enableReportStatus = Boolean.parseBoolean(enableReportStatus);
102-
System.setProperty(ENABLE_REPORT_STATUS, enableReportStatus);
103-
}
104-
10591
public String getServiceName() {
10692
return serviceName;
10793
}
@@ -230,7 +216,6 @@ private DynamicClassEntity createDynamicClass(DynamicClassConfiguration config,
230216
void init() {
231217
agentVersion = System.getProperty(AGENT_VERSION);
232218
setEnableDebug(System.getProperty(ENABLE_DEBUG));
233-
setEnableReportStatus(System.getProperty(ENABLE_REPORT_STATUS, Boolean.TRUE.toString()));
234219
setServiceName(StringUtil.strip(System.getProperty(SERVICE_NAME)));
235220
setStorageServiceHost(StringUtil.strip(System.getProperty(STORAGE_SERVICE_HOST)));
236221
configPath = StringUtil.strip(System.getProperty(CONFIG_PATH));
@@ -255,12 +240,11 @@ void readConfigFromFile(String configPath) {
255240
}
256241

257242
Map<String, String> configMap = parseConfigFile(configPath);
258-
if (configMap.size() == 0) {
243+
if (configMap.isEmpty()) {
259244
return;
260245
}
261246

262247
setEnableDebug(configMap.get(ENABLE_DEBUG));
263-
setEnableReportStatus(System.getProperty(ENABLE_REPORT_STATUS));
264248
setServiceName(configMap.get(SERVICE_NAME));
265249
setStorageServiceHost(configMap.get(STORAGE_SERVICE_HOST));
266250
setDynamicResultSizeLimit(configMap.get(DYNAMIC_RESULT_SIZE_LIMIT));
@@ -322,7 +306,7 @@ private void updateRuntimeConfig() {
322306
configMap.put(TIME_MACHINE, String.valueOf(startTimeMachine()));
323307
configMap.put(DISABLE_REPLAY, System.getProperty(DISABLE_REPLAY));
324308
configMap.put(DISABLE_RECORD, System.getProperty(DISABLE_RECORD));
325-
configMap.put(DURING_WORK, Boolean.toString(nextWorkTime() <= 0));
309+
configMap.put(DURING_WORK, Boolean.toString(inWorkingTime()));
326310
configMap.put(AGENT_VERSION, agentVersion);
327311
configMap.put(IP_VALIDATE, Boolean.toString(checkTargetAddress()));
328312
configMap.put(STORAGE_SERVICE_MODE, storageServiceMode);
@@ -351,13 +335,6 @@ private void publish(Config config) {
351335
}
352336
}
353337

354-
public boolean valid() {
355-
if (isLocalStorage()) {
356-
return true;
357-
}
358-
return checkTargetAddress() && inWorkingTime();
359-
}
360-
361338
public void setConfigInvalid() {
362339
setRecordRate(0);
363340
setAllowDayOfWeeks(0);
@@ -522,7 +499,7 @@ public void setTargetAddress(String targetAddress) {
522499
this.targetAddress = targetAddress;
523500
}
524501

525-
private boolean checkTargetAddress() {
502+
public boolean checkTargetAddress() {
526503
String localHost = NetUtils.getIpAddress();
527504
// Compatible containers can't get IPAddress
528505
if (StringUtil.isEmpty(localHost)) {
@@ -565,16 +542,4 @@ public String toString() {
565542
", dynamicClassList='" + dynamicClassList + '\'' +
566543
'}';
567544
}
568-
569-
public String getInvalidReason() {
570-
if (!checkTargetAddress()) {
571-
return "response [targetAddress] is not match";
572-
}
573-
574-
if (!inWorkingTime()) {
575-
return "not in working time, allow day of weeks is " + allowDayOfWeeks + ", time is " + allowTimeOfDayFrom + "-" + allowTimeOfDayTo;
576-
}
577-
578-
return "invalid config";
579-
}
580545
}

arex-instrumentation-foundation/src/main/java/io/arex/foundation/services/ConfigService.java

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -121,12 +121,12 @@ AgentStatusEnum getAgentStatus() {
121121
return AgentStatusEnum.START;
122122
}
123123

124-
if (ConfigManager.INSTANCE.valid() && ConfigManager.INSTANCE.getRecordRate() > 0) {
125-
return AgentStatusEnum.WORKING;
126-
}
127-
128124
if (ConfigManager.FIRST_TRANSFORM.get()) {
129-
return AgentStatusEnum.SLEEPING;
125+
if (ConfigManager.INSTANCE.inWorkingTime() && ConfigManager.INSTANCE.getRecordRate() > 0) {
126+
return AgentStatusEnum.WORKING;
127+
} else {
128+
return AgentStatusEnum.SLEEPING;
129+
}
130130
}
131131

132132
return AgentStatusEnum.UN_START;

0 commit comments

Comments
 (0)