From c3fcd93bf7b10b7fd8524873a63afdb6f47889e9 Mon Sep 17 00:00:00 2001 From: Peng Jiahui <46921893+Alancere@users.noreply.github.com> Date: Tue, 27 Feb 2024 16:00:55 +0800 Subject: [PATCH] [Release] sdk/resourcemanager/alertsmanagement/armalertsmanagement/0.10.0 (#22451) * [Release] sdk/resourcemanager/alertsmanagement/armalertsmanagement/0.10.0 generation from spec commit: 6d2438481021a94793b07b226df06d5f3c61d51d * add removeUnreferencedTypes flag --- .../armalertsmanagement/CHANGELOG.md | 52 + .../armalertsmanagement/README.md | 2 +- ...lertprocessingrules_client_example_test.go | 22 +- .../alertrulerecommendations_client.go | 154 +++ ...rulerecommendations_client_example_test.go | 1123 +++++++++++++++++ .../armalertsmanagement/alerts_client.go | 94 +- .../alerts_client_example_test.go | 12 +- .../armalertsmanagement/autorest.md | 7 +- .../armalertsmanagement/build.go | 2 +- .../armalertsmanagement/client_factory.go | 55 +- .../armalertsmanagement/constants.go | 2 +- .../fake/alertrulerecommendations_server.go | 154 +++ .../armalertsmanagement/fake/alerts_server.go | 2 +- .../fake/prometheusrulegroups_server.go | 307 +++++ .../fake/server_factory.go | 41 +- .../fake/tenantactivitylogalerts_server.go | 308 +++++ .../armalertsmanagement/fake/time_rfc3339.go | 42 +- .../armalertsmanagement/models.go | 399 ++++-- .../armalertsmanagement/models_serde.go | 1071 ++++++++++++---- .../operations_client_example_test.go | 2 +- .../armalertsmanagement/options.go | 82 +- .../polymorphic_helpers.go | 10 +- .../prometheusrulegroups_client.go | 419 ++++++ ...rometheusrulegroups_client_example_test.go | 473 +++++++ .../{response_types.go => responses.go} | 82 ++ .../armalertsmanagement/smartgroups_client.go | 34 +- .../smartgroups_client_example_test.go | 8 +- .../tenantactivitylogalerts_client.go | 392 ++++++ ...ntactivitylogalerts_client_example_test.go | 381 ++++++ .../armalertsmanagement/time_rfc3339.go | 42 +- 30 files changed, 5288 insertions(+), 486 deletions(-) create mode 100644 sdk/resourcemanager/alertsmanagement/armalertsmanagement/alertrulerecommendations_client.go create mode 100644 sdk/resourcemanager/alertsmanagement/armalertsmanagement/alertrulerecommendations_client_example_test.go create mode 100644 sdk/resourcemanager/alertsmanagement/armalertsmanagement/fake/alertrulerecommendations_server.go create mode 100644 sdk/resourcemanager/alertsmanagement/armalertsmanagement/fake/prometheusrulegroups_server.go create mode 100644 sdk/resourcemanager/alertsmanagement/armalertsmanagement/fake/tenantactivitylogalerts_server.go create mode 100644 sdk/resourcemanager/alertsmanagement/armalertsmanagement/prometheusrulegroups_client.go create mode 100644 sdk/resourcemanager/alertsmanagement/armalertsmanagement/prometheusrulegroups_client_example_test.go rename sdk/resourcemanager/alertsmanagement/armalertsmanagement/{response_types.go => responses.go} (57%) create mode 100644 sdk/resourcemanager/alertsmanagement/armalertsmanagement/tenantactivitylogalerts_client.go create mode 100644 sdk/resourcemanager/alertsmanagement/armalertsmanagement/tenantactivitylogalerts_client_example_test.go diff --git a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/CHANGELOG.md b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/CHANGELOG.md index 2702dd0a90d8..9b9abe1626af 100644 --- a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/CHANGELOG.md +++ b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/CHANGELOG.md @@ -1,5 +1,57 @@ # Release History +## 0.10.0 (2024-03-01) +### Breaking Changes + +- Type of `AlertsClientChangeStateOptions.Comment` has been changed from `*string` to `*Comments` + +### Features Added + +- New function `NewAlertRuleRecommendationsClient(string, azcore.TokenCredential, *arm.ClientOptions) (*AlertRuleRecommendationsClient, error)` +- New function `*AlertRuleRecommendationsClient.NewListByResourcePager(string, *AlertRuleRecommendationsClientListByResourceOptions) *runtime.Pager[AlertRuleRecommendationsClientListByResourceResponse]` +- New function `*AlertRuleRecommendationsClient.NewListByTargetTypePager(string, *AlertRuleRecommendationsClientListByTargetTypeOptions) *runtime.Pager[AlertRuleRecommendationsClientListByTargetTypeResponse]` +- New function `*ClientFactory.NewAlertRuleRecommendationsClient() *AlertRuleRecommendationsClient` +- New function `*ClientFactory.NewPrometheusRuleGroupsClient() *PrometheusRuleGroupsClient` +- New function `*ClientFactory.NewTenantActivityLogAlertsClient() *TenantActivityLogAlertsClient` +- New function `NewPrometheusRuleGroupsClient(string, azcore.TokenCredential, *arm.ClientOptions) (*PrometheusRuleGroupsClient, error)` +- New function `*PrometheusRuleGroupsClient.CreateOrUpdate(context.Context, string, string, PrometheusRuleGroupResource, *PrometheusRuleGroupsClientCreateOrUpdateOptions) (PrometheusRuleGroupsClientCreateOrUpdateResponse, error)` +- New function `*PrometheusRuleGroupsClient.Delete(context.Context, string, string, *PrometheusRuleGroupsClientDeleteOptions) (PrometheusRuleGroupsClientDeleteResponse, error)` +- New function `*PrometheusRuleGroupsClient.Get(context.Context, string, string, *PrometheusRuleGroupsClientGetOptions) (PrometheusRuleGroupsClientGetResponse, error)` +- New function `*PrometheusRuleGroupsClient.NewListByResourceGroupPager(string, *PrometheusRuleGroupsClientListByResourceGroupOptions) *runtime.Pager[PrometheusRuleGroupsClientListByResourceGroupResponse]` +- New function `*PrometheusRuleGroupsClient.NewListBySubscriptionPager(*PrometheusRuleGroupsClientListBySubscriptionOptions) *runtime.Pager[PrometheusRuleGroupsClientListBySubscriptionResponse]` +- New function `*PrometheusRuleGroupsClient.Update(context.Context, string, string, PrometheusRuleGroupResourcePatch, *PrometheusRuleGroupsClientUpdateOptions) (PrometheusRuleGroupsClientUpdateResponse, error)` +- New function `NewTenantActivityLogAlertsClient(azcore.TokenCredential, *arm.ClientOptions) (*TenantActivityLogAlertsClient, error)` +- New function `*TenantActivityLogAlertsClient.CreateOrUpdate(context.Context, string, string, TenantActivityLogAlertResource, *TenantActivityLogAlertsClientCreateOrUpdateOptions) (TenantActivityLogAlertsClientCreateOrUpdateResponse, error)` +- New function `*TenantActivityLogAlertsClient.Delete(context.Context, string, string, *TenantActivityLogAlertsClientDeleteOptions) (TenantActivityLogAlertsClientDeleteResponse, error)` +- New function `*TenantActivityLogAlertsClient.Get(context.Context, string, string, *TenantActivityLogAlertsClientGetOptions) (TenantActivityLogAlertsClientGetResponse, error)` +- New function `*TenantActivityLogAlertsClient.NewListByManagementGroupPager(string, *TenantActivityLogAlertsClientListByManagementGroupOptions) *runtime.Pager[TenantActivityLogAlertsClientListByManagementGroupResponse]` +- New function `*TenantActivityLogAlertsClient.NewListByTenantPager(*TenantActivityLogAlertsClientListByTenantOptions) *runtime.Pager[TenantActivityLogAlertsClientListByTenantResponse]` +- New function `*TenantActivityLogAlertsClient.Update(context.Context, string, string, TenantAlertRulePatchObject, *TenantActivityLogAlertsClientUpdateOptions) (TenantActivityLogAlertsClientUpdateResponse, error)` +- New struct `ActionGroup` +- New struct `ActionList` +- New struct `AlertRuleAllOfCondition` +- New struct `AlertRuleAnyOfOrLeafCondition` +- New struct `AlertRuleLeafCondition` +- New struct `AlertRuleProperties` +- New struct `AlertRuleRecommendationProperties` +- New struct `AlertRuleRecommendationResource` +- New struct `AlertRuleRecommendationsListResponse` +- New struct `Comments` +- New struct `PrometheusRule` +- New struct `PrometheusRuleGroupAction` +- New struct `PrometheusRuleGroupProperties` +- New struct `PrometheusRuleGroupResource` +- New struct `PrometheusRuleGroupResourceCollection` +- New struct `PrometheusRuleGroupResourcePatch` +- New struct `PrometheusRuleGroupResourcePatchProperties` +- New struct `PrometheusRuleResolveConfiguration` +- New struct `RuleArmTemplate` +- New struct `TenantActivityLogAlertResource` +- New struct `TenantAlertRuleList` +- New struct `TenantAlertRulePatchObject` +- New struct `TenantAlertRulePatchProperties` + + ## 0.9.0 (2023-11-24) ### Features Added diff --git a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/README.md b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/README.md index 9d6f92f683c8..ac93f95d5c34 100644 --- a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/README.md +++ b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/README.md @@ -57,7 +57,7 @@ clientFactory, err := armalertsmanagement.NewClientFactory(, cr A client groups a set of related APIs, providing access to its functionality. Create one or more clients to access the APIs you require using client factory. ```go -client := clientFactory.NewAlertsClient() +client := clientFactory.NewAlertProcessingRulesClient() ``` ## Fakes diff --git a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/alertprocessingrules_client_example_test.go b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/alertprocessingrules_client_example_test.go index 734cc9e11a65..0ce3a001d462 100644 --- a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/alertprocessingrules_client_example_test.go +++ b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/alertprocessingrules_client_example_test.go @@ -18,7 +18,7 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/alertsmanagement/armalertsmanagement" ) -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/a436672b07fb1fe276c203b086b3f0e0d0c4aa24/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/stable/2021-08-08/examples/AlertProcessingRules_List_Subscription.json +// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/6d2438481021a94793b07b226df06d5f3c61d51d/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/stable/2021-08-08/examples/AlertProcessingRules_List_Subscription.json func ExampleAlertProcessingRulesClient_NewListBySubscriptionPager() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { @@ -146,7 +146,7 @@ func ExampleAlertProcessingRulesClient_NewListBySubscriptionPager() { } } -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/a436672b07fb1fe276c203b086b3f0e0d0c4aa24/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/stable/2021-08-08/examples/AlertProcessingRules_List_ResourceGroup.json +// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/6d2438481021a94793b07b226df06d5f3c61d51d/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/stable/2021-08-08/examples/AlertProcessingRules_List_ResourceGroup.json func ExampleAlertProcessingRulesClient_NewListByResourceGroupPager() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { @@ -281,7 +281,7 @@ func ExampleAlertProcessingRulesClient_NewListByResourceGroupPager() { } } -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/a436672b07fb1fe276c203b086b3f0e0d0c4aa24/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/stable/2021-08-08/examples/AlertProcessingRules_GetById.json +// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/6d2438481021a94793b07b226df06d5f3c61d51d/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/stable/2021-08-08/examples/AlertProcessingRules_GetById.json func ExampleAlertProcessingRulesClient_GetByName() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { @@ -376,7 +376,7 @@ func ExampleAlertProcessingRulesClient_GetByName() { // } } -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/a436672b07fb1fe276c203b086b3f0e0d0c4aa24/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/stable/2021-08-08/examples/AlertProcessingRules_Create_or_update_add_action_group_all_alerts_in_subscription.json +// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/6d2438481021a94793b07b226df06d5f3c61d51d/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/stable/2021-08-08/examples/AlertProcessingRules_Create_or_update_add_action_group_all_alerts_in_subscription.json func ExampleAlertProcessingRulesClient_CreateOrUpdate_createOrUpdateARuleThatAddsAnActionGroupToAllAlertsInASubscription() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { @@ -439,7 +439,7 @@ func ExampleAlertProcessingRulesClient_CreateOrUpdate_createOrUpdateARuleThatAdd // } } -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/a436672b07fb1fe276c203b086b3f0e0d0c4aa24/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/stable/2021-08-08/examples/AlertProcessingRules_Create_or_update_add_two_action_groups_all_Sev0_Sev1_two_resource_groups.json +// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/6d2438481021a94793b07b226df06d5f3c61d51d/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/stable/2021-08-08/examples/AlertProcessingRules_Create_or_update_add_two_action_groups_all_Sev0_Sev1_two_resource_groups.json func ExampleAlertProcessingRulesClient_CreateOrUpdate_createOrUpdateARuleThatAddsTwoActionGroupsToAllSev0AndSev1AlertsInTwoResourceGroups() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { @@ -522,7 +522,7 @@ func ExampleAlertProcessingRulesClient_CreateOrUpdate_createOrUpdateARuleThatAdd // } } -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/a436672b07fb1fe276c203b086b3f0e0d0c4aa24/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/stable/2021-08-08/examples/AlertProcessingRules_Create_or_update_remove_all_action_groups_specific_VM_one-off_maintenance_window.json +// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/6d2438481021a94793b07b226df06d5f3c61d51d/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/stable/2021-08-08/examples/AlertProcessingRules_Create_or_update_remove_all_action_groups_specific_VM_one-off_maintenance_window.json func ExampleAlertProcessingRulesClient_CreateOrUpdate_createOrUpdateARuleThatRemovesAllActionGroupsFromAlertsOnASpecificVmDuringAOneOffMaintenanceWindow18002000AtASpecificDatePacificStandardTime() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { @@ -591,7 +591,7 @@ func ExampleAlertProcessingRulesClient_CreateOrUpdate_createOrUpdateARuleThatRem // } } -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/a436672b07fb1fe276c203b086b3f0e0d0c4aa24/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/stable/2021-08-08/examples/AlertProcessingRules_Create_or_update_remove_all_action_groups_from_specific_alert_rule.json +// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/6d2438481021a94793b07b226df06d5f3c61d51d/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/stable/2021-08-08/examples/AlertProcessingRules_Create_or_update_remove_all_action_groups_from_specific_alert_rule.json func ExampleAlertProcessingRulesClient_CreateOrUpdate_createOrUpdateARuleThatRemovesAllActionGroupsFromAllAlertsInASubscriptionComingFromASpecificAlertRule() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { @@ -664,7 +664,7 @@ func ExampleAlertProcessingRulesClient_CreateOrUpdate_createOrUpdateARuleThatRem // } } -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/a436672b07fb1fe276c203b086b3f0e0d0c4aa24/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/stable/2021-08-08/examples/AlertProcessingRules_Create_or_update_remove_all_action_groups_recurring_maintenance_window.json +// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/6d2438481021a94793b07b226df06d5f3c61d51d/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/stable/2021-08-08/examples/AlertProcessingRules_Create_or_update_remove_all_action_groups_recurring_maintenance_window.json func ExampleAlertProcessingRulesClient_CreateOrUpdate_createOrUpdateARuleThatRemovesAllActionGroupsFromAllAlertsOnAnyVmInTwoResourceGroupsDuringARecurringMaintenanceWindow22000400EverySatAndSunIndiaStandardTime() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { @@ -763,7 +763,7 @@ func ExampleAlertProcessingRulesClient_CreateOrUpdate_createOrUpdateARuleThatRem // } } -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/a436672b07fb1fe276c203b086b3f0e0d0c4aa24/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/stable/2021-08-08/examples/AlertProcessingRules_Create_or_update_remove_all_action_groups_outside_business_hours.json +// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/6d2438481021a94793b07b226df06d5f3c61d51d/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/stable/2021-08-08/examples/AlertProcessingRules_Create_or_update_remove_all_action_groups_outside_business_hours.json func ExampleAlertProcessingRulesClient_CreateOrUpdate_createOrUpdateARuleThatRemovesAllActionGroupsOutsideBusinessHoursMonFri09001700EasternStandardTime() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { @@ -852,7 +852,7 @@ func ExampleAlertProcessingRulesClient_CreateOrUpdate_createOrUpdateARuleThatRem // } } -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/a436672b07fb1fe276c203b086b3f0e0d0c4aa24/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/stable/2021-08-08/examples/AlertProcessingRules_Delete.json +// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/6d2438481021a94793b07b226df06d5f3c61d51d/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/stable/2021-08-08/examples/AlertProcessingRules_Delete.json func ExampleAlertProcessingRulesClient_Delete() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { @@ -869,7 +869,7 @@ func ExampleAlertProcessingRulesClient_Delete() { } } -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/a436672b07fb1fe276c203b086b3f0e0d0c4aa24/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/stable/2021-08-08/examples/AlertProcessingRules_Patch.json +// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/6d2438481021a94793b07b226df06d5f3c61d51d/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/stable/2021-08-08/examples/AlertProcessingRules_Patch.json func ExampleAlertProcessingRulesClient_Update() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { diff --git a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/alertrulerecommendations_client.go b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/alertrulerecommendations_client.go new file mode 100644 index 000000000000..f8c3a576cc91 --- /dev/null +++ b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/alertrulerecommendations_client.go @@ -0,0 +1,154 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armalertsmanagement + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// AlertRuleRecommendationsClient contains the methods for the AlertRuleRecommendations group. +// Don't use this type directly, use NewAlertRuleRecommendationsClient() instead. +type AlertRuleRecommendationsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewAlertRuleRecommendationsClient creates a new instance of AlertRuleRecommendationsClient with the specified values. +// - subscriptionID - The ID of the target subscription. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewAlertRuleRecommendationsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*AlertRuleRecommendationsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &AlertRuleRecommendationsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// NewListByResourcePager - Retrieve alert rule recommendations for a resource. +// +// Generated from API version 2023-01-01-preview +// - resourceURI - The identifier of the resource. +// - options - AlertRuleRecommendationsClientListByResourceOptions contains the optional parameters for the AlertRuleRecommendationsClient.NewListByResourcePager +// method. +func (client *AlertRuleRecommendationsClient) NewListByResourcePager(resourceURI string, options *AlertRuleRecommendationsClientListByResourceOptions) *runtime.Pager[AlertRuleRecommendationsClientListByResourceResponse] { + return runtime.NewPager(runtime.PagingHandler[AlertRuleRecommendationsClientListByResourceResponse]{ + More: func(page AlertRuleRecommendationsClientListByResourceResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *AlertRuleRecommendationsClientListByResourceResponse) (AlertRuleRecommendationsClientListByResourceResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "AlertRuleRecommendationsClient.NewListByResourcePager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByResourceCreateRequest(ctx, resourceURI, options) + }, nil) + if err != nil { + return AlertRuleRecommendationsClientListByResourceResponse{}, err + } + return client.listByResourceHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceCreateRequest creates the ListByResource request. +func (client *AlertRuleRecommendationsClient) listByResourceCreateRequest(ctx context.Context, resourceURI string, options *AlertRuleRecommendationsClientListByResourceOptions) (*policy.Request, error) { + urlPath := "/{resourceUri}/providers/Microsoft.AlertsManagement/alertRuleRecommendations" + urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", resourceURI) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceHandleResponse handles the ListByResource response. +func (client *AlertRuleRecommendationsClient) listByResourceHandleResponse(resp *http.Response) (AlertRuleRecommendationsClientListByResourceResponse, error) { + result := AlertRuleRecommendationsClientListByResourceResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AlertRuleRecommendationsListResponse); err != nil { + return AlertRuleRecommendationsClientListByResourceResponse{}, err + } + return result, nil +} + +// NewListByTargetTypePager - Retrieve alert rule recommendations for a target type. +// +// Generated from API version 2023-01-01-preview +// - targetType - The recommendations target type. +// - options - AlertRuleRecommendationsClientListByTargetTypeOptions contains the optional parameters for the AlertRuleRecommendationsClient.NewListByTargetTypePager +// method. +func (client *AlertRuleRecommendationsClient) NewListByTargetTypePager(targetType string, options *AlertRuleRecommendationsClientListByTargetTypeOptions) *runtime.Pager[AlertRuleRecommendationsClientListByTargetTypeResponse] { + return runtime.NewPager(runtime.PagingHandler[AlertRuleRecommendationsClientListByTargetTypeResponse]{ + More: func(page AlertRuleRecommendationsClientListByTargetTypeResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *AlertRuleRecommendationsClientListByTargetTypeResponse) (AlertRuleRecommendationsClientListByTargetTypeResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "AlertRuleRecommendationsClient.NewListByTargetTypePager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByTargetTypeCreateRequest(ctx, targetType, options) + }, nil) + if err != nil { + return AlertRuleRecommendationsClientListByTargetTypeResponse{}, err + } + return client.listByTargetTypeHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByTargetTypeCreateRequest creates the ListByTargetType request. +func (client *AlertRuleRecommendationsClient) listByTargetTypeCreateRequest(ctx context.Context, targetType string, options *AlertRuleRecommendationsClientListByTargetTypeOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/alertRuleRecommendations" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-01-01-preview") + reqQP.Set("targetType", targetType) + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByTargetTypeHandleResponse handles the ListByTargetType response. +func (client *AlertRuleRecommendationsClient) listByTargetTypeHandleResponse(resp *http.Response) (AlertRuleRecommendationsClientListByTargetTypeResponse, error) { + result := AlertRuleRecommendationsClientListByTargetTypeResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AlertRuleRecommendationsListResponse); err != nil { + return AlertRuleRecommendationsClientListByTargetTypeResponse{}, err + } + return result, nil +} diff --git a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/alertrulerecommendations_client_example_test.go b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/alertrulerecommendations_client_example_test.go new file mode 100644 index 000000000000..6ea78d57300c --- /dev/null +++ b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/alertrulerecommendations_client_example_test.go @@ -0,0 +1,1123 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// DO NOT EDIT. + +package armalertsmanagement_test + +import ( + "context" + "log" + + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/alertsmanagement/armalertsmanagement" +) + +// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/6d2438481021a94793b07b226df06d5f3c61d51d/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2023-01-01-preview/examples/AlertRuleRecommendations_GetByResource_MAC.json +func ExampleAlertRuleRecommendationsClient_NewListByResourcePager_listAlertRuleRecommendationsForMonitoringAccountsAtResourceLevel() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armalertsmanagement.NewClientFactory("", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + pager := clientFactory.NewAlertRuleRecommendationsClient().NewListByResourcePager("subscriptions/2f00cc51-6809-498f-9ffc-48c42aff570d/resourceGroups/GenevaAlertRP-RunnerResources-eastus/providers/microsoft.monitor/accounts/alertsrp-eastus-pgms", nil) + for pager.More() { + page, err := pager.NextPage(ctx) + if err != nil { + log.Fatalf("failed to advance page: %v", err) + } + for _, v := range page.Value { + // You could use page here. We use blank identifier for just demo purposes. + _ = v + } + // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // page.AlertRuleRecommendationsListResponse = armalertsmanagement.AlertRuleRecommendationsListResponse{ + // Value: []*armalertsmanagement.AlertRuleRecommendationResource{ + // { + // Name: to.Ptr("NodeRecordingRulesRuleGroup"), + // Type: to.Ptr("Microsoft.AlertsManagement/alertRuleRecommendations"), + // ID: to.Ptr("/subscriptions/2f00cc51-6809-498f-9ffc-48c42aff570d/resourceGroups/GenevaAlertRP-RunnerResources-eastus/providers/microsoft.monitor/accounts/alertsrp-eastus-pgms/providers/Microsoft.AlertsManagement/alertRuleRecommendations/NodeRecordingRulesRuleGroup"), + // Properties: &armalertsmanagement.AlertRuleRecommendationProperties{ + // AlertRuleType: to.Ptr("Microsoft.AlertsManagement/prometheusRuleGroups"), + // DisplayInformation: map[string]*string{ + // "ruleInfo": to.Ptr("Rule Information for first recording rule."), + // }, + // RuleArmTemplate: &armalertsmanagement.RuleArmTemplate{ + // Schema: to.Ptr("https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#"), + // ContentVersion: to.Ptr("1.0.0.0"), + // Parameters: map[string]any{ + // "actionGroupIds":map[string]any{ + // "type": "array", + // "defaultValue":[]any{ + // }, + // "metadata":map[string]any{ + // "description": "Insert Action groups ids to attach them to the below alert rules.", + // }, + // }, + // "alertName":map[string]any{ + // "type": "string", + // "defaultValue": "[concat('parameters('alertNamePrefix'), ' - ', parameters('clusterNameForPrometheus'))]", + // "metadata":map[string]any{ + // "description": "Name of the alert rule", + // }, + // "minLength": float64(1), + // }, + // "alertNamePrefix":map[string]any{ + // "type": "string", + // "defaultValue": "NodeRecordingRulesRuleGroup", + // "metadata":map[string]any{ + // "description": "prefix of the alert rule name", + // }, + // "minLength": float64(1), + // }, + // "clusterNameForPrometheus":map[string]any{ + // "type": "string", + // }, + // "location":map[string]any{ + // "type": "string", + // "defaultValue": "eastus", + // }, + // "targetResourceId":map[string]any{ + // "type": "string", + // "defaultValue": "/subscriptions/2f00cc51-6809-498f-9ffc-48c42aff570d/resourceGroups/GenevaAlertRP-RunnerResources-eastus/providers/microsoft.monitor/accounts/alertsrp-eastus-pgms", + // }, + // "targetResourceName":map[string]any{ + // "type": "string", + // "defaultValue": "alertsrp-eastus-pgms", + // }, + // }, + // Resources: []any{ + // map[string]any{ + // "name": "[parameters('alertName')]", + // "type": "Microsoft.AlertsManagement/prometheusRuleGroups", + // "apiVersion": "2021-07-22-preview", + // "location": "[parameters('location')]", + // "properties":map[string]any{ + // "description": "Node Recording Rules RuleGroup", + // "clusterName": "[parameters('clusterNameForPrometheus')]", + // "interval": "PT1M", + // "rules":[]any{ + // map[string]any{ + // "expression": "count without (cpu, mode) ( node_cpu_seconds_total{job=\"node\",mode=\"idle\"})", + // "record": "instance:node_num_cpu:sum", + // }, + // }, + // "scopes": "[variables('scopes')]", + // }, + // }}, + // Variables: map[string]any{ + // "copy":[]any{ + // map[string]any{ + // "name": "actionsForPrometheusRuleGroups", + // "count": "[length(parameters('actionGroupIds'))]", + // "input":map[string]any{ + // "actiongroupId": "[parameters('actionGroupIds')[copyIndex('actionsForPrometheusRuleGroups')]]", + // }, + // }, + // }, + // "scopes": "[array(parameters('targetResourceId'))]", + // }, + // }, + // }, + // }, + // { + // Name: to.Ptr("KubernetesReccordingRulesRuleGroup"), + // Type: to.Ptr("Microsoft.AlertsManagement/alertRuleRecommendations"), + // ID: to.Ptr("/subscriptions/2f00cc51-6809-498f-9ffc-48c42aff570d/resourceGroups/GenevaAlertRP-RunnerResources-eastus/providers/microsoft.monitor/accounts/alertsrp-eastus-pgms/providers/Microsoft.AlertsManagement/alertRuleRecommendations/KubernetesReccordingRulesRuleGroup"), + // Properties: &armalertsmanagement.AlertRuleRecommendationProperties{ + // AlertRuleType: to.Ptr("Microsoft.AlertsManagement/prometheusRuleGroups"), + // DisplayInformation: map[string]*string{ + // "ruleInfo": to.Ptr("Rule Information for second recording rule."), + // }, + // RuleArmTemplate: &armalertsmanagement.RuleArmTemplate{ + // Schema: to.Ptr("https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#"), + // ContentVersion: to.Ptr("1.0.0.0"), + // Parameters: map[string]any{ + // "actionGroupIds":map[string]any{ + // "type": "array", + // "defaultValue":[]any{ + // }, + // "metadata":map[string]any{ + // "description": "Insert Action groups ids to attach them to the below alert rules.", + // }, + // }, + // "alertName":map[string]any{ + // "type": "string", + // "defaultValue": "[concat('parameters('alertNamePrefix'), ' - ', parameters('clusterNameForPrometheus'))]", + // "metadata":map[string]any{ + // "description": "Name of the alert rule", + // }, + // "minLength": float64(1), + // }, + // "alertNamePrefix":map[string]any{ + // "type": "string", + // "defaultValue": "KubernetesReccordingRulesRuleGroup", + // "metadata":map[string]any{ + // "description": "prefix of the alert rule name", + // }, + // "minLength": float64(1), + // }, + // "clusterNameForPrometheus":map[string]any{ + // "type": "string", + // }, + // "location":map[string]any{ + // "type": "string", + // "defaultValue": "eastus", + // }, + // "targetResourceId":map[string]any{ + // "type": "string", + // "defaultValue": "/subscriptions/2f00cc51-6809-498f-9ffc-48c42aff570d/resourceGroups/GenevaAlertRP-RunnerResources-eastus/providers/microsoft.monitor/accounts/alertsrp-eastus-pgms", + // }, + // "targetResourceName":map[string]any{ + // "type": "string", + // "defaultValue": "alertsrp-eastus-pgms", + // }, + // }, + // Resources: []any{ + // map[string]any{ + // "name": "[parameters('alertName')]", + // "type": "Microsoft.AlertsManagement/prometheusRuleGroups", + // "apiVersion": "2021-07-22-preview", + // "location": "[parameters('location')]", + // "properties":map[string]any{ + // "description": "Kubernetes Recording Rules RuleGroup", + // "clusterName": "[parameters('clusterNameForPrometheus')]", + // "interval": "PT1M", + // "rules":[]any{ + // map[string]any{ + // "expression": "sum by (cluster, namespace, pod, container) ( irate(container_cpu_usage_seconds_total{job=\"cadvisor\", image!=\"\"}[5m])) * on (cluster, namespace, pod) group_left(node) topk by (cluster, namespace, pod) ( 1, max by(cluster, namespace, pod, node) (kube_pod_info{node!=\"\"}))", + // "record": "node_namespace_pod_container:container_cpu_usage_seconds_total:sum_irate", + // }, + // }, + // "scopes": "[variables('scopes')]", + // }, + // }}, + // Variables: map[string]any{ + // "copy":[]any{ + // map[string]any{ + // "name": "actionsForPrometheusRuleGroups", + // "count": "[length(parameters('actionGroupIds'))]", + // "input":map[string]any{ + // "actiongroupId": "[parameters('actionGroupIds')[copyIndex('actionsForPrometheusRuleGroups')]]", + // }, + // }, + // }, + // "scopes": "[array(parameters('targetResourceId'))]", + // }, + // }, + // }, + // }, + // { + // Name: to.Ptr("KubernetesAlert-DefaultAlert"), + // Type: to.Ptr("Microsoft.AlertsManagement/alertRuleRecommendations"), + // ID: to.Ptr("/subscriptions/2f00cc51-6809-498f-9ffc-48c42aff570d/resourceGroups/GenevaAlertRP-RunnerResources-eastus/providers/microsoft.monitor/accounts/alertsrp-eastus-pgms/providers/Microsoft.AlertsManagement/alertRuleRecommendations/KubernetesAlert-DefaultAlert"), + // Properties: &armalertsmanagement.AlertRuleRecommendationProperties{ + // AlertRuleType: to.Ptr("Microsoft.AlertsManagement/prometheusRuleGroups"), + // DisplayInformation: map[string]*string{ + // "ruleInfo": to.Ptr("Rule Information for alerting rule."), + // }, + // RuleArmTemplate: &armalertsmanagement.RuleArmTemplate{ + // Schema: to.Ptr("https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#"), + // ContentVersion: to.Ptr("1.0.0.0"), + // Parameters: map[string]any{ + // "actionGroupIds":map[string]any{ + // "type": "array", + // "defaultValue":[]any{ + // }, + // "metadata":map[string]any{ + // "description": "Insert Action groups ids to attach them to the below alert rules.", + // }, + // }, + // "alertName":map[string]any{ + // "type": "string", + // "defaultValue": "[concat('parameters('alertNamePrefix'), ' - ', parameters('clusterNameForPrometheus'))]", + // "metadata":map[string]any{ + // "description": "Name of the alert rule", + // }, + // "minLength": float64(1), + // }, + // "alertNamePrefix":map[string]any{ + // "type": "string", + // "defaultValue": "KubernetesAlert-DefaultAlerts", + // "metadata":map[string]any{ + // "description": "prefix of the alert rule name", + // }, + // "minLength": float64(1), + // }, + // "clusterNameForPrometheus":map[string]any{ + // "type": "string", + // }, + // "location":map[string]any{ + // "type": "string", + // "defaultValue": "eastus", + // }, + // "targetResourceId":map[string]any{ + // "type": "string", + // "defaultValue": "/subscriptions/2f00cc51-6809-498f-9ffc-48c42aff570d/resourceGroups/GenevaAlertRP-RunnerResources-eastus/providers/microsoft.monitor/accounts/alertsrp-eastus-pgms", + // }, + // "targetResourceName":map[string]any{ + // "type": "string", + // "defaultValue": "alertsrp-eastus-pgms", + // }, + // }, + // Resources: []any{ + // map[string]any{ + // "name": "[parameters('alertName')]", + // "type": "Microsoft.AlertsManagement/prometheusRuleGroups", + // "apiVersion": "2021-07-22-preview", + // "location": "[parameters('location')]", + // "properties":map[string]any{ + // "description": "Kubernetes Alert RuleGroup-DefaultAlerts", + // "clusterName": "[parameters('clusterNameForPrometheus')]", + // "interval": "PT1M", + // "rules":[]any{ + // map[string]any{ + // "Severity": float64(3), + // "actions": "[variables('actionsForPrometheusRuleGroups')]", + // "alert": "KubePodCrashLooping", + // "expression": "max_over_time(kube_pod_container_status_waiting_reason{reason=\"CrashLoopBackOff\", job=\"kube-state-metrics\"}[5m]) >= 1", + // "for": "PT15M", + // "labels":map[string]any{ + // "severity": "warning", + // }, + // }, + // map[string]any{ + // "Severity": float64(3), + // "actions": "[variables('actionsForPrometheusRuleGroups')]", + // "alert": "KubePodNotReady", + // "expression": "sum by (namespace, pod, cluster) ( max by(namespace, pod, cluster) ( kube_pod_status_phase{job=\"kube-state-metrics\", phase=~\"Pending|Unknown\"} ) * on(namespace, pod, cluster) group_left(owner_kind) topk by(namespace, pod, cluster) ( 1, max by(namespace, pod, owner_kind, cluster) (kube_pod_owner{owner_kind!=\"Job\"}) )) > 0", + // "for": "PT15M", + // "labels":map[string]any{ + // "severity": "warning", + // }, + // }, + // }, + // "scopes": "[variables('scopes')]", + // }, + // }}, + // Variables: map[string]any{ + // "copy":[]any{ + // map[string]any{ + // "name": "actionsForPrometheusRuleGroups", + // "count": "[length(parameters('actionGroupIds'))]", + // "input":map[string]any{ + // "actiongroupId": "[parameters('actionGroupIds')[copyIndex('actionsForPrometheusRuleGroups')]]", + // }, + // }, + // }, + // "scopes": "[array(parameters('targetResourceId'))]", + // }, + // }, + // }, + // }}, + // } + } +} + +// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/6d2438481021a94793b07b226df06d5f3c61d51d/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2023-01-01-preview/examples/AlertRuleRecommendations_GetByResource_VM.json +func ExampleAlertRuleRecommendationsClient_NewListByResourcePager_listAlertRuleRecommendationsForVirtualMachinesAtResourceLevel() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armalertsmanagement.NewClientFactory("", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + pager := clientFactory.NewAlertRuleRecommendationsClient().NewListByResourcePager("subscriptions/2f00cc51-6809-498f-9ffc-48c42aff570d/resourcegroups/test/providers/Microsoft.Compute/virtualMachines/testMachineCanBeSafelyDeleted", nil) + for pager.More() { + page, err := pager.NextPage(ctx) + if err != nil { + log.Fatalf("failed to advance page: %v", err) + } + for _, v := range page.Value { + // You could use page here. We use blank identifier for just demo purposes. + _ = v + } + // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // page.AlertRuleRecommendationsListResponse = armalertsmanagement.AlertRuleRecommendationsListResponse{ + // Value: []*armalertsmanagement.AlertRuleRecommendationResource{ + // { + // Name: to.Ptr("Percentage CPU"), + // Type: to.Ptr("Microsoft.AlertsManagement/alertRuleRecommendations"), + // ID: to.Ptr("/subscriptions/2f00cc51-6809-498f-9ffc-48c42aff570d/resourcegroups/test/providers/Microsoft.Compute/virtualMachines/testMachineCanBeSafelyDeleted/providers/Microsoft.AlertsManagement/alertRuleRecommendations/Percentage CPU"), + // Properties: &armalertsmanagement.AlertRuleRecommendationProperties{ + // AlertRuleType: to.Ptr("Microsoft.Insights/metricAlerts"), + // DisplayInformation: map[string]*string{ + // "displayUnits": to.Ptr("Percentage"), + // "infoBallonLink": to.Ptr("Rule1 InfoBalloon Link"), + // "infoBallonMessage": to.Ptr("Rule1 InfoBalloon Message"), + // "metricDisplayName": to.Ptr("Percentage CPU"), + // }, + // RuleArmTemplate: &armalertsmanagement.RuleArmTemplate{ + // Schema: to.Ptr("https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#"), + // ContentVersion: to.Ptr("1.0.0.0"), + // Parameters: map[string]any{ + // "actionGroupIds":map[string]any{ + // "type": "array", + // "defaultValue":[]any{ + // }, + // "metadata":map[string]any{ + // "description": "Insert Action groups ids to attach them to the below alert rules.", + // }, + // }, + // "alertName":map[string]any{ + // "type": "string", + // "defaultValue": "[concat('parameters('alertNamePrefix'), ' - ', parameters('targetResourceName'))]", + // "metadata":map[string]any{ + // "description": "Name of the alert rule", + // }, + // "minLength": float64(1), + // }, + // "alertNamePrefix":map[string]any{ + // "type": "string", + // "defaultValue": "Percentage CPU", + // "metadata":map[string]any{ + // "description": "prefix of the alert rule name", + // }, + // "minLength": float64(1), + // }, + // "alertSeverity":map[string]any{ + // "type": "int", + // "allowedValues":[]any{ + // float64(0), + // float64(1), + // float64(2), + // float64(3), + // float64(4), + // }, + // "defaultValue": float64(3), + // "metadata":map[string]any{ + // "description": "Severity of alert {0,1,2,3,4}", + // }, + // }, + // "targetResourceId":map[string]any{ + // "type": "string", + // "defaultValue": "/subscriptions/2f00cc51-6809-498f-9ffc-48c42aff570d/resourcegroups/test/providers/Microsoft.Compute/virtualMachines/testMachineCanBeSafelyDeleted", + // }, + // "targetResourceName":map[string]any{ + // "type": "string", + // "defaultValue": "testmachinecanbesafelydeleted", + // }, + // "threshold":map[string]any{ + // "type": "int", + // "defaultValue": float64(80), + // "metadata":map[string]any{ + // "description": "The threshold value at which the alert is activated.", + // }, + // }, + // }, + // Resources: []any{ + // map[string]any{ + // "name": "[parameters('alertName')]", + // "type": "Microsoft.Insights/metricAlerts", + // "apiVersion": "2018-03-01", + // "location": "global", + // "properties":map[string]any{ + // "description": "Percentage CPU is greater than 80 %", + // "actions": "[variables('actionsForMetricAlerts')]", + // "criteria":map[string]any{ + // "allOf":[]any{ + // map[string]any{ + // "name": "Metric1", + // "metricName": "Percentage CPU", + // "operator": "GreaterThan", + // "threshold": "[parameters('threshold')]", + // "timeAggregation": "Average", + // }, + // }, + // "odata.type": "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria", + // }, + // "enabled": true, + // "evaluationFrequency": "PT5M", + // "scopes": "[variables('scopes')]", + // "severity": "[parameters('alertSeverity')]", + // "windowSize": "PT5M", + // }, + // }}, + // Variables: map[string]any{ + // "copy":[]any{ + // map[string]any{ + // "name": "actionsForMetricAlerts", + // "count": "[length(parameters('actionGroupIds'))]", + // "input":map[string]any{ + // "actiongroupId": "[parameters('actionGroupIds')[copyIndex('actionsForMetricAlerts')]]", + // }, + // }, + // }, + // "scopes": "[array(parameters('targetResourceId'))]", + // }, + // }, + // }, + // }, + // { + // Name: to.Ptr("Available Memory Bytes"), + // Type: to.Ptr("Microsoft.AlertsManagement/alertRuleRecommendations"), + // ID: to.Ptr("/subscriptions/2f00cc51-6809-498f-9ffc-48c42aff570d/resourcegroups/test/providers/Microsoft.Compute/virtualMachines/testMachineCanBeSafelyDeleted/providers/Microsoft.AlertsManagement/alertRuleRecommendations/Available Memory Bytes"), + // Properties: &armalertsmanagement.AlertRuleRecommendationProperties{ + // AlertRuleType: to.Ptr("Microsoft.Insights/metricAlerts"), + // DisplayInformation: map[string]*string{ + // "displayUnits": to.Ptr("Gigabytes"), + // "infoBallonLink": to.Ptr("Rule2 InfoBalloon Link"), + // "infoBallonMessage": to.Ptr("Rule2 InfoBalloon Message"), + // "metricDisplayName": to.Ptr("Available Memory Bytes"), + // }, + // RuleArmTemplate: &armalertsmanagement.RuleArmTemplate{ + // Schema: to.Ptr("https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#"), + // ContentVersion: to.Ptr("1.0.0.0"), + // Parameters: map[string]any{ + // "actionGroupIds":map[string]any{ + // "type": "array", + // "defaultValue":[]any{ + // }, + // "metadata":map[string]any{ + // "description": "Insert Action groups ids to attach them to the below alert rules.", + // }, + // }, + // "alertName":map[string]any{ + // "type": "string", + // "defaultValue": "[concat('parameters('alertNamePrefix'), ' - ', parameters('targetResourceName'))]", + // "metadata":map[string]any{ + // "description": "Name of the alert rule", + // }, + // "minLength": float64(1), + // }, + // "alertNamePrefix":map[string]any{ + // "type": "string", + // "defaultValue": "Available Memory Bytes", + // "metadata":map[string]any{ + // "description": "prefix of the alert rule name", + // }, + // "minLength": float64(1), + // }, + // "alertSeverity":map[string]any{ + // "type": "int", + // "allowedValues":[]any{ + // float64(0), + // float64(1), + // float64(2), + // float64(3), + // float64(4), + // }, + // "defaultValue": float64(3), + // "metadata":map[string]any{ + // "description": "Severity of alert {0,1,2,3,4}", + // }, + // }, + // "targetResourceId":map[string]any{ + // "type": "string", + // "defaultValue": "/subscriptions/2f00cc51-6809-498f-9ffc-48c42aff570d/resourcegroups/test/providers/Microsoft.Compute/virtualMachines/testMachineCanBeSafelyDeleted", + // }, + // "targetResourceName":map[string]any{ + // "type": "string", + // "defaultValue": "testmachinecanbesafelydeleted", + // }, + // "threshold":map[string]any{ + // "type": "int", + // "defaultValue": float64(1000000000), + // "metadata":map[string]any{ + // "description": "The threshold value at which the alert is activated.", + // }, + // }, + // }, + // Resources: []any{ + // map[string]any{ + // "name": "[parameters('alertName')]", + // "type": "Microsoft.Insights/metricAlerts", + // "apiVersion": "2018-03-01", + // "location": "global", + // "properties":map[string]any{ + // "description": "Available Memory Bytes is less than 1 GB", + // "actions": "[variables('actionsForMetricAlerts')]", + // "criteria":map[string]any{ + // "allOf":[]any{ + // map[string]any{ + // "name": "Metric1", + // "metricName": "Available Memory Bytes", + // "operator": "LessThan", + // "threshold": "[parameters('threshold')]", + // "timeAggregation": "Average", + // }, + // }, + // "odata.type": "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria", + // }, + // "enabled": true, + // "evaluationFrequency": "PT5M", + // "scopes": "[variables('scopes')]", + // "severity": "[parameters('alertSeverity')]", + // "windowSize": "PT5M", + // }, + // }}, + // Variables: map[string]any{ + // "copy":[]any{ + // map[string]any{ + // "name": "actionsForMetricAlerts", + // "count": "[length(parameters('actionGroupIds'))]", + // "input":map[string]any{ + // "actiongroupId": "[parameters('actionGroupIds')[copyIndex('actionsForMetricAlerts')]]", + // }, + // }, + // }, + // "scopes": "[array(parameters('targetResourceId'))]", + // }, + // }, + // }, + // }}, + // } + } +} + +// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/6d2438481021a94793b07b226df06d5f3c61d51d/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2023-01-01-preview/examples/AlertRuleRecommendations_GetBySubscription_MAC.json +func ExampleAlertRuleRecommendationsClient_NewListByTargetTypePager_listAlertRuleRecommendationsForMonitoringAccountsAtSubscriptionLevel() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armalertsmanagement.NewClientFactory("", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + pager := clientFactory.NewAlertRuleRecommendationsClient().NewListByTargetTypePager("microsoft.monitor/accounts", nil) + for pager.More() { + page, err := pager.NextPage(ctx) + if err != nil { + log.Fatalf("failed to advance page: %v", err) + } + for _, v := range page.Value { + // You could use page here. We use blank identifier for just demo purposes. + _ = v + } + // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // page.AlertRuleRecommendationsListResponse = armalertsmanagement.AlertRuleRecommendationsListResponse{ + // Value: []*armalertsmanagement.AlertRuleRecommendationResource{ + // { + // Name: to.Ptr("NodeRecordingRulesRuleGroup"), + // Type: to.Ptr("Microsoft.AlertsManagement/alertRuleRecommendations"), + // ID: to.Ptr("/subscriptions/2f00cc51-6809-498f-9ffc-48c42aff570d/providers/Microsoft.AlertsManagement/alertRuleRecommendations/NodeRecordingRulesRuleGroup"), + // Properties: &armalertsmanagement.AlertRuleRecommendationProperties{ + // AlertRuleType: to.Ptr("Microsoft.AlertsManagement/prometheusRuleGroups"), + // DisplayInformation: map[string]*string{ + // "ruleInfo": to.Ptr("Rule Information for first recording rule."), + // }, + // RuleArmTemplate: &armalertsmanagement.RuleArmTemplate{ + // Schema: to.Ptr("https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#"), + // ContentVersion: to.Ptr("1.0.0.0"), + // Parameters: map[string]any{ + // "actionGroupIds":map[string]any{ + // "type": "array", + // "defaultValue":[]any{ + // }, + // "metadata":map[string]any{ + // "description": "Insert Action groups ids to attach them to the below alert rules.", + // }, + // }, + // "alertName":map[string]any{ + // "type": "string", + // "defaultValue": "[concat('parameters('alertNamePrefix'), ' - ', parameters('clusterNameForPrometheus'))]", + // "metadata":map[string]any{ + // "description": "Name of the alert rule", + // }, + // "minLength": float64(1), + // }, + // "alertNamePrefix":map[string]any{ + // "type": "string", + // "defaultValue": "NodeRecordingRulesRuleGroup", + // "metadata":map[string]any{ + // "description": "prefix of the alert rule name", + // }, + // "minLength": float64(1), + // }, + // "clusterNameForPrometheus":map[string]any{ + // "type": "string", + // }, + // "location":map[string]any{ + // "type": "string", + // }, + // "targetResourceId":map[string]any{ + // "type": "string", + // }, + // "targetResourceName":map[string]any{ + // "type": "string", + // }, + // }, + // Resources: []any{ + // map[string]any{ + // "name": "[parameters('alertName')]", + // "type": "Microsoft.AlertsManagement/prometheusRuleGroups", + // "apiVersion": "2021-07-22-preview", + // "location": "[parameters('location')]", + // "properties":map[string]any{ + // "description": "Node Recording Rules RuleGroup", + // "clusterName": "[parameters('clusterNameForPrometheus')]", + // "interval": "PT1M", + // "rules":[]any{ + // map[string]any{ + // "expression": "count without (cpu, mode) ( node_cpu_seconds_total{job=\"node\",mode=\"idle\"})", + // "record": "instance:node_num_cpu:sum", + // }, + // }, + // "scopes": "[variables('scopes')]", + // }, + // }}, + // Variables: map[string]any{ + // "copy":[]any{ + // map[string]any{ + // "name": "actionsForPrometheusRuleGroups", + // "count": "[length(parameters('actionGroupIds'))]", + // "input":map[string]any{ + // "actiongroupId": "[parameters('actionGroupIds')[copyIndex('actionsForPrometheusRuleGroups')]]", + // }, + // }, + // }, + // "scopes": "[array(parameters('targetResourceId'))]", + // }, + // }, + // }, + // }, + // { + // Name: to.Ptr("KubernetesReccordingRulesRuleGroup"), + // Type: to.Ptr("Microsoft.AlertsManagement/alertRuleRecommendations"), + // ID: to.Ptr("/subscriptions/2f00cc51-6809-498f-9ffc-48c42aff570d/providers/Microsoft.AlertsManagement/alertRuleRecommendations/KubernetesReccordingRulesRuleGroup"), + // Properties: &armalertsmanagement.AlertRuleRecommendationProperties{ + // AlertRuleType: to.Ptr("Microsoft.AlertsManagement/prometheusRuleGroups"), + // DisplayInformation: map[string]*string{ + // "ruleInfo": to.Ptr("Rule Information for second recording rule."), + // }, + // RuleArmTemplate: &armalertsmanagement.RuleArmTemplate{ + // Schema: to.Ptr("https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#"), + // ContentVersion: to.Ptr("1.0.0.0"), + // Parameters: map[string]any{ + // "actionGroupIds":map[string]any{ + // "type": "array", + // "defaultValue":[]any{ + // }, + // "metadata":map[string]any{ + // "description": "Insert Action groups ids to attach them to the below alert rules.", + // }, + // }, + // "alertName":map[string]any{ + // "type": "string", + // "defaultValue": "[concat('parameters('alertNamePrefix'), ' - ', parameters('clusterNameForPrometheus'))]", + // "metadata":map[string]any{ + // "description": "Name of the alert rule", + // }, + // "minLength": float64(1), + // }, + // "alertNamePrefix":map[string]any{ + // "type": "string", + // "defaultValue": "KubernetesReccordingRulesRuleGroup", + // "metadata":map[string]any{ + // "description": "prefix of the alert rule name", + // }, + // "minLength": float64(1), + // }, + // "clusterNameForPrometheus":map[string]any{ + // "type": "string", + // }, + // "location":map[string]any{ + // "type": "string", + // }, + // "targetResourceId":map[string]any{ + // "type": "string", + // }, + // "targetResourceName":map[string]any{ + // "type": "string", + // }, + // }, + // Resources: []any{ + // map[string]any{ + // "name": "[parameters('alertName')]", + // "type": "Microsoft.AlertsManagement/prometheusRuleGroups", + // "apiVersion": "2021-07-22-preview", + // "location": "[parameters('location')]", + // "properties":map[string]any{ + // "description": "Kubernetes Recording Rules RuleGroup", + // "clusterName": "[parameters('clusterNameForPrometheus')]", + // "interval": "PT1M", + // "rules":[]any{ + // map[string]any{ + // "expression": "sum by (cluster, namespace, pod, container) ( irate(container_cpu_usage_seconds_total{job=\"cadvisor\", image!=\"\"}[5m])) * on (cluster, namespace, pod) group_left(node) topk by (cluster, namespace, pod) ( 1, max by(cluster, namespace, pod, node) (kube_pod_info{node!=\"\"}))", + // "record": "node_namespace_pod_container:container_cpu_usage_seconds_total:sum_irate", + // }, + // }, + // "scopes": "[variables('scopes')]", + // }, + // }}, + // Variables: map[string]any{ + // "copy":[]any{ + // map[string]any{ + // "name": "actionsForPrometheusRuleGroups", + // "count": "[length(parameters('actionGroupIds'))]", + // "input":map[string]any{ + // "actiongroupId": "[parameters('actionGroupIds')[copyIndex('actionsForPrometheusRuleGroups')]]", + // }, + // }, + // }, + // "scopes": "[array(parameters('targetResourceId'))]", + // }, + // }, + // }, + // }, + // { + // Name: to.Ptr("KubernetesAlert-DefaultAlerts"), + // Type: to.Ptr("Microsoft.AlertsManagement/alertRuleRecommendations"), + // ID: to.Ptr("/subscriptions/2f00cc51-6809-498f-9ffc-48c42aff570d/providers/Microsoft.AlertsManagement/alertRuleRecommendations/KubernetesAlert-DefaultAlerts"), + // Properties: &armalertsmanagement.AlertRuleRecommendationProperties{ + // AlertRuleType: to.Ptr("Microsoft.AlertsManagement/prometheusRuleGroups"), + // DisplayInformation: map[string]*string{ + // "ruleInfo": to.Ptr("Rule Information for alerting rule."), + // }, + // RuleArmTemplate: &armalertsmanagement.RuleArmTemplate{ + // Schema: to.Ptr("https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#"), + // ContentVersion: to.Ptr("1.0.0.0"), + // Parameters: map[string]any{ + // "actionGroupIds":map[string]any{ + // "type": "array", + // "defaultValue":[]any{ + // }, + // "metadata":map[string]any{ + // "description": "Insert Action groups ids to attach them to the below alert rules.", + // }, + // }, + // "alertName":map[string]any{ + // "type": "string", + // "defaultValue": "[concat('parameters('alertNamePrefix'), ' - ', parameters('clusterNameForPrometheus'))]", + // "metadata":map[string]any{ + // "description": "Name of the alert rule", + // }, + // "minLength": float64(1), + // }, + // "alertNamePrefix":map[string]any{ + // "type": "string", + // "defaultValue": "KubernetesAlert-DefaultAlerts", + // "metadata":map[string]any{ + // "description": "prefix of the alert rule name", + // }, + // "minLength": float64(1), + // }, + // "clusterNameForPrometheus":map[string]any{ + // "type": "string", + // }, + // "location":map[string]any{ + // "type": "string", + // }, + // "targetResourceId":map[string]any{ + // "type": "string", + // }, + // "targetResourceName":map[string]any{ + // "type": "string", + // }, + // }, + // Resources: []any{ + // map[string]any{ + // "name": "[parameters('alertName')]", + // "type": "Microsoft.AlertsManagement/prometheusRuleGroups", + // "apiVersion": "2021-07-22-preview", + // "location": "[parameters('location')]", + // "properties":map[string]any{ + // "description": "Kubernetes Alert RuleGroup-DefaultAlerts", + // "clusterName": "[parameters('clusterNameForPrometheus')]", + // "interval": "PT1M", + // "rules":[]any{ + // map[string]any{ + // "Severity": float64(3), + // "actions": "[variables('actionsForPrometheusRuleGroups')]", + // "alert": "KubePodCrashLooping", + // "expression": "max_over_time(kube_pod_container_status_waiting_reason{reason=\"CrashLoopBackOff\", job=\"kube-state-metrics\"}[5m]) >= 1", + // "for": "PT15M", + // "labels":map[string]any{ + // "severity": "warning", + // }, + // }, + // map[string]any{ + // "Severity": float64(3), + // "actions": "[variables('actionsForPrometheusRuleGroups')]", + // "alert": "KubePodNotReady", + // "expression": "sum by (namespace, pod, cluster) ( max by(namespace, pod, cluster) ( kube_pod_status_phase{job=\"kube-state-metrics\", phase=~\"Pending|Unknown\"} ) * on(namespace, pod, cluster) group_left(owner_kind) topk by(namespace, pod, cluster) ( 1, max by(namespace, pod, owner_kind, cluster) (kube_pod_owner{owner_kind!=\"Job\"}) )) > 0", + // "for": "PT15M", + // "labels":map[string]any{ + // "severity": "warning", + // }, + // }, + // }, + // "scopes": "[variables('scopes')]", + // }, + // }}, + // Variables: map[string]any{ + // "copy":[]any{ + // map[string]any{ + // "name": "actionsForPrometheusRuleGroups", + // "count": "[length(parameters('actionGroupIds'))]", + // "input":map[string]any{ + // "actiongroupId": "[parameters('actionGroupIds')[copyIndex('actionsForPrometheusRuleGroups')]]", + // }, + // }, + // }, + // "scopes": "[array(parameters('targetResourceId'))]", + // }, + // }, + // }, + // }}, + // } + } +} + +// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/6d2438481021a94793b07b226df06d5f3c61d51d/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2023-01-01-preview/examples/AlertRuleRecommendations_GetBySubscription_VM.json +func ExampleAlertRuleRecommendationsClient_NewListByTargetTypePager_listAlertRuleRecommendationsForVirtualMachinesAtSubscriptionLevel() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armalertsmanagement.NewClientFactory("", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + pager := clientFactory.NewAlertRuleRecommendationsClient().NewListByTargetTypePager("microsoft.compute/virtualmachines", nil) + for pager.More() { + page, err := pager.NextPage(ctx) + if err != nil { + log.Fatalf("failed to advance page: %v", err) + } + for _, v := range page.Value { + // You could use page here. We use blank identifier for just demo purposes. + _ = v + } + // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // page.AlertRuleRecommendationsListResponse = armalertsmanagement.AlertRuleRecommendationsListResponse{ + // Value: []*armalertsmanagement.AlertRuleRecommendationResource{ + // { + // Name: to.Ptr("Percentage CPU"), + // Type: to.Ptr("Microsoft.AlertsManagement/alertRuleRecommendations"), + // ID: to.Ptr("/subscriptions/2f00cc51-6809-498f-9ffc-48c42aff570d/providers/Microsoft.AlertsManagement/alertRuleRecommendations/Percentage CPU"), + // Properties: &armalertsmanagement.AlertRuleRecommendationProperties{ + // AlertRuleType: to.Ptr("Microsoft.Insights/metricAlerts"), + // DisplayInformation: map[string]*string{ + // "displayUnits": to.Ptr("Percentage"), + // "infoBallonLink": to.Ptr("Rule1 InfoBalloon Link"), + // "infoBallonMessage": to.Ptr("Rule1 InfoBalloon Message"), + // "metricDisplayName": to.Ptr("Percentage CPU"), + // }, + // RuleArmTemplate: &armalertsmanagement.RuleArmTemplate{ + // Schema: to.Ptr("https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#"), + // ContentVersion: to.Ptr("1.0.0.0"), + // Parameters: map[string]any{ + // "actionGroupIds":map[string]any{ + // "type": "array", + // "defaultValue":[]any{ + // }, + // "metadata":map[string]any{ + // "description": "Insert Action groups ids to attach them to the below alert rules.", + // }, + // }, + // "alertName":map[string]any{ + // "type": "string", + // "defaultValue": "[concat('parameters('alertNamePrefix'), ' - ', parameters('targetResourceName'))]", + // "metadata":map[string]any{ + // "description": "Name of the alert rule", + // }, + // "minLength": float64(1), + // }, + // "alertNamePrefix":map[string]any{ + // "type": "string", + // "defaultValue": "Percentage CPU", + // "metadata":map[string]any{ + // "description": "prefix of the alert rule name", + // }, + // "minLength": float64(1), + // }, + // "alertSeverity":map[string]any{ + // "type": "int", + // "allowedValues":[]any{ + // float64(0), + // float64(1), + // float64(2), + // float64(3), + // float64(4), + // }, + // "defaultValue": float64(3), + // "metadata":map[string]any{ + // "description": "Severity of alert {0,1,2,3,4}", + // }, + // }, + // "targetResourceId":map[string]any{ + // "type": "string", + // }, + // "targetResourceName":map[string]any{ + // "type": "string", + // }, + // "threshold":map[string]any{ + // "type": "int", + // "defaultValue": float64(80), + // "metadata":map[string]any{ + // "description": "The threshold value at which the alert is activated.", + // }, + // }, + // }, + // Resources: []any{ + // map[string]any{ + // "name": "[parameters('alertName')]", + // "type": "Microsoft.Insights/metricAlerts", + // "apiVersion": "2018-03-01", + // "location": "global", + // "properties":map[string]any{ + // "description": "Percentage CPU is greater than 80 %", + // "actions": "[variables('actionsForMetricAlerts')]", + // "criteria":map[string]any{ + // "allOf":[]any{ + // map[string]any{ + // "name": "Metric1", + // "metricName": "Percentage CPU", + // "operator": "GreaterThan", + // "threshold": "[parameters('threshold')]", + // "timeAggregation": "Average", + // }, + // }, + // "odata.type": "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria", + // }, + // "enabled": true, + // "evaluationFrequency": "PT5M", + // "scopes": "[variables('scopes')]", + // "severity": "[parameters('alertSeverity')]", + // "windowSize": "PT5M", + // }, + // }}, + // Variables: map[string]any{ + // "copy":[]any{ + // map[string]any{ + // "name": "actionsForMetricAlerts", + // "count": "[length(parameters('actionGroupIds'))]", + // "input":map[string]any{ + // "actiongroupId": "[parameters('actionGroupIds')[copyIndex('actionsForMetricAlerts')]]", + // }, + // }, + // }, + // "scopes": "[array(parameters('targetResourceId'))]", + // }, + // }, + // }, + // }, + // { + // Name: to.Ptr("Available Memory Bytes"), + // Type: to.Ptr("Microsoft.AlertsManagement/alertRuleRecommendations"), + // ID: to.Ptr("/subscriptions/2f00cc51-6809-498f-9ffc-48c42aff570d/providers/Microsoft.AlertsManagement/alertRuleRecommendations/Available Memory Bytes"), + // Properties: &armalertsmanagement.AlertRuleRecommendationProperties{ + // AlertRuleType: to.Ptr("Microsoft.Insights/metricAlerts"), + // DisplayInformation: map[string]*string{ + // "displayUnits": to.Ptr("Gigabytes"), + // "infoBallonLink": to.Ptr("Rule2 InfoBalloon Link"), + // "infoBallonMessage": to.Ptr("Rule2 InfoBalloon Message"), + // "metricDisplayName": to.Ptr("Available Memory Bytes"), + // }, + // RuleArmTemplate: &armalertsmanagement.RuleArmTemplate{ + // Schema: to.Ptr("https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#"), + // ContentVersion: to.Ptr("1.0.0.0"), + // Parameters: map[string]any{ + // "actionGroupIds":map[string]any{ + // "type": "array", + // "defaultValue":[]any{ + // }, + // "metadata":map[string]any{ + // "description": "Insert Action groups ids to attach them to the below alert rules.", + // }, + // }, + // "alertName":map[string]any{ + // "type": "string", + // "defaultValue": "[concat('parameters('alertNamePrefix'), ' - ', parameters('targetResourceName'))]", + // "metadata":map[string]any{ + // "description": "Name of the alert rule", + // }, + // "minLength": float64(1), + // }, + // "alertNamePrefix":map[string]any{ + // "type": "string", + // "defaultValue": "Available Memory Bytes", + // "metadata":map[string]any{ + // "description": "prefix of the alert rule name", + // }, + // "minLength": float64(1), + // }, + // "alertSeverity":map[string]any{ + // "type": "int", + // "allowedValues":[]any{ + // float64(0), + // float64(1), + // float64(2), + // float64(3), + // float64(4), + // }, + // "defaultValue": float64(3), + // "metadata":map[string]any{ + // "description": "Severity of alert {0,1,2,3,4}", + // }, + // }, + // "targetResourceId":map[string]any{ + // "type": "string", + // }, + // "targetResourceName":map[string]any{ + // "type": "string", + // }, + // "threshold":map[string]any{ + // "type": "int", + // "defaultValue": float64(1000000000), + // "metadata":map[string]any{ + // "description": "The threshold value at which the alert is activated.", + // }, + // }, + // }, + // Resources: []any{ + // map[string]any{ + // "name": "[parameters('alertName')]", + // "type": "Microsoft.Insights/metricAlerts", + // "apiVersion": "2018-03-01", + // "location": "global", + // "properties":map[string]any{ + // "description": "Available Memory Bytes is less than 1 GB", + // "actions": "[variables('actionsForMetricAlerts')]", + // "criteria":map[string]any{ + // "allOf":[]any{ + // map[string]any{ + // "name": "Metric1", + // "metricName": "Available Memory Bytes", + // "operator": "LessThan", + // "threshold": "[parameters('threshold')]", + // "timeAggregation": "Average", + // }, + // }, + // "odata.type": "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria", + // }, + // "enabled": true, + // "evaluationFrequency": "PT5M", + // "scopes": "[variables('scopes')]", + // "severity": "[parameters('alertSeverity')]", + // "windowSize": "PT5M", + // }, + // }}, + // Variables: map[string]any{ + // "copy":[]any{ + // map[string]any{ + // "name": "actionsForMetricAlerts", + // "count": "[length(parameters('actionGroupIds'))]", + // "input":map[string]any{ + // "actiongroupId": "[parameters('actionGroupIds')[copyIndex('actionsForMetricAlerts')]]", + // }, + // }, + // }, + // "scopes": "[array(parameters('targetResourceId'))]", + // }, + // }, + // }, + // }}, + // } + } +} diff --git a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/alerts_client.go b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/alerts_client.go index 48bfbe95fa53..7243f1edb8e2 100644 --- a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/alerts_client.go +++ b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/alerts_client.go @@ -152,32 +152,15 @@ func (client *AlertsClient) getAllCreateRequest(ctx context.Context, options *Al return nil, err } reqQP := req.Raw().URL.Query() - if options != nil && options.TargetResource != nil { - reqQP.Set("targetResource", *options.TargetResource) - } - if options != nil && options.TargetResourceType != nil { - reqQP.Set("targetResourceType", *options.TargetResourceType) - } - if options != nil && options.TargetResourceGroup != nil { - reqQP.Set("targetResourceGroup", *options.TargetResourceGroup) - } - if options != nil && options.MonitorService != nil { - reqQP.Set("monitorService", string(*options.MonitorService)) - } - if options != nil && options.MonitorCondition != nil { - reqQP.Set("monitorCondition", string(*options.MonitorCondition)) - } - if options != nil && options.Severity != nil { - reqQP.Set("severity", string(*options.Severity)) + if options != nil && options.AlertRule != nil { + reqQP.Set("alertRule", *options.AlertRule) } if options != nil && options.AlertState != nil { reqQP.Set("alertState", string(*options.AlertState)) } - if options != nil && options.AlertRule != nil { - reqQP.Set("alertRule", *options.AlertRule) - } - if options != nil && options.SmartGroupID != nil { - reqQP.Set("smartGroupId", *options.SmartGroupID) + reqQP.Set("api-version", "2019-05-05-preview") + if options != nil && options.CustomTimeRange != nil { + reqQP.Set("customTimeRange", *options.CustomTimeRange) } if options != nil && options.IncludeContext != nil { reqQP.Set("includeContext", strconv.FormatBool(*options.IncludeContext)) @@ -185,25 +168,42 @@ func (client *AlertsClient) getAllCreateRequest(ctx context.Context, options *Al if options != nil && options.IncludeEgressConfig != nil { reqQP.Set("includeEgressConfig", strconv.FormatBool(*options.IncludeEgressConfig)) } + if options != nil && options.MonitorCondition != nil { + reqQP.Set("monitorCondition", string(*options.MonitorCondition)) + } + if options != nil && options.MonitorService != nil { + reqQP.Set("monitorService", string(*options.MonitorService)) + } if options != nil && options.PageCount != nil { reqQP.Set("pageCount", strconv.FormatInt(*options.PageCount, 10)) } + if options != nil && options.Select != nil { + reqQP.Set("select", *options.Select) + } + if options != nil && options.Severity != nil { + reqQP.Set("severity", string(*options.Severity)) + } + if options != nil && options.SmartGroupID != nil { + reqQP.Set("smartGroupId", *options.SmartGroupID) + } if options != nil && options.SortBy != nil { reqQP.Set("sortBy", string(*options.SortBy)) } if options != nil && options.SortOrder != nil { reqQP.Set("sortOrder", string(*options.SortOrder)) } - if options != nil && options.Select != nil { - reqQP.Set("select", *options.Select) + if options != nil && options.TargetResource != nil { + reqQP.Set("targetResource", *options.TargetResource) + } + if options != nil && options.TargetResourceGroup != nil { + reqQP.Set("targetResourceGroup", *options.TargetResourceGroup) + } + if options != nil && options.TargetResourceType != nil { + reqQP.Set("targetResourceType", *options.TargetResourceType) } if options != nil && options.TimeRange != nil { reqQP.Set("timeRange", string(*options.TimeRange)) } - if options != nil && options.CustomTimeRange != nil { - reqQP.Set("customTimeRange", *options.CustomTimeRange) - } - reqQP.Set("api-version", "2019-05-05-preview") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -379,41 +379,41 @@ func (client *AlertsClient) getSummaryCreateRequest(ctx context.Context, groupby return nil, err } reqQP := req.Raw().URL.Query() + if options != nil && options.AlertRule != nil { + reqQP.Set("alertRule", *options.AlertRule) + } + if options != nil && options.AlertState != nil { + reqQP.Set("alertState", string(*options.AlertState)) + } + reqQP.Set("api-version", "2019-05-05-preview") + if options != nil && options.CustomTimeRange != nil { + reqQP.Set("customTimeRange", *options.CustomTimeRange) + } reqQP.Set("groupby", string(groupby)) if options != nil && options.IncludeSmartGroupsCount != nil { reqQP.Set("includeSmartGroupsCount", strconv.FormatBool(*options.IncludeSmartGroupsCount)) } - if options != nil && options.TargetResource != nil { - reqQP.Set("targetResource", *options.TargetResource) - } - if options != nil && options.TargetResourceType != nil { - reqQP.Set("targetResourceType", *options.TargetResourceType) - } - if options != nil && options.TargetResourceGroup != nil { - reqQP.Set("targetResourceGroup", *options.TargetResourceGroup) + if options != nil && options.MonitorCondition != nil { + reqQP.Set("monitorCondition", string(*options.MonitorCondition)) } if options != nil && options.MonitorService != nil { reqQP.Set("monitorService", string(*options.MonitorService)) } - if options != nil && options.MonitorCondition != nil { - reqQP.Set("monitorCondition", string(*options.MonitorCondition)) - } if options != nil && options.Severity != nil { reqQP.Set("severity", string(*options.Severity)) } - if options != nil && options.AlertState != nil { - reqQP.Set("alertState", string(*options.AlertState)) + if options != nil && options.TargetResource != nil { + reqQP.Set("targetResource", *options.TargetResource) } - if options != nil && options.AlertRule != nil { - reqQP.Set("alertRule", *options.AlertRule) + if options != nil && options.TargetResourceGroup != nil { + reqQP.Set("targetResourceGroup", *options.TargetResourceGroup) + } + if options != nil && options.TargetResourceType != nil { + reqQP.Set("targetResourceType", *options.TargetResourceType) } if options != nil && options.TimeRange != nil { reqQP.Set("timeRange", string(*options.TimeRange)) } - if options != nil && options.CustomTimeRange != nil { - reqQP.Set("customTimeRange", *options.CustomTimeRange) - } - reqQP.Set("api-version", "2019-05-05-preview") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil diff --git a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/alerts_client_example_test.go b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/alerts_client_example_test.go index e4581f121c4c..45f93ca982a6 100644 --- a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/alerts_client_example_test.go +++ b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/alerts_client_example_test.go @@ -17,7 +17,7 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/alertsmanagement/armalertsmanagement" ) -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/a436672b07fb1fe276c203b086b3f0e0d0c4aa24/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2019-05-05-preview/examples/AlertsMetaData_MonitorService.json +// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/6d2438481021a94793b07b226df06d5f3c61d51d/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2019-05-05-preview/examples/AlertsMetaData_MonitorService.json func ExampleAlertsClient_MetaData() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { @@ -115,7 +115,7 @@ func ExampleAlertsClient_MetaData() { // } } -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/a436672b07fb1fe276c203b086b3f0e0d0c4aa24/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2019-05-05-preview/examples/Alerts_List.json +// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/6d2438481021a94793b07b226df06d5f3c61d51d/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2019-05-05-preview/examples/Alerts_List.json func ExampleAlertsClient_NewGetAllPager() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { @@ -228,7 +228,7 @@ func ExampleAlertsClient_NewGetAllPager() { } } -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/a436672b07fb1fe276c203b086b3f0e0d0c4aa24/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2019-05-05-preview/examples/Alerts_GetById.json +// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/6d2438481021a94793b07b226df06d5f3c61d51d/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2019-05-05-preview/examples/Alerts_GetById.json func ExampleAlertsClient_GetByID() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { @@ -282,7 +282,7 @@ func ExampleAlertsClient_GetByID() { // } } -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/a436672b07fb1fe276c203b086b3f0e0d0c4aa24/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2019-05-05-preview/examples/Alerts_ChangeState.json +// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/6d2438481021a94793b07b226df06d5f3c61d51d/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2019-05-05-preview/examples/Alerts_ChangeState.json func ExampleAlertsClient_ChangeState() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { @@ -336,7 +336,7 @@ func ExampleAlertsClient_ChangeState() { // } } -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/a436672b07fb1fe276c203b086b3f0e0d0c4aa24/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2019-05-05-preview/examples/Alerts_History.json +// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/6d2438481021a94793b07b226df06d5f3c61d51d/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2019-05-05-preview/examples/Alerts_History.json func ExampleAlertsClient_GetHistory() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { @@ -383,7 +383,7 @@ func ExampleAlertsClient_GetHistory() { // } } -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/a436672b07fb1fe276c203b086b3f0e0d0c4aa24/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2019-05-05-preview/examples/Alerts_Summary.json +// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/6d2438481021a94793b07b226df06d5f3c61d51d/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2019-05-05-preview/examples/Alerts_Summary.json func ExampleAlertsClient_GetSummary() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { diff --git a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/autorest.md b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/autorest.md index 7d42c93b5f02..70b84c5f69bc 100644 --- a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/autorest.md +++ b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/autorest.md @@ -5,10 +5,11 @@ ``` yaml azure-arm: true require: -- https://github.com/Azure/azure-rest-api-specs/blob/a436672b07fb1fe276c203b086b3f0e0d0c4aa24/specification/alertsmanagement/resource-manager/readme.md -- https://github.com/Azure/azure-rest-api-specs/blob/a436672b07fb1fe276c203b086b3f0e0d0c4aa24/specification/alertsmanagement/resource-manager/readme.go.md +- https://github.com/Azure/azure-rest-api-specs/blob/6d2438481021a94793b07b226df06d5f3c61d51d/specification/alertsmanagement/resource-manager/readme.md +- https://github.com/Azure/azure-rest-api-specs/blob/6d2438481021a94793b07b226df06d5f3c61d51d/specification/alertsmanagement/resource-manager/readme.go.md license-header: MICROSOFT_MIT_NO_VERSION -module-version: 0.9.0 +module-version: 0.10.0 modelerfour: lenient-model-deduplication: true +tag: package-2021-08 ``` \ No newline at end of file diff --git a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/build.go b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/build.go index 169627199393..c9338b9a825a 100644 --- a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/build.go +++ b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/build.go @@ -2,6 +2,6 @@ // Licensed under the MIT License. See License.txt in the project root for license information. // This file enables 'go generate' to regenerate this specific SDK -//go:generate pwsh ../../../../eng/scripts/build.ps1 -skipBuild -cleanGenerated -format -tidy -generate resourcemanager/alertsmanagement/armalertsmanagement +//go:generate pwsh ../../../../eng/scripts/build.ps1 -skipBuild -cleanGenerated -format -tidy -generate -removeUnreferencedTypes resourcemanager/alertsmanagement/armalertsmanagement package armalertsmanagement diff --git a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/client_factory.go b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/client_factory.go index 8cd4f2c0e855..0bff9358535f 100644 --- a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/client_factory.go +++ b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/client_factory.go @@ -17,8 +17,7 @@ import ( // Don't use this type directly, use NewClientFactory instead. type ClientFactory struct { subscriptionID string - credential azcore.TokenCredential - options *arm.ClientOptions + internal *arm.Client } // NewClientFactory creates a new instance of ClientFactory with the specified values. @@ -27,36 +26,66 @@ type ClientFactory struct { // - credential - used to authorize requests. Usually a credential from azidentity. // - options - pass nil to accept the default values. func NewClientFactory(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ClientFactory, error) { - _, err := arm.NewClient(moduleName, moduleVersion, credential, options) + internal, err := arm.NewClient(moduleName, moduleVersion, credential, options) if err != nil { return nil, err } return &ClientFactory{ - subscriptionID: subscriptionID, credential: credential, - options: options.Clone(), + subscriptionID: subscriptionID, + internal: internal, }, nil } // NewAlertProcessingRulesClient creates a new instance of AlertProcessingRulesClient. func (c *ClientFactory) NewAlertProcessingRulesClient() *AlertProcessingRulesClient { - subClient, _ := NewAlertProcessingRulesClient(c.subscriptionID, c.credential, c.options) - return subClient + return &AlertProcessingRulesClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewAlertRuleRecommendationsClient creates a new instance of AlertRuleRecommendationsClient. +func (c *ClientFactory) NewAlertRuleRecommendationsClient() *AlertRuleRecommendationsClient { + return &AlertRuleRecommendationsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } } // NewAlertsClient creates a new instance of AlertsClient. func (c *ClientFactory) NewAlertsClient() *AlertsClient { - subClient, _ := NewAlertsClient(c.subscriptionID, c.credential, c.options) - return subClient + return &AlertsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } } // NewOperationsClient creates a new instance of OperationsClient. func (c *ClientFactory) NewOperationsClient() *OperationsClient { - subClient, _ := NewOperationsClient(c.credential, c.options) - return subClient + return &OperationsClient{ + internal: c.internal, + } +} + +// NewPrometheusRuleGroupsClient creates a new instance of PrometheusRuleGroupsClient. +func (c *ClientFactory) NewPrometheusRuleGroupsClient() *PrometheusRuleGroupsClient { + return &PrometheusRuleGroupsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } } // NewSmartGroupsClient creates a new instance of SmartGroupsClient. func (c *ClientFactory) NewSmartGroupsClient() *SmartGroupsClient { - subClient, _ := NewSmartGroupsClient(c.subscriptionID, c.credential, c.options) - return subClient + return &SmartGroupsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewTenantActivityLogAlertsClient creates a new instance of TenantActivityLogAlertsClient. +func (c *ClientFactory) NewTenantActivityLogAlertsClient() *TenantActivityLogAlertsClient { + return &TenantActivityLogAlertsClient{ + internal: c.internal, + } } diff --git a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/constants.go b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/constants.go index db90b267bcc7..488ee7e08b12 100644 --- a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/constants.go +++ b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/constants.go @@ -10,7 +10,7 @@ package armalertsmanagement const ( moduleName = "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/alertsmanagement/armalertsmanagement" - moduleVersion = "v0.9.0" + moduleVersion = "v0.10.0" ) // ActionType - Action that should be applied. diff --git a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/fake/alertrulerecommendations_server.go b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/fake/alertrulerecommendations_server.go new file mode 100644 index 000000000000..eabf2dfcfc7e --- /dev/null +++ b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/fake/alertrulerecommendations_server.go @@ -0,0 +1,154 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package fake + +import ( + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/alertsmanagement/armalertsmanagement" + "net/http" + "net/url" + "regexp" +) + +// AlertRuleRecommendationsServer is a fake server for instances of the armalertsmanagement.AlertRuleRecommendationsClient type. +type AlertRuleRecommendationsServer struct { + // NewListByResourcePager is the fake for method AlertRuleRecommendationsClient.NewListByResourcePager + // HTTP status codes to indicate success: http.StatusOK + NewListByResourcePager func(resourceURI string, options *armalertsmanagement.AlertRuleRecommendationsClientListByResourceOptions) (resp azfake.PagerResponder[armalertsmanagement.AlertRuleRecommendationsClientListByResourceResponse]) + + // NewListByTargetTypePager is the fake for method AlertRuleRecommendationsClient.NewListByTargetTypePager + // HTTP status codes to indicate success: http.StatusOK + NewListByTargetTypePager func(targetType string, options *armalertsmanagement.AlertRuleRecommendationsClientListByTargetTypeOptions) (resp azfake.PagerResponder[armalertsmanagement.AlertRuleRecommendationsClientListByTargetTypeResponse]) +} + +// NewAlertRuleRecommendationsServerTransport creates a new instance of AlertRuleRecommendationsServerTransport with the provided implementation. +// The returned AlertRuleRecommendationsServerTransport instance is connected to an instance of armalertsmanagement.AlertRuleRecommendationsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewAlertRuleRecommendationsServerTransport(srv *AlertRuleRecommendationsServer) *AlertRuleRecommendationsServerTransport { + return &AlertRuleRecommendationsServerTransport{ + srv: srv, + newListByResourcePager: newTracker[azfake.PagerResponder[armalertsmanagement.AlertRuleRecommendationsClientListByResourceResponse]](), + newListByTargetTypePager: newTracker[azfake.PagerResponder[armalertsmanagement.AlertRuleRecommendationsClientListByTargetTypeResponse]](), + } +} + +// AlertRuleRecommendationsServerTransport connects instances of armalertsmanagement.AlertRuleRecommendationsClient to instances of AlertRuleRecommendationsServer. +// Don't use this type directly, use NewAlertRuleRecommendationsServerTransport instead. +type AlertRuleRecommendationsServerTransport struct { + srv *AlertRuleRecommendationsServer + newListByResourcePager *tracker[azfake.PagerResponder[armalertsmanagement.AlertRuleRecommendationsClientListByResourceResponse]] + newListByTargetTypePager *tracker[azfake.PagerResponder[armalertsmanagement.AlertRuleRecommendationsClientListByTargetTypeResponse]] +} + +// Do implements the policy.Transporter interface for AlertRuleRecommendationsServerTransport. +func (a *AlertRuleRecommendationsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + var resp *http.Response + var err error + + switch method { + case "AlertRuleRecommendationsClient.NewListByResourcePager": + resp, err = a.dispatchNewListByResourcePager(req) + case "AlertRuleRecommendationsClient.NewListByTargetTypePager": + resp, err = a.dispatchNewListByTargetTypePager(req) + default: + err = fmt.Errorf("unhandled API %s", method) + } + + if err != nil { + return nil, err + } + + return resp, nil +} + +func (a *AlertRuleRecommendationsServerTransport) dispatchNewListByResourcePager(req *http.Request) (*http.Response, error) { + if a.srv.NewListByResourcePager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByResourcePager not implemented")} + } + newListByResourcePager := a.newListByResourcePager.get(req) + if newListByResourcePager == nil { + const regexStr = `/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.AlertsManagement/alertRuleRecommendations` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 1 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceURIParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceUri")]) + if err != nil { + return nil, err + } + resp := a.srv.NewListByResourcePager(resourceURIParam, nil) + newListByResourcePager = &resp + a.newListByResourcePager.add(req, newListByResourcePager) + server.PagerResponderInjectNextLinks(newListByResourcePager, req, func(page *armalertsmanagement.AlertRuleRecommendationsClientListByResourceResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByResourcePager, req) + if err != nil { + return nil, err + } + if !contains([]int{http.StatusOK}, resp.StatusCode) { + a.newListByResourcePager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByResourcePager) { + a.newListByResourcePager.remove(req) + } + return resp, nil +} + +func (a *AlertRuleRecommendationsServerTransport) dispatchNewListByTargetTypePager(req *http.Request) (*http.Response, error) { + if a.srv.NewListByTargetTypePager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByTargetTypePager not implemented")} + } + newListByTargetTypePager := a.newListByTargetTypePager.get(req) + if newListByTargetTypePager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.AlertsManagement/alertRuleRecommendations` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 1 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + qp := req.URL.Query() + targetTypeParam, err := url.QueryUnescape(qp.Get("targetType")) + if err != nil { + return nil, err + } + resp := a.srv.NewListByTargetTypePager(targetTypeParam, nil) + newListByTargetTypePager = &resp + a.newListByTargetTypePager.add(req, newListByTargetTypePager) + server.PagerResponderInjectNextLinks(newListByTargetTypePager, req, func(page *armalertsmanagement.AlertRuleRecommendationsClientListByTargetTypeResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByTargetTypePager, req) + if err != nil { + return nil, err + } + if !contains([]int{http.StatusOK}, resp.StatusCode) { + a.newListByTargetTypePager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByTargetTypePager) { + a.newListByTargetTypePager.remove(req) + } + return resp, nil +} diff --git a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/fake/alerts_server.go b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/fake/alerts_server.go index ebdc590fdddb..2a5f81089ff9 100644 --- a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/fake/alerts_server.go +++ b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/fake/alerts_server.go @@ -114,7 +114,7 @@ func (a *AlertsServerTransport) dispatchChangeState(req *http.Request) (*http.Re return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) } qp := req.URL.Query() - body, err := server.UnmarshalRequestAsJSON[string](req) + body, err := server.UnmarshalRequestAsJSON[armalertsmanagement.Comments](req) if err != nil { return nil, err } diff --git a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/fake/prometheusrulegroups_server.go b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/fake/prometheusrulegroups_server.go new file mode 100644 index 000000000000..941e6607cf3a --- /dev/null +++ b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/fake/prometheusrulegroups_server.go @@ -0,0 +1,307 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/alertsmanagement/armalertsmanagement" + "net/http" + "net/url" + "regexp" +) + +// PrometheusRuleGroupsServer is a fake server for instances of the armalertsmanagement.PrometheusRuleGroupsClient type. +type PrometheusRuleGroupsServer struct { + // CreateOrUpdate is the fake for method PrometheusRuleGroupsClient.CreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + CreateOrUpdate func(ctx context.Context, resourceGroupName string, ruleGroupName string, parameters armalertsmanagement.PrometheusRuleGroupResource, options *armalertsmanagement.PrometheusRuleGroupsClientCreateOrUpdateOptions) (resp azfake.Responder[armalertsmanagement.PrometheusRuleGroupsClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // Delete is the fake for method PrometheusRuleGroupsClient.Delete + // HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent + Delete func(ctx context.Context, resourceGroupName string, ruleGroupName string, options *armalertsmanagement.PrometheusRuleGroupsClientDeleteOptions) (resp azfake.Responder[armalertsmanagement.PrometheusRuleGroupsClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method PrometheusRuleGroupsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, ruleGroupName string, options *armalertsmanagement.PrometheusRuleGroupsClientGetOptions) (resp azfake.Responder[armalertsmanagement.PrometheusRuleGroupsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByResourceGroupPager is the fake for method PrometheusRuleGroupsClient.NewListByResourceGroupPager + // HTTP status codes to indicate success: http.StatusOK + NewListByResourceGroupPager func(resourceGroupName string, options *armalertsmanagement.PrometheusRuleGroupsClientListByResourceGroupOptions) (resp azfake.PagerResponder[armalertsmanagement.PrometheusRuleGroupsClientListByResourceGroupResponse]) + + // NewListBySubscriptionPager is the fake for method PrometheusRuleGroupsClient.NewListBySubscriptionPager + // HTTP status codes to indicate success: http.StatusOK + NewListBySubscriptionPager func(options *armalertsmanagement.PrometheusRuleGroupsClientListBySubscriptionOptions) (resp azfake.PagerResponder[armalertsmanagement.PrometheusRuleGroupsClientListBySubscriptionResponse]) + + // Update is the fake for method PrometheusRuleGroupsClient.Update + // HTTP status codes to indicate success: http.StatusOK + Update func(ctx context.Context, resourceGroupName string, ruleGroupName string, parameters armalertsmanagement.PrometheusRuleGroupResourcePatch, options *armalertsmanagement.PrometheusRuleGroupsClientUpdateOptions) (resp azfake.Responder[armalertsmanagement.PrometheusRuleGroupsClientUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewPrometheusRuleGroupsServerTransport creates a new instance of PrometheusRuleGroupsServerTransport with the provided implementation. +// The returned PrometheusRuleGroupsServerTransport instance is connected to an instance of armalertsmanagement.PrometheusRuleGroupsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewPrometheusRuleGroupsServerTransport(srv *PrometheusRuleGroupsServer) *PrometheusRuleGroupsServerTransport { + return &PrometheusRuleGroupsServerTransport{ + srv: srv, + newListByResourceGroupPager: newTracker[azfake.PagerResponder[armalertsmanagement.PrometheusRuleGroupsClientListByResourceGroupResponse]](), + newListBySubscriptionPager: newTracker[azfake.PagerResponder[armalertsmanagement.PrometheusRuleGroupsClientListBySubscriptionResponse]](), + } +} + +// PrometheusRuleGroupsServerTransport connects instances of armalertsmanagement.PrometheusRuleGroupsClient to instances of PrometheusRuleGroupsServer. +// Don't use this type directly, use NewPrometheusRuleGroupsServerTransport instead. +type PrometheusRuleGroupsServerTransport struct { + srv *PrometheusRuleGroupsServer + newListByResourceGroupPager *tracker[azfake.PagerResponder[armalertsmanagement.PrometheusRuleGroupsClientListByResourceGroupResponse]] + newListBySubscriptionPager *tracker[azfake.PagerResponder[armalertsmanagement.PrometheusRuleGroupsClientListBySubscriptionResponse]] +} + +// Do implements the policy.Transporter interface for PrometheusRuleGroupsServerTransport. +func (p *PrometheusRuleGroupsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + var resp *http.Response + var err error + + switch method { + case "PrometheusRuleGroupsClient.CreateOrUpdate": + resp, err = p.dispatchCreateOrUpdate(req) + case "PrometheusRuleGroupsClient.Delete": + resp, err = p.dispatchDelete(req) + case "PrometheusRuleGroupsClient.Get": + resp, err = p.dispatchGet(req) + case "PrometheusRuleGroupsClient.NewListByResourceGroupPager": + resp, err = p.dispatchNewListByResourceGroupPager(req) + case "PrometheusRuleGroupsClient.NewListBySubscriptionPager": + resp, err = p.dispatchNewListBySubscriptionPager(req) + case "PrometheusRuleGroupsClient.Update": + resp, err = p.dispatchUpdate(req) + default: + err = fmt.Errorf("unhandled API %s", method) + } + + if err != nil { + return nil, err + } + + return resp, nil +} + +func (p *PrometheusRuleGroupsServerTransport) dispatchCreateOrUpdate(req *http.Request) (*http.Response, error) { + if p.srv.CreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method CreateOrUpdate not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.AlertsManagement/prometheusRuleGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armalertsmanagement.PrometheusRuleGroupResource](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + ruleGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("ruleGroupName")]) + if err != nil { + return nil, err + } + respr, errRespr := p.srv.CreateOrUpdate(req.Context(), resourceGroupNameParam, ruleGroupNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK, http.StatusCreated}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).PrometheusRuleGroupResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (p *PrometheusRuleGroupsServerTransport) dispatchDelete(req *http.Request) (*http.Response, error) { + if p.srv.Delete == nil { + return nil, &nonRetriableError{errors.New("fake for method Delete not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.AlertsManagement/prometheusRuleGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + ruleGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("ruleGroupName")]) + if err != nil { + return nil, err + } + respr, errRespr := p.srv.Delete(req.Context(), resourceGroupNameParam, ruleGroupNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK, http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (p *PrometheusRuleGroupsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if p.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.AlertsManagement/prometheusRuleGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + ruleGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("ruleGroupName")]) + if err != nil { + return nil, err + } + respr, errRespr := p.srv.Get(req.Context(), resourceGroupNameParam, ruleGroupNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).PrometheusRuleGroupResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (p *PrometheusRuleGroupsServerTransport) dispatchNewListByResourceGroupPager(req *http.Request) (*http.Response, error) { + if p.srv.NewListByResourceGroupPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByResourceGroupPager not implemented")} + } + newListByResourceGroupPager := p.newListByResourceGroupPager.get(req) + if newListByResourceGroupPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.AlertsManagement/prometheusRuleGroups` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + resp := p.srv.NewListByResourceGroupPager(resourceGroupNameParam, nil) + newListByResourceGroupPager = &resp + p.newListByResourceGroupPager.add(req, newListByResourceGroupPager) + } + resp, err := server.PagerResponderNext(newListByResourceGroupPager, req) + if err != nil { + return nil, err + } + if !contains([]int{http.StatusOK}, resp.StatusCode) { + p.newListByResourceGroupPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByResourceGroupPager) { + p.newListByResourceGroupPager.remove(req) + } + return resp, nil +} + +func (p *PrometheusRuleGroupsServerTransport) dispatchNewListBySubscriptionPager(req *http.Request) (*http.Response, error) { + if p.srv.NewListBySubscriptionPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListBySubscriptionPager not implemented")} + } + newListBySubscriptionPager := p.newListBySubscriptionPager.get(req) + if newListBySubscriptionPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.AlertsManagement/prometheusRuleGroups` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 1 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resp := p.srv.NewListBySubscriptionPager(nil) + newListBySubscriptionPager = &resp + p.newListBySubscriptionPager.add(req, newListBySubscriptionPager) + } + resp, err := server.PagerResponderNext(newListBySubscriptionPager, req) + if err != nil { + return nil, err + } + if !contains([]int{http.StatusOK}, resp.StatusCode) { + p.newListBySubscriptionPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListBySubscriptionPager) { + p.newListBySubscriptionPager.remove(req) + } + return resp, nil +} + +func (p *PrometheusRuleGroupsServerTransport) dispatchUpdate(req *http.Request) (*http.Response, error) { + if p.srv.Update == nil { + return nil, &nonRetriableError{errors.New("fake for method Update not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.AlertsManagement/prometheusRuleGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armalertsmanagement.PrometheusRuleGroupResourcePatch](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + ruleGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("ruleGroupName")]) + if err != nil { + return nil, err + } + respr, errRespr := p.srv.Update(req.Context(), resourceGroupNameParam, ruleGroupNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).PrometheusRuleGroupResource, req) + if err != nil { + return nil, err + } + return resp, nil +} diff --git a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/fake/server_factory.go b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/fake/server_factory.go index f319773b0517..ac9320b6a0a1 100644 --- a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/fake/server_factory.go +++ b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/fake/server_factory.go @@ -19,10 +19,13 @@ import ( // ServerFactory is a fake server for instances of the armalertsmanagement.ClientFactory type. type ServerFactory struct { - AlertProcessingRulesServer AlertProcessingRulesServer - AlertsServer AlertsServer - OperationsServer OperationsServer - SmartGroupsServer SmartGroupsServer + AlertProcessingRulesServer AlertProcessingRulesServer + AlertRuleRecommendationsServer AlertRuleRecommendationsServer + AlertsServer AlertsServer + OperationsServer OperationsServer + PrometheusRuleGroupsServer PrometheusRuleGroupsServer + SmartGroupsServer SmartGroupsServer + TenantActivityLogAlertsServer TenantActivityLogAlertsServer } // NewServerFactoryTransport creates a new instance of ServerFactoryTransport with the provided implementation. @@ -37,12 +40,15 @@ func NewServerFactoryTransport(srv *ServerFactory) *ServerFactoryTransport { // ServerFactoryTransport connects instances of armalertsmanagement.ClientFactory to instances of ServerFactory. // Don't use this type directly, use NewServerFactoryTransport instead. type ServerFactoryTransport struct { - srv *ServerFactory - trMu sync.Mutex - trAlertProcessingRulesServer *AlertProcessingRulesServerTransport - trAlertsServer *AlertsServerTransport - trOperationsServer *OperationsServerTransport - trSmartGroupsServer *SmartGroupsServerTransport + srv *ServerFactory + trMu sync.Mutex + trAlertProcessingRulesServer *AlertProcessingRulesServerTransport + trAlertRuleRecommendationsServer *AlertRuleRecommendationsServerTransport + trAlertsServer *AlertsServerTransport + trOperationsServer *OperationsServerTransport + trPrometheusRuleGroupsServer *PrometheusRuleGroupsServerTransport + trSmartGroupsServer *SmartGroupsServerTransport + trTenantActivityLogAlertsServer *TenantActivityLogAlertsServerTransport } // Do implements the policy.Transporter interface for ServerFactoryTransport. @@ -63,15 +69,30 @@ func (s *ServerFactoryTransport) Do(req *http.Request) (*http.Response, error) { return NewAlertProcessingRulesServerTransport(&s.srv.AlertProcessingRulesServer) }) resp, err = s.trAlertProcessingRulesServer.Do(req) + case "AlertRuleRecommendationsClient": + initServer(s, &s.trAlertRuleRecommendationsServer, func() *AlertRuleRecommendationsServerTransport { + return NewAlertRuleRecommendationsServerTransport(&s.srv.AlertRuleRecommendationsServer) + }) + resp, err = s.trAlertRuleRecommendationsServer.Do(req) case "AlertsClient": initServer(s, &s.trAlertsServer, func() *AlertsServerTransport { return NewAlertsServerTransport(&s.srv.AlertsServer) }) resp, err = s.trAlertsServer.Do(req) case "OperationsClient": initServer(s, &s.trOperationsServer, func() *OperationsServerTransport { return NewOperationsServerTransport(&s.srv.OperationsServer) }) resp, err = s.trOperationsServer.Do(req) + case "PrometheusRuleGroupsClient": + initServer(s, &s.trPrometheusRuleGroupsServer, func() *PrometheusRuleGroupsServerTransport { + return NewPrometheusRuleGroupsServerTransport(&s.srv.PrometheusRuleGroupsServer) + }) + resp, err = s.trPrometheusRuleGroupsServer.Do(req) case "SmartGroupsClient": initServer(s, &s.trSmartGroupsServer, func() *SmartGroupsServerTransport { return NewSmartGroupsServerTransport(&s.srv.SmartGroupsServer) }) resp, err = s.trSmartGroupsServer.Do(req) + case "TenantActivityLogAlertsClient": + initServer(s, &s.trTenantActivityLogAlertsServer, func() *TenantActivityLogAlertsServerTransport { + return NewTenantActivityLogAlertsServerTransport(&s.srv.TenantActivityLogAlertsServer) + }) + resp, err = s.trTenantActivityLogAlertsServer.Do(req) default: err = fmt.Errorf("unhandled client %s", client) } diff --git a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/fake/tenantactivitylogalerts_server.go b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/fake/tenantactivitylogalerts_server.go new file mode 100644 index 000000000000..c41adceb5a50 --- /dev/null +++ b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/fake/tenantactivitylogalerts_server.go @@ -0,0 +1,308 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/alertsmanagement/armalertsmanagement" + "net/http" + "net/url" + "regexp" +) + +// TenantActivityLogAlertsServer is a fake server for instances of the armalertsmanagement.TenantActivityLogAlertsClient type. +type TenantActivityLogAlertsServer struct { + // CreateOrUpdate is the fake for method TenantActivityLogAlertsClient.CreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + CreateOrUpdate func(ctx context.Context, managementGroupName string, alertRuleName string, tenantActivityLogAlertRule armalertsmanagement.TenantActivityLogAlertResource, options *armalertsmanagement.TenantActivityLogAlertsClientCreateOrUpdateOptions) (resp azfake.Responder[armalertsmanagement.TenantActivityLogAlertsClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // Delete is the fake for method TenantActivityLogAlertsClient.Delete + // HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent + Delete func(ctx context.Context, managementGroupName string, alertRuleName string, options *armalertsmanagement.TenantActivityLogAlertsClientDeleteOptions) (resp azfake.Responder[armalertsmanagement.TenantActivityLogAlertsClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method TenantActivityLogAlertsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, managementGroupName string, alertRuleName string, options *armalertsmanagement.TenantActivityLogAlertsClientGetOptions) (resp azfake.Responder[armalertsmanagement.TenantActivityLogAlertsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByManagementGroupPager is the fake for method TenantActivityLogAlertsClient.NewListByManagementGroupPager + // HTTP status codes to indicate success: http.StatusOK + NewListByManagementGroupPager func(managementGroupName string, options *armalertsmanagement.TenantActivityLogAlertsClientListByManagementGroupOptions) (resp azfake.PagerResponder[armalertsmanagement.TenantActivityLogAlertsClientListByManagementGroupResponse]) + + // NewListByTenantPager is the fake for method TenantActivityLogAlertsClient.NewListByTenantPager + // HTTP status codes to indicate success: http.StatusOK + NewListByTenantPager func(options *armalertsmanagement.TenantActivityLogAlertsClientListByTenantOptions) (resp azfake.PagerResponder[armalertsmanagement.TenantActivityLogAlertsClientListByTenantResponse]) + + // Update is the fake for method TenantActivityLogAlertsClient.Update + // HTTP status codes to indicate success: http.StatusOK + Update func(ctx context.Context, managementGroupName string, alertRuleName string, tenantActivityLogAlertRulePatch armalertsmanagement.TenantAlertRulePatchObject, options *armalertsmanagement.TenantActivityLogAlertsClientUpdateOptions) (resp azfake.Responder[armalertsmanagement.TenantActivityLogAlertsClientUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewTenantActivityLogAlertsServerTransport creates a new instance of TenantActivityLogAlertsServerTransport with the provided implementation. +// The returned TenantActivityLogAlertsServerTransport instance is connected to an instance of armalertsmanagement.TenantActivityLogAlertsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewTenantActivityLogAlertsServerTransport(srv *TenantActivityLogAlertsServer) *TenantActivityLogAlertsServerTransport { + return &TenantActivityLogAlertsServerTransport{ + srv: srv, + newListByManagementGroupPager: newTracker[azfake.PagerResponder[armalertsmanagement.TenantActivityLogAlertsClientListByManagementGroupResponse]](), + newListByTenantPager: newTracker[azfake.PagerResponder[armalertsmanagement.TenantActivityLogAlertsClientListByTenantResponse]](), + } +} + +// TenantActivityLogAlertsServerTransport connects instances of armalertsmanagement.TenantActivityLogAlertsClient to instances of TenantActivityLogAlertsServer. +// Don't use this type directly, use NewTenantActivityLogAlertsServerTransport instead. +type TenantActivityLogAlertsServerTransport struct { + srv *TenantActivityLogAlertsServer + newListByManagementGroupPager *tracker[azfake.PagerResponder[armalertsmanagement.TenantActivityLogAlertsClientListByManagementGroupResponse]] + newListByTenantPager *tracker[azfake.PagerResponder[armalertsmanagement.TenantActivityLogAlertsClientListByTenantResponse]] +} + +// Do implements the policy.Transporter interface for TenantActivityLogAlertsServerTransport. +func (t *TenantActivityLogAlertsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + var resp *http.Response + var err error + + switch method { + case "TenantActivityLogAlertsClient.CreateOrUpdate": + resp, err = t.dispatchCreateOrUpdate(req) + case "TenantActivityLogAlertsClient.Delete": + resp, err = t.dispatchDelete(req) + case "TenantActivityLogAlertsClient.Get": + resp, err = t.dispatchGet(req) + case "TenantActivityLogAlertsClient.NewListByManagementGroupPager": + resp, err = t.dispatchNewListByManagementGroupPager(req) + case "TenantActivityLogAlertsClient.NewListByTenantPager": + resp, err = t.dispatchNewListByTenantPager(req) + case "TenantActivityLogAlertsClient.Update": + resp, err = t.dispatchUpdate(req) + default: + err = fmt.Errorf("unhandled API %s", method) + } + + if err != nil { + return nil, err + } + + return resp, nil +} + +func (t *TenantActivityLogAlertsServerTransport) dispatchCreateOrUpdate(req *http.Request) (*http.Response, error) { + if t.srv.CreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method CreateOrUpdate not implemented")} + } + const regexStr = `/providers/Microsoft\.Management/managementGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.AlertsManagement/tenantActivityLogAlerts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armalertsmanagement.TenantActivityLogAlertResource](req) + if err != nil { + return nil, err + } + managementGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("managementGroupName")]) + if err != nil { + return nil, err + } + alertRuleNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("alertRuleName")]) + if err != nil { + return nil, err + } + respr, errRespr := t.srv.CreateOrUpdate(req.Context(), managementGroupNameParam, alertRuleNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK, http.StatusCreated}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).TenantActivityLogAlertResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (t *TenantActivityLogAlertsServerTransport) dispatchDelete(req *http.Request) (*http.Response, error) { + if t.srv.Delete == nil { + return nil, &nonRetriableError{errors.New("fake for method Delete not implemented")} + } + const regexStr = `/providers/Microsoft\.Management/managementGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.AlertsManagement/tenantActivityLogAlerts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + managementGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("managementGroupName")]) + if err != nil { + return nil, err + } + alertRuleNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("alertRuleName")]) + if err != nil { + return nil, err + } + respr, errRespr := t.srv.Delete(req.Context(), managementGroupNameParam, alertRuleNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK, http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (t *TenantActivityLogAlertsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if t.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/providers/Microsoft\.Management/managementGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.AlertsManagement/tenantActivityLogAlerts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + managementGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("managementGroupName")]) + if err != nil { + return nil, err + } + alertRuleNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("alertRuleName")]) + if err != nil { + return nil, err + } + respr, errRespr := t.srv.Get(req.Context(), managementGroupNameParam, alertRuleNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).TenantActivityLogAlertResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (t *TenantActivityLogAlertsServerTransport) dispatchNewListByManagementGroupPager(req *http.Request) (*http.Response, error) { + if t.srv.NewListByManagementGroupPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByManagementGroupPager not implemented")} + } + newListByManagementGroupPager := t.newListByManagementGroupPager.get(req) + if newListByManagementGroupPager == nil { + const regexStr = `/providers/Microsoft\.Management/managementGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.AlertsManagement/tenantActivityLogAlerts` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 1 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + managementGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("managementGroupName")]) + if err != nil { + return nil, err + } + resp := t.srv.NewListByManagementGroupPager(managementGroupNameParam, nil) + newListByManagementGroupPager = &resp + t.newListByManagementGroupPager.add(req, newListByManagementGroupPager) + server.PagerResponderInjectNextLinks(newListByManagementGroupPager, req, func(page *armalertsmanagement.TenantActivityLogAlertsClientListByManagementGroupResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByManagementGroupPager, req) + if err != nil { + return nil, err + } + if !contains([]int{http.StatusOK}, resp.StatusCode) { + t.newListByManagementGroupPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByManagementGroupPager) { + t.newListByManagementGroupPager.remove(req) + } + return resp, nil +} + +func (t *TenantActivityLogAlertsServerTransport) dispatchNewListByTenantPager(req *http.Request) (*http.Response, error) { + if t.srv.NewListByTenantPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByTenantPager not implemented")} + } + newListByTenantPager := t.newListByTenantPager.get(req) + if newListByTenantPager == nil { + resp := t.srv.NewListByTenantPager(nil) + newListByTenantPager = &resp + t.newListByTenantPager.add(req, newListByTenantPager) + server.PagerResponderInjectNextLinks(newListByTenantPager, req, func(page *armalertsmanagement.TenantActivityLogAlertsClientListByTenantResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByTenantPager, req) + if err != nil { + return nil, err + } + if !contains([]int{http.StatusOK}, resp.StatusCode) { + t.newListByTenantPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByTenantPager) { + t.newListByTenantPager.remove(req) + } + return resp, nil +} + +func (t *TenantActivityLogAlertsServerTransport) dispatchUpdate(req *http.Request) (*http.Response, error) { + if t.srv.Update == nil { + return nil, &nonRetriableError{errors.New("fake for method Update not implemented")} + } + const regexStr = `/providers/Microsoft\.Management/managementGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.AlertsManagement/tenantActivityLogAlerts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armalertsmanagement.TenantAlertRulePatchObject](req) + if err != nil { + return nil, err + } + managementGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("managementGroupName")]) + if err != nil { + return nil, err + } + alertRuleNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("alertRuleName")]) + if err != nil { + return nil, err + } + respr, errRespr := t.srv.Update(req.Context(), managementGroupNameParam, alertRuleNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).TenantActivityLogAlertResource, req) + if err != nil { + return nil, err + } + return resp, nil +} diff --git a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/fake/time_rfc3339.go b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/fake/time_rfc3339.go index b0535a7b63e6..81f308b0d343 100644 --- a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/fake/time_rfc3339.go +++ b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/fake/time_rfc3339.go @@ -19,12 +19,16 @@ import ( ) // Azure reports time in UTC but it doesn't include the 'Z' time zone suffix in some cases. -var tzOffsetRegex = regexp.MustCompile(`(Z|z|\+|-)(\d+:\d+)*"*$`) +var tzOffsetRegex = regexp.MustCompile(`(?:Z|z|\+|-)(?:\d+:\d+)*"*$`) const ( - utcDateTimeJSON = `"2006-01-02T15:04:05.999999999"` - utcDateTime = "2006-01-02T15:04:05.999999999" - dateTimeJSON = `"` + time.RFC3339Nano + `"` + utcDateTime = "2006-01-02T15:04:05.999999999" + utcDateTimeJSON = `"` + utcDateTime + `"` + utcDateTimeNoT = "2006-01-02 15:04:05.999999999" + utcDateTimeJSONNoT = `"` + utcDateTimeNoT + `"` + dateTimeNoT = `2006-01-02 15:04:05.999999999Z07:00` + dateTimeJSON = `"` + time.RFC3339Nano + `"` + dateTimeJSONNoT = `"` + dateTimeNoT + `"` ) type dateTimeRFC3339 time.Time @@ -40,17 +44,33 @@ func (t dateTimeRFC3339) MarshalText() ([]byte, error) { } func (t *dateTimeRFC3339) UnmarshalJSON(data []byte) error { - layout := utcDateTimeJSON - if tzOffsetRegex.Match(data) { + tzOffset := tzOffsetRegex.Match(data) + hasT := strings.Contains(string(data), "T") || strings.Contains(string(data), "t") + var layout string + if tzOffset && hasT { layout = dateTimeJSON + } else if tzOffset { + layout = dateTimeJSONNoT + } else if hasT { + layout = utcDateTimeJSON + } else { + layout = utcDateTimeJSONNoT } return t.Parse(layout, string(data)) } func (t *dateTimeRFC3339) UnmarshalText(data []byte) error { - layout := utcDateTime - if tzOffsetRegex.Match(data) { + tzOffset := tzOffsetRegex.Match(data) + hasT := strings.Contains(string(data), "T") || strings.Contains(string(data), "t") + var layout string + if tzOffset && hasT { layout = time.RFC3339Nano + } else if tzOffset { + layout = dateTimeNoT + } else if hasT { + layout = utcDateTime + } else { + layout = utcDateTimeNoT } return t.Parse(layout, string(data)) } @@ -61,6 +81,10 @@ func (t *dateTimeRFC3339) Parse(layout, value string) error { return err } +func (t dateTimeRFC3339) String() string { + return time.Time(t).Format(time.RFC3339Nano) +} + func populateDateTimeRFC3339(m map[string]any, k string, t *time.Time) { if t == nil { return @@ -74,7 +98,7 @@ func populateDateTimeRFC3339(m map[string]any, k string, t *time.Time) { } func unpopulateDateTimeRFC3339(data json.RawMessage, fn string, t **time.Time) error { - if data == nil || strings.EqualFold(string(data), "null") { + if data == nil || string(data) == "null" { return nil } var aux dateTimeRFC3339 diff --git a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/models.go b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/models.go index d5465d8b480a..55e3b9f72d74 100644 --- a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/models.go +++ b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/models.go @@ -19,6 +19,24 @@ type Action struct { // GetAction implements the ActionClassification interface for type Action. func (a *Action) GetAction() *Action { return a } +// ActionGroup - A pointer to an Azure Action Group. +type ActionGroup struct { + // REQUIRED; The resource ID of the Action Group. This cannot be null or empty. + ActionGroupID *string + + // Predefined list of properties and configuration items for the action group. + ActionProperties map[string]*string + + // the dictionary of custom properties to include with the post operation. These data are appended to the webhook payload. + WebhookProperties map[string]*string +} + +// ActionList - A list of Activity Log Alert rule actions. +type ActionList struct { + // The list of the Action Groups. + ActionGroups []*ActionGroup +} + // ActionStatus - Action status type ActionStatus struct { // Value indicating whether alert is suppressed. @@ -171,6 +189,115 @@ type AlertProperties struct { EgressConfig any } +// AlertRuleAllOfCondition - An Activity Log Alert rule condition that is met when all its member conditions are met. +type AlertRuleAllOfCondition struct { + // REQUIRED; The list of Activity Log Alert rule conditions. + AllOf []*AlertRuleAnyOfOrLeafCondition +} + +// AlertRuleAnyOfOrLeafCondition - An Activity Log Alert rule condition that is met when all its member conditions are met. +// Each condition can be of one of the following types:Important: Each type has its unique subset of properties. +// Properties from different types CANNOT exist in one condition. +// * Leaf Condition - must contain 'field' and either 'equals' or 'containsAny'.Please note, 'anyOf' should not be set in +// a Leaf Condition. +// * AnyOf Condition - must contain only 'anyOf' (which is an array of Leaf Conditions).Please note, 'field', 'equals' and +// 'containsAny' should not be set in an AnyOf Condition. +type AlertRuleAnyOfOrLeafCondition struct { + // An Activity Log Alert rule condition that is met when at least one of its member leaf conditions are met. + AnyOf []*AlertRuleLeafCondition + + // The value of the event's field will be compared to the values in this array (case-insensitive) to determine if the condition + // is met. + ContainsAny []*string + + // The value of the event's field will be compared to this value (case-insensitive) to determine if the condition is met. + Equals *string + + // The name of the Activity Log event's field that this condition will examine. The possible values for this field are (case-insensitive): + // 'resourceId', 'category', 'caller', 'level', 'operationName', + // 'resourceGroup', 'resourceProvider', 'status', 'subStatus', 'resourceType', or anything beginning with 'properties'. + Field *string +} + +// AlertRuleLeafCondition - An Activity Log Alert rule condition that is met by comparing the field and value of an Activity +// Log event. This condition must contain 'field' and either 'equals' or 'containsAny'. +type AlertRuleLeafCondition struct { + // The value of the event's field will be compared to the values in this array (case-insensitive) to determine if the condition + // is met. + ContainsAny []*string + + // The value of the event's field will be compared to this value (case-insensitive) to determine if the condition is met. + Equals *string + + // The name of the Activity Log event's field that this condition will examine. The possible values for this field are (case-insensitive): + // 'resourceId', 'category', 'caller', 'level', 'operationName', + // 'resourceGroup', 'resourceProvider', 'status', 'subStatus', 'resourceType', or anything beginning with 'properties'. + Field *string +} + +// AlertRuleProperties - An Azure Activity Log Alert rule. +type AlertRuleProperties struct { + // REQUIRED; The actions that will activate when the condition is met. + Actions *ActionList + + // REQUIRED; The condition that will cause this alert to activate. + Condition *AlertRuleAllOfCondition + + // A description of this Activity Log Alert rule. + Description *string + + // Indicates whether this Activity Log Alert rule is enabled. If an Activity Log Alert rule is not enabled, then none of its + // actions will be activated. + Enabled *bool + + // A list of resource IDs that will be used as prefixes. The alert will only apply to Activity Log events with resource IDs + // that fall under one of these prefixes. This list must include at least one + // item. + Scopes []*string + + // The tenant GUID. Must be provided for tenant-level and management group events rules. + TenantScope *string +} + +// AlertRuleRecommendationProperties - Describes the format of Alert Rule Recommendations response. +type AlertRuleRecommendationProperties struct { + // REQUIRED; The recommendation alert rule type. + AlertRuleType *string + + // REQUIRED; A dictionary that provides the display information for an alert rule recommendation. + DisplayInformation map[string]*string + + // REQUIRED; A complete ARM template to deploy the alert rules. + RuleArmTemplate *RuleArmTemplate +} + +// AlertRuleRecommendationResource - A single alert rule recommendation resource. +type AlertRuleRecommendationResource struct { + // REQUIRED; recommendation properties. + Properties *AlertRuleRecommendationProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// AlertRuleRecommendationsListResponse - List of alert rule recommendations. +type AlertRuleRecommendationsListResponse struct { + // REQUIRED; the values for the alert rule recommendations. + Value []*AlertRuleRecommendationResource + + // URL to fetch the next set of recommendations. + NextLink *string +} + // AlertsList - List the alerts. type AlertsList struct { // URL to fetch the next set of alerts. @@ -240,6 +367,11 @@ type AlertsSummaryGroupItem struct { Values []*AlertsSummaryGroupItem } +// Comments - Change alert state reason +type Comments struct { + Comments *string +} + // Condition to trigger an alert processing rule. type Condition struct { // Field for a given condition. @@ -273,69 +405,6 @@ func (d *DailyRecurrence) GetRecurrence() *Recurrence { } } -// ErrorResponse - An error response from the service. -type ErrorResponse struct { - // Details of error response. - Error *ErrorResponseBody -} - -// ErrorResponseAutoGenerated - An error response from the service. -type ErrorResponseAutoGenerated struct { - // Details of error response. - Error *ErrorResponseBodyAutoGenerated -} - -// ErrorResponseAutoGenerated2 - An error response from the service. -type ErrorResponseAutoGenerated2 struct { - // Details of error response. - Error *ErrorResponseBodyAutoGenerated2 -} - -// ErrorResponseBody - Details of error response. -type ErrorResponseBody struct { - // Error code, intended to be consumed programmatically. - Code *string - - // A list of additional details about the error. - Details []*ErrorResponseBody - - // Description of the error, intended for display in user interface. - Message *string - - // Target of the particular error, for example name of the property. - Target *string -} - -// ErrorResponseBodyAutoGenerated - Details of error response. -type ErrorResponseBodyAutoGenerated struct { - // Error code, intended to be consumed programmatically. - Code *string - - // A list of additional details about the error. - Details []*ErrorResponseBodyAutoGenerated - - // Description of the error, intended for display in user interface. - Message *string - - // Target of the particular error, for example name of the property. - Target *string -} - -// ErrorResponseBodyAutoGenerated2 - Details of error response. -type ErrorResponseBodyAutoGenerated2 struct { - // Error code, intended to be consumed programmatically. - Code *string - - // A list of additional details about the error. - Details []*ErrorResponseBodyAutoGenerated2 - - // Description of the error, intended for display in user interface. - Message *string - - // Target of the particular error, for example name of the property. - Target *string -} - // Essentials - This object contains consistent fields across different monitor services. type Essentials struct { // Action status @@ -401,24 +470,6 @@ type Essentials struct { StartDateTime *time.Time } -// ManagedResource - An azure managed resource object. -type ManagedResource struct { - // REQUIRED; Resource location - Location *string - - // Resource tags - Tags map[string]*string - - // READ-ONLY; Azure resource Id - ID *string - - // READ-ONLY; Azure resource name - Name *string - - // READ-ONLY; Azure resource type - Type *string -} - // MonitorServiceDetails - Details of a monitor service type MonitorServiceDetails struct { // Monitor service display name @@ -519,6 +570,123 @@ type PatchProperties struct { Enabled *bool } +type PrometheusRule struct { + // REQUIRED; the expression to run for the rule. + Expression *string + + // The array of actions that are performed when the alert rule becomes active, and when an alert condition is resolved. Only + // relevant for alerts. + Actions []*PrometheusRuleGroupAction + + // the name of the alert rule. + Alert *string + + // annotations for rule group. Only relevant for alerts. + Annotations map[string]*string + + // the flag that indicates whether the Prometheus rule is enabled. + Enabled *bool + + // the amount of time alert must be active before firing. Only relevant for alerts. + For *string + + // labels for rule group. Only relevant for alerts. + Labels map[string]*string + + // the name of the recording rule. + Record *string + + // defines the configuration for resolving fired alerts. Only relevant for alerts. + ResolveConfiguration *PrometheusRuleResolveConfiguration + + // the severity of the alerts fired by the rule. Only relevant for alerts. + Severity *int32 +} + +// PrometheusRuleGroupAction - An alert action. Only relevant for alerts. +type PrometheusRuleGroupAction struct { + // The resource id of the action group to use. + ActionGroupID *string + + // The properties of an action group object. + ActionProperties map[string]*string +} + +// PrometheusRuleGroupProperties - An alert rule. +type PrometheusRuleGroupProperties struct { + // REQUIRED; defines the rules in the Prometheus rule group. + Rules []*PrometheusRule + + // REQUIRED; the list of resource id's that this rule group is scoped to. + Scopes []*string + + // the cluster name of the rule group evaluation. + ClusterName *string + + // the description of the Prometheus rule group that will be included in the alert email. + Description *string + + // the flag that indicates whether the Prometheus rule group is enabled. + Enabled *bool + + // the interval in which to run the Prometheus rule group represented in ISO 8601 duration format. Should be between 1 and + // 15 minutes + Interval *string +} + +// PrometheusRuleGroupResource - The Prometheus rule group resource. +type PrometheusRuleGroupResource struct { + // REQUIRED; The geo-location where the resource lives + Location *string + + // REQUIRED; The Prometheus rule group properties of the resource. + Properties *PrometheusRuleGroupProperties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// PrometheusRuleGroupResourceCollection - Represents a collection of alert rule resources. +type PrometheusRuleGroupResourceCollection struct { + // the values for the alert rule resources. + Value []*PrometheusRuleGroupResource +} + +// PrometheusRuleGroupResourcePatch - The Prometheus rule group resource for patch operations. +type PrometheusRuleGroupResourcePatch struct { + Properties *PrometheusRuleGroupResourcePatchProperties + + // Resource tags + Tags map[string]*string +} + +type PrometheusRuleGroupResourcePatchProperties struct { + // the flag that indicates whether the Prometheus rule group is enabled. + Enabled *bool +} + +// PrometheusRuleResolveConfiguration - Specifies the Prometheus alert rule configuration. +type PrometheusRuleResolveConfiguration struct { + // the flag that indicates whether or not to auto resolve a fired alert. + AutoResolved *bool + + // the duration a rule must evaluate as healthy before the fired alert is automatically resolved represented in ISO 8601 duration + // format. Should be between 1 and 15 minutes + TimeToResolve *string +} + // Recurrence object. type Recurrence struct { // REQUIRED; Specifies when the recurrence should be applied. @@ -547,16 +715,22 @@ func (r *RemoveAllActionGroups) GetAction() *Action { } } -// Resource - An azure resource object -type Resource struct { - // READ-ONLY; Azure resource Id - ID *string +// RuleArmTemplate - A complete ARM template to deploy the alert rules. +type RuleArmTemplate struct { + // REQUIRED; A 4 number format for the version number of this template file. For example, 1.0.0.0 + ContentVersion *string - // READ-ONLY; Azure resource name - Name *string + // REQUIRED; Input parameter definitions + Parameters any - // READ-ONLY; Azure resource type - Type *string + // REQUIRED; Alert rule resource definitions + Resources []any + + // REQUIRED; JSON schema reference + Schema *string + + // REQUIRED; Variable definitions + Variables any } // Schedule - Scheduling configuration for a given alert processing rule. @@ -724,6 +898,53 @@ type SystemData struct { LastModifiedByType *CreatedByType } +// TenantActivityLogAlertResource - A Tenant Activity Log Alert rule resource. +type TenantActivityLogAlertResource struct { + // REQUIRED; The Activity Log Alert rule properties of the resource. + Properties *AlertRuleProperties + + // The location of the resource. Since Azure Activity Log Alerts is a global service, the location of the rules should always + // be 'global'. + Location *string + + // The tags of the resource. + Tags map[string]*string + + // READ-ONLY; The resource Id. + ID *string + + // READ-ONLY; The name of the resource. + Name *string + + // READ-ONLY; The type of the resource. + Type *string +} + +// TenantAlertRuleList - A list of Tenant Activity Log Alert rules. +type TenantAlertRuleList struct { + // Provides the link to retrieve the next set of elements. + NextLink *string + + // The list of Tenant Activity Log Alert rules. + Value []*TenantActivityLogAlertResource +} + +// TenantAlertRulePatchObject - An Activity Log Alert rule object for the body of patch operations. +type TenantAlertRulePatchObject struct { + // The activity log alert settings for an update operation. + Properties *TenantAlertRulePatchProperties + + // The resource tags + Tags map[string]*string +} + +// TenantAlertRulePatchProperties - An Activity Log Alert rule properties for patch operations. +type TenantAlertRulePatchProperties struct { + // Indicates whether this Activity Log Alert rule is enabled. If an Activity Log Alert rule is not enabled, then none of its + // actions will be activated. + Enabled *bool +} + // WeeklyRecurrence - Weekly recurrence object. type WeeklyRecurrence struct { // REQUIRED; Specifies the values for weekly recurrence pattern. diff --git a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/models_serde.go b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/models_serde.go index 6428cdef9d4b..5d77ba38aab5 100644 --- a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/models_serde.go +++ b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/models_serde.go @@ -42,6 +42,68 @@ func (a *Action) UnmarshalJSON(data []byte) error { return nil } +// MarshalJSON implements the json.Marshaller interface for type ActionGroup. +func (a ActionGroup) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "actionGroupId", a.ActionGroupID) + populate(objectMap, "actionProperties", a.ActionProperties) + populate(objectMap, "webhookProperties", a.WebhookProperties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ActionGroup. +func (a *ActionGroup) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "actionGroupId": + err = unpopulate(val, "ActionGroupID", &a.ActionGroupID) + delete(rawMsg, key) + case "actionProperties": + err = unpopulate(val, "ActionProperties", &a.ActionProperties) + delete(rawMsg, key) + case "webhookProperties": + err = unpopulate(val, "WebhookProperties", &a.WebhookProperties) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ActionList. +func (a ActionList) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "actionGroups", a.ActionGroups) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ActionList. +func (a *ActionList) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "actionGroups": + err = unpopulate(val, "ActionGroups", &a.ActionGroups) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + // MarshalJSON implements the json.Marshaller interface for type ActionStatus. func (a ActionStatus) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) @@ -424,6 +486,263 @@ func (a *AlertProperties) UnmarshalJSON(data []byte) error { return nil } +// MarshalJSON implements the json.Marshaller interface for type AlertRuleAllOfCondition. +func (a AlertRuleAllOfCondition) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "allOf", a.AllOf) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AlertRuleAllOfCondition. +func (a *AlertRuleAllOfCondition) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "allOf": + err = unpopulate(val, "AllOf", &a.AllOf) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AlertRuleAnyOfOrLeafCondition. +func (a AlertRuleAnyOfOrLeafCondition) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "anyOf", a.AnyOf) + populate(objectMap, "containsAny", a.ContainsAny) + populate(objectMap, "equals", a.Equals) + populate(objectMap, "field", a.Field) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AlertRuleAnyOfOrLeafCondition. +func (a *AlertRuleAnyOfOrLeafCondition) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "anyOf": + err = unpopulate(val, "AnyOf", &a.AnyOf) + delete(rawMsg, key) + case "containsAny": + err = unpopulate(val, "ContainsAny", &a.ContainsAny) + delete(rawMsg, key) + case "equals": + err = unpopulate(val, "Equals", &a.Equals) + delete(rawMsg, key) + case "field": + err = unpopulate(val, "Field", &a.Field) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AlertRuleLeafCondition. +func (a AlertRuleLeafCondition) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "containsAny", a.ContainsAny) + populate(objectMap, "equals", a.Equals) + populate(objectMap, "field", a.Field) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AlertRuleLeafCondition. +func (a *AlertRuleLeafCondition) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "containsAny": + err = unpopulate(val, "ContainsAny", &a.ContainsAny) + delete(rawMsg, key) + case "equals": + err = unpopulate(val, "Equals", &a.Equals) + delete(rawMsg, key) + case "field": + err = unpopulate(val, "Field", &a.Field) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AlertRuleProperties. +func (a AlertRuleProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "actions", a.Actions) + populate(objectMap, "condition", a.Condition) + populate(objectMap, "description", a.Description) + populate(objectMap, "enabled", a.Enabled) + populate(objectMap, "scopes", a.Scopes) + populate(objectMap, "tenantScope", a.TenantScope) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AlertRuleProperties. +func (a *AlertRuleProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "actions": + err = unpopulate(val, "Actions", &a.Actions) + delete(rawMsg, key) + case "condition": + err = unpopulate(val, "Condition", &a.Condition) + delete(rawMsg, key) + case "description": + err = unpopulate(val, "Description", &a.Description) + delete(rawMsg, key) + case "enabled": + err = unpopulate(val, "Enabled", &a.Enabled) + delete(rawMsg, key) + case "scopes": + err = unpopulate(val, "Scopes", &a.Scopes) + delete(rawMsg, key) + case "tenantScope": + err = unpopulate(val, "TenantScope", &a.TenantScope) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AlertRuleRecommendationProperties. +func (a AlertRuleRecommendationProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "alertRuleType", a.AlertRuleType) + populate(objectMap, "displayInformation", a.DisplayInformation) + populate(objectMap, "ruleArmTemplate", a.RuleArmTemplate) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AlertRuleRecommendationProperties. +func (a *AlertRuleRecommendationProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "alertRuleType": + err = unpopulate(val, "AlertRuleType", &a.AlertRuleType) + delete(rawMsg, key) + case "displayInformation": + err = unpopulate(val, "DisplayInformation", &a.DisplayInformation) + delete(rawMsg, key) + case "ruleArmTemplate": + err = unpopulate(val, "RuleArmTemplate", &a.RuleArmTemplate) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AlertRuleRecommendationResource. +func (a AlertRuleRecommendationResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", a.ID) + populate(objectMap, "name", a.Name) + populate(objectMap, "properties", a.Properties) + populate(objectMap, "systemData", a.SystemData) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AlertRuleRecommendationResource. +func (a *AlertRuleRecommendationResource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &a.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &a.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &a.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &a.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &a.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AlertRuleRecommendationsListResponse. +func (a AlertRuleRecommendationsListResponse) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", a.NextLink) + populate(objectMap, "value", a.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AlertRuleRecommendationsListResponse. +func (a *AlertRuleRecommendationsListResponse) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &a.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &a.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + // MarshalJSON implements the json.Marshaller interface for type AlertsList. func (a AlertsList) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) @@ -626,6 +945,33 @@ func (a *AlertsSummaryGroupItem) UnmarshalJSON(data []byte) error { return nil } +// MarshalJSON implements the json.Marshaller interface for type Comments. +func (c Comments) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "comments", c.Comments) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Comments. +func (c *Comments) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "comments": + err = unpopulate(val, "Comments", &c.Comments) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + // MarshalJSON implements the json.Marshaller interface for type Condition. func (c Condition) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) @@ -696,206 +1042,8 @@ func (d *DailyRecurrence) UnmarshalJSON(data []byte) error { return nil } -// MarshalJSON implements the json.Marshaller interface for type ErrorResponse. -func (e ErrorResponse) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]any) - populate(objectMap, "error", e.Error) - return json.Marshal(objectMap) -} - -// UnmarshalJSON implements the json.Unmarshaller interface for type ErrorResponse. -func (e *ErrorResponse) UnmarshalJSON(data []byte) error { - var rawMsg map[string]json.RawMessage - if err := json.Unmarshal(data, &rawMsg); err != nil { - return fmt.Errorf("unmarshalling type %T: %v", e, err) - } - for key, val := range rawMsg { - var err error - switch key { - case "error": - err = unpopulate(val, "Error", &e.Error) - delete(rawMsg, key) - } - if err != nil { - return fmt.Errorf("unmarshalling type %T: %v", e, err) - } - } - return nil -} - -// MarshalJSON implements the json.Marshaller interface for type ErrorResponseAutoGenerated. -func (e ErrorResponseAutoGenerated) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]any) - populate(objectMap, "error", e.Error) - return json.Marshal(objectMap) -} - -// UnmarshalJSON implements the json.Unmarshaller interface for type ErrorResponseAutoGenerated. -func (e *ErrorResponseAutoGenerated) UnmarshalJSON(data []byte) error { - var rawMsg map[string]json.RawMessage - if err := json.Unmarshal(data, &rawMsg); err != nil { - return fmt.Errorf("unmarshalling type %T: %v", e, err) - } - for key, val := range rawMsg { - var err error - switch key { - case "error": - err = unpopulate(val, "Error", &e.Error) - delete(rawMsg, key) - } - if err != nil { - return fmt.Errorf("unmarshalling type %T: %v", e, err) - } - } - return nil -} - -// MarshalJSON implements the json.Marshaller interface for type ErrorResponseAutoGenerated2. -func (e ErrorResponseAutoGenerated2) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]any) - populate(objectMap, "error", e.Error) - return json.Marshal(objectMap) -} - -// UnmarshalJSON implements the json.Unmarshaller interface for type ErrorResponseAutoGenerated2. -func (e *ErrorResponseAutoGenerated2) UnmarshalJSON(data []byte) error { - var rawMsg map[string]json.RawMessage - if err := json.Unmarshal(data, &rawMsg); err != nil { - return fmt.Errorf("unmarshalling type %T: %v", e, err) - } - for key, val := range rawMsg { - var err error - switch key { - case "error": - err = unpopulate(val, "Error", &e.Error) - delete(rawMsg, key) - } - if err != nil { - return fmt.Errorf("unmarshalling type %T: %v", e, err) - } - } - return nil -} - -// MarshalJSON implements the json.Marshaller interface for type ErrorResponseBody. -func (e ErrorResponseBody) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]any) - populate(objectMap, "code", e.Code) - populate(objectMap, "details", e.Details) - populate(objectMap, "message", e.Message) - populate(objectMap, "target", e.Target) - return json.Marshal(objectMap) -} - -// UnmarshalJSON implements the json.Unmarshaller interface for type ErrorResponseBody. -func (e *ErrorResponseBody) UnmarshalJSON(data []byte) error { - var rawMsg map[string]json.RawMessage - if err := json.Unmarshal(data, &rawMsg); err != nil { - return fmt.Errorf("unmarshalling type %T: %v", e, err) - } - for key, val := range rawMsg { - var err error - switch key { - case "code": - err = unpopulate(val, "Code", &e.Code) - delete(rawMsg, key) - case "details": - err = unpopulate(val, "Details", &e.Details) - delete(rawMsg, key) - case "message": - err = unpopulate(val, "Message", &e.Message) - delete(rawMsg, key) - case "target": - err = unpopulate(val, "Target", &e.Target) - delete(rawMsg, key) - } - if err != nil { - return fmt.Errorf("unmarshalling type %T: %v", e, err) - } - } - return nil -} - -// MarshalJSON implements the json.Marshaller interface for type ErrorResponseBodyAutoGenerated. -func (e ErrorResponseBodyAutoGenerated) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]any) - populate(objectMap, "code", e.Code) - populate(objectMap, "details", e.Details) - populate(objectMap, "message", e.Message) - populate(objectMap, "target", e.Target) - return json.Marshal(objectMap) -} - -// UnmarshalJSON implements the json.Unmarshaller interface for type ErrorResponseBodyAutoGenerated. -func (e *ErrorResponseBodyAutoGenerated) UnmarshalJSON(data []byte) error { - var rawMsg map[string]json.RawMessage - if err := json.Unmarshal(data, &rawMsg); err != nil { - return fmt.Errorf("unmarshalling type %T: %v", e, err) - } - for key, val := range rawMsg { - var err error - switch key { - case "code": - err = unpopulate(val, "Code", &e.Code) - delete(rawMsg, key) - case "details": - err = unpopulate(val, "Details", &e.Details) - delete(rawMsg, key) - case "message": - err = unpopulate(val, "Message", &e.Message) - delete(rawMsg, key) - case "target": - err = unpopulate(val, "Target", &e.Target) - delete(rawMsg, key) - } - if err != nil { - return fmt.Errorf("unmarshalling type %T: %v", e, err) - } - } - return nil -} - -// MarshalJSON implements the json.Marshaller interface for type ErrorResponseBodyAutoGenerated2. -func (e ErrorResponseBodyAutoGenerated2) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]any) - populate(objectMap, "code", e.Code) - populate(objectMap, "details", e.Details) - populate(objectMap, "message", e.Message) - populate(objectMap, "target", e.Target) - return json.Marshal(objectMap) -} - -// UnmarshalJSON implements the json.Unmarshaller interface for type ErrorResponseBodyAutoGenerated2. -func (e *ErrorResponseBodyAutoGenerated2) UnmarshalJSON(data []byte) error { - var rawMsg map[string]json.RawMessage - if err := json.Unmarshal(data, &rawMsg); err != nil { - return fmt.Errorf("unmarshalling type %T: %v", e, err) - } - for key, val := range rawMsg { - var err error - switch key { - case "code": - err = unpopulate(val, "Code", &e.Code) - delete(rawMsg, key) - case "details": - err = unpopulate(val, "Details", &e.Details) - delete(rawMsg, key) - case "message": - err = unpopulate(val, "Message", &e.Message) - delete(rawMsg, key) - case "target": - err = unpopulate(val, "Target", &e.Target) - delete(rawMsg, key) - } - if err != nil { - return fmt.Errorf("unmarshalling type %T: %v", e, err) - } - } - return nil -} - -// MarshalJSON implements the json.Marshaller interface for type Essentials. -func (e Essentials) MarshalJSON() ([]byte, error) { +// MarshalJSON implements the json.Marshaller interface for type Essentials. +func (e Essentials) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) populate(objectMap, "actionStatus", e.ActionStatus) populate(objectMap, "alertRule", e.AlertRule) @@ -993,49 +1141,6 @@ func (e *Essentials) UnmarshalJSON(data []byte) error { return nil } -// MarshalJSON implements the json.Marshaller interface for type ManagedResource. -func (m ManagedResource) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]any) - populate(objectMap, "id", m.ID) - populate(objectMap, "location", m.Location) - populate(objectMap, "name", m.Name) - populate(objectMap, "tags", m.Tags) - populate(objectMap, "type", m.Type) - return json.Marshal(objectMap) -} - -// UnmarshalJSON implements the json.Unmarshaller interface for type ManagedResource. -func (m *ManagedResource) UnmarshalJSON(data []byte) error { - var rawMsg map[string]json.RawMessage - if err := json.Unmarshal(data, &rawMsg); err != nil { - return fmt.Errorf("unmarshalling type %T: %v", m, err) - } - for key, val := range rawMsg { - var err error - switch key { - case "id": - err = unpopulate(val, "ID", &m.ID) - delete(rawMsg, key) - case "location": - err = unpopulate(val, "Location", &m.Location) - delete(rawMsg, key) - case "name": - err = unpopulate(val, "Name", &m.Name) - delete(rawMsg, key) - case "tags": - err = unpopulate(val, "Tags", &m.Tags) - delete(rawMsg, key) - case "type": - err = unpopulate(val, "Type", &m.Type) - delete(rawMsg, key) - } - if err != nil { - return fmt.Errorf("unmarshalling type %T: %v", m, err) - } - } - return nil -} - // MarshalJSON implements the json.Marshaller interface for type MonitorServiceDetails. func (m MonitorServiceDetails) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) @@ -1300,6 +1405,314 @@ func (p *PatchProperties) UnmarshalJSON(data []byte) error { return nil } +// MarshalJSON implements the json.Marshaller interface for type PrometheusRule. +func (p PrometheusRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "actions", p.Actions) + populate(objectMap, "alert", p.Alert) + populate(objectMap, "annotations", p.Annotations) + populate(objectMap, "enabled", p.Enabled) + populate(objectMap, "expression", p.Expression) + populate(objectMap, "for", p.For) + populate(objectMap, "labels", p.Labels) + populate(objectMap, "record", p.Record) + populate(objectMap, "resolveConfiguration", p.ResolveConfiguration) + populate(objectMap, "severity", p.Severity) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrometheusRule. +func (p *PrometheusRule) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "actions": + err = unpopulate(val, "Actions", &p.Actions) + delete(rawMsg, key) + case "alert": + err = unpopulate(val, "Alert", &p.Alert) + delete(rawMsg, key) + case "annotations": + err = unpopulate(val, "Annotations", &p.Annotations) + delete(rawMsg, key) + case "enabled": + err = unpopulate(val, "Enabled", &p.Enabled) + delete(rawMsg, key) + case "expression": + err = unpopulate(val, "Expression", &p.Expression) + delete(rawMsg, key) + case "for": + err = unpopulate(val, "For", &p.For) + delete(rawMsg, key) + case "labels": + err = unpopulate(val, "Labels", &p.Labels) + delete(rawMsg, key) + case "record": + err = unpopulate(val, "Record", &p.Record) + delete(rawMsg, key) + case "resolveConfiguration": + err = unpopulate(val, "ResolveConfiguration", &p.ResolveConfiguration) + delete(rawMsg, key) + case "severity": + err = unpopulate(val, "Severity", &p.Severity) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrometheusRuleGroupAction. +func (p PrometheusRuleGroupAction) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "actionGroupId", p.ActionGroupID) + populate(objectMap, "actionProperties", p.ActionProperties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrometheusRuleGroupAction. +func (p *PrometheusRuleGroupAction) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "actionGroupId": + err = unpopulate(val, "ActionGroupID", &p.ActionGroupID) + delete(rawMsg, key) + case "actionProperties": + err = unpopulate(val, "ActionProperties", &p.ActionProperties) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrometheusRuleGroupProperties. +func (p PrometheusRuleGroupProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "clusterName", p.ClusterName) + populate(objectMap, "description", p.Description) + populate(objectMap, "enabled", p.Enabled) + populate(objectMap, "interval", p.Interval) + populate(objectMap, "rules", p.Rules) + populate(objectMap, "scopes", p.Scopes) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrometheusRuleGroupProperties. +func (p *PrometheusRuleGroupProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "clusterName": + err = unpopulate(val, "ClusterName", &p.ClusterName) + delete(rawMsg, key) + case "description": + err = unpopulate(val, "Description", &p.Description) + delete(rawMsg, key) + case "enabled": + err = unpopulate(val, "Enabled", &p.Enabled) + delete(rawMsg, key) + case "interval": + err = unpopulate(val, "Interval", &p.Interval) + delete(rawMsg, key) + case "rules": + err = unpopulate(val, "Rules", &p.Rules) + delete(rawMsg, key) + case "scopes": + err = unpopulate(val, "Scopes", &p.Scopes) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrometheusRuleGroupResource. +func (p PrometheusRuleGroupResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", p.ID) + populate(objectMap, "location", p.Location) + populate(objectMap, "name", p.Name) + populate(objectMap, "properties", p.Properties) + populate(objectMap, "systemData", p.SystemData) + populate(objectMap, "tags", p.Tags) + populate(objectMap, "type", p.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrometheusRuleGroupResource. +func (p *PrometheusRuleGroupResource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &p.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &p.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &p.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &p.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &p.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &p.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &p.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrometheusRuleGroupResourceCollection. +func (p PrometheusRuleGroupResourceCollection) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", p.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrometheusRuleGroupResourceCollection. +func (p *PrometheusRuleGroupResourceCollection) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + err = unpopulate(val, "Value", &p.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrometheusRuleGroupResourcePatch. +func (p PrometheusRuleGroupResourcePatch) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", p.Properties) + populate(objectMap, "tags", p.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrometheusRuleGroupResourcePatch. +func (p *PrometheusRuleGroupResourcePatch) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, "Properties", &p.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &p.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrometheusRuleGroupResourcePatchProperties. +func (p PrometheusRuleGroupResourcePatchProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "enabled", p.Enabled) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrometheusRuleGroupResourcePatchProperties. +func (p *PrometheusRuleGroupResourcePatchProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "enabled": + err = unpopulate(val, "Enabled", &p.Enabled) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrometheusRuleResolveConfiguration. +func (p PrometheusRuleResolveConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "autoResolved", p.AutoResolved) + populate(objectMap, "timeToResolve", p.TimeToResolve) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrometheusRuleResolveConfiguration. +func (p *PrometheusRuleResolveConfiguration) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "autoResolved": + err = unpopulate(val, "AutoResolved", &p.AutoResolved) + delete(rawMsg, key) + case "timeToResolve": + err = unpopulate(val, "TimeToResolve", &p.TimeToResolve) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + // MarshalJSON implements the json.Marshaller interface for type Recurrence. func (r Recurrence) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) @@ -1362,17 +1775,19 @@ func (r *RemoveAllActionGroups) UnmarshalJSON(data []byte) error { return nil } -// MarshalJSON implements the json.Marshaller interface for type Resource. -func (r Resource) MarshalJSON() ([]byte, error) { +// MarshalJSON implements the json.Marshaller interface for type RuleArmTemplate. +func (r RuleArmTemplate) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) - populate(objectMap, "id", r.ID) - populate(objectMap, "name", r.Name) - populate(objectMap, "type", r.Type) + populate(objectMap, "contentVersion", r.ContentVersion) + populateAny(objectMap, "parameters", r.Parameters) + populate(objectMap, "resources", r.Resources) + populate(objectMap, "$schema", r.Schema) + populateAny(objectMap, "variables", r.Variables) return json.Marshal(objectMap) } -// UnmarshalJSON implements the json.Unmarshaller interface for type Resource. -func (r *Resource) UnmarshalJSON(data []byte) error { +// UnmarshalJSON implements the json.Unmarshaller interface for type RuleArmTemplate. +func (r *RuleArmTemplate) UnmarshalJSON(data []byte) error { var rawMsg map[string]json.RawMessage if err := json.Unmarshal(data, &rawMsg); err != nil { return fmt.Errorf("unmarshalling type %T: %v", r, err) @@ -1380,14 +1795,20 @@ func (r *Resource) UnmarshalJSON(data []byte) error { for key, val := range rawMsg { var err error switch key { - case "id": - err = unpopulate(val, "ID", &r.ID) + case "contentVersion": + err = unpopulate(val, "ContentVersion", &r.ContentVersion) delete(rawMsg, key) - case "name": - err = unpopulate(val, "Name", &r.Name) + case "parameters": + err = unpopulate(val, "Parameters", &r.Parameters) delete(rawMsg, key) - case "type": - err = unpopulate(val, "Type", &r.Type) + case "resources": + err = unpopulate(val, "Resources", &r.Resources) + delete(rawMsg, key) + case "$schema": + err = unpopulate(val, "Schema", &r.Schema) + delete(rawMsg, key) + case "variables": + err = unpopulate(val, "Variables", &r.Variables) delete(rawMsg, key) } if err != nil { @@ -1788,6 +2209,142 @@ func (s *SystemData) UnmarshalJSON(data []byte) error { return nil } +// MarshalJSON implements the json.Marshaller interface for type TenantActivityLogAlertResource. +func (t TenantActivityLogAlertResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", t.ID) + populate(objectMap, "location", t.Location) + populate(objectMap, "name", t.Name) + populate(objectMap, "properties", t.Properties) + populate(objectMap, "tags", t.Tags) + populate(objectMap, "type", t.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TenantActivityLogAlertResource. +func (t *TenantActivityLogAlertResource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &t.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &t.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &t.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &t.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &t.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &t.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type TenantAlertRuleList. +func (t TenantAlertRuleList) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", t.NextLink) + populate(objectMap, "value", t.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TenantAlertRuleList. +func (t *TenantAlertRuleList) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &t.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &t.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type TenantAlertRulePatchObject. +func (t TenantAlertRulePatchObject) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", t.Properties) + populate(objectMap, "tags", t.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TenantAlertRulePatchObject. +func (t *TenantAlertRulePatchObject) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, "Properties", &t.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &t.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type TenantAlertRulePatchProperties. +func (t TenantAlertRulePatchProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "enabled", t.Enabled) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TenantAlertRulePatchProperties. +func (t *TenantAlertRulePatchProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "enabled": + err = unpopulate(val, "Enabled", &t.Enabled) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + // MarshalJSON implements the json.Marshaller interface for type WeeklyRecurrence. func (w WeeklyRecurrence) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) @@ -1848,7 +2405,7 @@ func populateAny(m map[string]any, k string, v any) { } func unpopulate(data json.RawMessage, fn string, v any) error { - if data == nil { + if data == nil || string(data) == "null" { return nil } if err := json.Unmarshal(data, v); err != nil { diff --git a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/operations_client_example_test.go b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/operations_client_example_test.go index 477a5f6fa275..5c653a2bbaa3 100644 --- a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/operations_client_example_test.go +++ b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/operations_client_example_test.go @@ -17,7 +17,7 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/alertsmanagement/armalertsmanagement" ) -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/a436672b07fb1fe276c203b086b3f0e0d0c4aa24/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2019-05-05-preview/examples/Operations_List.json +// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/6d2438481021a94793b07b226df06d5f3c61d51d/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2019-05-05-preview/examples/Operations_List.json func ExampleOperationsClient_NewListPager() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { diff --git a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/options.go b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/options.go index 0797f819717a..95c0f243d9b5 100644 --- a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/options.go +++ b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/options.go @@ -42,10 +42,22 @@ type AlertProcessingRulesClientUpdateOptions struct { // placeholder for future optional parameters } +// AlertRuleRecommendationsClientListByResourceOptions contains the optional parameters for the AlertRuleRecommendationsClient.NewListByResourcePager +// method. +type AlertRuleRecommendationsClientListByResourceOptions struct { + // placeholder for future optional parameters +} + +// AlertRuleRecommendationsClientListByTargetTypeOptions contains the optional parameters for the AlertRuleRecommendationsClient.NewListByTargetTypePager +// method. +type AlertRuleRecommendationsClientListByTargetTypeOptions struct { + // placeholder for future optional parameters +} + // AlertsClientChangeStateOptions contains the optional parameters for the AlertsClient.ChangeState method. type AlertsClientChangeStateOptions struct { // reason of change alert state - Comment *string + Comment *Comments } // AlertsClientGetAllOptions contains the optional parameters for the AlertsClient.NewGetAllPager method. @@ -165,6 +177,39 @@ type OperationsClientListOptions struct { // placeholder for future optional parameters } +// PrometheusRuleGroupsClientCreateOrUpdateOptions contains the optional parameters for the PrometheusRuleGroupsClient.CreateOrUpdate +// method. +type PrometheusRuleGroupsClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// PrometheusRuleGroupsClientDeleteOptions contains the optional parameters for the PrometheusRuleGroupsClient.Delete method. +type PrometheusRuleGroupsClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// PrometheusRuleGroupsClientGetOptions contains the optional parameters for the PrometheusRuleGroupsClient.Get method. +type PrometheusRuleGroupsClientGetOptions struct { + // placeholder for future optional parameters +} + +// PrometheusRuleGroupsClientListByResourceGroupOptions contains the optional parameters for the PrometheusRuleGroupsClient.NewListByResourceGroupPager +// method. +type PrometheusRuleGroupsClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// PrometheusRuleGroupsClientListBySubscriptionOptions contains the optional parameters for the PrometheusRuleGroupsClient.NewListBySubscriptionPager +// method. +type PrometheusRuleGroupsClientListBySubscriptionOptions struct { + // placeholder for future optional parameters +} + +// PrometheusRuleGroupsClientUpdateOptions contains the optional parameters for the PrometheusRuleGroupsClient.Update method. +type PrometheusRuleGroupsClientUpdateOptions struct { + // placeholder for future optional parameters +} + // SmartGroupsClientChangeStateOptions contains the optional parameters for the SmartGroupsClient.ChangeState method. type SmartGroupsClientChangeStateOptions struct { // placeholder for future optional parameters @@ -216,3 +261,38 @@ type SmartGroupsClientGetByIDOptions struct { type SmartGroupsClientGetHistoryOptions struct { // placeholder for future optional parameters } + +// TenantActivityLogAlertsClientCreateOrUpdateOptions contains the optional parameters for the TenantActivityLogAlertsClient.CreateOrUpdate +// method. +type TenantActivityLogAlertsClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// TenantActivityLogAlertsClientDeleteOptions contains the optional parameters for the TenantActivityLogAlertsClient.Delete +// method. +type TenantActivityLogAlertsClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// TenantActivityLogAlertsClientGetOptions contains the optional parameters for the TenantActivityLogAlertsClient.Get method. +type TenantActivityLogAlertsClientGetOptions struct { + // placeholder for future optional parameters +} + +// TenantActivityLogAlertsClientListByManagementGroupOptions contains the optional parameters for the TenantActivityLogAlertsClient.NewListByManagementGroupPager +// method. +type TenantActivityLogAlertsClientListByManagementGroupOptions struct { + // placeholder for future optional parameters +} + +// TenantActivityLogAlertsClientListByTenantOptions contains the optional parameters for the TenantActivityLogAlertsClient.NewListByTenantPager +// method. +type TenantActivityLogAlertsClientListByTenantOptions struct { + // placeholder for future optional parameters +} + +// TenantActivityLogAlertsClientUpdateOptions contains the optional parameters for the TenantActivityLogAlertsClient.Update +// method. +type TenantActivityLogAlertsClientUpdateOptions struct { + // placeholder for future optional parameters +} diff --git a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/polymorphic_helpers.go b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/polymorphic_helpers.go index 42155afb11bb..9d269dab22e7 100644 --- a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/polymorphic_helpers.go +++ b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/polymorphic_helpers.go @@ -11,7 +11,7 @@ package armalertsmanagement import "encoding/json" func unmarshalActionClassification(rawMsg json.RawMessage) (ActionClassification, error) { - if rawMsg == nil { + if rawMsg == nil || string(rawMsg) == "null" { return nil, nil } var m map[string]any @@ -34,7 +34,7 @@ func unmarshalActionClassification(rawMsg json.RawMessage) (ActionClassification } func unmarshalActionClassificationArray(rawMsg json.RawMessage) ([]ActionClassification, error) { - if rawMsg == nil { + if rawMsg == nil || string(rawMsg) == "null" { return nil, nil } var rawMessages []json.RawMessage @@ -53,7 +53,7 @@ func unmarshalActionClassificationArray(rawMsg json.RawMessage) ([]ActionClassif } func unmarshalAlertsMetaDataPropertiesClassification(rawMsg json.RawMessage) (AlertsMetaDataPropertiesClassification, error) { - if rawMsg == nil { + if rawMsg == nil || string(rawMsg) == "null" { return nil, nil } var m map[string]any @@ -74,7 +74,7 @@ func unmarshalAlertsMetaDataPropertiesClassification(rawMsg json.RawMessage) (Al } func unmarshalRecurrenceClassification(rawMsg json.RawMessage) (RecurrenceClassification, error) { - if rawMsg == nil { + if rawMsg == nil || string(rawMsg) == "null" { return nil, nil } var m map[string]any @@ -99,7 +99,7 @@ func unmarshalRecurrenceClassification(rawMsg json.RawMessage) (RecurrenceClassi } func unmarshalRecurrenceClassificationArray(rawMsg json.RawMessage) ([]RecurrenceClassification, error) { - if rawMsg == nil { + if rawMsg == nil || string(rawMsg) == "null" { return nil, nil } var rawMessages []json.RawMessage diff --git a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/prometheusrulegroups_client.go b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/prometheusrulegroups_client.go new file mode 100644 index 000000000000..20ab0125bf09 --- /dev/null +++ b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/prometheusrulegroups_client.go @@ -0,0 +1,419 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armalertsmanagement + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// PrometheusRuleGroupsClient contains the methods for the PrometheusRuleGroups group. +// Don't use this type directly, use NewPrometheusRuleGroupsClient() instead. +type PrometheusRuleGroupsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewPrometheusRuleGroupsClient creates a new instance of PrometheusRuleGroupsClient with the specified values. +// - subscriptionID - The ID of the target subscription. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewPrometheusRuleGroupsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*PrometheusRuleGroupsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &PrometheusRuleGroupsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CreateOrUpdate - Create or update a Prometheus rule group definition. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2021-07-22-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - ruleGroupName - The name of the rule group. +// - parameters - The parameters of the rule group to create or update. +// - options - PrometheusRuleGroupsClientCreateOrUpdateOptions contains the optional parameters for the PrometheusRuleGroupsClient.CreateOrUpdate +// method. +func (client *PrometheusRuleGroupsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, ruleGroupName string, parameters PrometheusRuleGroupResource, options *PrometheusRuleGroupsClientCreateOrUpdateOptions) (PrometheusRuleGroupsClientCreateOrUpdateResponse, error) { + var err error + const operationName = "PrometheusRuleGroupsClient.CreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, ruleGroupName, parameters, options) + if err != nil { + return PrometheusRuleGroupsClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PrometheusRuleGroupsClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return PrometheusRuleGroupsClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *PrometheusRuleGroupsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, ruleGroupName string, parameters PrometheusRuleGroupResource, options *PrometheusRuleGroupsClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AlertsManagement/prometheusRuleGroups/{ruleGroupName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if ruleGroupName == "" { + return nil, errors.New("parameter ruleGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{ruleGroupName}", url.PathEscape(ruleGroupName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-07-22-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, parameters); err != nil { + return nil, err + } + return req, nil +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *PrometheusRuleGroupsClient) createOrUpdateHandleResponse(resp *http.Response) (PrometheusRuleGroupsClientCreateOrUpdateResponse, error) { + result := PrometheusRuleGroupsClientCreateOrUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PrometheusRuleGroupResource); err != nil { + return PrometheusRuleGroupsClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// Delete - Delete a Prometheus rule group definition. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2021-07-22-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - ruleGroupName - The name of the rule group. +// - options - PrometheusRuleGroupsClientDeleteOptions contains the optional parameters for the PrometheusRuleGroupsClient.Delete +// method. +func (client *PrometheusRuleGroupsClient) Delete(ctx context.Context, resourceGroupName string, ruleGroupName string, options *PrometheusRuleGroupsClientDeleteOptions) (PrometheusRuleGroupsClientDeleteResponse, error) { + var err error + const operationName = "PrometheusRuleGroupsClient.Delete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, ruleGroupName, options) + if err != nil { + return PrometheusRuleGroupsClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PrometheusRuleGroupsClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return PrometheusRuleGroupsClientDeleteResponse{}, err + } + return PrometheusRuleGroupsClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *PrometheusRuleGroupsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, ruleGroupName string, options *PrometheusRuleGroupsClientDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AlertsManagement/prometheusRuleGroups/{ruleGroupName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if ruleGroupName == "" { + return nil, errors.New("parameter ruleGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{ruleGroupName}", url.PathEscape(ruleGroupName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-07-22-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Retrieve a Prometheus rule group definition. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2021-07-22-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - ruleGroupName - The name of the rule group. +// - options - PrometheusRuleGroupsClientGetOptions contains the optional parameters for the PrometheusRuleGroupsClient.Get +// method. +func (client *PrometheusRuleGroupsClient) Get(ctx context.Context, resourceGroupName string, ruleGroupName string, options *PrometheusRuleGroupsClientGetOptions) (PrometheusRuleGroupsClientGetResponse, error) { + var err error + const operationName = "PrometheusRuleGroupsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, ruleGroupName, options) + if err != nil { + return PrometheusRuleGroupsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PrometheusRuleGroupsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return PrometheusRuleGroupsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *PrometheusRuleGroupsClient) getCreateRequest(ctx context.Context, resourceGroupName string, ruleGroupName string, options *PrometheusRuleGroupsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AlertsManagement/prometheusRuleGroups/{ruleGroupName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if ruleGroupName == "" { + return nil, errors.New("parameter ruleGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{ruleGroupName}", url.PathEscape(ruleGroupName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-07-22-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *PrometheusRuleGroupsClient) getHandleResponse(resp *http.Response) (PrometheusRuleGroupsClientGetResponse, error) { + result := PrometheusRuleGroupsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PrometheusRuleGroupResource); err != nil { + return PrometheusRuleGroupsClientGetResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - Retrieve Prometheus rule group definitions in a resource group. +// +// Generated from API version 2021-07-22-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - options - PrometheusRuleGroupsClientListByResourceGroupOptions contains the optional parameters for the PrometheusRuleGroupsClient.NewListByResourceGroupPager +// method. +func (client *PrometheusRuleGroupsClient) NewListByResourceGroupPager(resourceGroupName string, options *PrometheusRuleGroupsClientListByResourceGroupOptions) *runtime.Pager[PrometheusRuleGroupsClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[PrometheusRuleGroupsClientListByResourceGroupResponse]{ + More: func(page PrometheusRuleGroupsClientListByResourceGroupResponse) bool { + return false + }, + Fetcher: func(ctx context.Context, page *PrometheusRuleGroupsClientListByResourceGroupResponse) (PrometheusRuleGroupsClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "PrometheusRuleGroupsClient.NewListByResourceGroupPager") + req, err := client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options) + if err != nil { + return PrometheusRuleGroupsClientListByResourceGroupResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PrometheusRuleGroupsClientListByResourceGroupResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return PrometheusRuleGroupsClientListByResourceGroupResponse{}, runtime.NewResponseError(resp) + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *PrometheusRuleGroupsClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *PrometheusRuleGroupsClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AlertsManagement/prometheusRuleGroups" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-07-22-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *PrometheusRuleGroupsClient) listByResourceGroupHandleResponse(resp *http.Response) (PrometheusRuleGroupsClientListByResourceGroupResponse, error) { + result := PrometheusRuleGroupsClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PrometheusRuleGroupResourceCollection); err != nil { + return PrometheusRuleGroupsClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// NewListBySubscriptionPager - Retrieve Prometheus rule group definitions in a subscription. +// +// Generated from API version 2021-07-22-preview +// - options - PrometheusRuleGroupsClientListBySubscriptionOptions contains the optional parameters for the PrometheusRuleGroupsClient.NewListBySubscriptionPager +// method. +func (client *PrometheusRuleGroupsClient) NewListBySubscriptionPager(options *PrometheusRuleGroupsClientListBySubscriptionOptions) *runtime.Pager[PrometheusRuleGroupsClientListBySubscriptionResponse] { + return runtime.NewPager(runtime.PagingHandler[PrometheusRuleGroupsClientListBySubscriptionResponse]{ + More: func(page PrometheusRuleGroupsClientListBySubscriptionResponse) bool { + return false + }, + Fetcher: func(ctx context.Context, page *PrometheusRuleGroupsClientListBySubscriptionResponse) (PrometheusRuleGroupsClientListBySubscriptionResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "PrometheusRuleGroupsClient.NewListBySubscriptionPager") + req, err := client.listBySubscriptionCreateRequest(ctx, options) + if err != nil { + return PrometheusRuleGroupsClientListBySubscriptionResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PrometheusRuleGroupsClientListBySubscriptionResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return PrometheusRuleGroupsClientListBySubscriptionResponse{}, runtime.NewResponseError(resp) + } + return client.listBySubscriptionHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listBySubscriptionCreateRequest creates the ListBySubscription request. +func (client *PrometheusRuleGroupsClient) listBySubscriptionCreateRequest(ctx context.Context, options *PrometheusRuleGroupsClientListBySubscriptionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/prometheusRuleGroups" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-07-22-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listBySubscriptionHandleResponse handles the ListBySubscription response. +func (client *PrometheusRuleGroupsClient) listBySubscriptionHandleResponse(resp *http.Response) (PrometheusRuleGroupsClientListBySubscriptionResponse, error) { + result := PrometheusRuleGroupsClientListBySubscriptionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PrometheusRuleGroupResourceCollection); err != nil { + return PrometheusRuleGroupsClientListBySubscriptionResponse{}, err + } + return result, nil +} + +// Update - Update an Prometheus rule group definition. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2021-07-22-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - ruleGroupName - The name of the rule group. +// - parameters - The parameters of the rule group to update. +// - options - PrometheusRuleGroupsClientUpdateOptions contains the optional parameters for the PrometheusRuleGroupsClient.Update +// method. +func (client *PrometheusRuleGroupsClient) Update(ctx context.Context, resourceGroupName string, ruleGroupName string, parameters PrometheusRuleGroupResourcePatch, options *PrometheusRuleGroupsClientUpdateOptions) (PrometheusRuleGroupsClientUpdateResponse, error) { + var err error + const operationName = "PrometheusRuleGroupsClient.Update" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, ruleGroupName, parameters, options) + if err != nil { + return PrometheusRuleGroupsClientUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PrometheusRuleGroupsClientUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return PrometheusRuleGroupsClientUpdateResponse{}, err + } + resp, err := client.updateHandleResponse(httpResp) + return resp, err +} + +// updateCreateRequest creates the Update request. +func (client *PrometheusRuleGroupsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, ruleGroupName string, parameters PrometheusRuleGroupResourcePatch, options *PrometheusRuleGroupsClientUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AlertsManagement/prometheusRuleGroups/{ruleGroupName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if ruleGroupName == "" { + return nil, errors.New("parameter ruleGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{ruleGroupName}", url.PathEscape(ruleGroupName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-07-22-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, parameters); err != nil { + return nil, err + } + return req, nil +} + +// updateHandleResponse handles the Update response. +func (client *PrometheusRuleGroupsClient) updateHandleResponse(resp *http.Response) (PrometheusRuleGroupsClientUpdateResponse, error) { + result := PrometheusRuleGroupsClientUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PrometheusRuleGroupResource); err != nil { + return PrometheusRuleGroupsClientUpdateResponse{}, err + } + return result, nil +} diff --git a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/prometheusrulegroups_client_example_test.go b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/prometheusrulegroups_client_example_test.go new file mode 100644 index 000000000000..d42aa9d6742d --- /dev/null +++ b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/prometheusrulegroups_client_example_test.go @@ -0,0 +1,473 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// DO NOT EDIT. + +package armalertsmanagement_test + +import ( + "context" + "log" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/alertsmanagement/armalertsmanagement" +) + +// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/6d2438481021a94793b07b226df06d5f3c61d51d/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2021-07-22-preview/examples/listSubscriptionPrometheusRuleGroups.json +func ExamplePrometheusRuleGroupsClient_NewListBySubscriptionPager() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armalertsmanagement.NewClientFactory("", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + pager := clientFactory.NewPrometheusRuleGroupsClient().NewListBySubscriptionPager(nil) + for pager.More() { + page, err := pager.NextPage(ctx) + if err != nil { + log.Fatalf("failed to advance page: %v", err) + } + for _, v := range page.Value { + // You could use page here. We use blank identifier for just demo purposes. + _ = v + } + // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // page.PrometheusRuleGroupResourceCollection = armalertsmanagement.PrometheusRuleGroupResourceCollection{ + // Value: []*armalertsmanagement.PrometheusRuleGroupResource{ + // { + // Type: to.Ptr("Microsoft.AlertsManagement/prometheusRuleGroups"), + // ID: to.Ptr("/subscriptions/ffffffff-ffff-ffff-ffff-ffffffffffff/resourceGroups/promResourceGroup/providers/Microsoft.AlertsManagement/prometheusRuleGroups/myPrometheusRuleGroup"), + // SystemData: &armalertsmanagement.SystemData{ + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2018-06-12T22:05:09.000Z"); return t}()), + // CreatedBy: to.Ptr("abc@microsoft.com"), + // CreatedByType: to.Ptr(armalertsmanagement.CreatedByTypeUser), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2018-06-12T22:05:09.000Z"); return t}()), + // LastModifiedBy: to.Ptr("xyz@microsoft.com"), + // LastModifiedByType: to.Ptr(armalertsmanagement.CreatedByTypeUser), + // }, + // Location: to.Ptr("East US"), + // Properties: &armalertsmanagement.PrometheusRuleGroupProperties{ + // Description: to.Ptr("This is the description of the first rule group"), + // Rules: []*armalertsmanagement.PrometheusRule{ + // { + // Expression: to.Ptr("histogram_quantile(0.99, sum(rate(jobs_duration_seconds_bucket{service=\"billing-processing\"}[5m])) by (job_type))"), + // Record: to.Ptr("job_type:billing_jobs_duration_seconds:99p5m"), + // }, + // { + // Actions: []*armalertsmanagement.PrometheusRuleGroupAction{ + // { + // ActionGroupID: to.Ptr("/subscriptions/ffffffff-ffff-ffff-ffff-ffffffffffff/resourcegroups/promResourceGroup/providers/microsoft.insights/actiongroups/group2"), + // ActionProperties: map[string]*string{ + // "key11": to.Ptr("value11"), + // "key12": to.Ptr("value12"), + // }, + // }}, + // Alert: to.Ptr("Billing_Processing_Very_Slow"), + // Expression: to.Ptr("job_type:billing_jobs_duration_seconds:99p5m > 30"), + // For: to.Ptr("5m"), + // Labels: map[string]*string{ + // "team": to.Ptr("prod"), + // }, + // ResolveConfiguration: &armalertsmanagement.PrometheusRuleResolveConfiguration{ + // AutoResolved: to.Ptr(true), + // TimeToResolve: to.Ptr("10m"), + // }, + // Severity: to.Ptr[int32](2), + // }}, + // Scopes: []*string{ + // to.Ptr("/subscriptions/ffffffff-ffff-ffff-ffff-ffffffffffff/resourceGroups/promResourceGroup/providers/microsoft.monitor/accounts/monitoringAcount/myMonitoringAccount")}, + // }, + // }, + // { + // Type: to.Ptr("Microsoft.AlertsManagement/prometheusRuleGroups"), + // ID: to.Ptr("/subscriptions/ffffffff-ffff-ffff-ffff-ffffffffffff/resourceGroups/promResourceGroup/providers/Microsoft.AlertsManagement/prometheusRuleGroups/myPrometheusRuleGroup2"), + // SystemData: &armalertsmanagement.SystemData{ + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2018-06-12T22:05:13.000Z"); return t}()), + // CreatedBy: to.Ptr("abc@microsoft.com"), + // CreatedByType: to.Ptr(armalertsmanagement.CreatedByTypeUser), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2018-06-12T22:05:13.000Z"); return t}()), + // LastModifiedBy: to.Ptr("xyz@microsoft.com"), + // LastModifiedByType: to.Ptr(armalertsmanagement.CreatedByTypeUser), + // }, + // Location: to.Ptr("East US"), + // Properties: &armalertsmanagement.PrometheusRuleGroupProperties{ + // Description: to.Ptr("This is the description of the first rule group"), + // Rules: []*armalertsmanagement.PrometheusRule{ + // { + // Expression: to.Ptr("histogram_quantile(0.99, sum(rate(jobs_duration_seconds_bucket{service=\"billing-processing\"}[5m])) by (job_type))"), + // Record: to.Ptr("job_type:billing_jobs_duration_seconds:99p5m"), + // }, + // { + // Actions: []*armalertsmanagement.PrometheusRuleGroupAction{ + // { + // ActionGroupID: to.Ptr("/subscriptions/ffffffff-ffff-ffff-ffff-ffffffffffff/resourcegroups/promResourceGroup/providers/microsoft.insights/actiongroups/group2"), + // ActionProperties: map[string]*string{ + // "key11": to.Ptr("value11"), + // "key12": to.Ptr("value12"), + // }, + // }}, + // Alert: to.Ptr("Billing_Processing_Very_Slow"), + // Expression: to.Ptr("job_type:billing_jobs_duration_seconds:99p5m > 30"), + // For: to.Ptr("5m"), + // Labels: map[string]*string{ + // "team": to.Ptr("prod"), + // }, + // ResolveConfiguration: &armalertsmanagement.PrometheusRuleResolveConfiguration{ + // AutoResolved: to.Ptr(true), + // TimeToResolve: to.Ptr("10m"), + // }, + // Severity: to.Ptr[int32](2), + // }}, + // Scopes: []*string{ + // to.Ptr("/subscriptions/ffffffff-ffff-ffff-ffff-ffffffffffff/resourceGroups/promResourceGroup/providers/microsoft.monitor/accounts/monitoringAcount/myMonitoringAccount")}, + // }, + // }}, + // } + } +} + +// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/6d2438481021a94793b07b226df06d5f3c61d51d/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2021-07-22-preview/examples/listPrometheusRuleGroups.json +func ExamplePrometheusRuleGroupsClient_NewListByResourceGroupPager() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armalertsmanagement.NewClientFactory("", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + pager := clientFactory.NewPrometheusRuleGroupsClient().NewListByResourceGroupPager("promResourceGroup", nil) + for pager.More() { + page, err := pager.NextPage(ctx) + if err != nil { + log.Fatalf("failed to advance page: %v", err) + } + for _, v := range page.Value { + // You could use page here. We use blank identifier for just demo purposes. + _ = v + } + // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // page.PrometheusRuleGroupResourceCollection = armalertsmanagement.PrometheusRuleGroupResourceCollection{ + // Value: []*armalertsmanagement.PrometheusRuleGroupResource{ + // { + // Type: to.Ptr("Microsoft.AlertsManagement/prometheusRuleGroups"), + // ID: to.Ptr("/subscriptions/ffffffff-ffff-ffff-ffff-ffffffffffff/resourceGroups/promResourceGroup/providers/Microsoft.AlertsManagement/prometheusRuleGroups/myPrometheusRuleGroup"), + // SystemData: &armalertsmanagement.SystemData{ + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2018-06-12T22:05:09.000Z"); return t}()), + // CreatedBy: to.Ptr("abc@microsoft.com"), + // CreatedByType: to.Ptr(armalertsmanagement.CreatedByTypeUser), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2018-06-12T22:05:09.000Z"); return t}()), + // LastModifiedBy: to.Ptr("xyz@microsoft.com"), + // LastModifiedByType: to.Ptr(armalertsmanagement.CreatedByTypeUser), + // }, + // Location: to.Ptr("East US"), + // Properties: &armalertsmanagement.PrometheusRuleGroupProperties{ + // Description: to.Ptr("This is the description of the first rule group"), + // Rules: []*armalertsmanagement.PrometheusRule{ + // { + // Expression: to.Ptr("histogram_quantile(0.99, sum(rate(jobs_duration_seconds_bucket{service=\"billing-processing\"}[5m])) by (job_type))"), + // Record: to.Ptr("job_type:billing_jobs_duration_seconds:99p5m"), + // }, + // { + // Actions: []*armalertsmanagement.PrometheusRuleGroupAction{ + // { + // ActionGroupID: to.Ptr("/subscriptions/ffffffff-ffff-ffff-ffff-ffffffffffff/resourcegroups/gigtest/providers/microsoft.insights/actiongroups/group2"), + // ActionProperties: map[string]*string{ + // "key11": to.Ptr("value11"), + // "key12": to.Ptr("value12"), + // }, + // }}, + // Alert: to.Ptr("Billing_Processing_Very_Slow"), + // Expression: to.Ptr("job_type:billing_jobs_duration_seconds:99p5m > 30"), + // For: to.Ptr("5m"), + // Labels: map[string]*string{ + // "team": to.Ptr("prod"), + // }, + // ResolveConfiguration: &armalertsmanagement.PrometheusRuleResolveConfiguration{ + // AutoResolved: to.Ptr(true), + // TimeToResolve: to.Ptr("10m"), + // }, + // Severity: to.Ptr[int32](2), + // }}, + // Scopes: []*string{ + // to.Ptr("/subscriptions/ffffffff-ffff-ffff-ffff-ffffffffffff/resourceGroups/promResourceGroup/providers/microsoft.monitor/accounts/myMonitoringAccount")}, + // }, + // }}, + // } + } +} + +// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/6d2438481021a94793b07b226df06d5f3c61d51d/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2021-07-22-preview/examples/getPrometheusRuleGroup.json +func ExamplePrometheusRuleGroupsClient_Get() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armalertsmanagement.NewClientFactory("", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewPrometheusRuleGroupsClient().Get(ctx, "promResourceGroup", "myPrometheusRuleGroup", nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res.PrometheusRuleGroupResource = armalertsmanagement.PrometheusRuleGroupResource{ + // Type: to.Ptr("Microsoft.AlertsManagement/prometheusRuleGroups"), + // ID: to.Ptr("/subscriptions/ffffffff-ffff-ffff-ffff-ffffffffffff/resourceGroups/promResourceGroup/providers/Microsoft.AlertsManagement/prometheusRuleGroups/myPrometheusRuleGroup"), + // SystemData: &armalertsmanagement.SystemData{ + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2018-06-12T22:05:09.000Z"); return t}()), + // CreatedBy: to.Ptr("abc@microsoft.com"), + // CreatedByType: to.Ptr(armalertsmanagement.CreatedByTypeUser), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2018-06-12T22:05:09.000Z"); return t}()), + // LastModifiedBy: to.Ptr("xyz@microsoft.com"), + // LastModifiedByType: to.Ptr(armalertsmanagement.CreatedByTypeUser), + // }, + // Location: to.Ptr("global"), + // Properties: &armalertsmanagement.PrometheusRuleGroupProperties{ + // Description: to.Ptr("This is the description of the first rule group"), + // Rules: []*armalertsmanagement.PrometheusRule{ + // { + // Expression: to.Ptr("histogram_quantile(0.99, sum(rate(jobs_duration_seconds_bucket{service=\"billing-processing\"}[5m])) by (job_type))"), + // Record: to.Ptr("job_type:billing_jobs_duration_seconds:99p5m"), + // }, + // { + // Actions: []*armalertsmanagement.PrometheusRuleGroupAction{ + // { + // ActionGroupID: to.Ptr("/subscriptions/ffffffff-ffff-ffff-ffff-ffffffffffff/resourcegroups/promResourceGroup/providers/microsoft.insights/actiongroups/group2"), + // ActionProperties: map[string]*string{ + // "key11": to.Ptr("value11"), + // "key12": to.Ptr("value12"), + // }, + // }}, + // Alert: to.Ptr("Billing_Processing_Very_Slow"), + // Expression: to.Ptr("job_type:billing_jobs_duration_seconds:99p5m > 30"), + // For: to.Ptr("5m"), + // Labels: map[string]*string{ + // "team": to.Ptr("prod"), + // }, + // ResolveConfiguration: &armalertsmanagement.PrometheusRuleResolveConfiguration{ + // AutoResolved: to.Ptr(true), + // TimeToResolve: to.Ptr("10m"), + // }, + // Severity: to.Ptr[int32](2), + // }}, + // Scopes: []*string{ + // to.Ptr("/subscriptions/ffffffff-ffff-ffff-ffff-ffffffffffff/resourceGroups/promResourceGroup/providers/microsoft.monitor/accounts/myMonitoringAccount")}, + // }, + // } +} + +// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/6d2438481021a94793b07b226df06d5f3c61d51d/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2021-07-22-preview/examples/createOrUpdatePrometheusRuleGroup.json +func ExamplePrometheusRuleGroupsClient_CreateOrUpdate() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armalertsmanagement.NewClientFactory("", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewPrometheusRuleGroupsClient().CreateOrUpdate(ctx, "promResourceGroup", "myPrometheusRuleGroup", armalertsmanagement.PrometheusRuleGroupResource{ + Location: to.Ptr("East US"), + Properties: &armalertsmanagement.PrometheusRuleGroupProperties{ + Description: to.Ptr("This is the description of the first rule group"), + Rules: []*armalertsmanagement.PrometheusRule{ + { + Expression: to.Ptr("histogram_quantile(0.99, sum(rate(jobs_duration_seconds_bucket{service=\"billing-processing\"}[5m])) by (job_type))"), + Labels: map[string]*string{ + "team": to.Ptr("prod"), + }, + Record: to.Ptr("job_type:billing_jobs_duration_seconds:99p5m"), + }, + { + Actions: []*armalertsmanagement.PrometheusRuleGroupAction{ + { + ActionGroupID: to.Ptr("/subscriptions/ffffffff-ffff-ffff-ffff-ffffffffffff/resourcegroups/promResourceGroup/providers/microsoft.insights/actiongroups/group2"), + ActionProperties: map[string]*string{ + "key11": to.Ptr("value11"), + "key12": to.Ptr("value12"), + }, + }}, + Alert: to.Ptr("Billing_Processing_Very_Slow"), + Annotations: map[string]*string{ + "annotationName1": to.Ptr("annotationValue1"), + }, + Expression: to.Ptr("job_type:billing_jobs_duration_seconds:99p5m > 30"), + For: to.Ptr("PT5M"), + Labels: map[string]*string{ + "team": to.Ptr("prod"), + }, + ResolveConfiguration: &armalertsmanagement.PrometheusRuleResolveConfiguration{ + AutoResolved: to.Ptr(true), + TimeToResolve: to.Ptr("PT10M"), + }, + Severity: to.Ptr[int32](2), + }}, + Scopes: []*string{ + to.Ptr("/subscriptions/ffffffff-ffff-ffff-ffff-ffffffffffff/resourceGroups/promResourceGroup/providers/microsoft.monitor/accounts/myMonitoringAccount")}, + }, + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res.PrometheusRuleGroupResource = armalertsmanagement.PrometheusRuleGroupResource{ + // Type: to.Ptr("Microsoft.AlertsManagement/prometheusRuleGroups"), + // ID: to.Ptr("/subscriptions/ffffffff-ffff-ffff-ffff-ffffffffffff/resourceGroups/promResourceGroup/providers/Microsoft.AlertsManagement/prometheusRuleGroups/myPrometheusRuleGroup"), + // SystemData: &armalertsmanagement.SystemData{ + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2018-06-12T22:05:09.000Z"); return t}()), + // CreatedBy: to.Ptr("abc@microsoft.com"), + // CreatedByType: to.Ptr(armalertsmanagement.CreatedByTypeUser), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2018-06-12T22:05:09.000Z"); return t}()), + // LastModifiedBy: to.Ptr("xyz@microsoft.com"), + // LastModifiedByType: to.Ptr(armalertsmanagement.CreatedByTypeUser), + // }, + // Location: to.Ptr("East US"), + // Properties: &armalertsmanagement.PrometheusRuleGroupProperties{ + // Description: to.Ptr("This is the description of the first rule group"), + // Interval: to.Ptr("PT5M"), + // Rules: []*armalertsmanagement.PrometheusRule{ + // { + // Expression: to.Ptr("histogram_quantile(0.99, sum(rate(jobs_duration_seconds_bucket{service=\"billing-processing\"}[5m])) by (job_type))"), + // Labels: map[string]*string{ + // "team": to.Ptr("prod"), + // }, + // Record: to.Ptr("job_type:billing_jobs_duration_seconds:99p5m"), + // }, + // { + // Actions: []*armalertsmanagement.PrometheusRuleGroupAction{ + // { + // ActionGroupID: to.Ptr("/subscriptions/ffffffff-ffff-ffff-ffff-ffffffffffff/resourcegroups/promResourceGroup/providers/microsoft.insights/actiongroups/group2"), + // ActionProperties: map[string]*string{ + // "key11": to.Ptr("value11"), + // "key12": to.Ptr("value12"), + // }, + // }}, + // Alert: to.Ptr("Billing_Processing_Very_Slow"), + // Annotations: map[string]*string{ + // "annotationName1": to.Ptr("annotationValue1"), + // }, + // Expression: to.Ptr("job_type:billing_jobs_duration_seconds:99p5m > 30"), + // For: to.Ptr("PT5M"), + // Labels: map[string]*string{ + // "team": to.Ptr("prod"), + // }, + // ResolveConfiguration: &armalertsmanagement.PrometheusRuleResolveConfiguration{ + // AutoResolved: to.Ptr(true), + // TimeToResolve: to.Ptr("PT10M"), + // }, + // Severity: to.Ptr[int32](2), + // }}, + // Scopes: []*string{ + // to.Ptr("/subscriptions/ffffffff-ffff-ffff-ffff-ffffffffffff/resourceGroups/promResourceGroup/providers/microsoft.monitor/accounts/myMonitoringAccount")}, + // }, + // } +} + +// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/6d2438481021a94793b07b226df06d5f3c61d51d/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2021-07-22-preview/examples/patchPrometheusRuleGroup.json +func ExamplePrometheusRuleGroupsClient_Update() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armalertsmanagement.NewClientFactory("", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewPrometheusRuleGroupsClient().Update(ctx, "promResourceGroup", "myPrometheusRuleGroup", armalertsmanagement.PrometheusRuleGroupResourcePatch{ + Properties: &armalertsmanagement.PrometheusRuleGroupResourcePatchProperties{ + Enabled: to.Ptr(false), + }, + Tags: map[string]*string{ + "tag1": to.Ptr("value1"), + }, + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res.PrometheusRuleGroupResource = armalertsmanagement.PrometheusRuleGroupResource{ + // Type: to.Ptr("Microsoft.AlertsManagement/prometheusRuleGroups"), + // ID: to.Ptr("/subscriptions/ffffffff-ffff-ffff-ffff-ffffffffffff/resourceGroups/promResourceGroup/providers/Microsoft.AlertsManagement/prometheusRuleGroups/myPrometheusRuleGroup"), + // SystemData: &armalertsmanagement.SystemData{ + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2018-06-12T22:05:09.000Z"); return t}()), + // CreatedBy: to.Ptr("abc@microsoft.com"), + // CreatedByType: to.Ptr(armalertsmanagement.CreatedByTypeUser), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2018-06-12T22:05:09.000Z"); return t}()), + // LastModifiedBy: to.Ptr("xyz@microsoft.com"), + // LastModifiedByType: to.Ptr(armalertsmanagement.CreatedByTypeUser), + // }, + // Location: to.Ptr("East US"), + // Tags: map[string]*string{ + // "tag1": to.Ptr("value1"), + // }, + // Properties: &armalertsmanagement.PrometheusRuleGroupProperties{ + // Description: to.Ptr("This is the description of the first rule group"), + // Enabled: to.Ptr(false), + // Rules: []*armalertsmanagement.PrometheusRule{ + // { + // Expression: to.Ptr("histogram_quantile(0.99, sum(rate(jobs_duration_seconds_bucket{service=\"billing-processing\"}[5m])) by (job_type))"), + // Record: to.Ptr("job_type:billing_jobs_duration_seconds:99p5m"), + // }, + // { + // Actions: []*armalertsmanagement.PrometheusRuleGroupAction{ + // { + // ActionGroupID: to.Ptr("/subscriptions/ffffffff-ffff-ffff-ffff-ffffffffffff/resourcegroups/promResourceGroup/providers/microsoft.insights/actiongroups/group2"), + // ActionProperties: map[string]*string{ + // "key11": to.Ptr("value11"), + // "key12": to.Ptr("value12"), + // }, + // }}, + // Alert: to.Ptr("Billing_Processing_Very_Slow"), + // Expression: to.Ptr("job_type:billing_jobs_duration_seconds:99p5m > 30"), + // For: to.Ptr("5m"), + // Labels: map[string]*string{ + // "team": to.Ptr("prod"), + // }, + // ResolveConfiguration: &armalertsmanagement.PrometheusRuleResolveConfiguration{ + // AutoResolved: to.Ptr(true), + // TimeToResolve: to.Ptr("10m"), + // }, + // Severity: to.Ptr[int32](2), + // }}, + // Scopes: []*string{ + // to.Ptr("/subscriptions/ffffffff-ffff-ffff-ffff-ffffffffffff/resourceGroups/promResourceGroup/providers/microsoft.monitor/accounts/monitoringAcount/myMonitoringAccount")}, + // }, + // } +} + +// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/6d2438481021a94793b07b226df06d5f3c61d51d/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2021-07-22-preview/examples/deletePrometheusRuleGroup.json +func ExamplePrometheusRuleGroupsClient_Delete() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armalertsmanagement.NewClientFactory("", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + _, err = clientFactory.NewPrometheusRuleGroupsClient().Delete(ctx, "promResourceGroup", "myPrometheusRuleGroup", nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } +} diff --git a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/response_types.go b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/responses.go similarity index 57% rename from sdk/resourcemanager/alertsmanagement/armalertsmanagement/response_types.go rename to sdk/resourcemanager/alertsmanagement/armalertsmanagement/responses.go index a7bb9bdff918..8c562fc3658c 100644 --- a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/response_types.go +++ b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/responses.go @@ -59,6 +59,18 @@ type AlertProcessingRulesClientUpdateResponse struct { XMSRequestID *string } +// AlertRuleRecommendationsClientListByResourceResponse contains the response from method AlertRuleRecommendationsClient.NewListByResourcePager. +type AlertRuleRecommendationsClientListByResourceResponse struct { + // List of alert rule recommendations. + AlertRuleRecommendationsListResponse +} + +// AlertRuleRecommendationsClientListByTargetTypeResponse contains the response from method AlertRuleRecommendationsClient.NewListByTargetTypePager. +type AlertRuleRecommendationsClientListByTargetTypeResponse struct { + // List of alert rule recommendations. + AlertRuleRecommendationsListResponse +} + // AlertsClientChangeStateResponse contains the response from method AlertsClient.ChangeState. type AlertsClientChangeStateResponse struct { // An alert created in alert management service. @@ -101,6 +113,41 @@ type OperationsClientListResponse struct { OperationsList } +// PrometheusRuleGroupsClientCreateOrUpdateResponse contains the response from method PrometheusRuleGroupsClient.CreateOrUpdate. +type PrometheusRuleGroupsClientCreateOrUpdateResponse struct { + // The Prometheus rule group resource. + PrometheusRuleGroupResource +} + +// PrometheusRuleGroupsClientDeleteResponse contains the response from method PrometheusRuleGroupsClient.Delete. +type PrometheusRuleGroupsClientDeleteResponse struct { + // placeholder for future response values +} + +// PrometheusRuleGroupsClientGetResponse contains the response from method PrometheusRuleGroupsClient.Get. +type PrometheusRuleGroupsClientGetResponse struct { + // The Prometheus rule group resource. + PrometheusRuleGroupResource +} + +// PrometheusRuleGroupsClientListByResourceGroupResponse contains the response from method PrometheusRuleGroupsClient.NewListByResourceGroupPager. +type PrometheusRuleGroupsClientListByResourceGroupResponse struct { + // Represents a collection of alert rule resources. + PrometheusRuleGroupResourceCollection +} + +// PrometheusRuleGroupsClientListBySubscriptionResponse contains the response from method PrometheusRuleGroupsClient.NewListBySubscriptionPager. +type PrometheusRuleGroupsClientListBySubscriptionResponse struct { + // Represents a collection of alert rule resources. + PrometheusRuleGroupResourceCollection +} + +// PrometheusRuleGroupsClientUpdateResponse contains the response from method PrometheusRuleGroupsClient.Update. +type PrometheusRuleGroupsClientUpdateResponse struct { + // The Prometheus rule group resource. + PrometheusRuleGroupResource +} + // SmartGroupsClientChangeStateResponse contains the response from method SmartGroupsClient.ChangeState. type SmartGroupsClientChangeStateResponse struct { // Set of related alerts grouped together smartly by AMS. @@ -130,3 +177,38 @@ type SmartGroupsClientGetHistoryResponse struct { // Alert Modification details SmartGroupModification } + +// TenantActivityLogAlertsClientCreateOrUpdateResponse contains the response from method TenantActivityLogAlertsClient.CreateOrUpdate. +type TenantActivityLogAlertsClientCreateOrUpdateResponse struct { + // A Tenant Activity Log Alert rule resource. + TenantActivityLogAlertResource +} + +// TenantActivityLogAlertsClientDeleteResponse contains the response from method TenantActivityLogAlertsClient.Delete. +type TenantActivityLogAlertsClientDeleteResponse struct { + // placeholder for future response values +} + +// TenantActivityLogAlertsClientGetResponse contains the response from method TenantActivityLogAlertsClient.Get. +type TenantActivityLogAlertsClientGetResponse struct { + // A Tenant Activity Log Alert rule resource. + TenantActivityLogAlertResource +} + +// TenantActivityLogAlertsClientListByManagementGroupResponse contains the response from method TenantActivityLogAlertsClient.NewListByManagementGroupPager. +type TenantActivityLogAlertsClientListByManagementGroupResponse struct { + // A list of Tenant Activity Log Alert rules. + TenantAlertRuleList +} + +// TenantActivityLogAlertsClientListByTenantResponse contains the response from method TenantActivityLogAlertsClient.NewListByTenantPager. +type TenantActivityLogAlertsClientListByTenantResponse struct { + // A list of Tenant Activity Log Alert rules. + TenantAlertRuleList +} + +// TenantActivityLogAlertsClientUpdateResponse contains the response from method TenantActivityLogAlertsClient.Update. +type TenantActivityLogAlertsClientUpdateResponse struct { + // A Tenant Activity Log Alert rule resource. + TenantActivityLogAlertResource +} diff --git a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/smartgroups_client.go b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/smartgroups_client.go index 6fb083a03258..4abbc62e1e68 100644 --- a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/smartgroups_client.go +++ b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/smartgroups_client.go @@ -147,20 +147,15 @@ func (client *SmartGroupsClient) getAllCreateRequest(ctx context.Context, option return nil, err } reqQP := req.Raw().URL.Query() - if options != nil && options.TargetResource != nil { - reqQP.Set("targetResource", *options.TargetResource) - } - if options != nil && options.TargetResourceGroup != nil { - reqQP.Set("targetResourceGroup", *options.TargetResourceGroup) - } - if options != nil && options.TargetResourceType != nil { - reqQP.Set("targetResourceType", *options.TargetResourceType) + reqQP.Set("api-version", "2019-05-05-preview") + if options != nil && options.MonitorCondition != nil { + reqQP.Set("monitorCondition", string(*options.MonitorCondition)) } if options != nil && options.MonitorService != nil { reqQP.Set("monitorService", string(*options.MonitorService)) } - if options != nil && options.MonitorCondition != nil { - reqQP.Set("monitorCondition", string(*options.MonitorCondition)) + if options != nil && options.PageCount != nil { + reqQP.Set("pageCount", strconv.FormatInt(*options.PageCount, 10)) } if options != nil && options.Severity != nil { reqQP.Set("severity", string(*options.Severity)) @@ -168,19 +163,24 @@ func (client *SmartGroupsClient) getAllCreateRequest(ctx context.Context, option if options != nil && options.SmartGroupState != nil { reqQP.Set("smartGroupState", string(*options.SmartGroupState)) } - if options != nil && options.TimeRange != nil { - reqQP.Set("timeRange", string(*options.TimeRange)) - } - if options != nil && options.PageCount != nil { - reqQP.Set("pageCount", strconv.FormatInt(*options.PageCount, 10)) - } if options != nil && options.SortBy != nil { reqQP.Set("sortBy", string(*options.SortBy)) } if options != nil && options.SortOrder != nil { reqQP.Set("sortOrder", string(*options.SortOrder)) } - reqQP.Set("api-version", "2019-05-05-preview") + if options != nil && options.TargetResource != nil { + reqQP.Set("targetResource", *options.TargetResource) + } + if options != nil && options.TargetResourceGroup != nil { + reqQP.Set("targetResourceGroup", *options.TargetResourceGroup) + } + if options != nil && options.TargetResourceType != nil { + reqQP.Set("targetResourceType", *options.TargetResourceType) + } + if options != nil && options.TimeRange != nil { + reqQP.Set("timeRange", string(*options.TimeRange)) + } req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil diff --git a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/smartgroups_client_example_test.go b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/smartgroups_client_example_test.go index d5ff55212622..a0bf5e6e5d9d 100644 --- a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/smartgroups_client_example_test.go +++ b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/smartgroups_client_example_test.go @@ -17,7 +17,7 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/alertsmanagement/armalertsmanagement" ) -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/a436672b07fb1fe276c203b086b3f0e0d0c4aa24/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2019-05-05-preview/examples/SmartGroups_List.json +// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/6d2438481021a94793b07b226df06d5f3c61d51d/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2019-05-05-preview/examples/SmartGroups_List.json func ExampleSmartGroupsClient_NewGetAllPager() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { @@ -172,7 +172,7 @@ func ExampleSmartGroupsClient_NewGetAllPager() { } } -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/a436672b07fb1fe276c203b086b3f0e0d0c4aa24/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2019-05-05-preview/examples/SmartGroups_GetById.json +// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/6d2438481021a94793b07b226df06d5f3c61d51d/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2019-05-05-preview/examples/SmartGroups_GetById.json func ExampleSmartGroupsClient_GetByID() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { @@ -244,7 +244,7 @@ func ExampleSmartGroupsClient_GetByID() { // } } -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/a436672b07fb1fe276c203b086b3f0e0d0c4aa24/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2019-05-05-preview/examples/SmartGroups_ChangeState.json +// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/6d2438481021a94793b07b226df06d5f3c61d51d/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2019-05-05-preview/examples/SmartGroups_ChangeState.json func ExampleSmartGroupsClient_ChangeState() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { @@ -316,7 +316,7 @@ func ExampleSmartGroupsClient_ChangeState() { // } } -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/a436672b07fb1fe276c203b086b3f0e0d0c4aa24/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2019-05-05-preview/examples/SmartGroups_History.json +// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/6d2438481021a94793b07b226df06d5f3c61d51d/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2019-05-05-preview/examples/SmartGroups_History.json func ExampleSmartGroupsClient_GetHistory() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { diff --git a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/tenantactivitylogalerts_client.go b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/tenantactivitylogalerts_client.go new file mode 100644 index 000000000000..4cd43f6a03d3 --- /dev/null +++ b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/tenantactivitylogalerts_client.go @@ -0,0 +1,392 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armalertsmanagement + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// TenantActivityLogAlertsClient contains the methods for the TenantActivityLogAlerts group. +// Don't use this type directly, use NewTenantActivityLogAlertsClient() instead. +type TenantActivityLogAlertsClient struct { + internal *arm.Client +} + +// NewTenantActivityLogAlertsClient creates a new instance of TenantActivityLogAlertsClient with the specified values. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewTenantActivityLogAlertsClient(credential azcore.TokenCredential, options *arm.ClientOptions) (*TenantActivityLogAlertsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &TenantActivityLogAlertsClient{ + internal: cl, + } + return client, nil +} + +// CreateOrUpdate - Create a new Tenant Activity Log Alert rule or update an existing one. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-04-01-preview +// - managementGroupName - The name of the management group. The name is case insensitive. +// - alertRuleName - The name of the Tenant Activity Log Alert rule. +// - tenantActivityLogAlertRule - The Tenant Activity Log Alert rule to create or use for the update. +// - options - TenantActivityLogAlertsClientCreateOrUpdateOptions contains the optional parameters for the TenantActivityLogAlertsClient.CreateOrUpdate +// method. +func (client *TenantActivityLogAlertsClient) CreateOrUpdate(ctx context.Context, managementGroupName string, alertRuleName string, tenantActivityLogAlertRule TenantActivityLogAlertResource, options *TenantActivityLogAlertsClientCreateOrUpdateOptions) (TenantActivityLogAlertsClientCreateOrUpdateResponse, error) { + var err error + const operationName = "TenantActivityLogAlertsClient.CreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, managementGroupName, alertRuleName, tenantActivityLogAlertRule, options) + if err != nil { + return TenantActivityLogAlertsClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return TenantActivityLogAlertsClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return TenantActivityLogAlertsClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *TenantActivityLogAlertsClient) createOrUpdateCreateRequest(ctx context.Context, managementGroupName string, alertRuleName string, tenantActivityLogAlertRule TenantActivityLogAlertResource, options *TenantActivityLogAlertsClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.Management/managementGroups/{managementGroupName}/providers/Microsoft.AlertsManagement/tenantActivityLogAlerts/{alertRuleName}" + if managementGroupName == "" { + return nil, errors.New("parameter managementGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{managementGroupName}", url.PathEscape(managementGroupName)) + if alertRuleName == "" { + return nil, errors.New("parameter alertRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{alertRuleName}", url.PathEscape(alertRuleName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, tenantActivityLogAlertRule); err != nil { + return nil, err + } + return req, nil +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *TenantActivityLogAlertsClient) createOrUpdateHandleResponse(resp *http.Response) (TenantActivityLogAlertsClientCreateOrUpdateResponse, error) { + result := TenantActivityLogAlertsClientCreateOrUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.TenantActivityLogAlertResource); err != nil { + return TenantActivityLogAlertsClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// Delete - Delete a Tenant Activity Log Alert rule. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-04-01-preview +// - managementGroupName - The name of the management group. The name is case insensitive. +// - alertRuleName - The name of the Tenant Activity Log Alert rule. +// - options - TenantActivityLogAlertsClientDeleteOptions contains the optional parameters for the TenantActivityLogAlertsClient.Delete +// method. +func (client *TenantActivityLogAlertsClient) Delete(ctx context.Context, managementGroupName string, alertRuleName string, options *TenantActivityLogAlertsClientDeleteOptions) (TenantActivityLogAlertsClientDeleteResponse, error) { + var err error + const operationName = "TenantActivityLogAlertsClient.Delete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, managementGroupName, alertRuleName, options) + if err != nil { + return TenantActivityLogAlertsClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return TenantActivityLogAlertsClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return TenantActivityLogAlertsClientDeleteResponse{}, err + } + return TenantActivityLogAlertsClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *TenantActivityLogAlertsClient) deleteCreateRequest(ctx context.Context, managementGroupName string, alertRuleName string, options *TenantActivityLogAlertsClientDeleteOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.Management/managementGroups/{managementGroupName}/providers/Microsoft.AlertsManagement/tenantActivityLogAlerts/{alertRuleName}" + if managementGroupName == "" { + return nil, errors.New("parameter managementGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{managementGroupName}", url.PathEscape(managementGroupName)) + if alertRuleName == "" { + return nil, errors.New("parameter alertRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{alertRuleName}", url.PathEscape(alertRuleName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Get Tenant Activity Log Alert rule. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-04-01-preview +// - managementGroupName - The name of the management group. The name is case insensitive. +// - alertRuleName - The name of the Tenant Activity Log Alert rule. +// - options - TenantActivityLogAlertsClientGetOptions contains the optional parameters for the TenantActivityLogAlertsClient.Get +// method. +func (client *TenantActivityLogAlertsClient) Get(ctx context.Context, managementGroupName string, alertRuleName string, options *TenantActivityLogAlertsClientGetOptions) (TenantActivityLogAlertsClientGetResponse, error) { + var err error + const operationName = "TenantActivityLogAlertsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, managementGroupName, alertRuleName, options) + if err != nil { + return TenantActivityLogAlertsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return TenantActivityLogAlertsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return TenantActivityLogAlertsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *TenantActivityLogAlertsClient) getCreateRequest(ctx context.Context, managementGroupName string, alertRuleName string, options *TenantActivityLogAlertsClientGetOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.Management/managementGroups/{managementGroupName}/providers/Microsoft.AlertsManagement/tenantActivityLogAlerts/{alertRuleName}" + if managementGroupName == "" { + return nil, errors.New("parameter managementGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{managementGroupName}", url.PathEscape(managementGroupName)) + if alertRuleName == "" { + return nil, errors.New("parameter alertRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{alertRuleName}", url.PathEscape(alertRuleName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *TenantActivityLogAlertsClient) getHandleResponse(resp *http.Response) (TenantActivityLogAlertsClientGetResponse, error) { + result := TenantActivityLogAlertsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.TenantActivityLogAlertResource); err != nil { + return TenantActivityLogAlertsClientGetResponse{}, err + } + return result, nil +} + +// NewListByManagementGroupPager - Get a list of all Tenant Activity Log Alert rules in a management group. +// +// Generated from API version 2023-04-01-preview +// - managementGroupName - The name of the management group. The name is case insensitive. +// - options - TenantActivityLogAlertsClientListByManagementGroupOptions contains the optional parameters for the TenantActivityLogAlertsClient.NewListByManagementGroupPager +// method. +func (client *TenantActivityLogAlertsClient) NewListByManagementGroupPager(managementGroupName string, options *TenantActivityLogAlertsClientListByManagementGroupOptions) *runtime.Pager[TenantActivityLogAlertsClientListByManagementGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[TenantActivityLogAlertsClientListByManagementGroupResponse]{ + More: func(page TenantActivityLogAlertsClientListByManagementGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *TenantActivityLogAlertsClientListByManagementGroupResponse) (TenantActivityLogAlertsClientListByManagementGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "TenantActivityLogAlertsClient.NewListByManagementGroupPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByManagementGroupCreateRequest(ctx, managementGroupName, options) + }, nil) + if err != nil { + return TenantActivityLogAlertsClientListByManagementGroupResponse{}, err + } + return client.listByManagementGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByManagementGroupCreateRequest creates the ListByManagementGroup request. +func (client *TenantActivityLogAlertsClient) listByManagementGroupCreateRequest(ctx context.Context, managementGroupName string, options *TenantActivityLogAlertsClientListByManagementGroupOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.Management/managementGroups/{managementGroupName}/providers/Microsoft.AlertsManagement/tenantActivityLogAlerts" + if managementGroupName == "" { + return nil, errors.New("parameter managementGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{managementGroupName}", url.PathEscape(managementGroupName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByManagementGroupHandleResponse handles the ListByManagementGroup response. +func (client *TenantActivityLogAlertsClient) listByManagementGroupHandleResponse(resp *http.Response) (TenantActivityLogAlertsClientListByManagementGroupResponse, error) { + result := TenantActivityLogAlertsClientListByManagementGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.TenantAlertRuleList); err != nil { + return TenantActivityLogAlertsClientListByManagementGroupResponse{}, err + } + return result, nil +} + +// NewListByTenantPager - Get a list of all Tenant Activity Log Alert rules in the tenant. +// +// Generated from API version 2023-04-01-preview +// - options - TenantActivityLogAlertsClientListByTenantOptions contains the optional parameters for the TenantActivityLogAlertsClient.NewListByTenantPager +// method. +func (client *TenantActivityLogAlertsClient) NewListByTenantPager(options *TenantActivityLogAlertsClientListByTenantOptions) *runtime.Pager[TenantActivityLogAlertsClientListByTenantResponse] { + return runtime.NewPager(runtime.PagingHandler[TenantActivityLogAlertsClientListByTenantResponse]{ + More: func(page TenantActivityLogAlertsClientListByTenantResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *TenantActivityLogAlertsClientListByTenantResponse) (TenantActivityLogAlertsClientListByTenantResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "TenantActivityLogAlertsClient.NewListByTenantPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByTenantCreateRequest(ctx, options) + }, nil) + if err != nil { + return TenantActivityLogAlertsClientListByTenantResponse{}, err + } + return client.listByTenantHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByTenantCreateRequest creates the ListByTenant request. +func (client *TenantActivityLogAlertsClient) listByTenantCreateRequest(ctx context.Context, options *TenantActivityLogAlertsClientListByTenantOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.AlertsManagement/tenantActivityLogAlerts" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByTenantHandleResponse handles the ListByTenant response. +func (client *TenantActivityLogAlertsClient) listByTenantHandleResponse(resp *http.Response) (TenantActivityLogAlertsClientListByTenantResponse, error) { + result := TenantActivityLogAlertsClientListByTenantResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.TenantAlertRuleList); err != nil { + return TenantActivityLogAlertsClientListByTenantResponse{}, err + } + return result, nil +} + +// Update - Updates 'tags' and 'enabled' fields in an existing Tenant Alert rule. This method is used to update the Alert +// rule tags, and to enable or disable the Alert rule. To update other fields use +// CreateOrUpdate operation. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-04-01-preview +// - managementGroupName - The name of the management group. The name is case insensitive. +// - alertRuleName - The name of the Tenant Activity Log Alert rule. +// - tenantActivityLogAlertRulePatch - Parameters supplied to the operation. +// - options - TenantActivityLogAlertsClientUpdateOptions contains the optional parameters for the TenantActivityLogAlertsClient.Update +// method. +func (client *TenantActivityLogAlertsClient) Update(ctx context.Context, managementGroupName string, alertRuleName string, tenantActivityLogAlertRulePatch TenantAlertRulePatchObject, options *TenantActivityLogAlertsClientUpdateOptions) (TenantActivityLogAlertsClientUpdateResponse, error) { + var err error + const operationName = "TenantActivityLogAlertsClient.Update" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, managementGroupName, alertRuleName, tenantActivityLogAlertRulePatch, options) + if err != nil { + return TenantActivityLogAlertsClientUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return TenantActivityLogAlertsClientUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return TenantActivityLogAlertsClientUpdateResponse{}, err + } + resp, err := client.updateHandleResponse(httpResp) + return resp, err +} + +// updateCreateRequest creates the Update request. +func (client *TenantActivityLogAlertsClient) updateCreateRequest(ctx context.Context, managementGroupName string, alertRuleName string, tenantActivityLogAlertRulePatch TenantAlertRulePatchObject, options *TenantActivityLogAlertsClientUpdateOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.Management/managementGroups/{managementGroupName}/providers/Microsoft.AlertsManagement/tenantActivityLogAlerts/{alertRuleName}" + if managementGroupName == "" { + return nil, errors.New("parameter managementGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{managementGroupName}", url.PathEscape(managementGroupName)) + if alertRuleName == "" { + return nil, errors.New("parameter alertRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{alertRuleName}", url.PathEscape(alertRuleName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, tenantActivityLogAlertRulePatch); err != nil { + return nil, err + } + return req, nil +} + +// updateHandleResponse handles the Update response. +func (client *TenantActivityLogAlertsClient) updateHandleResponse(resp *http.Response) (TenantActivityLogAlertsClientUpdateResponse, error) { + result := TenantActivityLogAlertsClientUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.TenantActivityLogAlertResource); err != nil { + return TenantActivityLogAlertsClientUpdateResponse{}, err + } + return result, nil +} diff --git a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/tenantactivitylogalerts_client_example_test.go b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/tenantactivitylogalerts_client_example_test.go new file mode 100644 index 000000000000..a4cc5e971e34 --- /dev/null +++ b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/tenantactivitylogalerts_client_example_test.go @@ -0,0 +1,381 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// DO NOT EDIT. + +package armalertsmanagement_test + +import ( + "context" + "log" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/alertsmanagement/armalertsmanagement" +) + +// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/6d2438481021a94793b07b226df06d5f3c61d51d/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2023-04-01-preview/examples/TenantActivityLogAlertRule_CreateOrUpdate.json +func ExampleTenantActivityLogAlertsClient_CreateOrUpdate() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armalertsmanagement.NewClientFactory("", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewTenantActivityLogAlertsClient().CreateOrUpdate(ctx, "72f988bf-86f1-41af-91ab-2d7cd011db47", "SampleActivityLogAlertSHRuleOnTenantLevel", armalertsmanagement.TenantActivityLogAlertResource{ + Location: to.Ptr("Global"), + Tags: map[string]*string{}, + Properties: &armalertsmanagement.AlertRuleProperties{ + Description: to.Ptr("Description of sample Activity Log Alert service health rule on tenant level events."), + Actions: &armalertsmanagement.ActionList{ + ActionGroups: []*armalertsmanagement.ActionGroup{ + { + ActionGroupID: to.Ptr("/providers/Microsoft.Management/ManagementGroups/72f988bf-86f1-41af-91ab-2d7cd011db47/providers/Microsoft.Insights/actionGroups/SampleActionGroup"), + ActionProperties: map[string]*string{ + "Email.Title": to.Ptr("my email title"), + }, + WebhookProperties: map[string]*string{ + "sampleWebhookProperty": to.Ptr("SamplePropertyValue"), + }, + }}, + }, + Condition: &armalertsmanagement.AlertRuleAllOfCondition{ + AllOf: []*armalertsmanagement.AlertRuleAnyOfOrLeafCondition{ + { + Equals: to.Ptr("ServiceHealth"), + Field: to.Ptr("category"), + }}, + }, + Enabled: to.Ptr(true), + TenantScope: to.Ptr("72f988bf-86f1-41af-91ab-2d7cd011db47"), + }, + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res.TenantActivityLogAlertResource = armalertsmanagement.TenantActivityLogAlertResource{ + // Name: to.Ptr("SampleActivityLogAlertSHRuleOnTenantLevel"), + // Type: to.Ptr("Microsoft.AlertsManagement/TenantActivityLogAlerts"), + // ID: to.Ptr("/providers/Microsoft.Management/ManagementGroups/72f988bf-86f1-41af-91ab-2d7cd011db47/providers/Microsoft.AlertsManagement/TenantActivityLogAlerts/SampleActivityLogAlertSHRuleOnTenantLevel"), + // Location: to.Ptr("Global"), + // Tags: map[string]*string{ + // }, + // Properties: &armalertsmanagement.AlertRuleProperties{ + // Description: to.Ptr("Description of sample Activity Log Alert service health rule on tenant level events."), + // Actions: &armalertsmanagement.ActionList{ + // ActionGroups: []*armalertsmanagement.ActionGroup{ + // { + // ActionGroupID: to.Ptr("/providers/Microsoft.Management/ManagementGroups/72f988bf-86f1-41af-91ab-2d7cd011db47/providers/Microsoft.Insights/actionGroups/SampleActionGroup"), + // ActionProperties: map[string]*string{ + // "Email.Title": to.Ptr("my email title"), + // }, + // WebhookProperties: map[string]*string{ + // "sampleWebhookProperty": to.Ptr("SamplePropertyValue"), + // }, + // }}, + // }, + // Condition: &armalertsmanagement.AlertRuleAllOfCondition{ + // AllOf: []*armalertsmanagement.AlertRuleAnyOfOrLeafCondition{ + // { + // Equals: to.Ptr("ServiceHealth"), + // Field: to.Ptr("category"), + // }}, + // }, + // Enabled: to.Ptr(true), + // TenantScope: to.Ptr("72f988bf-86f1-41af-91ab-2d7cd011db47"), + // }, + // } +} + +// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/6d2438481021a94793b07b226df06d5f3c61d51d/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2023-04-01-preview/examples/TenantActivityLogAlertRule_GetRule.json +func ExampleTenantActivityLogAlertsClient_Get() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armalertsmanagement.NewClientFactory("", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewTenantActivityLogAlertsClient().Get(ctx, "72f988bf-86f1-41af-91ab-2d7cd011db47", "SampleActivityLogAlertSHRuleOnTenantLevel", nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res.TenantActivityLogAlertResource = armalertsmanagement.TenantActivityLogAlertResource{ + // Name: to.Ptr("SampleActivityLogAlertSHRuleOnTenantLevel"), + // Type: to.Ptr("Microsoft.AlertsManagement/TenantActivityLogAlerts"), + // ID: to.Ptr("/providers/Microsoft.Management/ManagementGroups/72f988bf-86f1-41af-91ab-2d7cd011db47/providers/Microsoft.AlertsManagement/TenantActivityLogAlerts/SampleActivityLogAlertSHRuleOnTenantLevel"), + // Location: to.Ptr("Global"), + // Tags: map[string]*string{ + // }, + // Properties: &armalertsmanagement.AlertRuleProperties{ + // Description: to.Ptr("Description of sample Activity Log Alert service health rule on tenant level events."), + // Actions: &armalertsmanagement.ActionList{ + // ActionGroups: []*armalertsmanagement.ActionGroup{ + // { + // ActionGroupID: to.Ptr("/providers/Microsoft.Management/ManagementGroups/72f988bf-86f1-41af-91ab-2d7cd011db47/providers/Microsoft.Insights/actionGroups/SampleActionGroup"), + // ActionProperties: map[string]*string{ + // "Email.Title": to.Ptr("my email title"), + // }, + // WebhookProperties: map[string]*string{ + // "sampleWebhookProperty": to.Ptr("SamplePropertyValue"), + // }, + // }}, + // }, + // Condition: &armalertsmanagement.AlertRuleAllOfCondition{ + // AllOf: []*armalertsmanagement.AlertRuleAnyOfOrLeafCondition{ + // { + // Equals: to.Ptr("ServiceHealth"), + // Field: to.Ptr("category"), + // }}, + // }, + // Enabled: to.Ptr(true), + // TenantScope: to.Ptr("72f988bf-86f1-41af-91ab-2d7cd011db47"), + // }, + // } +} + +// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/6d2438481021a94793b07b226df06d5f3c61d51d/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2023-04-01-preview/examples/TenantActivityLogAlertRule_DeleteRule.json +func ExampleTenantActivityLogAlertsClient_Delete() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armalertsmanagement.NewClientFactory("", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + _, err = clientFactory.NewTenantActivityLogAlertsClient().Delete(ctx, "72f988bf-86f1-41af-91ab-2d7cd011db47", "SampleActivityLogAlertSHRuleOnTenantLevel", nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } +} + +// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/6d2438481021a94793b07b226df06d5f3c61d51d/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2023-04-01-preview/examples/TenantActivityLogAlertRule_UpdateRule.json +func ExampleTenantActivityLogAlertsClient_Update() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armalertsmanagement.NewClientFactory("", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewTenantActivityLogAlertsClient().Update(ctx, "72f988bf-86f1-41af-91ab-2d7cd011db47", "SampleActivityLogAlertSHRuleOnTenantLevel", armalertsmanagement.TenantAlertRulePatchObject{ + Properties: &armalertsmanagement.TenantAlertRulePatchProperties{ + Enabled: to.Ptr(false), + }, + Tags: map[string]*string{ + "key1": to.Ptr("value1"), + "key2": to.Ptr("value2"), + }, + }, nil) + if err != nil { + log.Fatalf("failed to finish the request: %v", err) + } + // You could use response here. We use blank identifier for just demo purposes. + _ = res + // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // res.TenantActivityLogAlertResource = armalertsmanagement.TenantActivityLogAlertResource{ + // Name: to.Ptr("SampleActivityLogAlertSHRuleOnTenantLevel"), + // Type: to.Ptr("Microsoft.AlertsManagement/TenantActivityLogAlerts"), + // ID: to.Ptr("/providers/Microsoft.Management/ManagementGroups/72f988bf-86f1-41af-91ab-2d7cd011db47/providers/Microsoft.AlertsManagement/TenantActivityLogAlerts/SampleActivityLogAlertSHRuleOnTenantLevel"), + // Location: to.Ptr("Global"), + // Tags: map[string]*string{ + // "key1": to.Ptr("value1"), + // "key2": to.Ptr("value2"), + // }, + // Properties: &armalertsmanagement.AlertRuleProperties{ + // Description: to.Ptr("Description of sample Activity Log Alert service health rule on tenant level events."), + // Actions: &armalertsmanagement.ActionList{ + // ActionGroups: []*armalertsmanagement.ActionGroup{ + // { + // ActionGroupID: to.Ptr("/providers/Microsoft.Management/ManagementGroups/72f988bf-86f1-41af-91ab-2d7cd011db47/providers/Microsoft.Insights/actionGroups/SampleActionGroup"), + // ActionProperties: map[string]*string{ + // "Email.Title": to.Ptr("my email title"), + // }, + // WebhookProperties: map[string]*string{ + // "sampleWebhookProperty": to.Ptr("SamplePropertyValue"), + // }, + // }}, + // }, + // Condition: &armalertsmanagement.AlertRuleAllOfCondition{ + // AllOf: []*armalertsmanagement.AlertRuleAnyOfOrLeafCondition{ + // { + // Equals: to.Ptr("ServiceHealth"), + // Field: to.Ptr("category"), + // }}, + // }, + // Enabled: to.Ptr(false), + // TenantScope: to.Ptr("72f988bf-86f1-41af-91ab-2d7cd011db47"), + // }, + // } +} + +// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/6d2438481021a94793b07b226df06d5f3c61d51d/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2023-04-01-preview/examples/TenantActivityLogAlertRule_ListByTenant.json +func ExampleTenantActivityLogAlertsClient_NewListByTenantPager() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armalertsmanagement.NewClientFactory("", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + pager := clientFactory.NewTenantActivityLogAlertsClient().NewListByTenantPager(nil) + for pager.More() { + page, err := pager.NextPage(ctx) + if err != nil { + log.Fatalf("failed to advance page: %v", err) + } + for _, v := range page.Value { + // You could use page here. We use blank identifier for just demo purposes. + _ = v + } + // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // page.TenantAlertRuleList = armalertsmanagement.TenantAlertRuleList{ + // Value: []*armalertsmanagement.TenantActivityLogAlertResource{ + // { + // Name: to.Ptr("SampleActivityLogAlertSHRuleOnTenantLevel"), + // Type: to.Ptr("Microsoft.AlertsManagement/TenantActivityLogAlerts"), + // ID: to.Ptr("/providers/Microsoft.Management/ManagementGroups/72f988bf-86f1-41af-91ab-2d7cd011db47/providers/Microsoft.AlertsManagement/TenantActivityLogAlerts/SampleActivityLogAlertSHRuleOnTenantLevel"), + // Location: to.Ptr("Global"), + // Tags: map[string]*string{ + // }, + // Properties: &armalertsmanagement.AlertRuleProperties{ + // Description: to.Ptr("Description of sample Activity Log Alert service health rule on tenant level events."), + // Actions: &armalertsmanagement.ActionList{ + // ActionGroups: []*armalertsmanagement.ActionGroup{ + // { + // ActionGroupID: to.Ptr("/providers/Microsoft.Management/ManagementGroups/72f988bf-86f1-41af-91ab-2d7cd011db47/providers/Microsoft.Insights/actionGroups/SampleActionGroup"), + // ActionProperties: map[string]*string{ + // "Email.Title": to.Ptr("my email title"), + // }, + // WebhookProperties: map[string]*string{ + // "sampleWebhookProperty": to.Ptr("SamplePropertyValue"), + // }, + // }}, + // }, + // Condition: &armalertsmanagement.AlertRuleAllOfCondition{ + // AllOf: []*armalertsmanagement.AlertRuleAnyOfOrLeafCondition{ + // { + // Equals: to.Ptr("ServiceHealth"), + // Field: to.Ptr("category"), + // }}, + // }, + // Enabled: to.Ptr(true), + // TenantScope: to.Ptr("72f988bf-86f1-41af-91ab-2d7cd011db47"), + // }, + // }, + // { + // Name: to.Ptr("SampleActivityLogAlertSHRuleOnTenantLevel"), + // Type: to.Ptr("Microsoft.AlertsManagement/TenantActivityLogAlerts"), + // ID: to.Ptr("/providers/Microsoft.Management/ManagementGroups/MyManagementGroup/providers/Microsoft.AlertsManagement/TenantActivityLogAlerts/SampleActivityLogAlertSHRuleOnTenantLevel"), + // Location: to.Ptr("Global"), + // Tags: map[string]*string{ + // }, + // Properties: &armalertsmanagement.AlertRuleProperties{ + // Description: to.Ptr("Description of sample Activity Log Alert service health rule on tenant level events."), + // Actions: &armalertsmanagement.ActionList{ + // ActionGroups: []*armalertsmanagement.ActionGroup{ + // { + // ActionGroupID: to.Ptr("/providers/Microsoft.Management/ManagementGroups/MyManagementGroup/providers/Microsoft.Insights/actionGroups/SampleActionGroup"), + // ActionProperties: map[string]*string{ + // "Email.Title": to.Ptr("my email title"), + // }, + // WebhookProperties: map[string]*string{ + // "sampleWebhookProperty": to.Ptr("SamplePropertyValue"), + // }, + // }}, + // }, + // Condition: &armalertsmanagement.AlertRuleAllOfCondition{ + // AllOf: []*armalertsmanagement.AlertRuleAnyOfOrLeafCondition{ + // { + // Equals: to.Ptr("ServiceHealth"), + // Field: to.Ptr("category"), + // }}, + // }, + // Enabled: to.Ptr(true), + // TenantScope: to.Ptr("72f988bf-86f1-41af-91ab-2d7cd011db47"), + // }, + // }}, + // } + } +} + +// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/6d2438481021a94793b07b226df06d5f3c61d51d/specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2023-04-01-preview/examples/TenantActivityLogAlertRule_ListByManagementGroup.json +func ExampleTenantActivityLogAlertsClient_NewListByManagementGroupPager() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armalertsmanagement.NewClientFactory("", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + pager := clientFactory.NewTenantActivityLogAlertsClient().NewListByManagementGroupPager("72f988bf-86f1-41af-91ab-2d7cd011db47", nil) + for pager.More() { + page, err := pager.NextPage(ctx) + if err != nil { + log.Fatalf("failed to advance page: %v", err) + } + for _, v := range page.Value { + // You could use page here. We use blank identifier for just demo purposes. + _ = v + } + // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. + // page.TenantAlertRuleList = armalertsmanagement.TenantAlertRuleList{ + // Value: []*armalertsmanagement.TenantActivityLogAlertResource{ + // { + // Name: to.Ptr("SampleActivityLogAlertSHRuleOnTenantLevel"), + // Type: to.Ptr("Microsoft.AlertsManagement/TenantActivityLogAlerts"), + // ID: to.Ptr("/providers/Microsoft.Management/ManagementGroups/72f988bf-86f1-41af-91ab-2d7cd011db47/providers/Microsoft.AlertsManagement/TenantActivityLogAlerts/SampleActivityLogAlertSHRuleOnTenantLevel"), + // Location: to.Ptr("Global"), + // Tags: map[string]*string{ + // }, + // Properties: &armalertsmanagement.AlertRuleProperties{ + // Description: to.Ptr("Description of sample Activity Log Alert service health rule on tenant level events."), + // Actions: &armalertsmanagement.ActionList{ + // ActionGroups: []*armalertsmanagement.ActionGroup{ + // { + // ActionGroupID: to.Ptr("/providers/Microsoft.Management/ManagementGroups/72f988bf-86f1-41af-91ab-2d7cd011db47/providers/Microsoft.Insights/actionGroups/SampleActionGroup"), + // ActionProperties: map[string]*string{ + // "Email.Title": to.Ptr("my email title"), + // }, + // WebhookProperties: map[string]*string{ + // "sampleWebhookProperty": to.Ptr("SamplePropertyValue"), + // }, + // }}, + // }, + // Condition: &armalertsmanagement.AlertRuleAllOfCondition{ + // AllOf: []*armalertsmanagement.AlertRuleAnyOfOrLeafCondition{ + // { + // Equals: to.Ptr("ServiceHealth"), + // Field: to.Ptr("category"), + // }}, + // }, + // Enabled: to.Ptr(true), + // TenantScope: to.Ptr("72f988bf-86f1-41af-91ab-2d7cd011db47"), + // }, + // }}, + // } + } +} diff --git a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/time_rfc3339.go b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/time_rfc3339.go index 7d1609021ddd..baccd3c76435 100644 --- a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/time_rfc3339.go +++ b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/time_rfc3339.go @@ -19,12 +19,16 @@ import ( ) // Azure reports time in UTC but it doesn't include the 'Z' time zone suffix in some cases. -var tzOffsetRegex = regexp.MustCompile(`(Z|z|\+|-)(\d+:\d+)*"*$`) +var tzOffsetRegex = regexp.MustCompile(`(?:Z|z|\+|-)(?:\d+:\d+)*"*$`) const ( - utcDateTimeJSON = `"2006-01-02T15:04:05.999999999"` - utcDateTime = "2006-01-02T15:04:05.999999999" - dateTimeJSON = `"` + time.RFC3339Nano + `"` + utcDateTime = "2006-01-02T15:04:05.999999999" + utcDateTimeJSON = `"` + utcDateTime + `"` + utcDateTimeNoT = "2006-01-02 15:04:05.999999999" + utcDateTimeJSONNoT = `"` + utcDateTimeNoT + `"` + dateTimeNoT = `2006-01-02 15:04:05.999999999Z07:00` + dateTimeJSON = `"` + time.RFC3339Nano + `"` + dateTimeJSONNoT = `"` + dateTimeNoT + `"` ) type dateTimeRFC3339 time.Time @@ -40,17 +44,33 @@ func (t dateTimeRFC3339) MarshalText() ([]byte, error) { } func (t *dateTimeRFC3339) UnmarshalJSON(data []byte) error { - layout := utcDateTimeJSON - if tzOffsetRegex.Match(data) { + tzOffset := tzOffsetRegex.Match(data) + hasT := strings.Contains(string(data), "T") || strings.Contains(string(data), "t") + var layout string + if tzOffset && hasT { layout = dateTimeJSON + } else if tzOffset { + layout = dateTimeJSONNoT + } else if hasT { + layout = utcDateTimeJSON + } else { + layout = utcDateTimeJSONNoT } return t.Parse(layout, string(data)) } func (t *dateTimeRFC3339) UnmarshalText(data []byte) error { - layout := utcDateTime - if tzOffsetRegex.Match(data) { + tzOffset := tzOffsetRegex.Match(data) + hasT := strings.Contains(string(data), "T") || strings.Contains(string(data), "t") + var layout string + if tzOffset && hasT { layout = time.RFC3339Nano + } else if tzOffset { + layout = dateTimeNoT + } else if hasT { + layout = utcDateTime + } else { + layout = utcDateTimeNoT } return t.Parse(layout, string(data)) } @@ -61,6 +81,10 @@ func (t *dateTimeRFC3339) Parse(layout, value string) error { return err } +func (t dateTimeRFC3339) String() string { + return time.Time(t).Format(time.RFC3339Nano) +} + func populateDateTimeRFC3339(m map[string]any, k string, t *time.Time) { if t == nil { return @@ -74,7 +98,7 @@ func populateDateTimeRFC3339(m map[string]any, k string, t *time.Time) { } func unpopulateDateTimeRFC3339(data json.RawMessage, fn string, t **time.Time) error { - if data == nil || strings.EqualFold(string(data), "null") { + if data == nil || string(data) == "null" { return nil } var aux dateTimeRFC3339