Skip to content

Commit

Permalink
Adding the ITs for the support of Date Math Index Resolution and a fi…
Browse files Browse the repository at this point in the history
…x for moving the alert to the error state in case of not being able to publish the emails (#113)
  • Loading branch information
adityaj1107 authored Jun 30, 2021
1 parent 2a35c0c commit d6371ff
Show file tree
Hide file tree
Showing 5 changed files with 49 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ fun isValidEmail(email: String): Boolean {
fun Destination.isAllowed(allowList: List<String>): Boolean = allowList.contains(this.type.value)

fun BaseMessage.isHostInDenylist(networks: List<String>): Boolean {
if (this.url != null) {
if (this.url != null || this.uri.host != null) {
val ipStr = IPAddressString(this.uri.host)
for (network in networks) {
val netStr = IPAddressString(network)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,13 +52,15 @@ import org.opensearch.index.query.QueryBuilders
import org.opensearch.rest.RestStatus
import org.opensearch.script.Script
import org.opensearch.search.builder.SearchSourceBuilder
import java.net.URLEncoder
import java.time.Instant
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import java.time.temporal.ChronoUnit
import java.time.temporal.ChronoUnit.DAYS
import java.time.temporal.ChronoUnit.MILLIS
import java.time.temporal.ChronoUnit.MINUTES
import kotlin.collections.HashMap

class MonitorRunnerIT : AlertingRestTestCase() {

Expand Down Expand Up @@ -370,6 +372,46 @@ class MonitorRunnerIT : AlertingRestTestCase() {
assertEquals("Alert saved for test monitor", 0, alerts.size)
}

fun `test execute monitor search with date math`() {
// Give the index name in the date math format.
val testIndex = "<my-index-{now/d{YYYY.MM.dd|+12:00}}>"
// Add percent encoding for the http client to resolve the format.
val encodedTestIndex = createTestIndex(
URLEncoder.encode(testIndex, "utf-8")
)

val fiveDaysAgo = ZonedDateTime.now().minus(5, DAYS).truncatedTo(MILLIS)
val testTime = DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(fiveDaysAgo)
val testDoc = """{ "test_strict_date_time" : "$testTime" }"""
indexDoc(encodedTestIndex, "1", testDoc)

// Queries that use period_start/end should expect these values to always be formatted as 'epoch_millis'. Either
// the query should specify the format (like below) or the mapping for the index/field being queried should allow
// epoch_millis as an alternative (OpenSearch's default mapping for date fields "strict_date_optional_time||epoch_millis")
val query = QueryBuilders.rangeQuery("test_strict_date_time")
.gt("{{period_end}}||-10d")
.lte("{{period_end}}")
.format("epoch_millis")
val input = SearchInput(indices = listOf(testIndex), query = SearchSourceBuilder().query(query))
val triggerScript = """
// make sure there is exactly one hit
return ctx.results[0].hits.hits.size() == 1
""".trimIndent()
val trigger = randomTrigger(condition = Script(triggerScript))
val monitor = randomMonitor(inputs = listOf(input), triggers = listOf(trigger))

val response = executeMonitor(monitor, params = DRYRUN_MONITOR)

val output = entityAsMap(response)

assertEquals(monitor.name, output["monitor_name"])
@Suppress("UNCHECKED_CAST")
val searchResult = (output.objectMap("input_results")["results"] as List<Map<String, Any>>).first()
@Suppress("UNCHECKED_CAST")
val total = searchResult.stringMap("hits")?.get("total") as Map<String, String>
assertEquals("Incorrect search result", 1, total["value"])
}

fun `test monitor with one bad action and one good action`() {
val goodAction = randomAction(template = randomTemplateScript("Hello {{ctx.monitor.name}}"), destinationId = createDestination().id)
val syntaxErrorAction = randomAction(
Expand Down Expand Up @@ -709,7 +751,7 @@ class MonitorRunnerIT : AlertingRestTestCase() {
)
}

fun `test execute monitor with email destination creates alert`() {
fun `test execute monitor with email destination creates alerts in error state`() {
putAlertMappings() // Required as we do not have a create alert API.

val emailAccount = createRandomEmailAccount()
Expand Down Expand Up @@ -742,7 +784,8 @@ class MonitorRunnerIT : AlertingRestTestCase() {

val alerts = searchAlerts(monitor)
assertEquals("Alert not saved", 1, alerts.size)
verifyAlert(alerts.single(), monitor, ACTIVE)
verifyAlert(alerts.single(), monitor, ERROR)
Assert.assertTrue(alerts.single().errorMessage?.contains("Failed running action") as Boolean)
}

fun `test execute monitor with custom webhook destination`() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ class AlertingUtilsTests : OpenSearchTestCase() {

private fun createMessageWithHost(host: String): BaseMessage {
return CustomWebhookMessage.Builder("abc")
.withUrl(host)
.withHost(host)
.withPath("incomingwebhooks/383c0e2b-d028-44f4-8d38-696754bc4574")
.withMessage("{\"Content\":\"Message test\"}")
.withMethod("POST")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ protected PasswordAuthentication getPasswordAuthentication() {

SendMessage(mailmsg);
} catch (MessagingException e) {
return e.getMessage();
throw new MessagingException(e.getMessage());
}
}
return "Sent";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ public void testMailMessageWithAuth() throws Exception {
assertEquals(expectedEmailResponse.getStatusCode(), actualEmailResponse.getStatusCode());
}

@Test
@Test(expected = IllegalStateException.class)
public void testFailingMailMessage() throws Exception {

DestinationResponse expectedEmailResponse = new DestinationResponse.Builder()
Expand Down

0 comments on commit d6371ff

Please sign in to comment.