|
| 1 | +/* |
| 2 | + * SPDX-License-Identifier: Apache-2.0 |
| 3 | + * |
| 4 | + * The OpenSearch Contributors require contributions made to |
| 5 | + * this file be licensed under the Apache-2.0 license or a |
| 6 | + * compatible open source license. |
| 7 | + * |
| 8 | + * Modifications Copyright OpenSearch Contributors. See |
| 9 | + * GitHub history for details. |
| 10 | + */ |
| 11 | + |
| 12 | +package org.opensearch.ad.e2e; |
| 13 | + |
| 14 | +import static org.opensearch.ad.TestHelpers.toHttpEntity; |
| 15 | +import static org.opensearch.ad.settings.AnomalyDetectorSettings.BACKOFF_MINUTES; |
| 16 | +import static org.opensearch.ad.settings.AnomalyDetectorSettings.MAX_RETRY_FOR_UNRESPONSIVE_NODE; |
| 17 | + |
| 18 | +import java.io.File; |
| 19 | +import java.io.FileReader; |
| 20 | +import java.io.IOException; |
| 21 | +import java.io.InputStreamReader; |
| 22 | +import java.nio.charset.Charset; |
| 23 | +import java.time.Instant; |
| 24 | +import java.util.ArrayList; |
| 25 | +import java.util.List; |
| 26 | +import java.util.Locale; |
| 27 | +import java.util.Map; |
| 28 | + |
| 29 | +import org.apache.hc.core5.http.HttpHeaders; |
| 30 | +import org.apache.hc.core5.http.message.BasicHeader; |
| 31 | +import org.opensearch.ad.ODFERestTestCase; |
| 32 | +import org.opensearch.ad.TestHelpers; |
| 33 | +import org.opensearch.client.Request; |
| 34 | +import org.opensearch.client.RequestOptions; |
| 35 | +import org.opensearch.client.Response; |
| 36 | +import org.opensearch.client.RestClient; |
| 37 | +import org.opensearch.client.WarningsHandler; |
| 38 | +import org.opensearch.common.Strings; |
| 39 | +import org.opensearch.common.xcontent.XContentBuilder; |
| 40 | +import org.opensearch.common.xcontent.json.JsonXContent; |
| 41 | + |
| 42 | +import com.google.common.collect.ImmutableList; |
| 43 | +import com.google.gson.JsonArray; |
| 44 | +import com.google.gson.JsonObject; |
| 45 | +import com.google.gson.JsonParser; |
| 46 | + |
| 47 | +public class AbstractSyntheticDataTest extends ODFERestTestCase { |
| 48 | + /** |
| 49 | + * In real time AD, we mute a node for a detector if that node keeps returning |
| 50 | + * ResourceNotFoundException (5 times in a row). This is a problem for batch mode |
| 51 | + * testing as we issue a large amount of requests quickly. Due to the speed, we |
| 52 | + * won't be able to finish cold start before the ResourceNotFoundException mutes |
| 53 | + * a node. Since our test case has only one node, there is no other nodes to fall |
| 54 | + * back on. Here we disable such fault tolerance by setting max retries before |
| 55 | + * muting to a large number and the actual wait time during muting to 0. |
| 56 | + * |
| 57 | + * @throws IOException when failing to create http request body |
| 58 | + */ |
| 59 | + protected void disableResourceNotFoundFaultTolerence() throws IOException { |
| 60 | + XContentBuilder settingCommand = JsonXContent.contentBuilder(); |
| 61 | + |
| 62 | + settingCommand.startObject(); |
| 63 | + settingCommand.startObject("persistent"); |
| 64 | + settingCommand.field(MAX_RETRY_FOR_UNRESPONSIVE_NODE.getKey(), 100_000); |
| 65 | + settingCommand.field(BACKOFF_MINUTES.getKey(), 0); |
| 66 | + settingCommand.endObject(); |
| 67 | + settingCommand.endObject(); |
| 68 | + Request request = new Request("PUT", "/_cluster/settings"); |
| 69 | + request.setJsonEntity(Strings.toString(settingCommand)); |
| 70 | + |
| 71 | + adminClient().performRequest(request); |
| 72 | + } |
| 73 | + |
| 74 | + protected List<JsonObject> getData(String datasetFileName) throws Exception { |
| 75 | + JsonArray jsonArray = JsonParser |
| 76 | + .parseReader(new FileReader(new File(getClass().getResource(datasetFileName).toURI()), Charset.defaultCharset())) |
| 77 | + .getAsJsonArray(); |
| 78 | + List<JsonObject> list = new ArrayList<>(jsonArray.size()); |
| 79 | + jsonArray.iterator().forEachRemaining(i -> list.add(i.getAsJsonObject())); |
| 80 | + return list; |
| 81 | + } |
| 82 | + |
| 83 | + protected Map<String, Object> getDetectionResult(String detectorId, Instant begin, Instant end, RestClient client) { |
| 84 | + try { |
| 85 | + Request request = new Request( |
| 86 | + "POST", |
| 87 | + String.format(Locale.ROOT, "/_opendistro/_anomaly_detection/detectors/%s/_run", detectorId) |
| 88 | + ); |
| 89 | + request |
| 90 | + .setJsonEntity( |
| 91 | + String.format(Locale.ROOT, "{ \"period_start\": %d, \"period_end\": %d }", begin.toEpochMilli(), end.toEpochMilli()) |
| 92 | + ); |
| 93 | + return entityAsMap(client.performRequest(request)); |
| 94 | + } catch (Exception e) { |
| 95 | + throw new RuntimeException(e); |
| 96 | + } |
| 97 | + } |
| 98 | + |
| 99 | + protected void bulkIndexTrainData( |
| 100 | + String datasetName, |
| 101 | + List<JsonObject> data, |
| 102 | + int trainTestSplit, |
| 103 | + RestClient client, |
| 104 | + String categoryField |
| 105 | + ) throws Exception { |
| 106 | + Request request = new Request("PUT", datasetName); |
| 107 | + String requestBody = null; |
| 108 | + if (Strings.isEmpty(categoryField)) { |
| 109 | + requestBody = "{ \"mappings\": { \"properties\": { \"timestamp\": { \"type\": \"date\"}," |
| 110 | + + " \"Feature1\": { \"type\": \"double\" }, \"Feature2\": { \"type\": \"double\" } } } }"; |
| 111 | + } else { |
| 112 | + requestBody = String |
| 113 | + .format( |
| 114 | + Locale.ROOT, |
| 115 | + "{ \"mappings\": { \"properties\": { \"timestamp\": { \"type\": \"date\"}," |
| 116 | + + " \"Feature1\": { \"type\": \"double\" }, \"Feature2\": { \"type\": \"double\" }," |
| 117 | + + "\"%s\": { \"type\": \"keyword\"} } } }", |
| 118 | + categoryField |
| 119 | + ); |
| 120 | + } |
| 121 | + |
| 122 | + request.setJsonEntity(requestBody); |
| 123 | + setWarningHandler(request, false); |
| 124 | + client.performRequest(request); |
| 125 | + Thread.sleep(1_000); |
| 126 | + |
| 127 | + StringBuilder bulkRequestBuilder = new StringBuilder(); |
| 128 | + for (int i = 0; i < trainTestSplit; i++) { |
| 129 | + bulkRequestBuilder.append("{ \"index\" : { \"_index\" : \"" + datasetName + "\", \"_id\" : \"" + i + "\" } }\n"); |
| 130 | + bulkRequestBuilder.append(data.get(i).toString()).append("\n"); |
| 131 | + } |
| 132 | + TestHelpers |
| 133 | + .makeRequest( |
| 134 | + client, |
| 135 | + "POST", |
| 136 | + "_bulk?refresh=true", |
| 137 | + null, |
| 138 | + toHttpEntity(bulkRequestBuilder.toString()), |
| 139 | + ImmutableList.of(new BasicHeader(HttpHeaders.USER_AGENT, "Kibana")) |
| 140 | + ); |
| 141 | + Thread.sleep(1_000); |
| 142 | + waitAllSyncheticDataIngested(trainTestSplit, datasetName, client); |
| 143 | + } |
| 144 | + |
| 145 | + protected String createDetector( |
| 146 | + String datasetName, |
| 147 | + int intervalMinutes, |
| 148 | + RestClient client, |
| 149 | + String categoryField, |
| 150 | + long windowDelayInMins |
| 151 | + ) throws Exception { |
| 152 | + Request request = new Request("POST", "/_plugins/_anomaly_detection/detectors/"); |
| 153 | + String requestBody = null; |
| 154 | + if (Strings.isEmpty(categoryField)) { |
| 155 | + requestBody = String |
| 156 | + .format( |
| 157 | + Locale.ROOT, |
| 158 | + "{ \"name\": \"test\", \"description\": \"test\", \"time_field\": \"timestamp\"" |
| 159 | + + ", \"indices\": [\"%s\"], \"feature_attributes\": [{ \"feature_name\": \"feature 1\", \"feature_enabled\": " |
| 160 | + + "\"true\", \"aggregation_query\": { \"Feature1\": { \"sum\": { \"field\": \"Feature1\" } } } }, { \"feature_name\"" |
| 161 | + + ": \"feature 2\", \"feature_enabled\": \"true\", \"aggregation_query\": { \"Feature2\": { \"sum\": { \"field\": " |
| 162 | + + "\"Feature2\" } } } }], \"detection_interval\": { \"period\": { \"interval\": %d, \"unit\": \"Minutes\" } }, " |
| 163 | + + "\"window_delay\": { \"period\": {\"interval\": %d, \"unit\": \"MINUTES\"}}," |
| 164 | + + "\"schema_version\": 0 }", |
| 165 | + datasetName, |
| 166 | + intervalMinutes, |
| 167 | + windowDelayInMins |
| 168 | + ); |
| 169 | + } else { |
| 170 | + requestBody = String |
| 171 | + .format( |
| 172 | + Locale.ROOT, |
| 173 | + "{ \"name\": \"test\", \"description\": \"test\", \"time_field\": \"timestamp\"" |
| 174 | + + ", \"indices\": [\"%s\"], \"feature_attributes\": [{ \"feature_name\": \"feature 1\", \"feature_enabled\": " |
| 175 | + + "\"true\", \"aggregation_query\": { \"Feature1\": { \"sum\": { \"field\": \"Feature1\" } } } }, { \"feature_name\"" |
| 176 | + + ": \"feature 2\", \"feature_enabled\": \"true\", \"aggregation_query\": { \"Feature2\": { \"sum\": { \"field\": " |
| 177 | + + "\"Feature2\" } } } }], \"detection_interval\": { \"period\": { \"interval\": %d, \"unit\": \"Minutes\" } }, " |
| 178 | + + "\"category_field\": [\"%s\"], " |
| 179 | + + "\"window_delay\": { \"period\": {\"interval\": %d, \"unit\": \"MINUTES\"}}," |
| 180 | + + "\"schema_version\": 0 }", |
| 181 | + datasetName, |
| 182 | + intervalMinutes, |
| 183 | + categoryField, |
| 184 | + windowDelayInMins |
| 185 | + ); |
| 186 | + } |
| 187 | + |
| 188 | + request.setJsonEntity(requestBody); |
| 189 | + Map<String, Object> response = entityAsMap(client.performRequest(request)); |
| 190 | + String detectorId = (String) response.get("_id"); |
| 191 | + Thread.sleep(1_000); |
| 192 | + return detectorId; |
| 193 | + } |
| 194 | + |
| 195 | + protected void waitAllSyncheticDataIngested(int expectedSize, String datasetName, RestClient client) throws Exception { |
| 196 | + int maxWaitCycles = 3; |
| 197 | + do { |
| 198 | + Request request = new Request("POST", String.format(Locale.ROOT, "/%s/_search", datasetName)); |
| 199 | + request |
| 200 | + .setJsonEntity( |
| 201 | + String |
| 202 | + .format( |
| 203 | + Locale.ROOT, |
| 204 | + "{\"query\": {" |
| 205 | + + " \"match_all\": {}" |
| 206 | + + " }," |
| 207 | + + " \"size\": 1," |
| 208 | + + " \"sort\": [" |
| 209 | + + " {" |
| 210 | + + " \"timestamp\": {" |
| 211 | + + " \"order\": \"desc\"" |
| 212 | + + " }" |
| 213 | + + " }" |
| 214 | + + " ]}" |
| 215 | + ) |
| 216 | + ); |
| 217 | + // Make sure all of the test data has been ingested |
| 218 | + // Expected response: |
| 219 | + // "_index":"synthetic","_type":"_doc","_id":"10080","_score":null,"_source":{"timestamp":"2019-11-08T00:00:00Z","Feature1":156.30028000000001,"Feature2":100.211205,"host":"host1"},"sort":[1573171200000]} |
| 220 | + Response response = client.performRequest(request); |
| 221 | + JsonObject json = JsonParser |
| 222 | + .parseReader(new InputStreamReader(response.getEntity().getContent(), Charset.defaultCharset())) |
| 223 | + .getAsJsonObject(); |
| 224 | + JsonArray hits = json.getAsJsonObject("hits").getAsJsonArray("hits"); |
| 225 | + if (hits != null |
| 226 | + && hits.size() == 1 |
| 227 | + && expectedSize - 1 == hits.get(0).getAsJsonObject().getAsJsonPrimitive("_id").getAsLong()) { |
| 228 | + break; |
| 229 | + } else { |
| 230 | + request = new Request("POST", String.format(Locale.ROOT, "/%s/_refresh", datasetName)); |
| 231 | + client.performRequest(request); |
| 232 | + } |
| 233 | + Thread.sleep(1_000); |
| 234 | + } while (maxWaitCycles-- >= 0); |
| 235 | + } |
| 236 | + |
| 237 | + protected void setWarningHandler(Request request, boolean strictDeprecationMode) { |
| 238 | + RequestOptions.Builder options = RequestOptions.DEFAULT.toBuilder(); |
| 239 | + options.setWarningsHandler(strictDeprecationMode ? WarningsHandler.STRICT : WarningsHandler.PERMISSIVE); |
| 240 | + request.setOptions(options.build()); |
| 241 | + } |
| 242 | +} |
0 commit comments