JCLOUDS-1598: Support Metric Alert Operation (#134)

This commit is contained in:
SATYANAN-ANAND 2022-02-25 10:12:43 -08:00 committed by GitHub
parent 99f2ff86da
commit 83deb0efef
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
15 changed files with 1096 additions and 0 deletions

View File

@ -31,6 +31,7 @@ import org.jclouds.azurecompute.arm.features.JobApi;
import org.jclouds.azurecompute.arm.features.LoadBalancerApi;
import org.jclouds.azurecompute.arm.features.LocalNetworkGatewayApi;
import org.jclouds.azurecompute.arm.features.LocationApi;
import org.jclouds.azurecompute.arm.features.MetricAlertApi;
import org.jclouds.azurecompute.arm.features.MetricDefinitionsApi;
import org.jclouds.azurecompute.arm.features.MetricsApi;
import org.jclouds.azurecompute.arm.features.NetworkInterfaceCardApi;
@ -315,4 +316,14 @@ public interface AzureComputeApi extends Closeable {
*/
@Delegate
AlertApi getAlertApi(@PathParam("resourceid") String resourceid);
/**
* The Metric Alert API includes operations to get insights available for
* entities within your subscription
*
* @see <a href=
* "https://docs.microsoft.com/en-us/rest/api/monitor/metric-alerts">docs</a>
*/
@Delegate
MetricAlertApi getMetricAlertApi(@PathParam("resourcegroup") String resourcegroup);
}

View File

@ -49,6 +49,7 @@ import org.jclouds.azurecompute.arm.features.ImageApi;
import org.jclouds.azurecompute.arm.features.LoadBalancerApi;
import org.jclouds.azurecompute.arm.features.LocalNetworkGatewayApi;
import org.jclouds.azurecompute.arm.features.LocationApi;
import org.jclouds.azurecompute.arm.features.MetricAlertApi;
import org.jclouds.azurecompute.arm.features.MetricDefinitionsApi;
import org.jclouds.azurecompute.arm.features.MetricsApi;
import org.jclouds.azurecompute.arm.features.NetworkInterfaceCardApi;
@ -140,6 +141,7 @@ public class AzureComputeProviderMetadata extends BaseProviderMetadata {
properties.put(API_VERSION_PREFIX + VirtualNetworkGatewayConnectionApi.class.getSimpleName(), "2018-02-01");
properties.put(API_VERSION_PREFIX + ActivityLogAlertApi.class.getSimpleName(), "2020-10-01");
properties.put(API_VERSION_PREFIX + AlertApi.class.getSimpleName(), "2019-03-01");
properties.put(API_VERSION_PREFIX + MetricAlertApi.class.getSimpleName(), "2018-03-01");
return properties;
}

View File

@ -0,0 +1,56 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jclouds.azurecompute.arm.domain;
import java.util.List;
import org.jclouds.javax.annotation.Nullable;
import org.jclouds.json.SerializedNames;
import com.google.auto.value.AutoValue;
@AutoValue
public abstract class Criteria {
@Nullable
public abstract List<MetricAlertCriteria> allOf();
@Nullable
public abstract String odatatype();
@SerializedNames({ "allOf", "odata.type" })
public static Criteria create(final List<MetricAlertCriteria> allOf,
final String odatatype) {
return builder().allOf(allOf).odatatype(odatatype).build();
}
public abstract Builder toBuilder();
public static Builder builder() {
return new AutoValue_Criteria.Builder();
}
@AutoValue.Builder
public abstract static class Builder {
public abstract Builder allOf(List<MetricAlertCriteria> allOf);
public abstract Builder odatatype(String odatatype);
public abstract Criteria build();
}
}

View File

@ -0,0 +1,37 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jclouds.azurecompute.arm.domain;
import org.jclouds.json.SerializedNames;
import com.google.auto.value.AutoValue;
@AutoValue
public abstract class DynamicThresholdFailingPeriods {
public abstract int minFailingPeriodsToAlert();
public abstract int numberOfEvaluationPeriods();
@SerializedNames({ "minFailingPeriodsToAlert", "numberOfEvaluationPeriods" })
public static DynamicThresholdFailingPeriods create(final int minFailingPeriodsToAlert,
final int numberOfEvaluationPeriods) {
return new AutoValue_DynamicThresholdFailingPeriods(minFailingPeriodsToAlert, numberOfEvaluationPeriods);
}
}

View File

@ -0,0 +1,91 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jclouds.azurecompute.arm.domain;
import java.util.Map;
import org.jclouds.javax.annotation.Nullable;
import org.jclouds.json.SerializedNames;
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableMap;
@AutoValue
public abstract class MetricAlert {
/**
* The id of the resource
*/
public abstract String id();
/**
* The name of the resource
*/
public abstract String name();
/**
* The location of the resource
*/
public abstract String location();
/**
* The type of the resource
*/
public abstract String type();
@Nullable
public abstract Map<String, String> tags();
@Nullable
public abstract MetricAlertProperties properties();
@SerializedNames({ "id", "name", "location", "type", "tags", "properties" })
public static MetricAlert create(final String id, final String name, final String location,
final String type, final Map<String, String> tags, final MetricAlertProperties properties) {
return builder().id(id).name(name).location(location).type(type).tags(tags).properties(properties).build();
}
public abstract Builder toBuilder();
public static Builder builder() {
return new AutoValue_MetricAlert.Builder();
}
@AutoValue.Builder
public abstract static class Builder {
public abstract Builder id(String id);
public abstract Builder name(String name);
public abstract Builder location(String location);
public abstract Builder type(String type);
public abstract Builder tags(Map<String, String> tags);
public abstract Builder properties(MetricAlertProperties properties);
abstract Map<String, String> tags();
abstract MetricAlert autoBuild();
public MetricAlert build() {
tags(tags() != null ? ImmutableMap.copyOf(tags()) : null);
return autoBuild();
}
}
}

View File

@ -0,0 +1,38 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jclouds.azurecompute.arm.domain;
import org.jclouds.javax.annotation.Nullable;
import org.jclouds.json.SerializedNames;
import com.google.auto.value.AutoValue;
@AutoValue
public abstract class MetricAlertAction {
@Nullable
public abstract String actionGroupId();
@Nullable
public abstract Object webhookProperties();
@SerializedNames({ "actionGroupId", "webhookProperties" })
public static MetricAlertAction create(final String actionGroupId, final Object webhookProperties) {
return new AutoValue_MetricAlertAction(actionGroupId, webhookProperties);
}
}

View File

@ -0,0 +1,116 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jclouds.azurecompute.arm.domain;
import java.util.List;
import org.jclouds.azurecompute.arm.util.GetEnumValue;
import org.jclouds.javax.annotation.Nullable;
import org.jclouds.json.SerializedNames;
import com.google.auto.value.AutoValue;
@AutoValue
public abstract class MetricAlertCriteria {
@Nullable
public abstract String criterionType();
@Nullable
public abstract List<MetricDimension> dimensions();
@Nullable
public abstract String metricName();
@Nullable
public abstract String metricNamespace();
@Nullable
public abstract String name();
@Nullable
public abstract Operator operator();
public abstract boolean skipMetricValidation();
public abstract int threshold();
@Nullable
public abstract AggregationTypeEnum timeAggregation();
@Nullable
public abstract DynamicThresholdSensitivity alertSensitivity();
@Nullable
public abstract DynamicThresholdFailingPeriods failingPeriods();
@Nullable
public abstract String ignoreDataBefore();
@Nullable
public abstract String componentId();
public abstract int failedLocationCount();
@Nullable
public abstract String webTestId();
@SerializedNames({ "criterionType", "dimensions", "metricName", "metricNamespace", "name", "operator",
"skipMetricValidation", "threshold", "timeAggregation", "alertSensitivity", "failingPeriods",
"ignoreDataBefore", "componentId", "failedLocationCount", "webTestId" })
public static MetricAlertCriteria create(final String criterionType, List<MetricDimension> dimensions,
final String metricName, final String metricNamespace, final String name, final Operator operator,
final boolean skipMetricValidation, final int threshold, final AggregationTypeEnum timeAggregation,
final DynamicThresholdSensitivity alertSensitivity, final DynamicThresholdFailingPeriods failingPeriods,
final String ignoreDataBefore, final String componentId, final int failedLocationCount,
final String webTestId) {
return new AutoValue_MetricAlertCriteria(criterionType, dimensions, metricName, metricNamespace, name, operator,
skipMetricValidation, threshold, timeAggregation, alertSensitivity, failingPeriods, ignoreDataBefore,
componentId, failedLocationCount, webTestId);
}
public enum AggregationTypeEnum {
Average, Count, Maximum, Minimum, Total;
public static AggregationTypeEnum fromValue(final String text) {
return (AggregationTypeEnum) GetEnumValue.fromValueOrDefault(text, AggregationTypeEnum.Average);
}
}
public enum Operator {
Equals, GreaterThan, GreaterThanOrEqual, LessThan, LessThanOrEqual, GreaterOrLessThan;
public static Operator fromValue(final String text) {
return (Operator) GetEnumValue.fromValueOrDefault(text, Operator.Equals);
}
}
public enum DynamicThresholdSensitivity {
High, Low, Medium;
public static DynamicThresholdSensitivity fromValue(final String text) {
return (DynamicThresholdSensitivity) GetEnumValue.fromValueOrDefault(text,
DynamicThresholdSensitivity.High);
}
}
public enum DynamicThresholdOperator {
GreaterOrLessThan, GreaterThan, LessThan;
public static DynamicThresholdOperator fromValue(final String text) {
return (DynamicThresholdOperator) GetEnumValue.fromValueOrDefault(text,
DynamicThresholdOperator.GreaterOrLessThan);
}
}
}

View File

@ -0,0 +1,117 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jclouds.azurecompute.arm.domain;
import java.util.Date;
import java.util.List;
import org.jclouds.javax.annotation.Nullable;
import org.jclouds.json.SerializedNames;
import com.google.auto.value.AutoValue;
@AutoValue
public abstract class MetricAlertProperties {
@Nullable
public abstract List<MetricAlertAction> actions();
public abstract boolean autoMitigate();
@Nullable
public abstract Criteria criteria();
@Nullable
public abstract String description();
public abstract boolean enabled();
@Nullable
public abstract String evaluationFrequency();
public abstract boolean isMigrated();
@Nullable
public abstract Date lastUpdatedTime();
@Nullable
public abstract List<String> scopes();
public abstract int severity();
@Nullable
public abstract String targetResourceRegion();
@Nullable
public abstract String targetResourceType();
@Nullable
public abstract String windowSize();
@SerializedNames({ "actions", "autoMitigate", "criteria", "description", "enabled", "evaluationFrequency",
"isMigrated", "lastUpdatedTime", "scopes", "severity", "targetResourceRegion", "targetResourceType",
"windowSize" })
public static MetricAlertProperties create(final List<MetricAlertAction> actions, final boolean autoMitigate,
final Criteria criteria, final String description, final boolean enabled, final String evaluationFrequency,
final boolean isMigrated, final Date lastUpdatedTime, final List<String> scopes, final int severity,
final String targetResourceRegion, final String targetResourceType, final String windowSize) {
return builder().actions(actions).criteria(criteria).autoMitigate(autoMitigate).description(description)
.enabled(enabled).evaluationFrequency(evaluationFrequency).isMigrated(isMigrated)
.lastUpdatedTime(lastUpdatedTime).scopes(scopes).severity(severity)
.targetResourceRegion(targetResourceRegion).targetResourceType(targetResourceType)
.windowSize(windowSize).build();
}
public abstract Builder toBuilder();
public static Builder builder() {
return new AutoValue_MetricAlertProperties.Builder();
}
@AutoValue.Builder
public abstract static class Builder {
public abstract Builder autoMitigate(boolean autoMitigate);
public abstract Builder description(String description);
public abstract Builder enabled(boolean enabled);
public abstract Builder evaluationFrequency(String evaluationFrequency);
public abstract Builder isMigrated(boolean isMigrated);
public abstract Builder lastUpdatedTime(Date lastUpdatedTime);
public abstract Builder severity(int severity);
public abstract Builder targetResourceRegion(String targetResourceRegion);
public abstract Builder targetResourceType(String targetResourceType);
public abstract Builder windowSize(String windowSize);
public abstract Builder scopes(List<String> scopes);
public abstract Builder actions(List<MetricAlertAction> actions);
public abstract Builder criteria(Criteria criteria);
public abstract MetricAlertProperties build();
}
}

View File

@ -0,0 +1,60 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jclouds.azurecompute.arm.domain;
import java.util.List;
import org.jclouds.javax.annotation.Nullable;
import org.jclouds.json.SerializedNames;
import com.google.auto.value.AutoValue;
@AutoValue
public abstract class MetricDimension {
@Nullable
public abstract String name();
@Nullable
public abstract String operator();
@Nullable
public abstract List<String> values();
@SerializedNames({ "name", "operator", "values" })
public static MetricDimension create(final String name, final String operator, final List<String> values) {
return builder().name(name).operator(operator).values(values).build();
}
public abstract Builder toBuilder();
public static Builder builder() {
return new AutoValue_MetricDimension.Builder();
}
@AutoValue.Builder
public abstract static class Builder {
public abstract Builder name(String name);
public abstract Builder operator(String operator);
public abstract Builder values(List<String> values);
public abstract MetricDimension build();
}
}

View File

@ -0,0 +1,87 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jclouds.azurecompute.arm.features;
import java.net.URI;
import java.util.List;
import java.util.Map;
import javax.inject.Named;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.MediaType;
import org.jclouds.Fallbacks;
import org.jclouds.azurecompute.arm.domain.MetricAlert;
import org.jclouds.azurecompute.arm.domain.MetricAlertProperties;
import org.jclouds.azurecompute.arm.filters.ApiVersionFilter;
import org.jclouds.azurecompute.arm.functions.URIParser;
import org.jclouds.oauth.v2.filters.OAuthFilter;
import org.jclouds.rest.annotations.Fallback;
import org.jclouds.rest.annotations.MapBinder;
import org.jclouds.rest.annotations.PayloadParam;
import org.jclouds.rest.annotations.QueryParams;
import org.jclouds.rest.annotations.RequestFilters;
import org.jclouds.rest.annotations.ResponseParser;
import org.jclouds.rest.annotations.SelectJson;
import org.jclouds.rest.binders.BindToJsonPayload;
/**
* The Metric Alert API includes operations for managing metric type alert rules
* in your subscription.
*
* @see <a href=
* "https://docs.microsoft.com/en-us/rest/api/monitor/metric-alerts">docs</a>
*/
@Path("/resourcegroups/{resourcegroup}/providers/Microsoft.Insights/metricAlerts")
@RequestFilters({ OAuthFilter.class, ApiVersionFilter.class })
@Consumes(MediaType.APPLICATION_JSON)
public interface MetricAlertApi {
@Named("metricalert:get")
@GET
@Path("/{name}")
@Fallback(Fallbacks.NullOnNotFoundOr404.class)
MetricAlert get(@PathParam("name") String name);
@Named("metricalert:list")
@GET
@SelectJson("value")
@Fallback(Fallbacks.EmptyListOnNotFoundOr404.class)
List<MetricAlert> list();
@Named("metricalert:createOrUpdate")
@PUT
@MapBinder(BindToJsonPayload.class)
@Path("/{ruleName}")
@QueryParams(keys = "validating", values = "false")
MetricAlert createOrUpdate(@PathParam("ruleName") String ruleName,
@PayloadParam("properties") MetricAlertProperties properties,
@PayloadParam("tags") Map<String, String> tags, @PayloadParam("location") String location);
@Named("metricalert:delete")
@DELETE
@Path("/{ruleName}")
@ResponseParser(URIParser.class)
@Fallback(Fallbacks.NullOnNotFoundOr404.class)
URI delete(@PathParam("ruleName") String ruleName);
}

View File

@ -0,0 +1,105 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jclouds.azurecompute.arm.features;
import static org.testng.Assert.assertTrue;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.jclouds.azurecompute.arm.domain.Criteria;
import org.jclouds.azurecompute.arm.domain.MetricAlert;
import org.jclouds.azurecompute.arm.domain.MetricAlertCriteria;
import org.jclouds.azurecompute.arm.domain.MetricAlertCriteria.Operator;
import org.jclouds.azurecompute.arm.domain.MetricAlertProperties;
import org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiLiveTest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
@Test(groups = "live", testName = "MetricAlertApiLiveTest", singleThreaded = true)
public class MetricAlertApiLiveTest extends BaseAzureComputeApiLiveTest {
private String alertRuleName;
private String subscriptionid;
private final String GLOBAL = "Global";
@BeforeClass
@Override
public void setup() {
super.setup();
subscriptionid = getSubscriptionId();
createTestResourceGroup();
alertRuleName = String.format("vn-%s-%s", this.getClass().getSimpleName().toLowerCase(),
System.getProperty("user.name"));
}
private MetricAlertApi api() {
return api.getMetricAlertApi(resourceGroupName);
}
@Test
public void testCreate() {
MetricAlert metricAlert = api().createOrUpdate(alertRuleName, getMetricAlertProperties(),
ImmutableMap.of("createdBy", "jclouds"), GLOBAL);
assertTrue(!metricAlert.type().isEmpty());
}
@Test(dependsOnMethods = "testCreate")
public void testGet() {
final MetricAlert rule = api().get(alertRuleName);
assertTrue(!rule.name().isEmpty());
}
@Test(dependsOnMethods = "testCreate")
public void testList() {
List<MetricAlert> list = api().list();
final MetricAlert rule = api().get(alertRuleName);
boolean alertRulePresent = Iterables.any(list, new Predicate<MetricAlert>() {
@Override
public boolean apply(@Nullable MetricAlert input) {
return input.name().equals(rule.name());
}
});
assertTrue(alertRulePresent);
}
@Test(dependsOnMethods = "testList", alwaysRun = true)
public void testDelete() throws Exception {
URI uri = api().delete(alertRuleName);
assertResourceDeleted(uri);
}
public MetricAlertProperties getMetricAlertProperties() {
final List<MetricAlertCriteria> lstMetricAlertCriteria = new ArrayList<>();
lstMetricAlertCriteria.add(MetricAlertCriteria.create("StaticThresholdCriterion", null, "CPU Credits Consumed",
"Microsoft.Compute/virtualMachines", "Metric1", Operator.GreaterThan, false, 0,
MetricAlertCriteria.AggregationTypeEnum.Average, null, null, null, null, 0, null));
final Criteria criteria = Criteria.create(lstMetricAlertCriteria,
"Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria");
return MetricAlertProperties.create(Collections.emptyList(), true, criteria, "", true, "PT5M", false, null,
Arrays.asList("/subscriptions/" + subscriptionid + "/resourceGroups/" + resourceGroupName), 3, "eastus",
"Microsoft.Compute/virtualMachines", "PT5M");
}
}

View File

@ -0,0 +1,212 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jclouds.azurecompute.arm.features;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.testng.Assert.assertEquals;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jclouds.azurecompute.arm.domain.Criteria;
import org.jclouds.azurecompute.arm.domain.MetricAlert;
import org.jclouds.azurecompute.arm.domain.MetricAlertAction;
import org.jclouds.azurecompute.arm.domain.MetricAlertCriteria;
import org.jclouds.azurecompute.arm.domain.MetricAlertCriteria.Operator;
import org.jclouds.azurecompute.arm.domain.MetricAlertProperties;
import org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiMockTest;
import org.testng.annotations.Test;
import okhttp3.mockwebserver.MockResponse;
@Test(groups = "unit", testName = "MetricAlertApiMockTest", singleThreaded = true)
public class MetricAlertApiMockTest extends BaseAzureComputeApiMockTest {
public void testList() throws InterruptedException {
server.enqueue(jsonResponse("/metricalertgetbyresource.json"));
final MetricAlertApi metricAlertApi = api.getMetricAlertApi("myResourceGroup");
List<MetricAlert> list = metricAlertApi.list();
assertEquals(list, getMetricAlertRuleList());
assertSent(server, "GET",
"/subscriptions/SUBSCRIPTIONID/resourcegroups/myResourceGroup/providers/Microsoft.Insights/metricAlerts?api-version=2018-03-01");
}
private List<MetricAlert> getMetricAlertRuleList() {
List<MetricAlert> metricAlertRules = new ArrayList<MetricAlert>();
metricAlertRules.add(MetricAlert.create(
"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/microsoft.insights/metricalerts/MetricAlert1",
"MetricAlert1", "global", "Microsoft.Insights/metricAlerts", Collections.emptyMap(),
myMetricAlertProperties0()));
metricAlertRules.add(MetricAlert.create(
"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/microsoft.insights/metricalerts/MetricAlert2",
"MetricAlert2", "global", "Microsoft.Insights/metricAlerts", Collections.emptyMap(),
myMetricAlertProperties1()));
return metricAlertRules;
}
public MetricAlertProperties myMetricAlertProperties0() {
return MetricAlertProperties.create(Collections.emptyList(), true, criteria0("Available Memory Bytes"),
"MetricAlert1", true, "PT1M", false, null, scope0(), 0, "eastus", "Microsoft.Compute/virtualMachines",
"PT1M");
}
public MetricAlertProperties myMetricAlertProperties1() {
return MetricAlertProperties.create(actions(), true, criteria1("Percentage CPU"), "", false, "PT1M", false,
null, scope1(), 3, "eastus", "Microsoft.Compute/virtualMachines", "PT5M");
}
public List<String> scope0() {
List<String> list = new ArrayList<String>();
list.add(
"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/LinuxVM");
list.add(
"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/CentOSVM");
return list;
}
public List<String> scope1() {
List<String> list = new ArrayList<String>();
list.add(
"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/LinuxVM");
return list;
}
public Criteria criteria0(String metricName) {
List<MetricAlertCriteria> lstMetricAlertCriteria = new ArrayList<>();
lstMetricAlertCriteria.add(MetricAlertCriteria.create("StaticThresholdCriterion", null, metricName,
"Microsoft.Compute/virtualMachines", "criteria1", Operator.GreaterThan, false, 0,
MetricAlertCriteria.AggregationTypeEnum.Total, null, null, null, null, 0, null));
final Criteria criteria = Criteria.create(lstMetricAlertCriteria,
"Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria");
return criteria;
}
public Criteria criteria1(String metricName) {
List<MetricAlertCriteria> lstMetricAlertCriteria = new ArrayList<>();
lstMetricAlertCriteria.add(MetricAlertCriteria.create("StaticThresholdCriterion", null, metricName,
"Microsoft.Compute/virtualMachines", "criteria1", Operator.GreaterThan, false, 0,
MetricAlertCriteria.AggregationTypeEnum.Average, null, null, null, null, 0, null));
final Criteria criteria = Criteria.create(lstMetricAlertCriteria,
"Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria");
return criteria;
}
public List<MetricAlertAction> actions() {
List<MetricAlertAction> list = new ArrayList<>();
MetricAlertAction actionGroup = MetricAlertAction.create(
"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/microsoft.insights/actionGroups/metricaction",
null);
list.add(actionGroup);
return list;
}
public void testListEmpty() throws Exception {
server.enqueue(new MockResponse().setResponseCode(404));
final MetricAlertApi metricAlertApi = api.getMetricAlertApi("myResourceGroup");
List<MetricAlert> list = metricAlertApi.list();
assertTrue(list.isEmpty());
assertSent(server, "GET",
"/subscriptions/SUBSCRIPTIONID/resourcegroups/myResourceGroup/providers/Microsoft.Insights/metricAlerts?api-version=2018-03-01");
}
public void testGet() throws InterruptedException {
server.enqueue(jsonResponse("/metricalertget.json"));
final MetricAlertApi metricAlerApi = api.getMetricAlertApi("myResourceGroup");
MetricAlert actual = metricAlerApi.get("MetricAlertTest");
MetricAlert expected = MetricAlert.create(
"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Insights/metricalerts/MetricAlertTest",
"MetricAlertTest", "global", "Microsoft.Insights/metricAlerts", tags(), getMetricAlertProperties());
assertEquals(expected, actual);
assertSent(server, "GET",
"/subscriptions/SUBSCRIPTIONID/resourcegroups/myResourceGroup/providers/Microsoft.Insights/metricAlerts/MetricAlertTest?api-version=2018-03-01");
}
public Map<String, String> tags() {
Map<String, String> tags = new HashMap<>();
tags.put("createdBy", "jclouds");
return tags;
}
public MetricAlertProperties getMetricAlertProperties() {
final List<MetricAlertAction> actionList = new ArrayList<>();
final MetricAlertAction action = MetricAlertAction.create(
"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/microsoft.insights/actiongroups/actionemail",
null);
actionList.add(action);
final List<MetricAlertCriteria> lstMetricAlertCriteria = new ArrayList<>();
lstMetricAlertCriteria.add(MetricAlertCriteria.create("StaticThresholdCriterion", null, "CPU Credits Consumed",
"Microsoft.Compute/virtualMachines", "Metric1", Operator.GreaterThan, false, 0,
MetricAlertCriteria.AggregationTypeEnum.Average, null, null, null, null, 0, null));
final Criteria criteria = Criteria.create(lstMetricAlertCriteria,
"Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria");
return MetricAlertProperties.create(actionList, true, criteria, "", false, "PT5M", false, null, scope1(), 3,
"eastus", "Microsoft.Compute/virtualMachines", "PT5M");
}
public void testGetReturns404() throws InterruptedException {
server.enqueue(response404());
final MetricAlertApi metricAlerApi = api.getMetricAlertApi("myResourceGroup");
MetricAlert alert = metricAlerApi.get("MetricAlertTest");
assertNull(alert);
assertSent(server, "GET",
"/subscriptions/SUBSCRIPTIONID/resourcegroups/myResourceGroup/providers/Microsoft.Insights/metricAlerts/MetricAlertTest?api-version=2018-03-01");
}
public void testDelete() throws Exception {
server.enqueue(response202WithHeader());
final MetricAlertApi metricAlerApi = api.getMetricAlertApi("myResourceGroup");
URI uri = metricAlerApi.delete("MetricAlertTest");
assertEquals(server.getRequestCount(), 1);
assertNotNull(uri);
assertSent(server, "DELETE",
"/subscriptions/SUBSCRIPTIONID/resourcegroups/myResourceGroup/providers/Microsoft.Insights/metricAlerts/MetricAlertTest?api-version=2018-03-01");
}
public void testDeleteReturns404() throws Exception {
server.enqueue(response404());
final MetricAlertApi metricAlerApi = api.getMetricAlertApi("myResourceGroup");
URI uri = metricAlerApi.delete("MetricAlertTest");
assertEquals(server.getRequestCount(), 1);
assertNull(uri);
assertSent(server, "DELETE",
"/subscriptions/SUBSCRIPTIONID/resourcegroups/myResourceGroup/providers/Microsoft.Insights/metricAlerts/MetricAlertTest?api-version=2018-03-01");
}
public void testCreate() throws Exception {
server.enqueue(jsonResponse("/metricalertcreateorupdate.json"));
final MetricAlertApi metricAlertApi = api.getMetricAlertApi("myResourceGroup");
MetricAlert alertRule = metricAlertApi.createOrUpdate("MetricAlertTest", getMetricAlertProperties(), tags(),
"global");
MetricAlert expected = MetricAlert.create(
"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Insights/metricalerts/MetricAlertTest",
"MetricAlertTest", "global", "Microsoft.Insights/metricAlerts", tags(), getMetricAlertProperties());
assertEquals(alertRule, expected);
assertSent(server, "PUT",
"/subscriptions/SUBSCRIPTIONID/resourcegroups/myResourceGroup/providers/Microsoft.Insights/metricAlerts/MetricAlertTest?validating=false&api-version=2018-03-01");
}
}

View File

@ -0,0 +1,42 @@
{
"id": "/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Insights/metricalerts/MetricAlertTest",
"name": "MetricAlertTest",
"type": "Microsoft.Insights/metricAlerts",
"location": "global",
"tags": {
"createdBy": "jclouds"
},
"properties": {
"description": "",
"severity": 3,
"enabled": false,
"scopes": [
"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/LinuxVM"
],
"evaluationFrequency": "PT5M",
"windowSize": "PT5M",
"criteria": {
"allOf": [
{
"threshold": 0,
"name": "Metric1",
"metricNamespace": "Microsoft.Compute/virtualMachines",
"metricName": "CPU Credits Consumed",
"operator": "GreaterThan",
"timeAggregation": "Average",
"criterionType": "StaticThresholdCriterion"
}
],
"odata.type": "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria"
},
"autoMitigate": true,
"targetResourceRegion": "eastus",
"targetResourceType":"Microsoft.Compute/virtualMachines",
"actions": [
{
"actionGroupId": "/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/microsoft.insights/actiongroups/actionemail",
"webHookProperties": {}
}
]
}
}

View File

@ -0,0 +1,42 @@
{
"id": "/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Insights/metricalerts/MetricAlertTest",
"name": "MetricAlertTest",
"type": "Microsoft.Insights/metricAlerts",
"location": "global",
"tags": {
"createdBy": "jclouds"
},
"properties": {
"description": "",
"severity": 3,
"enabled": false,
"scopes": [
"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/LinuxVM"
],
"evaluationFrequency": "PT5M",
"windowSize": "PT5M",
"criteria": {
"allOf": [
{
"threshold": 0,
"name": "Metric1",
"metricNamespace": "Microsoft.Compute/virtualMachines",
"metricName": "CPU Credits Consumed",
"operator": "GreaterThan",
"timeAggregation": "Average",
"criterionType": "StaticThresholdCriterion"
}
],
"odata.type": "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria"
},
"autoMitigate": true,
"targetResourceRegion": "eastus",
"targetResourceType":"Microsoft.Compute/virtualMachines",
"actions": [
{
"actionGroupId": "/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/microsoft.insights/actiongroups/actionemail",
"webHookProperties": {}
}
]
}
}

View File

@ -0,0 +1,80 @@
{
"value": [
{
"id": "/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/microsoft.insights/metricalerts/MetricAlert1",
"name": "MetricAlert1",
"type": "Microsoft.Insights/metricAlerts",
"location": "global",
"tags": {},
"properties": {
"description": "MetricAlert1",
"severity": 0,
"enabled": true,
"scopes": [
"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/LinuxVM",
"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/CentOSVM"
],
"evaluationFrequency": "PT1M",
"windowSize": "PT1M",
"criteria": {
"allOf": [
{
"threshold": 0,
"name": "criteria1",
"metricNamespace": "Microsoft.Compute/virtualMachines",
"metricName": "Available Memory Bytes",
"operator": "GreaterThan",
"timeAggregation": "Total",
"criterionType": "StaticThresholdCriterion"
}
],
"odata.type": "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria"
},
"autoMitigate": true,
"targetResourceType": "Microsoft.Compute/virtualMachines",
"targetResourceRegion": "eastus",
"actions": []
}
},
{
"id": "/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/microsoft.insights/metricalerts/MetricAlert2",
"name": "MetricAlert2",
"type": "Microsoft.Insights/metricAlerts",
"location": "global",
"tags": {},
"properties": {
"description": "",
"severity": 3,
"enabled": false,
"scopes": [
"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/LinuxVM"
],
"evaluationFrequency": "PT1M",
"windowSize": "PT5M",
"criteria": {
"allOf": [
{
"threshold": 0,
"name": "criteria1",
"metricNamespace": "Microsoft.Compute/virtualMachines",
"metricName": "Percentage CPU",
"operator": "GreaterThan",
"timeAggregation": "Average",
"criterionType": "StaticThresholdCriterion"
}
],
"odata.type": "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria"
},
"autoMitigate": true,
"targetResourceType": "Microsoft.Compute/virtualMachines",
"targetResourceRegion": "eastus",
"actions": [
{
"actionGroupId": "/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/microsoft.insights/actionGroups/metricaction",
"webHookProperties": {}
}
]
}
}
]
}