Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[backport to 2.15] Merge Single-Stream and HC Detector Workflows (#1237) (#1239) #1242

Merged
merged 1 commit into from
Jun 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
210 changes: 8 additions & 202 deletions src/main/java/org/opensearch/ad/AnomalyDetectorProfileRunner.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,8 @@

package org.opensearch.ad;

import static org.opensearch.core.xcontent.XContentParserUtils.ensureExpectedToken;

import java.util.Set;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.util.Throwables;
import org.apache.logging.log4j.message.ParameterizedMessage;
import org.opensearch.action.get.GetRequest;
import org.opensearch.ad.constant.ADCommonName;
import org.opensearch.ad.indices.ADIndex;
import org.opensearch.ad.indices.ADIndexManagement;
import org.opensearch.ad.model.ADTask;
Expand All @@ -32,31 +24,23 @@
import org.opensearch.ad.task.ADTaskCacheManager;
import org.opensearch.ad.task.ADTaskManager;
import org.opensearch.ad.transport.ADProfileAction;
import org.opensearch.ad.transport.RCFPollingAction;
import org.opensearch.ad.transport.RCFPollingRequest;
import org.opensearch.ad.transport.RCFPollingResponse;
import org.opensearch.client.Client;
import org.opensearch.common.xcontent.LoggingDeprecationHandler;
import org.opensearch.common.xcontent.XContentType;
import org.opensearch.core.action.ActionListener;
import org.opensearch.core.xcontent.NamedXContentRegistry;
import org.opensearch.core.xcontent.XContentParser;
import org.opensearch.timeseries.AnalysisType;
import org.opensearch.timeseries.ProfileRunner;
import org.opensearch.timeseries.common.exception.NotSerializedExceptionName;
import org.opensearch.timeseries.common.exception.ResourceNotFoundException;
import org.opensearch.timeseries.constant.CommonMessages;
import org.opensearch.timeseries.constant.CommonName;
import org.opensearch.timeseries.model.Config;
import org.opensearch.timeseries.model.ConfigState;
import org.opensearch.timeseries.model.Job;
import org.opensearch.timeseries.model.ProfileName;
import org.opensearch.timeseries.util.DiscoveryNodeFilterer;
import org.opensearch.timeseries.util.ExceptionUtil;
import org.opensearch.timeseries.util.MultiResponsesDelegateActionListener;
import org.opensearch.timeseries.util.SecurityClientUtil;
import org.opensearch.transport.TransportService;

/**
* Since version 2.15, we have merged the single-stream and HC detector workflows. Consequently, separate logic for profiling is no longer necessary.
*
* During a Blue/Green (B/G) deployment, if an old node communicates with a new node regarding an old model, we will not execute RCFPollingAction to
* determine model updates. However, we have fallback logic that checks for anomaly results. If any results are found, the initialization progress is
* set to 100%.
*
*/
public class AnomalyDetectorProfileRunner extends
ProfileRunner<ADTaskCacheManager, ADTaskType, ADTask, ADIndex, ADIndexManagement, ADTaskProfile, ADTaskManager, DetectorProfile, ADProfileAction, ADTaskProfileRunner> {

Expand Down Expand Up @@ -95,182 +79,4 @@ public AnomalyDetectorProfileRunner(
protected DetectorProfile.Builder createProfileBuilder() {
return new DetectorProfile.Builder();
}

@Override
protected void prepareProfile(Config config, ActionListener<DetectorProfile> listener, Set<ProfileName> profilesToCollect) {
boolean isHC = config.isHighCardinality();
if (isHC) {
super.prepareProfile(config, listener, profilesToCollect);
} else {
String configId = config.getId();
GetRequest getRequest = new GetRequest(CommonName.JOB_INDEX, configId);
client.get(getRequest, ActionListener.wrap(getResponse -> {
if (getResponse != null && getResponse.isExists()) {
try (
XContentParser parser = XContentType.JSON
.xContent()
.createParser(xContentRegistry, LoggingDeprecationHandler.INSTANCE, getResponse.getSourceAsString())
) {
ensureExpectedToken(XContentParser.Token.START_OBJECT, parser.nextToken(), parser);
Job job = Job.parse(parser);
long enabledTimeMs = job.getEnabledTime().toEpochMilli();

int totalResponsesToWait = 0;
if (profilesToCollect.contains(ProfileName.ERROR)) {
totalResponsesToWait++;
}

// total number of listeners we need to define. Needed by MultiResponsesDelegateActionListener to decide
// when to consolidate results and return to users

if (profilesToCollect.contains(ProfileName.STATE) || profilesToCollect.contains(ProfileName.INIT_PROGRESS)) {
totalResponsesToWait++;
}
if (profilesToCollect.contains(ProfileName.COORDINATING_NODE)
|| profilesToCollect.contains(ProfileName.TOTAL_SIZE_IN_BYTES)
|| profilesToCollect.contains(ProfileName.MODELS)) {
totalResponsesToWait++;
}
if (profilesToCollect.contains(ProfileName.AD_TASK)) {
totalResponsesToWait++;
}

MultiResponsesDelegateActionListener<DetectorProfile> delegateListener =
new MultiResponsesDelegateActionListener<DetectorProfile>(
listener,
totalResponsesToWait,
CommonMessages.FAIL_FETCH_ERR_MSG + configId,
false
);
if (profilesToCollect.contains(ProfileName.ERROR)) {
taskManager.getAndExecuteOnLatestConfigLevelTask(configId, realTimeTaskTypes, task -> {
DetectorProfile.Builder profileBuilder = createProfileBuilder();
if (task.isPresent()) {
long lastUpdateTimeMs = task.get().getLastUpdateTime().toEpochMilli();

// if state index hasn't been updated, we should not use the error field
// For example, before a detector is enabled, if the error message contains
// the phrase "stopped due to blah", we should not show this when the detector
// is enabled.
if (lastUpdateTimeMs > enabledTimeMs && task.get().getError() != null) {
profileBuilder.error(task.get().getError());
}
delegateListener.onResponse(profileBuilder.build());
} else {
// detector state for this detector does not exist
delegateListener.onResponse(profileBuilder.build());
}
}, transportService, false, delegateListener);
}

// total number of listeners we need to define. Needed by MultiResponsesDelegateActionListener to decide
// when to consolidate results and return to users

if (profilesToCollect.contains(ProfileName.STATE) || profilesToCollect.contains(ProfileName.INIT_PROGRESS)) {
profileStateRelated(config, delegateListener, job.isEnabled(), profilesToCollect);
}
if (profilesToCollect.contains(ProfileName.COORDINATING_NODE)
|| profilesToCollect.contains(ProfileName.TOTAL_SIZE_IN_BYTES)
|| profilesToCollect.contains(ProfileName.MODELS)) {
profileModels(config, profilesToCollect, job, delegateListener);
}
if (profilesToCollect.contains(ProfileName.AD_TASK)) {
getLatestHistoricalTaskProfile(configId, transportService, null, delegateListener);
}

} catch (Exception e) {
logger.error(CommonMessages.FAIL_TO_GET_PROFILE_MSG, e);
listener.onFailure(e);
}
} else {
onGetDetectorForPrepare(configId, listener, profilesToCollect);
}
}, exception -> {
if (ExceptionUtil.isIndexNotAvailable(exception)) {
logger.info(exception.getMessage());
onGetDetectorForPrepare(configId, listener, profilesToCollect);
} else {
logger.error(CommonMessages.FAIL_TO_GET_PROFILE_MSG + configId);
listener.onFailure(exception);
}
}));
}
}

/**
* We expect three kinds of states:
* -Disabled: if get ad job api says the job is disabled;
* -Init: if rcf model's total updates is less than required
* -Running: if neither of the above applies and no exceptions.
* @param config config accessor
* @param listener listener to process the returned state or exception
* @param enabled whether the detector job is enabled or not
* @param profilesToCollect target profiles to fetch
*/
private void profileStateRelated(
Config config,
MultiResponsesDelegateActionListener<DetectorProfile> listener,
boolean enabled,
Set<ProfileName> profilesToCollect
) {
if (enabled) {
RCFPollingRequest request = new RCFPollingRequest(config.getId());
client.execute(RCFPollingAction.INSTANCE, request, onPollRCFUpdates(config, profilesToCollect, listener));
} else {
DetectorProfile.Builder builder = new DetectorProfile.Builder();
if (profilesToCollect.contains(ProfileName.STATE)) {
builder.state(ConfigState.DISABLED);
}
listener.onResponse(builder.build());
}
}

/**
* Listener for polling rcf updates through transport messaging
* @param detector anomaly detector
* @param profilesToCollect profiles to collect like state
* @param listener delegate listener
* @return Listener for polling rcf updates through transport messaging
*/
private ActionListener<RCFPollingResponse> onPollRCFUpdates(
Config detector,
Set<ProfileName> profilesToCollect,
MultiResponsesDelegateActionListener<DetectorProfile> listener
) {
return ActionListener.wrap(rcfPollResponse -> {
long totalUpdates = rcfPollResponse.getTotalUpdates();
if (totalUpdates < requiredSamples) {
processInitResponse(detector, profilesToCollect, totalUpdates, false, new DetectorProfile.Builder(), listener);
} else {
DetectorProfile.Builder builder = createProfileBuilder();
createRunningStateAndInitProgress(profilesToCollect, builder);
listener.onResponse(builder.build());
}
}, exception -> {
// we will get an AnomalyDetectionException wrapping the real exception inside
Throwable cause = Throwables.getRootCause(exception);

// exception can be a RemoteTransportException
Exception causeException = (Exception) cause;
if (ExceptionUtil
.isException(
causeException,
ResourceNotFoundException.class,
NotSerializedExceptionName.RESOURCE_NOT_FOUND_EXCEPTION_NAME_UNDERSCORE.getName()
)
|| (ExceptionUtil.isIndexNotAvailable(causeException)
&& causeException.getMessage().contains(ADCommonName.CHECKPOINT_INDEX_NAME))) {
// cannot find checkpoint
// We don't want to show the estimated time remaining to initialize
// a detector before cold start finishes, where the actual
// initialization time may be much shorter if sufficient historical
// data exists.
processInitResponse(detector, profilesToCollect, 0L, true, createProfileBuilder(), listener);
} else {
logger.error(new ParameterizedMessage("Fail to get init progress through messaging for {}", detector.getId()), exception);
listener.onFailure(exception);
}
});
}

}
1 change: 1 addition & 0 deletions src/main/java/org/opensearch/ad/ml/ADCheckpointDao.java
Original file line number Diff line number Diff line change
Expand Up @@ -447,6 +447,7 @@ ThresholdedRandomCutForest toTrcf(String checkpoint) {
});
trcf = trcfMapper.toModel(state);
} catch (RuntimeException e) {
logger.info("checkpoint to restore: " + checkpoint);
logger.error("Failed to deserialize TRCF model", e);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ protected ProfileNodeResponse nodeOperation(ProfileNodeRequest request) {

// state profile requires totalUpdates as well
if (profiles.contains(ProfileName.INIT_PROGRESS) || profiles.contains(ProfileName.STATE)) {
totalUpdates = cacheProvider.get().getTotalUpdates(configId);// get toal updates
totalUpdates = cacheProvider.get().getTotalUpdates(configId);// get total updates
}
if (profiles.contains(ProfileName.TOTAL_SIZE_IN_BYTES)) {
modelSize = cacheProvider.get().getModelSize(configId);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ protected enum ErrorResultStatus {
NULL_POINTER_EXCEPTION
}

protected AnomalyDetectorProfileRunner runner;
protected OldAnomalyDetectorProfileRunner oldRunner;
protected Client client;
protected SecurityClientUtil clientUtil;
protected DiscoveryNodeFilterer nodeFilter;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ private void setUpClientGet(
return null;
}).when(nodeStateManager).getConfig(anyString(), eq(AnalysisType.AD), any(ActionListener.class));
clientUtil = new SecurityClientUtil(nodeStateManager, Settings.EMPTY);
runner = new AnomalyDetectorProfileRunner(
oldRunner = new OldAnomalyDetectorProfileRunner(
client,
clientUtil,
xContentRegistry(),
Expand Down Expand Up @@ -198,7 +198,7 @@ public void testDetectorNotExist() throws IOException, InterruptedException {
setUpClientGet(DetectorStatus.INDEX_NOT_EXIST, JobStatus.INDEX_NOT_EXIT, RCFPollingStatus.EMPTY, ErrorResultStatus.NO_ERROR);
final CountDownLatch inProgressLatch = new CountDownLatch(1);

runner.profile("x123", ActionListener.wrap(response -> {
oldRunner.profile("x123", ActionListener.wrap(response -> {
assertTrue("Should not reach here", false);
inProgressLatch.countDown();
}, exception -> {
Expand All @@ -213,7 +213,7 @@ public void testDisabledJobIndexTemplate(JobStatus status) throws IOException, I
ConfigProfile expectedProfile = new DetectorProfile.Builder().state(ConfigState.DISABLED).build();
final CountDownLatch inProgressLatch = new CountDownLatch(1);

runner.profile(detector.getId(), ActionListener.wrap(response -> {
oldRunner.profile(detector.getId(), ActionListener.wrap(response -> {
assertEquals(expectedProfile, response);
inProgressLatch.countDown();
}, exception -> {
Expand All @@ -237,7 +237,7 @@ public void testInitOrRunningStateTemplate(RCFPollingStatus status, ConfigState
DetectorProfile expectedProfile = new DetectorProfile.Builder().state(expectedState).build();
final CountDownLatch inProgressLatch = new CountDownLatch(1);

runner.profile(detector.getId(), ActionListener.wrap(response -> {
oldRunner.profile(detector.getId(), ActionListener.wrap(response -> {
assertEquals(expectedProfile, response);
inProgressLatch.countDown();
}, exception -> {
Expand Down Expand Up @@ -307,7 +307,7 @@ public void testErrorStateTemplate(
DetectorProfile expectedProfile = builder.build();
final CountDownLatch inProgressLatch = new CountDownLatch(1);

runner.profile(detector.getId(), ActionListener.wrap(response -> {
oldRunner.profile(detector.getId(), ActionListener.wrap(response -> {
assertEquals(expectedProfile, response);
inProgressLatch.countDown();
}, exception -> {
Expand Down Expand Up @@ -516,7 +516,7 @@ public void testProfileModels() throws InterruptedException, IOException {

final CountDownLatch inProgressLatch = new CountDownLatch(1);

runner.profile(detector.getId(), ActionListener.wrap(profileResponse -> {
oldRunner.profile(detector.getId(), ActionListener.wrap(profileResponse -> {
assertEquals(node1, profileResponse.getCoordinatingNode());
assertEquals(modelSize * 2, profileResponse.getTotalSizeInBytes());
assertEquals(2, profileResponse.getModelProfile().length);
Expand Down Expand Up @@ -547,7 +547,7 @@ public void testInitProgress() throws IOException, InterruptedException {
expectedProfile.setInitProgress(profile);
final CountDownLatch inProgressLatch = new CountDownLatch(1);

runner.profile(detector.getId(), ActionListener.wrap(response -> {
oldRunner.profile(detector.getId(), ActionListener.wrap(response -> {
assertEquals(expectedProfile, response);
inProgressLatch.countDown();
}, exception -> {
Expand All @@ -566,7 +566,7 @@ public void testInitProgressFailImmediately() throws IOException, InterruptedExc
expectedProfile.setInitProgress(profile);
final CountDownLatch inProgressLatch = new CountDownLatch(1);

runner.profile(detector.getId(), ActionListener.wrap(response -> {
oldRunner.profile(detector.getId(), ActionListener.wrap(response -> {
assertTrue("Should not reach here ", false);
inProgressLatch.countDown();
}, exception -> {
Expand All @@ -584,7 +584,7 @@ public void testInitNoUpdateNoIndex() throws IOException, InterruptedException {
.build();
final CountDownLatch inProgressLatch = new CountDownLatch(1);

runner.profile(detector.getId(), ActionListener.wrap(response -> {
oldRunner.profile(detector.getId(), ActionListener.wrap(response -> {
assertEquals(expectedProfile, response);
inProgressLatch.countDown();
}, exception -> {
Expand All @@ -606,7 +606,7 @@ public void testInitNoIndex() throws IOException, InterruptedException {
.build();
final CountDownLatch inProgressLatch = new CountDownLatch(1);

runner.profile(detector.getId(), ActionListener.wrap(response -> {
oldRunner.profile(detector.getId(), ActionListener.wrap(response -> {
assertEquals(expectedProfile, response);
inProgressLatch.countDown();
}, exception -> {
Expand Down Expand Up @@ -640,7 +640,7 @@ public void testFailRCFPolling() throws IOException, InterruptedException {
setUpClientGet(DetectorStatus.EXIST, JobStatus.ENABLED, RCFPollingStatus.EXCEPTION, ErrorResultStatus.NO_ERROR);
final CountDownLatch inProgressLatch = new CountDownLatch(1);

runner.profile(detector.getId(), ActionListener.wrap(response -> {
oldRunner.profile(detector.getId(), ActionListener.wrap(response -> {
assertTrue("Should not reach here ", false);
inProgressLatch.countDown();
}, exception -> {
Expand Down
Loading
Loading