diff --git a/sdk/resourcemanager/advisor/armadvisor/CHANGELOG.md b/sdk/resourcemanager/advisor/armadvisor/CHANGELOG.md index 49967ccd50d3..5e0c8613f266 100644 --- a/sdk/resourcemanager/advisor/armadvisor/CHANGELOG.md +++ b/sdk/resourcemanager/advisor/armadvisor/CHANGELOG.md @@ -1,5 +1,116 @@ # Release History +## 2.0.0-beta.1 (2026-03-19) +### Breaking Changes + +- Type of `RecommendationsClientGenerateResponse.RetryAfter` has been changed from `*string` to `*int32` +- Struct `Resource` has been removed + +### Features Added + +- New enum type `Aggregated` with values `AggregatedDay`, `AggregatedMonth`, `AggregatedWeek` +- New enum type `Control` with values `ControlBusinessContinuity`, `ControlDisasterRecovery`, `ControlHighAvailability`, `ControlMonitoringAndAlerting`, `ControlOther`, `ControlPersonalized`, `ControlPrioritizedRecommendations`, `ControlScalability`, `ControlServiceUpgradeAndRetirement` +- New enum type `CreatedByType` with values `CreatedByTypeApplication`, `CreatedByTypeKey`, `CreatedByTypeManagedIdentity`, `CreatedByTypeUser` +- New enum type `Duration` with values `Duration14`, `Duration21`, `Duration30`, `Duration60`, `Duration7`, `Duration90` +- New enum type `PredictionType` with values `PredictionTypePredictiveRightsizing` +- New enum type `Priority` with values `PriorityCritical`, `PriorityHigh`, `PriorityInformational`, `PriorityLow`, `PriorityMedium` +- New enum type `PriorityName` with values `PriorityNameHigh`, `PriorityNameLow`, `PriorityNameMedium` +- New enum type `Reason` with values `ReasonAlternativeSolution`, `ReasonExcessiveInvestment`, `ReasonIncompatible`, `ReasonRiskAccepted`, `ReasonTooComplex`, `ReasonUnclear` +- New enum type `ReasonForRejectionName` with values `ReasonForRejectionNameNotARisk`, `ReasonForRejectionNameRiskAccepted` +- New enum type `RecommendationStatusName` with values `RecommendationStatusNameApproved`, `RecommendationStatusNamePending`, `RecommendationStatusNameRejected` +- New enum type `ReviewStatus` with values `ReviewStatusCompleted`, `ReviewStatusInProgress`, `ReviewStatusNew`, `ReviewStatusTriaged` +- New enum type `State` with values `StateApproved`, `StateCompleted`, `StateDismissed`, `StateInProgress`, `StatePending`, `StatePostponed`, `StateRejected` +- New function `NewAssessmentTypesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*AssessmentTypesClient, error)` +- New function `*AssessmentTypesClient.NewListPager(options *AssessmentTypesClientListOptions) *runtime.Pager[AssessmentTypesClientListResponse]` +- New function `NewAssessmentsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*AssessmentsClient, error)` +- New function `*AssessmentsClient.Delete(ctx context.Context, assessmentName string, options *AssessmentsClientDeleteOptions) (AssessmentsClientDeleteResponse, error)` +- New function `*AssessmentsClient.Get(ctx context.Context, assessmentName string, options *AssessmentsClientGetOptions) (AssessmentsClientGetResponse, error)` +- New function `*AssessmentsClient.NewListPager(options *AssessmentsClientListOptions) *runtime.Pager[AssessmentsClientListResponse]` +- New function `*AssessmentsClient.Put(ctx context.Context, assessmentName string, assessmentContract AssessmentResult, options *AssessmentsClientPutOptions) (AssessmentsClientPutResponse, error)` +- New function `NewClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*Client, error)` +- New function `*Client.NewAssessmentTypesClient() *AssessmentTypesClient` +- New function `*Client.NewAssessmentsClient() *AssessmentsClient` +- New function `*Client.NewConfigurationsClient() *ConfigurationsClient` +- New function `*Client.NewOperationsClient() *OperationsClient` +- New function `*Client.NewRecommendationMetadataClient() *RecommendationMetadataClient` +- New function `*Client.NewRecommendationsClient() *RecommendationsClient` +- New function `*Client.NewResiliencyReviewsClient() *ResiliencyReviewsClient` +- New function `*Client.NewScoresClient() *ScoresClient` +- New function `*Client.NewSuppressionsClient() *SuppressionsClient` +- New function `*Client.NewTriageRecommendationsClient() *TriageRecommendationsClient` +- New function `*Client.NewTriageResourcesClient() *TriageResourcesClient` +- New function `*Client.NewWorkloadsClient() *WorkloadsClient` +- New function `*Client.Predict(ctx context.Context, predictionRequest PredictionRequest, options *ClientPredictOptions) (ClientPredictResponse, error)` +- New function `*ClientFactory.NewAssessmentTypesClient() *AssessmentTypesClient` +- New function `*ClientFactory.NewAssessmentsClient() *AssessmentsClient` +- New function `*ClientFactory.NewClient() *Client` +- New function `*ClientFactory.NewResiliencyReviewsClient() *ResiliencyReviewsClient` +- New function `*ClientFactory.NewScoresClient() *ScoresClient` +- New function `*ClientFactory.NewTriageRecommendationsClient() *TriageRecommendationsClient` +- New function `*ClientFactory.NewTriageResourcesClient() *TriageResourcesClient` +- New function `*ClientFactory.NewWorkloadsClient() *WorkloadsClient` +- New function `PossiblePriorityValues() []Priority` +- New function `PossibleReasonValues() []Reason` +- New function `*RecommendationsClient.NewListByTenantPager(resourceURI string, options *RecommendationsClientListByTenantOptions) *runtime.Pager[RecommendationsClientListByTenantResponse]` +- New function `*RecommendationsClient.Patch(ctx context.Context, resourceURI string, recommendationID string, trackedProperties TrackedRecommendationPropertiesPayload, options *RecommendationsClientPatchOptions) (RecommendationsClientPatchResponse, error)` +- New function `NewResiliencyReviewsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ResiliencyReviewsClient, error)` +- New function `*ResiliencyReviewsClient.Get(ctx context.Context, reviewID string, options *ResiliencyReviewsClientGetOptions) (ResiliencyReviewsClientGetResponse, error)` +- New function `*ResiliencyReviewsClient.NewListPager(options *ResiliencyReviewsClientListOptions) *runtime.Pager[ResiliencyReviewsClientListResponse]` +- New function `NewScoresClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ScoresClient, error)` +- New function `*ScoresClient.Get(ctx context.Context, name string, options *ScoresClientGetOptions) (ScoresClientGetResponse, error)` +- New function `*ScoresClient.NewListPager(options *ScoresClientListOptions) *runtime.Pager[ScoresClientListResponse]` +- New function `NewTriageRecommendationsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*TriageRecommendationsClient, error)` +- New function `*TriageRecommendationsClient.ApproveTriageRecommendation(ctx context.Context, reviewID string, recommendationID string, options *TriageRecommendationsClientApproveTriageRecommendationOptions) (TriageRecommendationsClientApproveTriageRecommendationResponse, error)` +- New function `*TriageRecommendationsClient.Get(ctx context.Context, reviewID string, recommendationID string, options *TriageRecommendationsClientGetOptions) (TriageRecommendationsClientGetResponse, error)` +- New function `*TriageRecommendationsClient.NewListPager(reviewID string, options *TriageRecommendationsClientListOptions) *runtime.Pager[TriageRecommendationsClientListResponse]` +- New function `*TriageRecommendationsClient.RejectTriageRecommendation(ctx context.Context, reviewID string, recommendationID string, recommendationRejectBody RecommendationRejectBody, options *TriageRecommendationsClientRejectTriageRecommendationOptions) (TriageRecommendationsClientRejectTriageRecommendationResponse, error)` +- New function `*TriageRecommendationsClient.ResetTriageRecommendation(ctx context.Context, reviewID string, recommendationID string, options *TriageRecommendationsClientResetTriageRecommendationOptions) (TriageRecommendationsClientResetTriageRecommendationResponse, error)` +- New function `NewTriageResourcesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*TriageResourcesClient, error)` +- New function `*TriageResourcesClient.Get(ctx context.Context, reviewID string, recommendationID string, recommendationResourceID string, options *TriageResourcesClientGetOptions) (TriageResourcesClientGetResponse, error)` +- New function `*TriageResourcesClient.NewListPager(reviewID string, recommendationID string, options *TriageResourcesClientListOptions) *runtime.Pager[TriageResourcesClientListResponse]` +- New function `NewWorkloadsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*WorkloadsClient, error)` +- New function `*WorkloadsClient.NewListPager(options *WorkloadsClientListOptions) *runtime.Pager[WorkloadsClientListResponse]` +- New struct `AssessmentListResult` +- New struct `AssessmentResult` +- New struct `AssessmentResultProperties` +- New struct `AssessmentTypeListResult` +- New struct `AssessmentTypeResult` +- New struct `PredictionRequest` +- New struct `PredictionRequestProperties` +- New struct `PredictionResponse` +- New struct `PredictionResponseProperties` +- New struct `RecommendationPropertiesResourceWorkload` +- New struct `RecommendationPropertiesReview` +- New struct `RecommendationRejectBody` +- New struct `ResiliencyReview` +- New struct `ResiliencyReviewCollection` +- New struct `ResiliencyReviewProperties` +- New struct `ScoreEntity` +- New struct `ScoreEntityForAdvisor` +- New struct `ScoreEntityProperties` +- New struct `ScoreResponse` +- New struct `SystemData` +- New struct `TimeSeriesEntity` +- New struct `TrackedRecommendationProperties` +- New struct `TrackedRecommendationPropertiesPayload` +- New struct `TrackedRecommendationPropertiesPayloadProperties` +- New struct `TriageRecommendation` +- New struct `TriageRecommendationCollection` +- New struct `TriageRecommendationProperties` +- New struct `TriageResource` +- New struct `TriageResourceCollection` +- New struct `TriageResourceProperties` +- New struct `WorkloadListResult` +- New struct `WorkloadResult` +- New field `SystemData` in struct `ConfigData` +- New field `Duration` in struct `ConfigDataProperties` +- New field `SystemData` in struct `MetadataEntity` +- New field `Control`, `Notes`, `ResourceWorkload`, `Review`, `SourceSystem`, `Tracked`, `TrackedProperties` in struct `RecommendationProperties` +- New field `RetryAfter` in struct `RecommendationsClientGetGenerateStatusResponse` +- New field `SystemData` in struct `ResourceRecommendationBase` +- New field `SystemData` in struct `SuppressionContract` + + ## 1.2.0 (2023-11-24) ### Features Added diff --git a/sdk/resourcemanager/advisor/armadvisor/README.md b/sdk/resourcemanager/advisor/armadvisor/README.md index 9d6f872e016c..f206d4bc6b97 100644 --- a/sdk/resourcemanager/advisor/armadvisor/README.md +++ b/sdk/resourcemanager/advisor/armadvisor/README.md @@ -18,7 +18,7 @@ This project uses [Go modules](https://github.com/golang/go/wiki/Modules) for ve Install the Azure Advisor module: ```sh -go get github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/advisor/armadvisor +go get github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/advisor/armadvisor/v2 ``` ## Authorization @@ -55,7 +55,7 @@ clientFactory, err := armadvisor.NewClientFactory(, cred, &opti 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.NewSuppressionsClient() +client := clientFactory.NewAssessmentTypesClient() ``` ## Fakes diff --git a/sdk/resourcemanager/advisor/armadvisor/advisor_live_test.go b/sdk/resourcemanager/advisor/armadvisor/advisor_live_test.go index b1ad55791aa4..30262d875e5a 100644 --- a/sdk/resourcemanager/advisor/armadvisor/advisor_live_test.go +++ b/sdk/resourcemanager/advisor/armadvisor/advisor_live_test.go @@ -14,7 +14,7 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/sdk/internal/recording" - "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/advisor/armadvisor" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/advisor/armadvisor/v2" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/internal/v3/testutil" "github.com/stretchr/testify/suite" ) diff --git a/sdk/resourcemanager/advisor/armadvisor/assessments_client.go b/sdk/resourcemanager/advisor/armadvisor/assessments_client.go new file mode 100644 index 000000000000..55d021390290 --- /dev/null +++ b/sdk/resourcemanager/advisor/armadvisor/assessments_client.go @@ -0,0 +1,271 @@ +// 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) Go Code Generator. DO NOT EDIT. + +package armadvisor + +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" +) + +// AssessmentsClient contains the methods for the Assessments group. +// Don't use this type directly, use NewAssessmentsClient() instead. +type AssessmentsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewAssessmentsClient creates a new instance of AssessmentsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewAssessmentsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*AssessmentsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &AssessmentsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Delete - Delete an existing Azure Advisor assessment. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-05-01-preview +// - assessmentName - Advisor assessment name. +// - options - AssessmentsClientDeleteOptions contains the optional parameters for the AssessmentsClient.Delete method. +func (client *AssessmentsClient) Delete(ctx context.Context, assessmentName string, options *AssessmentsClientDeleteOptions) (AssessmentsClientDeleteResponse, error) { + var err error + const operationName = "AssessmentsClient.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, assessmentName, options) + if err != nil { + return AssessmentsClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AssessmentsClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return AssessmentsClientDeleteResponse{}, err + } + return AssessmentsClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *AssessmentsClient) deleteCreateRequest(ctx context.Context, assessmentName string, _ *AssessmentsClientDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Advisor/assessments/{assessmentName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if assessmentName == "" { + return nil, errors.New("parameter assessmentName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{assessmentName}", url.PathEscape(assessmentName)) + 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", "2025-05-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + return req, nil +} + +// Get - Get an existing Azure Advisor assessment. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-05-01-preview +// - assessmentName - Advisor assessment name. +// - options - AssessmentsClientGetOptions contains the optional parameters for the AssessmentsClient.Get method. +func (client *AssessmentsClient) Get(ctx context.Context, assessmentName string, options *AssessmentsClientGetOptions) (AssessmentsClientGetResponse, error) { + var err error + const operationName = "AssessmentsClient.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, assessmentName, options) + if err != nil { + return AssessmentsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AssessmentsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return AssessmentsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *AssessmentsClient) getCreateRequest(ctx context.Context, assessmentName string, _ *AssessmentsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Advisor/assessments/{assessmentName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if assessmentName == "" { + return nil, errors.New("parameter assessmentName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{assessmentName}", url.PathEscape(assessmentName)) + 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", "2025-05-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 *AssessmentsClient) getHandleResponse(resp *http.Response) (AssessmentsClientGetResponse, error) { + result := AssessmentsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AssessmentResult); err != nil { + return AssessmentsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Get list of Azure Advisor assessments. +// +// Generated from API version 2025-05-01-preview +// - options - AssessmentsClientListOptions contains the optional parameters for the AssessmentsClient.NewListPager method. +func (client *AssessmentsClient) NewListPager(options *AssessmentsClientListOptions) *runtime.Pager[AssessmentsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[AssessmentsClientListResponse]{ + More: func(page AssessmentsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *AssessmentsClientListResponse) (AssessmentsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "AssessmentsClient.NewListPager") + 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.listCreateRequest(ctx, options) + }, nil) + if err != nil { + return AssessmentsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *AssessmentsClient) listCreateRequest(ctx context.Context, options *AssessmentsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Advisor/assessments" + 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() + if options != nil && options.Skiptoken != nil { + reqQP.Set("$skiptoken", *options.Skiptoken) + } + if options != nil && options.Top != nil { + reqQP.Set("$top", *options.Top) + } + reqQP.Set("api-version", "2025-05-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *AssessmentsClient) listHandleResponse(resp *http.Response) (AssessmentsClientListResponse, error) { + result := AssessmentsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AssessmentListResult); err != nil { + return AssessmentsClientListResponse{}, err + } + return result, nil +} + +// Put - Create or Overwrite Azure Advisor assessment. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-05-01-preview +// - assessmentName - Advisor assessment name. +// - assessmentContract - The Azure Advisor assessment data structure. +// - options - AssessmentsClientPutOptions contains the optional parameters for the AssessmentsClient.Put method. +func (client *AssessmentsClient) Put(ctx context.Context, assessmentName string, assessmentContract AssessmentResult, options *AssessmentsClientPutOptions) (AssessmentsClientPutResponse, error) { + var err error + const operationName = "AssessmentsClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, assessmentName, assessmentContract, options) + if err != nil { + return AssessmentsClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AssessmentsClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return AssessmentsClientPutResponse{}, err + } + resp, err := client.putHandleResponse(httpResp) + return resp, err +} + +// putCreateRequest creates the Put request. +func (client *AssessmentsClient) putCreateRequest(ctx context.Context, assessmentName string, assessmentContract AssessmentResult, _ *AssessmentsClientPutOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Advisor/assessments/{assessmentName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if assessmentName == "" { + return nil, errors.New("parameter assessmentName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{assessmentName}", url.PathEscape(assessmentName)) + 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", "2025-05-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, assessmentContract); err != nil { + return nil, err + } + return req, nil +} + +// putHandleResponse handles the Put response. +func (client *AssessmentsClient) putHandleResponse(resp *http.Response) (AssessmentsClientPutResponse, error) { + result := AssessmentsClientPutResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AssessmentResult); err != nil { + return AssessmentsClientPutResponse{}, err + } + return result, nil +} diff --git a/sdk/resourcemanager/advisor/armadvisor/assessments_client_example_test.go b/sdk/resourcemanager/advisor/armadvisor/assessments_client_example_test.go new file mode 100644 index 000000000000..64ed265d20ff --- /dev/null +++ b/sdk/resourcemanager/advisor/armadvisor/assessments_client_example_test.go @@ -0,0 +1,192 @@ +// 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) Go Code Generator. DO NOT EDIT. + +package armadvisor_test + +import ( + "context" + "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/advisor/armadvisor/v2" + "log" +) + +// Generated from example definition: 2025-05-01-preview/DeleteAssessment.json +func ExampleAssessmentsClient_Delete() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armadvisor.NewClientFactory("00000000-1111-2222-3333-444444444444", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewAssessmentsClient().Delete(ctx, "assessment1", 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 = armadvisor.AssessmentsClientDeleteResponse{ + // } +} + +// Generated from example definition: 2025-05-01-preview/GetAssessment.json +func ExampleAssessmentsClient_Get() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armadvisor.NewClientFactory("00000000-1111-2222-3333-444444444444", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewAssessmentsClient().Get(ctx, "assessment1", 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 = armadvisor.AssessmentsClientGetResponse{ + // AssessmentResult: &armadvisor.AssessmentResult{ + // ID: to.Ptr("/subscriptions/2f2edd23-bded-4c8d-bdef-1f32a9b83f84/providers/Microsoft.Advisor/assessments/MCWAR1"), + // Name: to.Ptr("MCWAR1"), + // Type: to.Ptr("Microsoft.Advisor/assessments"), + // SystemData: &armadvisor.SystemData{ + // CreatedBy: to.Ptr("string"), + // CreatedByType: to.Ptr(armadvisor.CreatedByTypeUser), + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2020-04-03T04:41:33.937Z"); return t}()), + // LastModifiedBy: to.Ptr("string"), + // LastModifiedByType: to.Ptr(armadvisor.CreatedByTypeUser), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2020-04-03T04:41:33.937Z"); return t}()), + // }, + // Properties: &armadvisor.AssessmentResultProperties{ + // WorkloadID: to.Ptr("f72b7134-800f-4f1b-a5bd-691e2140c7d5"), + // WorkloadName: to.Ptr("Workload1"), + // AssessmentID: to.Ptr("fa5cb863-6ed4-4b6b-8c72-06f847cac885"), + // Description: to.Ptr("Evaluate your mission critical workloads by assessing the technical design"), + // TypeID: to.Ptr("23513bdb-e8a2-4f0b-8b6b-191ee1f52d34"), + // Type: to.Ptr("Mission Critical Well-Architected Review"), + // TypeVersion: to.Ptr("20221031192816.497"), + // Locale: to.Ptr("en-us"), + // Score: to.Ptr[int32](60), + // State: to.Ptr("InProgress"), + // }, + // }, + // } +} + +// Generated from example definition: 2025-05-01-preview/ListAssessments.json +func ExampleAssessmentsClient_NewListPager() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armadvisor.NewClientFactory("00000000-1111-2222-3333-444444444444", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + pager := clientFactory.NewAssessmentsClient().NewListPager(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 = armadvisor.AssessmentsClientListResponse{ + // AssessmentListResult: armadvisor.AssessmentListResult{ + // Value: []*armadvisor.AssessmentResult{ + // { + // ID: to.Ptr("/subscriptions/2f2edd23-bded-4c8d-bdef-1f32a9b83f84/providers/Microsoft.Advisor/assessments/MCWAR1"), + // Name: to.Ptr("MCWAR1"), + // Type: to.Ptr("Microsoft.Advisor/assessments"), + // SystemData: &armadvisor.SystemData{ + // CreatedBy: to.Ptr("string"), + // CreatedByType: to.Ptr(armadvisor.CreatedByTypeUser), + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2020-04-03T04:41:33.937Z"); return t}()), + // LastModifiedBy: to.Ptr("string"), + // LastModifiedByType: to.Ptr(armadvisor.CreatedByTypeUser), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2020-04-03T04:41:33.937Z"); return t}()), + // }, + // Properties: &armadvisor.AssessmentResultProperties{ + // WorkloadID: to.Ptr("f72b7134-800f-4f1b-a5bd-691e2140c7d5"), + // WorkloadName: to.Ptr("Workload1"), + // AssessmentID: to.Ptr("fa5cb863-6ed4-4b6b-8c72-06f847cac885"), + // Description: to.Ptr("Evaluate your mission critical workloads by assessing the technical design"), + // TypeID: to.Ptr("23513bdb-e8a2-4f0b-8b6b-191ee1f52d34"), + // Type: to.Ptr("Mission Critical Well-Architected Review"), + // TypeVersion: to.Ptr("20221031192816.497"), + // Locale: to.Ptr("en-us"), + // Score: to.Ptr[int32](60), + // State: to.Ptr("InProgress"), + // }, + // }, + // }, + // NextLink: to.Ptr("https://management.azure.com/subscriptions/2f2edd23-bded-4c8d-bdef-1f32a9b83f84/providers/Microsoft.Advisor/assessments?api-version=2023-07-01&$top=10&$skiptoken=skiptoken"), + // }, + // } + } +} + +// Generated from example definition: 2025-05-01-preview/PutAssessment.json +func ExampleAssessmentsClient_Put() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armadvisor.NewClientFactory("00000000-1111-2222-3333-444444444444", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewAssessmentsClient().Put(ctx, "assessment1", armadvisor.AssessmentResult{ + Properties: &armadvisor.AssessmentResultProperties{ + WorkloadID: to.Ptr("f72b7134-800f-4f1b-a5bd-691e2140c7d5"), + TypeID: to.Ptr("23513bdb-e8a2-4f0b-8b6b-191ee1f52d34"), + Locale: to.Ptr("en-us"), + }, + }, 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 = armadvisor.AssessmentsClientPutResponse{ + // AssessmentResult: &armadvisor.AssessmentResult{ + // ID: to.Ptr("/subscriptions/2f2edd23-bded-4c8d-bdef-1f32a9b83f84/providers/Microsoft.Advisor/assessments/MCWAR1"), + // Name: to.Ptr("MCWAR1"), + // Type: to.Ptr("Microsoft.Advisor/assessments"), + // SystemData: &armadvisor.SystemData{ + // CreatedBy: to.Ptr("string"), + // CreatedByType: to.Ptr(armadvisor.CreatedByTypeUser), + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2020-04-03T04:41:33.937Z"); return t}()), + // LastModifiedBy: to.Ptr("string"), + // LastModifiedByType: to.Ptr(armadvisor.CreatedByTypeUser), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2020-04-03T04:41:33.937Z"); return t}()), + // }, + // Properties: &armadvisor.AssessmentResultProperties{ + // WorkloadID: to.Ptr("f72b7134-800f-4f1b-a5bd-691e2140c7d5"), + // WorkloadName: to.Ptr("Workload1"), + // AssessmentID: to.Ptr("fa5cb863-6ed4-4b6b-8c72-06f847cac885"), + // Description: to.Ptr("Evaluate your mission critical workloads by assessing the technical design"), + // TypeID: to.Ptr("23513bdb-e8a2-4f0b-8b6b-191ee1f52d34"), + // Type: to.Ptr("Mission Critical Well-Architected Review"), + // TypeVersion: to.Ptr("20221031192816.497"), + // Locale: to.Ptr("en-us"), + // Score: to.Ptr[int32](60), + // State: to.Ptr("Inprogress"), + // }, + // }, + // } +} diff --git a/sdk/resourcemanager/advisor/armadvisor/assessmenttypes_client.go b/sdk/resourcemanager/advisor/armadvisor/assessmenttypes_client.go new file mode 100644 index 000000000000..f1755ff1d0b1 --- /dev/null +++ b/sdk/resourcemanager/advisor/armadvisor/assessmenttypes_client.go @@ -0,0 +1,97 @@ +// 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) Go Code Generator. DO NOT EDIT. + +package armadvisor + +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" +) + +// AssessmentTypesClient contains the methods for the AssessmentTypes group. +// Don't use this type directly, use NewAssessmentTypesClient() instead. +type AssessmentTypesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewAssessmentTypesClient creates a new instance of AssessmentTypesClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewAssessmentTypesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*AssessmentTypesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &AssessmentTypesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// NewListPager - Get assessment types list. +// +// Get list of Azure Advisor assessment types. +// +// Generated from API version 2025-05-01-preview +// - options - AssessmentTypesClientListOptions contains the optional parameters for the AssessmentTypesClient.NewListPager +// method. +func (client *AssessmentTypesClient) NewListPager(options *AssessmentTypesClientListOptions) *runtime.Pager[AssessmentTypesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[AssessmentTypesClientListResponse]{ + More: func(page AssessmentTypesClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *AssessmentTypesClientListResponse) (AssessmentTypesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "AssessmentTypesClient.NewListPager") + 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.listCreateRequest(ctx, options) + }, nil) + if err != nil { + return AssessmentTypesClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *AssessmentTypesClient) listCreateRequest(ctx context.Context, _ *AssessmentTypesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Advisor/assessmentTypes" + 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", "2025-05-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *AssessmentTypesClient) listHandleResponse(resp *http.Response) (AssessmentTypesClientListResponse, error) { + result := AssessmentTypesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AssessmentTypeListResult); err != nil { + return AssessmentTypesClientListResponse{}, err + } + return result, nil +} diff --git a/sdk/resourcemanager/advisor/armadvisor/assessmenttypes_client_example_test.go b/sdk/resourcemanager/advisor/armadvisor/assessmenttypes_client_example_test.go new file mode 100644 index 000000000000..22c1fa9e5575 --- /dev/null +++ b/sdk/resourcemanager/advisor/armadvisor/assessmenttypes_client_example_test.go @@ -0,0 +1,50 @@ +// 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) Go Code Generator. DO NOT EDIT. + +package armadvisor_test + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/advisor/armadvisor/v2" + "log" +) + +// Generated from example definition: 2025-05-01-preview/ListAssessmentTypes.json +func ExampleAssessmentTypesClient_NewListPager() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armadvisor.NewClientFactory("00000000-1111-2222-3333-444444444444", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + pager := clientFactory.NewAssessmentTypesClient().NewListPager(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 = armadvisor.AssessmentTypesClientListResponse{ + // AssessmentTypeListResult: armadvisor.AssessmentTypeListResult{ + // Value: []*armadvisor.AssessmentTypeResult{ + // { + // ID: to.Ptr("23513bdb-e8a2-4f0b-8b6b-191ee1f52d34"), + // Title: to.Ptr("Mission Critical | Well-Architected Review"), + // Description: to.Ptr("Evaluate your mission critical workloads by assessing the technical design areas and overall operational effectiveness."), + // Locale: to.Ptr("en-us"), + // Version: to.Ptr("20221031192816.497"), + // }, + // }, + // }, + // } + } +} diff --git a/sdk/resourcemanager/advisor/armadvisor/autorest.md b/sdk/resourcemanager/advisor/armadvisor/autorest.md deleted file mode 100644 index 582c1196e2a5..000000000000 --- a/sdk/resourcemanager/advisor/armadvisor/autorest.md +++ /dev/null @@ -1,12 +0,0 @@ -### AutoRest Configuration - -> see https://aka.ms/autorest - -``` yaml -azure-arm: true -require: -- https://github.com/Azure/azure-rest-api-specs/blob/7a2ac91de424f271cf91cc8009f3fe9ee8249086/specification/advisor/resource-manager/readme.md -- https://github.com/Azure/azure-rest-api-specs/blob/7a2ac91de424f271cf91cc8009f3fe9ee8249086/specification/advisor/resource-manager/readme.go.md -license-header: MICROSOFT_MIT_NO_VERSION -module-version: 1.2.0 -``` \ No newline at end of file diff --git a/sdk/resourcemanager/advisor/armadvisor/build.go b/sdk/resourcemanager/advisor/armadvisor/build.go deleted file mode 100644 index 4336a832733f..000000000000 --- a/sdk/resourcemanager/advisor/armadvisor/build.go +++ /dev/null @@ -1,7 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// 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/advisor/armadvisor - -package armadvisor diff --git a/sdk/resourcemanager/advisor/armadvisor/client.go b/sdk/resourcemanager/advisor/armadvisor/client.go new file mode 100644 index 000000000000..8897affb7d31 --- /dev/null +++ b/sdk/resourcemanager/advisor/armadvisor/client.go @@ -0,0 +1,193 @@ +// 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) Go Code Generator. DO NOT EDIT. + +package armadvisor + +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" +) + +// Client - REST APIs for Azure Advisor Resiliency Reviews. +// Don't use this type directly, use NewClient() instead. +type Client struct { + internal *arm.Client + subscriptionID string +} + +// NewClient creates a new instance of Client with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*Client, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &Client{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// NewAssessmentTypesClient creates a new instance of [AssessmentTypesClient]. +func (client *Client) NewAssessmentTypesClient() *AssessmentTypesClient { + return &AssessmentTypesClient{ + internal: client.internal, + subscriptionID: client.subscriptionID, + } +} + +// NewAssessmentsClient creates a new instance of [AssessmentsClient]. +func (client *Client) NewAssessmentsClient() *AssessmentsClient { + return &AssessmentsClient{ + internal: client.internal, + subscriptionID: client.subscriptionID, + } +} + +// NewConfigurationsClient creates a new instance of [ConfigurationsClient]. +func (client *Client) NewConfigurationsClient() *ConfigurationsClient { + return &ConfigurationsClient{ + internal: client.internal, + subscriptionID: client.subscriptionID, + } +} + +// NewOperationsClient creates a new instance of [OperationsClient]. +func (client *Client) NewOperationsClient() *OperationsClient { + return &OperationsClient{ + internal: client.internal, + } +} + +// NewRecommendationMetadataClient creates a new instance of [RecommendationMetadataClient]. +func (client *Client) NewRecommendationMetadataClient() *RecommendationMetadataClient { + return &RecommendationMetadataClient{ + internal: client.internal, + } +} + +// NewRecommendationsClient creates a new instance of [RecommendationsClient]. +func (client *Client) NewRecommendationsClient() *RecommendationsClient { + return &RecommendationsClient{ + internal: client.internal, + subscriptionID: client.subscriptionID, + } +} + +// NewResiliencyReviewsClient creates a new instance of [ResiliencyReviewsClient]. +func (client *Client) NewResiliencyReviewsClient() *ResiliencyReviewsClient { + return &ResiliencyReviewsClient{ + internal: client.internal, + subscriptionID: client.subscriptionID, + } +} + +// NewScoresClient creates a new instance of [ScoresClient]. +func (client *Client) NewScoresClient() *ScoresClient { + return &ScoresClient{ + internal: client.internal, + subscriptionID: client.subscriptionID, + } +} + +// NewSuppressionsClient creates a new instance of [SuppressionsClient]. +func (client *Client) NewSuppressionsClient() *SuppressionsClient { + return &SuppressionsClient{ + internal: client.internal, + subscriptionID: client.subscriptionID, + } +} + +// NewTriageRecommendationsClient creates a new instance of [TriageRecommendationsClient]. +func (client *Client) NewTriageRecommendationsClient() *TriageRecommendationsClient { + return &TriageRecommendationsClient{ + internal: client.internal, + subscriptionID: client.subscriptionID, + } +} + +// NewTriageResourcesClient creates a new instance of [TriageResourcesClient]. +func (client *Client) NewTriageResourcesClient() *TriageResourcesClient { + return &TriageResourcesClient{ + internal: client.internal, + subscriptionID: client.subscriptionID, + } +} + +// NewWorkloadsClient creates a new instance of [WorkloadsClient]. +func (client *Client) NewWorkloadsClient() *WorkloadsClient { + return &WorkloadsClient{ + internal: client.internal, + subscriptionID: client.subscriptionID, + } +} + +// Predict - Predicts a recommendation. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-05-01-preview +// - predictionRequest - The request body +// - options - ClientPredictOptions contains the optional parameters for the Client.Predict method. +func (client *Client) Predict(ctx context.Context, predictionRequest PredictionRequest, options *ClientPredictOptions) (ClientPredictResponse, error) { + var err error + const operationName = "Client.Predict" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.predictCreateRequest(ctx, predictionRequest, options) + if err != nil { + return ClientPredictResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientPredictResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ClientPredictResponse{}, err + } + resp, err := client.predictHandleResponse(httpResp) + return resp, err +} + +// predictCreateRequest creates the Predict request. +func (client *Client) predictCreateRequest(ctx context.Context, predictionRequest PredictionRequest, _ *ClientPredictOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Advisor/predict" + 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.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2025-05-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, predictionRequest); err != nil { + return nil, err + } + return req, nil +} + +// predictHandleResponse handles the Predict response. +func (client *Client) predictHandleResponse(resp *http.Response) (ClientPredictResponse, error) { + result := ClientPredictResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PredictionResponse); err != nil { + return ClientPredictResponse{}, err + } + return result, nil +} diff --git a/sdk/resourcemanager/advisor/armadvisor/client_example_test.go b/sdk/resourcemanager/advisor/armadvisor/client_example_test.go new file mode 100644 index 000000000000..55c846020d9b --- /dev/null +++ b/sdk/resourcemanager/advisor/armadvisor/client_example_test.go @@ -0,0 +1,70 @@ +// 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) Go Code Generator. DO NOT EDIT. + +package armadvisor_test + +import ( + "context" + "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/advisor/armadvisor/v2" + "log" +) + +// Generated from example definition: 2025-05-01-preview/Predict.json +func ExampleClient_Predict() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armadvisor.NewClientFactory("12345678-1234-1234-1234-123456789012", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewClient().Predict(ctx, armadvisor.PredictionRequest{ + Properties: &armadvisor.PredictionRequestProperties{ + PredictionType: to.Ptr(armadvisor.PredictionTypePredictiveRightsizing), + ExtendedProperties: map[string]any{ + "region": "CentralUS", + "deploymentType": "Linux_IaaS_Software_Store", + "sku": "Standard_Dv4", + "type": "iaas", + "numberOfInstances": 10, + }, + }, + }, 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 = armadvisor.ClientPredictResponse{ + // PredictionResponse: &armadvisor.PredictionResponse{ + // Properties: &armadvisor.PredictionResponseProperties{ + // PredictionType: to.Ptr(armadvisor.PredictionTypePredictiveRightsizing), + // ExtendedProperties: map[string]any{ + // "region": "CentralUS", + // "deploymentType": "Linux_IaaS_Software_Store", + // "sku": "Standard_Dv4", + // "type": "iaas", + // "numberOfInstances": 10, + // "prediction": map[string]any{ + // "recommendedSku": "Standard_Dv2", + // "numberOfInstances": 8, + // "confidence": 0.9, + // }, + // }, + // Category: to.Ptr(armadvisor.CategoryCost), + // Impact: to.Ptr(armadvisor.ImpactLow), + // ImpactedField: to.Ptr("Microsoft.Compute/virtualMachines"), + // LastUpdated: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2022-02-14T14:47:18.436Z"); return t}()), + // ShortDescription: &armadvisor.ShortDescription{ + // Solution: to.Ptr("We recommend using 8 instances of type Standard_Dv2."), + // }, + // }, + // }, + // } +} diff --git a/sdk/resourcemanager/advisor/armadvisor/client_factory.go b/sdk/resourcemanager/advisor/armadvisor/client_factory.go index 7e23ac8f9e9f..e10887ef4abd 100644 --- a/sdk/resourcemanager/advisor/armadvisor/client_factory.go +++ b/sdk/resourcemanager/advisor/armadvisor/client_factory.go @@ -1,7 +1,6 @@ // 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. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package armadvisor @@ -14,52 +13,123 @@ 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. // The parameter values will be propagated to any client created from this factory. -// - subscriptionID - The Azure subscription ID. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. // - 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 } +// NewAssessmentTypesClient creates a new instance of AssessmentTypesClient. +func (c *ClientFactory) NewAssessmentTypesClient() *AssessmentTypesClient { + return &AssessmentTypesClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewAssessmentsClient creates a new instance of AssessmentsClient. +func (c *ClientFactory) NewAssessmentsClient() *AssessmentsClient { + return &AssessmentsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewClient creates a new instance of Client. +func (c *ClientFactory) NewClient() *Client { + return &Client{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + // NewConfigurationsClient creates a new instance of ConfigurationsClient. func (c *ClientFactory) NewConfigurationsClient() *ConfigurationsClient { - subClient, _ := NewConfigurationsClient(c.subscriptionID, c.credential, c.options) - return subClient + return &ConfigurationsClient{ + 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, + } } // NewRecommendationMetadataClient creates a new instance of RecommendationMetadataClient. func (c *ClientFactory) NewRecommendationMetadataClient() *RecommendationMetadataClient { - subClient, _ := NewRecommendationMetadataClient(c.credential, c.options) - return subClient + return &RecommendationMetadataClient{ + internal: c.internal, + } } // NewRecommendationsClient creates a new instance of RecommendationsClient. func (c *ClientFactory) NewRecommendationsClient() *RecommendationsClient { - subClient, _ := NewRecommendationsClient(c.subscriptionID, c.credential, c.options) - return subClient + return &RecommendationsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewResiliencyReviewsClient creates a new instance of ResiliencyReviewsClient. +func (c *ClientFactory) NewResiliencyReviewsClient() *ResiliencyReviewsClient { + return &ResiliencyReviewsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewScoresClient creates a new instance of ScoresClient. +func (c *ClientFactory) NewScoresClient() *ScoresClient { + return &ScoresClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } } // NewSuppressionsClient creates a new instance of SuppressionsClient. func (c *ClientFactory) NewSuppressionsClient() *SuppressionsClient { - subClient, _ := NewSuppressionsClient(c.subscriptionID, c.credential, c.options) - return subClient + return &SuppressionsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewTriageRecommendationsClient creates a new instance of TriageRecommendationsClient. +func (c *ClientFactory) NewTriageRecommendationsClient() *TriageRecommendationsClient { + return &TriageRecommendationsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewTriageResourcesClient creates a new instance of TriageResourcesClient. +func (c *ClientFactory) NewTriageResourcesClient() *TriageResourcesClient { + return &TriageResourcesClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewWorkloadsClient creates a new instance of WorkloadsClient. +func (c *ClientFactory) NewWorkloadsClient() *WorkloadsClient { + return &WorkloadsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } } diff --git a/sdk/resourcemanager/advisor/armadvisor/configurations_client.go b/sdk/resourcemanager/advisor/armadvisor/configurations_client.go index a9bd02b6cbd2..791981e8e685 100644 --- a/sdk/resourcemanager/advisor/armadvisor/configurations_client.go +++ b/sdk/resourcemanager/advisor/armadvisor/configurations_client.go @@ -1,7 +1,6 @@ // 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. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package armadvisor @@ -25,9 +24,9 @@ type ConfigurationsClient struct { } // NewConfigurationsClient creates a new instance of ConfigurationsClient with the specified values. -// - subscriptionID - The Azure subscription ID. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. // - credential - used to authorize requests. Usually a credential from azidentity. -// - options - pass nil to accept the default values. +// - options - Contains optional client configuration. Pass nil to accept the default values. func NewConfigurationsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ConfigurationsClient, error) { cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) if err != nil { @@ -41,9 +40,11 @@ func NewConfigurationsClient(subscriptionID string, credential azcore.TokenCrede } // CreateInResourceGroup - Create/Overwrite Azure Advisor configuration. +// +// Create/Overwrite Azure Advisor configuration. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2020-01-01 +// Generated from API version 2025-05-01-preview // - configurationName - Advisor configuration name. Value must be 'default' // - resourceGroup - The name of the Azure resource group. // - configContract - The Azure Advisor configuration data structure. @@ -72,7 +73,7 @@ func (client *ConfigurationsClient) CreateInResourceGroup(ctx context.Context, c } // createInResourceGroupCreateRequest creates the CreateInResourceGroup request. -func (client *ConfigurationsClient) createInResourceGroupCreateRequest(ctx context.Context, configurationName ConfigurationName, resourceGroup string, configContract ConfigData, options *ConfigurationsClientCreateInResourceGroupOptions) (*policy.Request, error) { +func (client *ConfigurationsClient) createInResourceGroupCreateRequest(ctx context.Context, configurationName ConfigurationName, resourceGroup string, configContract ConfigData, _ *ConfigurationsClientCreateInResourceGroupOptions) (*policy.Request, error) { urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Advisor/configurations/{configurationName}" if client.subscriptionID == "" { return nil, errors.New("parameter client.subscriptionID cannot be empty") @@ -91,9 +92,10 @@ func (client *ConfigurationsClient) createInResourceGroupCreateRequest(ctx conte return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2020-01-01") + reqQP.Set("api-version", "2025-05-01-preview") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, configContract); err != nil { return nil, err } @@ -109,11 +111,12 @@ func (client *ConfigurationsClient) createInResourceGroupHandleResponse(resp *ht return result, nil } -// CreateInSubscription - Create/Overwrite Azure Advisor configuration and also delete all configurations of contained resource -// groups. +// CreateInSubscription - Create/Overwrite Azure Advisor configuration. +// +// Create/Overwrite Azure Advisor configuration and also delete all configurations of contained resource groups. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2020-01-01 +// Generated from API version 2025-05-01-preview // - configurationName - Advisor configuration name. Value must be 'default' // - configContract - The Azure Advisor configuration data structure. // - options - ConfigurationsClientCreateInSubscriptionOptions contains the optional parameters for the ConfigurationsClient.CreateInSubscription @@ -141,7 +144,7 @@ func (client *ConfigurationsClient) CreateInSubscription(ctx context.Context, co } // createInSubscriptionCreateRequest creates the CreateInSubscription request. -func (client *ConfigurationsClient) createInSubscriptionCreateRequest(ctx context.Context, configurationName ConfigurationName, configContract ConfigData, options *ConfigurationsClientCreateInSubscriptionOptions) (*policy.Request, error) { +func (client *ConfigurationsClient) createInSubscriptionCreateRequest(ctx context.Context, configurationName ConfigurationName, configContract ConfigData, _ *ConfigurationsClientCreateInSubscriptionOptions) (*policy.Request, error) { urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Advisor/configurations/{configurationName}" if client.subscriptionID == "" { return nil, errors.New("parameter client.subscriptionID cannot be empty") @@ -156,9 +159,10 @@ func (client *ConfigurationsClient) createInSubscriptionCreateRequest(ctx contex return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2020-01-01") + reqQP.Set("api-version", "2025-05-01-preview") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, configContract); err != nil { return nil, err } @@ -176,28 +180,29 @@ func (client *ConfigurationsClient) createInSubscriptionHandleResponse(resp *htt // NewListByResourceGroupPager - Retrieve Azure Advisor configurations. // -// Generated from API version 2020-01-01 +// Retrieve Azure Advisor configurations. +// +// Generated from API version 2025-05-01-preview // - resourceGroup - The name of the Azure resource group. // - options - ConfigurationsClientListByResourceGroupOptions contains the optional parameters for the ConfigurationsClient.NewListByResourceGroupPager // method. func (client *ConfigurationsClient) NewListByResourceGroupPager(resourceGroup string, options *ConfigurationsClientListByResourceGroupOptions) *runtime.Pager[ConfigurationsClientListByResourceGroupResponse] { return runtime.NewPager(runtime.PagingHandler[ConfigurationsClientListByResourceGroupResponse]{ More: func(page ConfigurationsClientListByResourceGroupResponse) bool { - return false + return page.NextLink != nil && len(*page.NextLink) > 0 }, Fetcher: func(ctx context.Context, page *ConfigurationsClientListByResourceGroupResponse) (ConfigurationsClientListByResourceGroupResponse, error) { ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ConfigurationsClient.NewListByResourceGroupPager") - req, err := client.listByResourceGroupCreateRequest(ctx, resourceGroup, options) - if err != nil { - return ConfigurationsClientListByResourceGroupResponse{}, err + nextLink := "" + if page != nil { + nextLink = *page.NextLink } - resp, err := client.internal.Pipeline().Do(req) + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByResourceGroupCreateRequest(ctx, resourceGroup, options) + }, nil) if err != nil { return ConfigurationsClientListByResourceGroupResponse{}, err } - if !runtime.HasStatusCode(resp, http.StatusOK) { - return ConfigurationsClientListByResourceGroupResponse{}, runtime.NewResponseError(resp) - } return client.listByResourceGroupHandleResponse(resp) }, Tracer: client.internal.Tracer(), @@ -205,7 +210,7 @@ func (client *ConfigurationsClient) NewListByResourceGroupPager(resourceGroup st } // listByResourceGroupCreateRequest creates the ListByResourceGroup request. -func (client *ConfigurationsClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroup string, options *ConfigurationsClientListByResourceGroupOptions) (*policy.Request, error) { +func (client *ConfigurationsClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroup string, _ *ConfigurationsClientListByResourceGroupOptions) (*policy.Request, error) { urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Advisor/configurations" if client.subscriptionID == "" { return nil, errors.New("parameter client.subscriptionID cannot be empty") @@ -220,7 +225,7 @@ func (client *ConfigurationsClient) listByResourceGroupCreateRequest(ctx context return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2020-01-01") + reqQP.Set("api-version", "2025-05-01-preview") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -235,10 +240,11 @@ func (client *ConfigurationsClient) listByResourceGroupHandleResponse(resp *http return result, nil } -// NewListBySubscriptionPager - Retrieve Azure Advisor configurations and also retrieve configurations of contained resource -// groups. +// NewListBySubscriptionPager - Retrieve Azure Advisor configurations. +// +// Retrieve Azure Advisor configurations and also retrieve configurations of contained resource groups. // -// Generated from API version 2020-01-01 +// Generated from API version 2025-05-01-preview // - options - ConfigurationsClientListBySubscriptionOptions contains the optional parameters for the ConfigurationsClient.NewListBySubscriptionPager // method. func (client *ConfigurationsClient) NewListBySubscriptionPager(options *ConfigurationsClientListBySubscriptionOptions) *runtime.Pager[ConfigurationsClientListBySubscriptionResponse] { @@ -265,7 +271,7 @@ func (client *ConfigurationsClient) NewListBySubscriptionPager(options *Configur } // listBySubscriptionCreateRequest creates the ListBySubscription request. -func (client *ConfigurationsClient) listBySubscriptionCreateRequest(ctx context.Context, options *ConfigurationsClientListBySubscriptionOptions) (*policy.Request, error) { +func (client *ConfigurationsClient) listBySubscriptionCreateRequest(ctx context.Context, _ *ConfigurationsClientListBySubscriptionOptions) (*policy.Request, error) { urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Advisor/configurations" if client.subscriptionID == "" { return nil, errors.New("parameter client.subscriptionID cannot be empty") @@ -276,7 +282,7 @@ func (client *ConfigurationsClient) listBySubscriptionCreateRequest(ctx context. return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2020-01-01") + reqQP.Set("api-version", "2025-05-01-preview") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil diff --git a/sdk/resourcemanager/advisor/armadvisor/configurations_client_example_test.go b/sdk/resourcemanager/advisor/armadvisor/configurations_client_example_test.go index 5a9dac4766b7..887722ed078e 100644 --- a/sdk/resourcemanager/advisor/armadvisor/configurations_client_example_test.go +++ b/sdk/resourcemanager/advisor/armadvisor/configurations_client_example_test.go @@ -1,100 +1,119 @@ // 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. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package armadvisor_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/advisor/armadvisor" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/advisor/armadvisor/v2" + "log" ) -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/7a2ac91de424f271cf91cc8009f3fe9ee8249086/specification/advisor/resource-manager/Microsoft.Advisor/stable/2020-01-01/examples/ListConfigurations.json -func ExampleConfigurationsClient_NewListBySubscriptionPager() { +// Generated from example definition: 2025-05-01-preview/CreateConfiguration.json +func ExampleConfigurationsClient_CreateInResourceGroup() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() - clientFactory, err := armadvisor.NewClientFactory("", cred, nil) + clientFactory, err := armadvisor.NewClientFactory("58c3f667-7a62-4bfd-a658-846493e9a493", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } - pager := clientFactory.NewConfigurationsClient().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.ConfigurationListResult = armadvisor.ConfigurationListResult{ - // Value: []*armadvisor.ConfigData{ - // { - // Name: to.Ptr("default"), - // Type: to.Ptr("Microsoft.Advisor/configurations"), - // ID: to.Ptr("/subscriptions/subscriptionId/resourceGroups/resourceGroup/providers/Microsoft.Advisor/configurations/default"), - // Properties: &armadvisor.ConfigDataProperties{ - // Digests: []*armadvisor.DigestConfig{ - // { - // Name: to.Ptr("digestConfigName"), - // ActionGroupResourceID: to.Ptr("/subscriptions/subscriptionId/resourceGroups/resourceGroup/providers/microsoft.insights/actionGroups/actionGroupName"), - // Categories: []*armadvisor.Category{ - // to.Ptr(armadvisor.CategoryHighAvailability), - // to.Ptr(armadvisor.CategorySecurity), - // to.Ptr(armadvisor.CategoryPerformance), - // to.Ptr(armadvisor.CategoryCost), - // to.Ptr(armadvisor.CategoryOperationalExcellence)}, - // Frequency: to.Ptr[int32](30), - // State: to.Ptr(armadvisor.DigestConfigStateActive), - // Language: to.Ptr("en"), - // }}, - // Exclude: to.Ptr(false), - // LowCPUThreshold: to.Ptr(armadvisor.CPUThresholdFive), - // }, - // }}, - // } + res, err := clientFactory.NewConfigurationsClient().CreateInResourceGroup(ctx, armadvisor.ConfigurationNameDefault, "resourceGroup", armadvisor.ConfigData{ + Properties: &armadvisor.ConfigDataProperties{ + LowCPUThreshold: to.Ptr(armadvisor.CPUThresholdFive), + Duration: to.Ptr(armadvisor.Duration7), + Exclude: to.Ptr(true), + Digests: []*armadvisor.DigestConfig{ + { + Name: to.Ptr("digestConfigName"), + ActionGroupResourceID: to.Ptr("/subscriptions/58c3f667-7a62-4bfd-a658-846493e9a493/resourceGroups/resourceGroup/providers/microsoft.insights/actionGroups/actionGroupName"), + Frequency: to.Ptr[int32](30), + Categories: []*armadvisor.Category{ + to.Ptr(armadvisor.CategoryHighAvailability), + to.Ptr(armadvisor.CategorySecurity), + to.Ptr(armadvisor.CategoryPerformance), + to.Ptr(armadvisor.CategoryCost), + to.Ptr(armadvisor.CategoryOperationalExcellence), + }, + Language: to.Ptr("en"), + State: to.Ptr(armadvisor.DigestConfigStateActive), + }, + }, + }, + }, 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 = armadvisor.ConfigurationsClientCreateInResourceGroupResponse{ + // ConfigData: &armadvisor.ConfigData{ + // ID: to.Ptr("/subscriptions/58c3f667-7a62-4bfd-a658-846493e9a493/resourceGroups/resourceGroup/providers/Microsoft.Advisor/configurations/default"), + // Type: to.Ptr("Microsoft.Advisor/configurations"), + // Name: to.Ptr("default"), + // Properties: &armadvisor.ConfigDataProperties{ + // LowCPUThreshold: to.Ptr(armadvisor.CPUThresholdFive), + // Duration: to.Ptr(armadvisor.Duration7), + // Exclude: to.Ptr(true), + // Digests: []*armadvisor.DigestConfig{ + // { + // Name: to.Ptr("digestConfigName"), + // ActionGroupResourceID: to.Ptr("/subscriptions/58c3f667-7a62-4bfd-a658-846493e9a493/resourceGroups/resourceGroup/providers/microsoft.insights/actionGroups/actionGroupName"), + // Frequency: to.Ptr[int32](30), + // Categories: []*armadvisor.Category{ + // to.Ptr(armadvisor.CategoryHighAvailability), + // to.Ptr(armadvisor.CategorySecurity), + // to.Ptr(armadvisor.CategoryPerformance), + // to.Ptr(armadvisor.CategoryCost), + // to.Ptr(armadvisor.CategoryOperationalExcellence), + // }, + // Language: to.Ptr("en"), + // State: to.Ptr(armadvisor.DigestConfigStateActive), + // }, + // }, + // }, + // }, + // } } -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/7a2ac91de424f271cf91cc8009f3fe9ee8249086/specification/advisor/resource-manager/Microsoft.Advisor/stable/2020-01-01/examples/CreateConfiguration.json +// Generated from example definition: 2025-05-01-preview/CreateConfiguration_CreateInSubscription.json func ExampleConfigurationsClient_CreateInSubscription() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() - clientFactory, err := armadvisor.NewClientFactory("", cred, nil) + clientFactory, err := armadvisor.NewClientFactory("58c3f667-7a62-4bfd-a658-846493e9a493", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } res, err := clientFactory.NewConfigurationsClient().CreateInSubscription(ctx, armadvisor.ConfigurationNameDefault, armadvisor.ConfigData{ Properties: &armadvisor.ConfigDataProperties{ + LowCPUThreshold: to.Ptr(armadvisor.CPUThresholdFive), + Duration: to.Ptr(armadvisor.Duration7), + Exclude: to.Ptr(true), Digests: []*armadvisor.DigestConfig{ { Name: to.Ptr("digestConfigName"), - ActionGroupResourceID: to.Ptr("/subscriptions/subscriptionId/resourceGroups/resourceGroup/providers/microsoft.insights/actionGroups/actionGroupName"), + ActionGroupResourceID: to.Ptr("/subscriptions/58c3f667-7a62-4bfd-a658-846493e9a493/resourceGroups/resourceGroup/providers/microsoft.insights/actionGroups/actionGroupName"), + Frequency: to.Ptr[int32](30), Categories: []*armadvisor.Category{ to.Ptr(armadvisor.CategoryHighAvailability), to.Ptr(armadvisor.CategorySecurity), to.Ptr(armadvisor.CategoryPerformance), to.Ptr(armadvisor.CategoryCost), - to.Ptr(armadvisor.CategoryOperationalExcellence)}, - Frequency: to.Ptr[int32](30), - State: to.Ptr(armadvisor.DigestConfigStateActive), - Language: to.Ptr("en"), - }}, - Exclude: to.Ptr(true), - LowCPUThreshold: to.Ptr(armadvisor.CPUThresholdFive), + to.Ptr(armadvisor.CategoryOperationalExcellence), + }, + Language: to.Ptr("en"), + State: to.Ptr(armadvisor.DigestConfigStateActive), + }, + }, }, }, nil) if err != nil { @@ -103,27 +122,148 @@ func ExampleConfigurationsClient_CreateInSubscription() { // 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.ConfigData = armadvisor.ConfigData{ - // Name: to.Ptr("default"), - // Type: to.Ptr("Microsoft.Advisor/configurations"), - // ID: to.Ptr("/subscriptions/subscriptionId/resourceGroups/resourceGroup/providers/Microsoft.Advisor/configurations/default"), - // Properties: &armadvisor.ConfigDataProperties{ - // Digests: []*armadvisor.DigestConfig{ - // { - // Name: to.Ptr("digestConfigName"), - // ActionGroupResourceID: to.Ptr("/subscriptions/subscriptionId/resourceGroups/resourceGroup/providers/microsoft.insights/actionGroups/actionGroupName"), - // Categories: []*armadvisor.Category{ - // to.Ptr(armadvisor.CategoryHighAvailability), - // to.Ptr(armadvisor.CategorySecurity), - // to.Ptr(armadvisor.CategoryPerformance), - // to.Ptr(armadvisor.CategoryCost), - // to.Ptr(armadvisor.CategoryOperationalExcellence)}, + // res = armadvisor.ConfigurationsClientCreateInSubscriptionResponse{ + // ConfigData: &armadvisor.ConfigData{ + // ID: to.Ptr("/subscriptions/58c3f667-7a62-4bfd-a658-846493e9a493/resourceGroups/resourceGroup/providers/Microsoft.Advisor/configurations/default"), + // Type: to.Ptr("Microsoft.Advisor/configurations"), + // Name: to.Ptr("default"), + // Properties: &armadvisor.ConfigDataProperties{ + // LowCPUThreshold: to.Ptr(armadvisor.CPUThresholdFive), + // Duration: to.Ptr(armadvisor.Duration7), + // Exclude: to.Ptr(true), + // Digests: []*armadvisor.DigestConfig{ + // { + // Name: to.Ptr("digestConfigName"), + // ActionGroupResourceID: to.Ptr("/subscriptions/58c3f667-7a62-4bfd-a658-846493e9a493/resourceGroups/resourceGroup/providers/microsoft.insights/actionGroups/actionGroupName"), // Frequency: to.Ptr[int32](30), - // State: to.Ptr(armadvisor.DigestConfigStateActive), + // Categories: []*armadvisor.Category{ + // to.Ptr(armadvisor.CategoryHighAvailability), + // to.Ptr(armadvisor.CategorySecurity), + // to.Ptr(armadvisor.CategoryPerformance), + // to.Ptr(armadvisor.CategoryCost), + // to.Ptr(armadvisor.CategoryOperationalExcellence), + // }, // Language: to.Ptr("en"), - // }}, - // Exclude: to.Ptr(true), - // LowCPUThreshold: to.Ptr(armadvisor.CPUThresholdFive), + // State: to.Ptr(armadvisor.DigestConfigStateActive), + // }, + // }, // }, - // } + // }, + // } +} + +// Generated from example definition: 2025-05-01-preview/ListConfigurations.json +func ExampleConfigurationsClient_NewListByResourceGroupPager() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armadvisor.NewClientFactory("12345678-1234-1234-1234-123456789012", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + pager := clientFactory.NewConfigurationsClient().NewListByResourceGroupPager("resourceGroup", 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 = armadvisor.ConfigurationsClientListByResourceGroupResponse{ + // ConfigurationListResult: armadvisor.ConfigurationListResult{ + // Value: []*armadvisor.ConfigData{ + // { + // ID: to.Ptr("/subscriptions/subscriptionId/resourceGroups/resourceGroup/providers/Microsoft.Advisor/configurations/default"), + // Type: to.Ptr("Microsoft.Advisor/configurations"), + // Name: to.Ptr("default"), + // Properties: &armadvisor.ConfigDataProperties{ + // LowCPUThreshold: to.Ptr(armadvisor.CPUThresholdFive), + // Duration: to.Ptr(armadvisor.Duration7), + // Exclude: to.Ptr(false), + // Digests: []*armadvisor.DigestConfig{ + // { + // Name: to.Ptr("digestConfigName"), + // ActionGroupResourceID: to.Ptr("/subscriptions/subscriptionId/resourceGroups/resourceGroup/providers/microsoft.insights/actionGroups/actionGroupName"), + // Frequency: to.Ptr[int32](30), + // Categories: []*armadvisor.Category{ + // to.Ptr(armadvisor.CategoryHighAvailability), + // to.Ptr(armadvisor.CategorySecurity), + // to.Ptr(armadvisor.CategoryPerformance), + // to.Ptr(armadvisor.CategoryCost), + // to.Ptr(armadvisor.CategoryOperationalExcellence), + // }, + // Language: to.Ptr("en"), + // State: to.Ptr(armadvisor.DigestConfigStateActive), + // }, + // }, + // }, + // }, + // }, + // NextLink: to.Ptr("https://management.azure.com/subscriptions/12345678-1234-1234-1234-123456789012/resourceGroups/resourceGroup/providers/Microsoft.Advisor/configurations?api-version=2025-05-01-preview&$skipToken=abc123"), + // }, + // } + } +} + +// Generated from example definition: 2025-05-01-preview/ListConfigurations_ListBySubscription.json +func ExampleConfigurationsClient_NewListBySubscriptionPager() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armadvisor.NewClientFactory("12345678-1234-1234-1234-123456789012", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + pager := clientFactory.NewConfigurationsClient().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 = armadvisor.ConfigurationsClientListBySubscriptionResponse{ + // ConfigurationListResult: armadvisor.ConfigurationListResult{ + // Value: []*armadvisor.ConfigData{ + // { + // ID: to.Ptr("/subscriptions/subscriptionId/resourceGroups/resourceGroup/providers/Microsoft.Advisor/configurations/default"), + // Type: to.Ptr("Microsoft.Advisor/configurations"), + // Name: to.Ptr("default"), + // Properties: &armadvisor.ConfigDataProperties{ + // LowCPUThreshold: to.Ptr(armadvisor.CPUThresholdFive), + // Duration: to.Ptr(armadvisor.Duration7), + // Exclude: to.Ptr(false), + // Digests: []*armadvisor.DigestConfig{ + // { + // Name: to.Ptr("digestConfigName"), + // ActionGroupResourceID: to.Ptr("/subscriptions/subscriptionId/resourceGroups/resourceGroup/providers/microsoft.insights/actionGroups/actionGroupName"), + // Frequency: to.Ptr[int32](30), + // Categories: []*armadvisor.Category{ + // to.Ptr(armadvisor.CategoryHighAvailability), + // to.Ptr(armadvisor.CategorySecurity), + // to.Ptr(armadvisor.CategoryPerformance), + // to.Ptr(armadvisor.CategoryCost), + // to.Ptr(armadvisor.CategoryOperationalExcellence), + // }, + // Language: to.Ptr("en"), + // State: to.Ptr(armadvisor.DigestConfigStateActive), + // }, + // }, + // }, + // }, + // }, + // NextLink: to.Ptr("https://management.azure.com/subscriptions/12345678-1234-1234-1234-123456789012/providers/Microsoft.Advisor/configurations?api-version=2025-05-01-preview&$skipToken=abc123"), + // }, + // } + } } diff --git a/sdk/resourcemanager/advisor/armadvisor/constants.go b/sdk/resourcemanager/advisor/armadvisor/constants.go index dbfc2e10dace..e48be2065995 100644 --- a/sdk/resourcemanager/advisor/armadvisor/constants.go +++ b/sdk/resourcemanager/advisor/armadvisor/constants.go @@ -1,15 +1,27 @@ // 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. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package armadvisor +// Aggregated - The aggregation level of the score. +type Aggregated string + const ( - moduleName = "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/advisor/armadvisor" - moduleVersion = "v1.2.0" + AggregatedDay Aggregated = "day" + AggregatedMonth Aggregated = "month" + AggregatedWeek Aggregated = "week" ) +// PossibleAggregatedValues returns the possible values for the Aggregated const type. +func PossibleAggregatedValues() []Aggregated { + return []Aggregated{ + AggregatedDay, + AggregatedMonth, + AggregatedWeek, + } +} + // CPUThreshold - Minimum percentage threshold for Advisor low CPU utilization evaluation. Valid only for subscriptions. Valid // values: 5 (default), 10, 15 or 20. type CPUThreshold string @@ -31,6 +43,7 @@ func PossibleCPUThresholdValues() []CPUThreshold { } } +// Category - The category of the recommendation. type Category string const ( @@ -65,6 +78,60 @@ func PossibleConfigurationNameValues() []ConfigurationName { } } +// Control - The sub-category of the recommendation. +type Control string + +const ( + ControlBusinessContinuity Control = "BusinessContinuity" + ControlDisasterRecovery Control = "DisasterRecovery" + ControlHighAvailability Control = "HighAvailability" + ControlMonitoringAndAlerting Control = "MonitoringAndAlerting" + ControlOther Control = "Other" + ControlPersonalized Control = "Personalized" + ControlPrioritizedRecommendations Control = "PrioritizedRecommendations" + ControlScalability Control = "Scalability" + ControlServiceUpgradeAndRetirement Control = "ServiceUpgradeAndRetirement" +) + +// PossibleControlValues returns the possible values for the Control const type. +func PossibleControlValues() []Control { + return []Control{ + ControlBusinessContinuity, + ControlDisasterRecovery, + ControlHighAvailability, + ControlMonitoringAndAlerting, + ControlOther, + ControlPersonalized, + ControlPrioritizedRecommendations, + ControlScalability, + ControlServiceUpgradeAndRetirement, + } +} + +// CreatedByType - The kind of entity that created the resource. +type CreatedByType string + +const ( + // CreatedByTypeApplication - The entity was created by an application. + CreatedByTypeApplication CreatedByType = "Application" + // CreatedByTypeKey - The entity was created by a key. + CreatedByTypeKey CreatedByType = "Key" + // CreatedByTypeManagedIdentity - The entity was created by a managed identity. + CreatedByTypeManagedIdentity CreatedByType = "ManagedIdentity" + // CreatedByTypeUser - The entity was created by a user. + CreatedByTypeUser CreatedByType = "User" +) + +// PossibleCreatedByTypeValues returns the possible values for the CreatedByType const type. +func PossibleCreatedByTypeValues() []CreatedByType { + return []CreatedByType{ + CreatedByTypeApplication, + CreatedByTypeKey, + CreatedByTypeManagedIdentity, + CreatedByTypeUser, + } +} + // DigestConfigState - State of digest configuration. type DigestConfigState string @@ -81,6 +148,31 @@ func PossibleDigestConfigStateValues() []DigestConfigState { } } +// Duration - Minimum duration for Advisor low CPU utilization evaluation. Valid only for subscriptions. Valid values: 7 (default), +// 14, 21, 30, 60 or 90. +type Duration string + +const ( + Duration14 Duration = "14" + Duration21 Duration = "21" + Duration30 Duration = "30" + Duration60 Duration = "60" + Duration7 Duration = "7" + Duration90 Duration = "90" +) + +// PossibleDurationValues returns the possible values for the Duration const type. +func PossibleDurationValues() []Duration { + return []Duration{ + Duration14, + Duration21, + Duration30, + Duration60, + Duration7, + Duration90, + } +} + // Impact - The business impact of the recommendation. type Impact string @@ -99,6 +191,150 @@ func PossibleImpactValues() []Impact { } } +// PredictionType - Type of the prediction. +type PredictionType string + +const ( + PredictionTypePredictiveRightsizing PredictionType = "PredictiveRightsizing" +) + +// PossiblePredictionTypeValues returns the possible values for the PredictionType const type. +func PossiblePredictionTypeValues() []PredictionType { + return []PredictionType{ + PredictionTypePredictiveRightsizing, + } +} + +// Priority - The Priority of the Recommendation. +type Priority string + +const ( + PriorityCritical Priority = "Critical" + PriorityHigh Priority = "High" + PriorityInformational Priority = "Informational" + PriorityLow Priority = "Low" + PriorityMedium Priority = "Medium" +) + +// PossiblePriorityValues returns the possible values for the Priority const type. +func PossiblePriorityValues() []Priority { + return []Priority{ + PriorityCritical, + PriorityHigh, + PriorityInformational, + PriorityLow, + PriorityMedium, + } +} + +// PriorityName - Recommendation priority name enum. +type PriorityName string + +const ( + // PriorityNameHigh - High + PriorityNameHigh PriorityName = "High" + // PriorityNameLow - Low + PriorityNameLow PriorityName = "Low" + // PriorityNameMedium - Medium + PriorityNameMedium PriorityName = "Medium" +) + +// PossiblePriorityNameValues returns the possible values for the PriorityName const type. +func PossiblePriorityNameValues() []PriorityName { + return []PriorityName{ + PriorityNameHigh, + PriorityNameLow, + PriorityNameMedium, + } +} + +// Reason - The reason the state of the Recommendation was changed. +type Reason string + +const ( + ReasonAlternativeSolution Reason = "AlternativeSolution" + ReasonExcessiveInvestment Reason = "ExcessiveInvestment" + ReasonIncompatible Reason = "Incompatible" + ReasonRiskAccepted Reason = "RiskAccepted" + ReasonTooComplex Reason = "TooComplex" + ReasonUnclear Reason = "Unclear" +) + +// PossibleReasonValues returns the possible values for the Reason const type. +func PossibleReasonValues() []Reason { + return []Reason{ + ReasonAlternativeSolution, + ReasonExcessiveInvestment, + ReasonIncompatible, + ReasonRiskAccepted, + ReasonTooComplex, + ReasonUnclear, + } +} + +// ReasonForRejectionName - Reason for rejecting recommendation name enum. +type ReasonForRejectionName string + +const ( + // ReasonForRejectionNameNotARisk - Not A Risk + ReasonForRejectionNameNotARisk ReasonForRejectionName = "NotARisk" + // ReasonForRejectionNameRiskAccepted - Risk Accepted + ReasonForRejectionNameRiskAccepted ReasonForRejectionName = "RiskAccepted" +) + +// PossibleReasonForRejectionNameValues returns the possible values for the ReasonForRejectionName const type. +func PossibleReasonForRejectionNameValues() []ReasonForRejectionName { + return []ReasonForRejectionName{ + ReasonForRejectionNameNotARisk, + ReasonForRejectionNameRiskAccepted, + } +} + +// RecommendationStatusName - Recommendation status name enum. +type RecommendationStatusName string + +const ( + // RecommendationStatusNameApproved - Approved + RecommendationStatusNameApproved RecommendationStatusName = "Approved" + // RecommendationStatusNamePending - Pending + RecommendationStatusNamePending RecommendationStatusName = "Pending" + // RecommendationStatusNameRejected - Rejected + RecommendationStatusNameRejected RecommendationStatusName = "Rejected" +) + +// PossibleRecommendationStatusNameValues returns the possible values for the RecommendationStatusName const type. +func PossibleRecommendationStatusNameValues() []RecommendationStatusName { + return []RecommendationStatusName{ + RecommendationStatusNameApproved, + RecommendationStatusNamePending, + RecommendationStatusNameRejected, + } +} + +// ReviewStatus - Review status. +type ReviewStatus string + +const ( + // ReviewStatusCompleted - Completed + ReviewStatusCompleted ReviewStatus = "Completed" + // ReviewStatusInProgress - In Progress + ReviewStatusInProgress ReviewStatus = "InProgress" + // ReviewStatusNew - New + ReviewStatusNew ReviewStatus = "New" + // ReviewStatusTriaged - Triaged + ReviewStatusTriaged ReviewStatus = "Triaged" +) + +// PossibleReviewStatusValues returns the possible values for the ReviewStatus const type. +func PossibleReviewStatusValues() []ReviewStatus { + return []ReviewStatus{ + ReviewStatusCompleted, + ReviewStatusInProgress, + ReviewStatusNew, + ReviewStatusTriaged, + } +} + // Risk - The potential risk of not implementing the recommendation. type Risk string @@ -117,6 +353,7 @@ func PossibleRiskValues() []Risk { } } +// Scenario - The list of scenarios applicable to this metadata entity. type Scenario string const ( @@ -129,3 +366,29 @@ func PossibleScenarioValues() []Scenario { ScenarioAlerts, } } + +// State - The state of the Recommendation +type State string + +const ( + StateApproved State = "Approved" + StateCompleted State = "Completed" + StateDismissed State = "Dismissed" + StateInProgress State = "InProgress" + StatePending State = "Pending" + StatePostponed State = "Postponed" + StateRejected State = "Rejected" +) + +// PossibleStateValues returns the possible values for the State const type. +func PossibleStateValues() []State { + return []State{ + StateApproved, + StateCompleted, + StateDismissed, + StateInProgress, + StatePending, + StatePostponed, + StateRejected, + } +} diff --git a/sdk/resourcemanager/advisor/armadvisor/fake/assessments_server.go b/sdk/resourcemanager/advisor/armadvisor/fake/assessments_server.go new file mode 100644 index 000000000000..7184a9884bdc --- /dev/null +++ b/sdk/resourcemanager/advisor/armadvisor/fake/assessments_server.go @@ -0,0 +1,253 @@ +// 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) Go Code Generator. DO NOT EDIT. + +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/advisor/armadvisor/v2" + "net/http" + "net/url" + "regexp" +) + +// AssessmentsServer is a fake server for instances of the armadvisor.AssessmentsClient type. +type AssessmentsServer struct { + // Delete is the fake for method AssessmentsClient.Delete + // HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent + Delete func(ctx context.Context, assessmentName string, options *armadvisor.AssessmentsClientDeleteOptions) (resp azfake.Responder[armadvisor.AssessmentsClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method AssessmentsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, assessmentName string, options *armadvisor.AssessmentsClientGetOptions) (resp azfake.Responder[armadvisor.AssessmentsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListPager is the fake for method AssessmentsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(options *armadvisor.AssessmentsClientListOptions) (resp azfake.PagerResponder[armadvisor.AssessmentsClientListResponse]) + + // Put is the fake for method AssessmentsClient.Put + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + Put func(ctx context.Context, assessmentName string, assessmentContract armadvisor.AssessmentResult, options *armadvisor.AssessmentsClientPutOptions) (resp azfake.Responder[armadvisor.AssessmentsClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewAssessmentsServerTransport creates a new instance of AssessmentsServerTransport with the provided implementation. +// The returned AssessmentsServerTransport instance is connected to an instance of armadvisor.AssessmentsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewAssessmentsServerTransport(srv *AssessmentsServer) *AssessmentsServerTransport { + return &AssessmentsServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[armadvisor.AssessmentsClientListResponse]](), + } +} + +// AssessmentsServerTransport connects instances of armadvisor.AssessmentsClient to instances of AssessmentsServer. +// Don't use this type directly, use NewAssessmentsServerTransport instead. +type AssessmentsServerTransport struct { + srv *AssessmentsServer + newListPager *tracker[azfake.PagerResponder[armadvisor.AssessmentsClientListResponse]] +} + +// Do implements the policy.Transporter interface for AssessmentsServerTransport. +func (a *AssessmentsServerTransport) 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")} + } + + return a.dispatchToMethodFake(req, method) +} + +func (a *AssessmentsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result) + defer close(resultChan) + + go func() { + var intercepted bool + var res result + if assessmentsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = assessmentsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "AssessmentsClient.Delete": + res.resp, res.err = a.dispatchDelete(req) + case "AssessmentsClient.Get": + res.resp, res.err = a.dispatchGet(req) + case "AssessmentsClient.NewListPager": + res.resp, res.err = a.dispatchNewListPager(req) + case "AssessmentsClient.Put": + res.resp, res.err = a.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + select { + case resultChan <- res: + case <-req.Context().Done(): + } + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (a *AssessmentsServerTransport) dispatchDelete(req *http.Request) (*http.Response, error) { + if a.srv.Delete == nil { + return nil, &nonRetriableError{errors.New("fake for method Delete not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Advisor/assessments/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + assessmentNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("assessmentName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Delete(req.Context(), assessmentNameParam, 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 (a *AssessmentsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if a.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Advisor/assessments/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + assessmentNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("assessmentName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Get(req.Context(), assessmentNameParam, 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).AssessmentResult, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *AssessmentsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if a.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := a.newListPager.get(req) + if newListPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Advisor/assessments` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + qp := req.URL.Query() + topUnescaped, err := url.QueryUnescape(qp.Get("$top")) + if err != nil { + return nil, err + } + topParam := getOptional(topUnescaped) + skiptokenUnescaped, err := url.QueryUnescape(qp.Get("$skiptoken")) + if err != nil { + return nil, err + } + skiptokenParam := getOptional(skiptokenUnescaped) + var options *armadvisor.AssessmentsClientListOptions + if topParam != nil || skiptokenParam != nil { + options = &armadvisor.AssessmentsClientListOptions{ + Top: topParam, + Skiptoken: skiptokenParam, + } + } + resp := a.srv.NewListPager(options) + newListPager = &resp + a.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armadvisor.AssessmentsClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !contains([]int{http.StatusOK}, resp.StatusCode) { + a.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + a.newListPager.remove(req) + } + return resp, nil +} + +func (a *AssessmentsServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if a.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Advisor/assessments/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armadvisor.AssessmentResult](req) + if err != nil { + return nil, err + } + assessmentNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("assessmentName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Put(req.Context(), assessmentNameParam, 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).AssessmentResult, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to AssessmentsServerTransport +var assessmentsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/sdk/resourcemanager/advisor/armadvisor/fake/assessmenttypes_server.go b/sdk/resourcemanager/advisor/armadvisor/fake/assessmenttypes_server.go new file mode 100644 index 000000000000..e1419dcb9ae9 --- /dev/null +++ b/sdk/resourcemanager/advisor/armadvisor/fake/assessmenttypes_server.go @@ -0,0 +1,124 @@ +// 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) Go Code Generator. DO NOT EDIT. + +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/advisor/armadvisor/v2" + "net/http" + "regexp" +) + +// AssessmentTypesServer is a fake server for instances of the armadvisor.AssessmentTypesClient type. +type AssessmentTypesServer struct { + // NewListPager is the fake for method AssessmentTypesClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(options *armadvisor.AssessmentTypesClientListOptions) (resp azfake.PagerResponder[armadvisor.AssessmentTypesClientListResponse]) +} + +// NewAssessmentTypesServerTransport creates a new instance of AssessmentTypesServerTransport with the provided implementation. +// The returned AssessmentTypesServerTransport instance is connected to an instance of armadvisor.AssessmentTypesClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewAssessmentTypesServerTransport(srv *AssessmentTypesServer) *AssessmentTypesServerTransport { + return &AssessmentTypesServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[armadvisor.AssessmentTypesClientListResponse]](), + } +} + +// AssessmentTypesServerTransport connects instances of armadvisor.AssessmentTypesClient to instances of AssessmentTypesServer. +// Don't use this type directly, use NewAssessmentTypesServerTransport instead. +type AssessmentTypesServerTransport struct { + srv *AssessmentTypesServer + newListPager *tracker[azfake.PagerResponder[armadvisor.AssessmentTypesClientListResponse]] +} + +// Do implements the policy.Transporter interface for AssessmentTypesServerTransport. +func (a *AssessmentTypesServerTransport) 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")} + } + + return a.dispatchToMethodFake(req, method) +} + +func (a *AssessmentTypesServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result) + defer close(resultChan) + + go func() { + var intercepted bool + var res result + if assessmentTypesServerTransportInterceptor != nil { + res.resp, res.err, intercepted = assessmentTypesServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "AssessmentTypesClient.NewListPager": + res.resp, res.err = a.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + select { + case resultChan <- res: + case <-req.Context().Done(): + } + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (a *AssessmentTypesServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if a.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := a.newListPager.get(req) + if newListPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Advisor/assessmentTypes` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resp := a.srv.NewListPager(nil) + newListPager = &resp + a.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armadvisor.AssessmentTypesClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !contains([]int{http.StatusOK}, resp.StatusCode) { + a.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + a.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to AssessmentTypesServerTransport +var assessmentTypesServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/sdk/resourcemanager/advisor/armadvisor/fake/configurations_server.go b/sdk/resourcemanager/advisor/armadvisor/fake/configurations_server.go index 3bd8abfc8f9f..7dd3c75cf7fb 100644 --- a/sdk/resourcemanager/advisor/armadvisor/fake/configurations_server.go +++ b/sdk/resourcemanager/advisor/armadvisor/fake/configurations_server.go @@ -1,7 +1,6 @@ // 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. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package fake @@ -13,7 +12,7 @@ import ( "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/advisor/armadvisor" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/advisor/armadvisor/v2" "net/http" "net/url" "regexp" @@ -65,27 +64,46 @@ func (c *ConfigurationsServerTransport) Do(req *http.Request) (*http.Response, e return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} } - var resp *http.Response - var err error + return c.dispatchToMethodFake(req, method) +} - switch method { - case "ConfigurationsClient.CreateInResourceGroup": - resp, err = c.dispatchCreateInResourceGroup(req) - case "ConfigurationsClient.CreateInSubscription": - resp, err = c.dispatchCreateInSubscription(req) - case "ConfigurationsClient.NewListByResourceGroupPager": - resp, err = c.dispatchNewListByResourceGroupPager(req) - case "ConfigurationsClient.NewListBySubscriptionPager": - resp, err = c.dispatchNewListBySubscriptionPager(req) - default: - err = fmt.Errorf("unhandled API %s", method) - } +func (c *ConfigurationsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result) + defer close(resultChan) - if err != nil { - return nil, err - } + go func() { + var intercepted bool + var res result + if configurationsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = configurationsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ConfigurationsClient.CreateInResourceGroup": + res.resp, res.err = c.dispatchCreateInResourceGroup(req) + case "ConfigurationsClient.CreateInSubscription": + res.resp, res.err = c.dispatchCreateInSubscription(req) + case "ConfigurationsClient.NewListByResourceGroupPager": + res.resp, res.err = c.dispatchNewListByResourceGroupPager(req) + case "ConfigurationsClient.NewListBySubscriptionPager": + res.resp, res.err = c.dispatchNewListBySubscriptionPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } - return resp, nil + } + select { + case resultChan <- res: + case <-req.Context().Done(): + } + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } } func (c *ConfigurationsServerTransport) dispatchCreateInResourceGroup(req *http.Request) (*http.Response, error) { @@ -95,7 +113,7 @@ func (c *ConfigurationsServerTransport) dispatchCreateInResourceGroup(req *http. const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Advisor/configurations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` regex := regexp.MustCompile(regexStr) matches := regex.FindStringSubmatch(req.URL.EscapedPath()) - if matches == nil || len(matches) < 3 { + if len(matches) < 4 { return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) } body, err := server.UnmarshalRequestAsJSON[armadvisor.ConfigData](req) @@ -138,7 +156,7 @@ func (c *ConfigurationsServerTransport) dispatchCreateInSubscription(req *http.R const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Advisor/configurations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` regex := regexp.MustCompile(regexStr) matches := regex.FindStringSubmatch(req.URL.EscapedPath()) - if matches == nil || len(matches) < 2 { + if len(matches) < 3 { return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) } body, err := server.UnmarshalRequestAsJSON[armadvisor.ConfigData](req) @@ -179,7 +197,7 @@ func (c *ConfigurationsServerTransport) dispatchNewListByResourceGroupPager(req const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Advisor/configurations` regex := regexp.MustCompile(regexStr) matches := regex.FindStringSubmatch(req.URL.EscapedPath()) - if matches == nil || len(matches) < 2 { + if len(matches) < 3 { return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) } resourceGroupParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroup")]) @@ -189,6 +207,9 @@ func (c *ConfigurationsServerTransport) dispatchNewListByResourceGroupPager(req resp := c.srv.NewListByResourceGroupPager(resourceGroupParam, nil) newListByResourceGroupPager = &resp c.newListByResourceGroupPager.add(req, newListByResourceGroupPager) + server.PagerResponderInjectNextLinks(newListByResourceGroupPager, req, func(page *armadvisor.ConfigurationsClientListByResourceGroupResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) } resp, err := server.PagerResponderNext(newListByResourceGroupPager, req) if err != nil { @@ -213,7 +234,7 @@ func (c *ConfigurationsServerTransport) dispatchNewListBySubscriptionPager(req * const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Advisor/configurations` regex := regexp.MustCompile(regexStr) matches := regex.FindStringSubmatch(req.URL.EscapedPath()) - if matches == nil || len(matches) < 1 { + if len(matches) < 2 { return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) } resp := c.srv.NewListBySubscriptionPager(nil) @@ -236,3 +257,9 @@ func (c *ConfigurationsServerTransport) dispatchNewListBySubscriptionPager(req * } return resp, nil } + +// set this to conditionally intercept incoming requests to ConfigurationsServerTransport +var configurationsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/sdk/resourcemanager/advisor/armadvisor/fake/internal.go b/sdk/resourcemanager/advisor/armadvisor/fake/internal.go index 2197c62dfe9a..67a59e461dd8 100644 --- a/sdk/resourcemanager/advisor/armadvisor/fake/internal.go +++ b/sdk/resourcemanager/advisor/armadvisor/fake/internal.go @@ -1,7 +1,6 @@ // 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. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package fake @@ -12,6 +11,11 @@ import ( "sync" ) +type result struct { + resp *http.Response + err error +} + type nonRetriableError struct { error } @@ -36,6 +40,14 @@ func getOptional[T any](v T) *T { return &v } +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} + func parseOptional[T any](v string, parse func(v string) (T, error)) (*T, error) { if v == "" { return nil, nil diff --git a/sdk/resourcemanager/advisor/armadvisor/fake/operations_server.go b/sdk/resourcemanager/advisor/armadvisor/fake/operations_server.go index 63d01ca68fd4..38729da71b39 100644 --- a/sdk/resourcemanager/advisor/armadvisor/fake/operations_server.go +++ b/sdk/resourcemanager/advisor/armadvisor/fake/operations_server.go @@ -1,7 +1,6 @@ // 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. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package fake @@ -12,7 +11,7 @@ import ( "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/advisor/armadvisor" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/advisor/armadvisor/v2" "net/http" ) @@ -48,21 +47,40 @@ func (o *OperationsServerTransport) Do(req *http.Request) (*http.Response, error return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} } - var resp *http.Response - var err error + return o.dispatchToMethodFake(req, method) +} - switch method { - case "OperationsClient.NewListPager": - resp, err = o.dispatchNewListPager(req) - default: - err = fmt.Errorf("unhandled API %s", method) - } +func (o *OperationsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result) + defer close(resultChan) - if err != nil { - return nil, err - } + go func() { + var intercepted bool + var res result + if operationsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = operationsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "OperationsClient.NewListPager": + res.resp, res.err = o.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } - return resp, nil + } + select { + case resultChan <- res: + case <-req.Context().Done(): + } + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } } func (o *OperationsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { @@ -91,3 +109,9 @@ func (o *OperationsServerTransport) dispatchNewListPager(req *http.Request) (*ht } return resp, nil } + +// set this to conditionally intercept incoming requests to OperationsServerTransport +var operationsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/sdk/resourcemanager/advisor/armadvisor/fake/recommendationmetadata_server.go b/sdk/resourcemanager/advisor/armadvisor/fake/recommendationmetadata_server.go index c25899af8cc6..a8976744ed6a 100644 --- a/sdk/resourcemanager/advisor/armadvisor/fake/recommendationmetadata_server.go +++ b/sdk/resourcemanager/advisor/armadvisor/fake/recommendationmetadata_server.go @@ -1,7 +1,6 @@ // 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. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package fake @@ -13,7 +12,7 @@ import ( "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/advisor/armadvisor" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/advisor/armadvisor/v2" "net/http" "net/url" "regexp" @@ -55,23 +54,42 @@ func (r *RecommendationMetadataServerTransport) Do(req *http.Request) (*http.Res return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} } - var resp *http.Response - var err error + return r.dispatchToMethodFake(req, method) +} - switch method { - case "RecommendationMetadataClient.Get": - resp, err = r.dispatchGet(req) - case "RecommendationMetadataClient.NewListPager": - resp, err = r.dispatchNewListPager(req) - default: - err = fmt.Errorf("unhandled API %s", method) - } +func (r *RecommendationMetadataServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result) + defer close(resultChan) - if err != nil { - return nil, err - } + go func() { + var intercepted bool + var res result + if recommendationMetadataServerTransportInterceptor != nil { + res.resp, res.err, intercepted = recommendationMetadataServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "RecommendationMetadataClient.Get": + res.resp, res.err = r.dispatchGet(req) + case "RecommendationMetadataClient.NewListPager": + res.resp, res.err = r.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } - return resp, nil + } + select { + case resultChan <- res: + case <-req.Context().Done(): + } + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } } func (r *RecommendationMetadataServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { @@ -81,7 +99,7 @@ func (r *RecommendationMetadataServerTransport) dispatchGet(req *http.Request) ( const regexStr = `/providers/Microsoft\.Advisor/metadata/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` regex := regexp.MustCompile(regexStr) matches := regex.FindStringSubmatch(req.URL.EscapedPath()) - if matches == nil || len(matches) < 1 { + if len(matches) < 2 { return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) } nameParam, err := url.PathUnescape(matches[regex.SubexpIndex("name")]) @@ -129,3 +147,9 @@ func (r *RecommendationMetadataServerTransport) dispatchNewListPager(req *http.R } return resp, nil } + +// set this to conditionally intercept incoming requests to RecommendationMetadataServerTransport +var recommendationMetadataServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/sdk/resourcemanager/advisor/armadvisor/fake/recommendations_server.go b/sdk/resourcemanager/advisor/armadvisor/fake/recommendations_server.go index 31c5d5bfc844..c492e6b8b090 100644 --- a/sdk/resourcemanager/advisor/armadvisor/fake/recommendations_server.go +++ b/sdk/resourcemanager/advisor/armadvisor/fake/recommendations_server.go @@ -1,7 +1,6 @@ // 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. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package fake @@ -13,7 +12,7 @@ import ( "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/advisor/armadvisor" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/advisor/armadvisor/v2" "net/http" "net/url" "regexp" @@ -37,6 +36,14 @@ type RecommendationsServer struct { // NewListPager is the fake for method RecommendationsClient.NewListPager // HTTP status codes to indicate success: http.StatusOK NewListPager func(options *armadvisor.RecommendationsClientListOptions) (resp azfake.PagerResponder[armadvisor.RecommendationsClientListResponse]) + + // NewListByTenantPager is the fake for method RecommendationsClient.NewListByTenantPager + // HTTP status codes to indicate success: http.StatusOK + NewListByTenantPager func(resourceURI string, options *armadvisor.RecommendationsClientListByTenantOptions) (resp azfake.PagerResponder[armadvisor.RecommendationsClientListByTenantResponse]) + + // Patch is the fake for method RecommendationsClient.Patch + // HTTP status codes to indicate success: http.StatusOK + Patch func(ctx context.Context, resourceURI string, recommendationID string, trackedProperties armadvisor.TrackedRecommendationPropertiesPayload, options *armadvisor.RecommendationsClientPatchOptions) (resp azfake.Responder[armadvisor.RecommendationsClientPatchResponse], errResp azfake.ErrorResponder) } // NewRecommendationsServerTransport creates a new instance of RecommendationsServerTransport with the provided implementation. @@ -44,16 +51,18 @@ type RecommendationsServer struct { // azcore.ClientOptions.Transporter field in the client's constructor parameters. func NewRecommendationsServerTransport(srv *RecommendationsServer) *RecommendationsServerTransport { return &RecommendationsServerTransport{ - srv: srv, - newListPager: newTracker[azfake.PagerResponder[armadvisor.RecommendationsClientListResponse]](), + srv: srv, + newListPager: newTracker[azfake.PagerResponder[armadvisor.RecommendationsClientListResponse]](), + newListByTenantPager: newTracker[azfake.PagerResponder[armadvisor.RecommendationsClientListByTenantResponse]](), } } // RecommendationsServerTransport connects instances of armadvisor.RecommendationsClient to instances of RecommendationsServer. // Don't use this type directly, use NewRecommendationsServerTransport instead. type RecommendationsServerTransport struct { - srv *RecommendationsServer - newListPager *tracker[azfake.PagerResponder[armadvisor.RecommendationsClientListResponse]] + srv *RecommendationsServer + newListPager *tracker[azfake.PagerResponder[armadvisor.RecommendationsClientListResponse]] + newListByTenantPager *tracker[azfake.PagerResponder[armadvisor.RecommendationsClientListByTenantResponse]] } // Do implements the policy.Transporter interface for RecommendationsServerTransport. @@ -64,27 +73,50 @@ func (r *RecommendationsServerTransport) Do(req *http.Request) (*http.Response, return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} } - var resp *http.Response - var err error + return r.dispatchToMethodFake(req, method) +} - switch method { - case "RecommendationsClient.Generate": - resp, err = r.dispatchGenerate(req) - case "RecommendationsClient.Get": - resp, err = r.dispatchGet(req) - case "RecommendationsClient.GetGenerateStatus": - resp, err = r.dispatchGetGenerateStatus(req) - case "RecommendationsClient.NewListPager": - resp, err = r.dispatchNewListPager(req) - default: - err = fmt.Errorf("unhandled API %s", method) - } +func (r *RecommendationsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result) + defer close(resultChan) - if err != nil { - return nil, err - } + go func() { + var intercepted bool + var res result + if recommendationsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = recommendationsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "RecommendationsClient.Generate": + res.resp, res.err = r.dispatchGenerate(req) + case "RecommendationsClient.Get": + res.resp, res.err = r.dispatchGet(req) + case "RecommendationsClient.GetGenerateStatus": + res.resp, res.err = r.dispatchGetGenerateStatus(req) + case "RecommendationsClient.NewListPager": + res.resp, res.err = r.dispatchNewListPager(req) + case "RecommendationsClient.NewListByTenantPager": + res.resp, res.err = r.dispatchNewListByTenantPager(req) + case "RecommendationsClient.Patch": + res.resp, res.err = r.dispatchPatch(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } - return resp, nil + } + select { + case resultChan <- res: + case <-req.Context().Done(): + } + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } } func (r *RecommendationsServerTransport) dispatchGenerate(req *http.Request) (*http.Response, error) { @@ -94,7 +126,7 @@ func (r *RecommendationsServerTransport) dispatchGenerate(req *http.Request) (*h const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Advisor/generateRecommendations` regex := regexp.MustCompile(regexStr) matches := regex.FindStringSubmatch(req.URL.EscapedPath()) - if matches == nil || len(matches) < 1 { + if len(matches) < 2 { return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) } respr, errRespr := r.srv.Generate(req.Context(), nil) @@ -113,7 +145,7 @@ func (r *RecommendationsServerTransport) dispatchGenerate(req *http.Request) (*h resp.Header.Set("Location", *val) } if val := server.GetResponse(respr).RetryAfter; val != nil { - resp.Header.Set("Retry-After", *val) + resp.Header.Set("Retry-After", strconv.FormatInt(int64(*val), 10)) } return resp, nil } @@ -125,7 +157,7 @@ func (r *RecommendationsServerTransport) dispatchGet(req *http.Request) (*http.R const regexStr = `/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Advisor/recommendations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` regex := regexp.MustCompile(regexStr) matches := regex.FindStringSubmatch(req.URL.EscapedPath()) - if matches == nil || len(matches) < 2 { + if len(matches) < 3 { return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) } resourceURIParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceUri")]) @@ -158,7 +190,7 @@ func (r *RecommendationsServerTransport) dispatchGetGenerateStatus(req *http.Req const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Advisor/generateRecommendations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` regex := regexp.MustCompile(regexStr) matches := regex.FindStringSubmatch(req.URL.EscapedPath()) - if matches == nil || len(matches) < 2 { + if len(matches) < 3 { return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) } operationIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("operationId")]) @@ -177,6 +209,9 @@ func (r *RecommendationsServerTransport) dispatchGetGenerateStatus(req *http.Req if err != nil { return nil, err } + if val := server.GetResponse(respr).RetryAfter; val != nil { + resp.Header.Set("Retry-After", strconv.FormatInt(int64(*val), 10)) + } return resp, nil } @@ -189,7 +224,7 @@ func (r *RecommendationsServerTransport) dispatchNewListPager(req *http.Request) const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Advisor/recommendations` regex := regexp.MustCompile(regexStr) matches := regex.FindStringSubmatch(req.URL.EscapedPath()) - if matches == nil || len(matches) < 1 { + if len(matches) < 2 { return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) } qp := req.URL.Query() @@ -245,3 +280,116 @@ func (r *RecommendationsServerTransport) dispatchNewListPager(req *http.Request) } return resp, nil } + +func (r *RecommendationsServerTransport) dispatchNewListByTenantPager(req *http.Request) (*http.Response, error) { + if r.srv.NewListByTenantPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByTenantPager not implemented")} + } + newListByTenantPager := r.newListByTenantPager.get(req) + if newListByTenantPager == nil { + const regexStr = `/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Advisor/recommendations` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + qp := req.URL.Query() + resourceURIParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceUri")]) + if err != nil { + return nil, err + } + filterUnescaped, err := url.QueryUnescape(qp.Get("$filter")) + if err != nil { + return nil, err + } + filterParam := getOptional(filterUnescaped) + topUnescaped, err := url.QueryUnescape(qp.Get("$top")) + if err != nil { + return nil, err + } + topParam, err := parseOptional(topUnescaped, func(v string) (int32, error) { + p, parseErr := strconv.ParseInt(v, 10, 32) + if parseErr != nil { + return 0, parseErr + } + return int32(p), nil + }) + if err != nil { + return nil, err + } + skipTokenUnescaped, err := url.QueryUnescape(qp.Get("$skipToken")) + if err != nil { + return nil, err + } + skipTokenParam := getOptional(skipTokenUnescaped) + var options *armadvisor.RecommendationsClientListByTenantOptions + if filterParam != nil || topParam != nil || skipTokenParam != nil { + options = &armadvisor.RecommendationsClientListByTenantOptions{ + Filter: filterParam, + Top: topParam, + SkipToken: skipTokenParam, + } + } + resp := r.srv.NewListByTenantPager(resourceURIParam, options) + newListByTenantPager = &resp + r.newListByTenantPager.add(req, newListByTenantPager) + server.PagerResponderInjectNextLinks(newListByTenantPager, req, func(page *armadvisor.RecommendationsClientListByTenantResponse, 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) { + r.newListByTenantPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByTenantPager) { + r.newListByTenantPager.remove(req) + } + return resp, nil +} + +func (r *RecommendationsServerTransport) dispatchPatch(req *http.Request) (*http.Response, error) { + if r.srv.Patch == nil { + return nil, &nonRetriableError{errors.New("fake for method Patch not implemented")} + } + const regexStr = `/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Advisor/recommendations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armadvisor.TrackedRecommendationPropertiesPayload](req) + if err != nil { + return nil, err + } + resourceURIParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceUri")]) + if err != nil { + return nil, err + } + recommendationIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("recommendationId")]) + if err != nil { + return nil, err + } + respr, errRespr := r.srv.Patch(req.Context(), resourceURIParam, recommendationIDParam, 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).ResourceRecommendationBase, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to RecommendationsServerTransport +var recommendationsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/sdk/resourcemanager/advisor/armadvisor/fake/resiliencyreviews_server.go b/sdk/resourcemanager/advisor/armadvisor/fake/resiliencyreviews_server.go new file mode 100644 index 000000000000..ad85abc4decd --- /dev/null +++ b/sdk/resourcemanager/advisor/armadvisor/fake/resiliencyreviews_server.go @@ -0,0 +1,204 @@ +// 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) Go Code Generator. DO NOT EDIT. + +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/advisor/armadvisor/v2" + "net/http" + "net/url" + "regexp" + "strconv" +) + +// ResiliencyReviewsServer is a fake server for instances of the armadvisor.ResiliencyReviewsClient type. +type ResiliencyReviewsServer struct { + // Get is the fake for method ResiliencyReviewsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, reviewID string, options *armadvisor.ResiliencyReviewsClientGetOptions) (resp azfake.Responder[armadvisor.ResiliencyReviewsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListPager is the fake for method ResiliencyReviewsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(options *armadvisor.ResiliencyReviewsClientListOptions) (resp azfake.PagerResponder[armadvisor.ResiliencyReviewsClientListResponse]) +} + +// NewResiliencyReviewsServerTransport creates a new instance of ResiliencyReviewsServerTransport with the provided implementation. +// The returned ResiliencyReviewsServerTransport instance is connected to an instance of armadvisor.ResiliencyReviewsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewResiliencyReviewsServerTransport(srv *ResiliencyReviewsServer) *ResiliencyReviewsServerTransport { + return &ResiliencyReviewsServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[armadvisor.ResiliencyReviewsClientListResponse]](), + } +} + +// ResiliencyReviewsServerTransport connects instances of armadvisor.ResiliencyReviewsClient to instances of ResiliencyReviewsServer. +// Don't use this type directly, use NewResiliencyReviewsServerTransport instead. +type ResiliencyReviewsServerTransport struct { + srv *ResiliencyReviewsServer + newListPager *tracker[azfake.PagerResponder[armadvisor.ResiliencyReviewsClientListResponse]] +} + +// Do implements the policy.Transporter interface for ResiliencyReviewsServerTransport. +func (r *ResiliencyReviewsServerTransport) 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")} + } + + return r.dispatchToMethodFake(req, method) +} + +func (r *ResiliencyReviewsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result) + defer close(resultChan) + + go func() { + var intercepted bool + var res result + if resiliencyReviewsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = resiliencyReviewsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ResiliencyReviewsClient.Get": + res.resp, res.err = r.dispatchGet(req) + case "ResiliencyReviewsClient.NewListPager": + res.resp, res.err = r.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + select { + case resultChan <- res: + case <-req.Context().Done(): + } + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (r *ResiliencyReviewsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if r.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Advisor/resiliencyReviews/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + reviewIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("reviewId")]) + if err != nil { + return nil, err + } + respr, errRespr := r.srv.Get(req.Context(), reviewIDParam, 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).ResiliencyReview, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (r *ResiliencyReviewsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if r.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := r.newListPager.get(req) + if newListPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Advisor/resiliencyReviews` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + qp := req.URL.Query() + topUnescaped, err := url.QueryUnescape(qp.Get("$top")) + if err != nil { + return nil, err + } + topParam, err := parseOptional(topUnescaped, func(v string) (int32, error) { + p, parseErr := strconv.ParseInt(v, 10, 32) + if parseErr != nil { + return 0, parseErr + } + return int32(p), nil + }) + if err != nil { + return nil, err + } + skipUnescaped, err := url.QueryUnescape(qp.Get("$skip")) + if err != nil { + return nil, err + } + skipParam, err := parseOptional(skipUnescaped, func(v string) (int32, error) { + p, parseErr := strconv.ParseInt(v, 10, 32) + if parseErr != nil { + return 0, parseErr + } + return int32(p), nil + }) + if err != nil { + return nil, err + } + filterUnescaped, err := url.QueryUnescape(qp.Get("$filter")) + if err != nil { + return nil, err + } + filterParam := getOptional(filterUnescaped) + var options *armadvisor.ResiliencyReviewsClientListOptions + if topParam != nil || skipParam != nil || filterParam != nil { + options = &armadvisor.ResiliencyReviewsClientListOptions{ + Top: topParam, + Skip: skipParam, + Filter: filterParam, + } + } + resp := r.srv.NewListPager(options) + newListPager = &resp + r.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armadvisor.ResiliencyReviewsClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !contains([]int{http.StatusOK}, resp.StatusCode) { + r.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + r.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ResiliencyReviewsServerTransport +var resiliencyReviewsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/sdk/resourcemanager/advisor/armadvisor/fake/scores_server.go b/sdk/resourcemanager/advisor/armadvisor/fake/scores_server.go new file mode 100644 index 000000000000..74719f17e9ed --- /dev/null +++ b/sdk/resourcemanager/advisor/armadvisor/fake/scores_server.go @@ -0,0 +1,157 @@ +// 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) Go Code Generator. DO NOT EDIT. + +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/advisor/armadvisor/v2" + "net/http" + "net/url" + "regexp" +) + +// ScoresServer is a fake server for instances of the armadvisor.ScoresClient type. +type ScoresServer struct { + // Get is the fake for method ScoresClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, name string, options *armadvisor.ScoresClientGetOptions) (resp azfake.Responder[armadvisor.ScoresClientGetResponse], errResp azfake.ErrorResponder) + + // NewListPager is the fake for method ScoresClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(options *armadvisor.ScoresClientListOptions) (resp azfake.PagerResponder[armadvisor.ScoresClientListResponse]) +} + +// NewScoresServerTransport creates a new instance of ScoresServerTransport with the provided implementation. +// The returned ScoresServerTransport instance is connected to an instance of armadvisor.ScoresClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewScoresServerTransport(srv *ScoresServer) *ScoresServerTransport { + return &ScoresServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[armadvisor.ScoresClientListResponse]](), + } +} + +// ScoresServerTransport connects instances of armadvisor.ScoresClient to instances of ScoresServer. +// Don't use this type directly, use NewScoresServerTransport instead. +type ScoresServerTransport struct { + srv *ScoresServer + newListPager *tracker[azfake.PagerResponder[armadvisor.ScoresClientListResponse]] +} + +// Do implements the policy.Transporter interface for ScoresServerTransport. +func (s *ScoresServerTransport) 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")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *ScoresServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result) + defer close(resultChan) + + go func() { + var intercepted bool + var res result + if scoresServerTransportInterceptor != nil { + res.resp, res.err, intercepted = scoresServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ScoresClient.Get": + res.resp, res.err = s.dispatchGet(req) + case "ScoresClient.NewListPager": + res.resp, res.err = s.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + select { + case resultChan <- res: + case <-req.Context().Done(): + } + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *ScoresServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if s.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Advisor/advisorScore/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + nameParam, err := url.PathUnescape(matches[regex.SubexpIndex("name")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Get(req.Context(), nameParam, 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).ScoreEntityForAdvisor, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ScoresServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if s.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := s.newListPager.get(req) + if newListPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Advisor/advisorScore` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resp := s.srv.NewListPager(nil) + newListPager = &resp + s.newListPager.add(req, newListPager) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !contains([]int{http.StatusOK}, resp.StatusCode) { + s.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + s.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ScoresServerTransport +var scoresServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/sdk/resourcemanager/advisor/armadvisor/fake/server.go b/sdk/resourcemanager/advisor/armadvisor/fake/server.go new file mode 100644 index 000000000000..7c3f8f87cc4c --- /dev/null +++ b/sdk/resourcemanager/advisor/armadvisor/fake/server.go @@ -0,0 +1,242 @@ +// 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) Go Code Generator. DO NOT EDIT. + +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/advisor/armadvisor/v2" + "net/http" + "regexp" + "strings" + "sync" +) + +// Server is a fake server for instances of the armadvisor.Client type. +type Server struct { + // AssessmentTypesServer contains the fakes for client AssessmentTypesClient + AssessmentTypesServer AssessmentTypesServer + + // AssessmentsServer contains the fakes for client AssessmentsClient + AssessmentsServer AssessmentsServer + + // ConfigurationsServer contains the fakes for client ConfigurationsClient + ConfigurationsServer ConfigurationsServer + + // OperationsServer contains the fakes for client OperationsClient + OperationsServer OperationsServer + + // RecommendationMetadataServer contains the fakes for client RecommendationMetadataClient + RecommendationMetadataServer RecommendationMetadataServer + + // RecommendationsServer contains the fakes for client RecommendationsClient + RecommendationsServer RecommendationsServer + + // ResiliencyReviewsServer contains the fakes for client ResiliencyReviewsClient + ResiliencyReviewsServer ResiliencyReviewsServer + + // ScoresServer contains the fakes for client ScoresClient + ScoresServer ScoresServer + + // SuppressionsServer contains the fakes for client SuppressionsClient + SuppressionsServer SuppressionsServer + + // TriageRecommendationsServer contains the fakes for client TriageRecommendationsClient + TriageRecommendationsServer TriageRecommendationsServer + + // TriageResourcesServer contains the fakes for client TriageResourcesClient + TriageResourcesServer TriageResourcesServer + + // WorkloadsServer contains the fakes for client WorkloadsClient + WorkloadsServer WorkloadsServer + + // Predict is the fake for method Client.Predict + // HTTP status codes to indicate success: http.StatusOK + Predict func(ctx context.Context, predictionRequest armadvisor.PredictionRequest, options *armadvisor.ClientPredictOptions) (resp azfake.Responder[armadvisor.ClientPredictResponse], errResp azfake.ErrorResponder) +} + +// NewServerTransport creates a new instance of ServerTransport with the provided implementation. +// The returned ServerTransport instance is connected to an instance of armadvisor.Client via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewServerTransport(srv *Server) *ServerTransport { + return &ServerTransport{srv: srv} +} + +// ServerTransport connects instances of armadvisor.Client to instances of Server. +// Don't use this type directly, use NewServerTransport instead. +type ServerTransport struct { + srv *Server + trMu sync.Mutex + trAssessmentTypesServer *AssessmentTypesServerTransport + trAssessmentsServer *AssessmentsServerTransport + trConfigurationsServer *ConfigurationsServerTransport + trOperationsServer *OperationsServerTransport + trRecommendationMetadataServer *RecommendationMetadataServerTransport + trRecommendationsServer *RecommendationsServerTransport + trResiliencyReviewsServer *ResiliencyReviewsServerTransport + trScoresServer *ScoresServerTransport + trSuppressionsServer *SuppressionsServerTransport + trTriageRecommendationsServer *TriageRecommendationsServerTransport + trTriageResourcesServer *TriageResourcesServerTransport + trWorkloadsServer *WorkloadsServerTransport +} + +// Do implements the policy.Transporter interface for ServerTransport. +func (s *ServerTransport) 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")} + } + + if client := method[:strings.Index(method, ".")]; client != "Client" { + return s.dispatchToClientFake(req, client) + } + return s.dispatchToMethodFake(req, method) +} + +func (s *ServerTransport) dispatchToClientFake(req *http.Request, client string) (*http.Response, error) { + var resp *http.Response + var err error + + switch client { + case "AssessmentTypesClient": + initServer(&s.trMu, &s.trAssessmentTypesServer, func() *AssessmentTypesServerTransport { + return NewAssessmentTypesServerTransport(&s.srv.AssessmentTypesServer) + }) + resp, err = s.trAssessmentTypesServer.Do(req) + case "AssessmentsClient": + initServer(&s.trMu, &s.trAssessmentsServer, func() *AssessmentsServerTransport { + return NewAssessmentsServerTransport(&s.srv.AssessmentsServer) + }) + resp, err = s.trAssessmentsServer.Do(req) + case "ConfigurationsClient": + initServer(&s.trMu, &s.trConfigurationsServer, func() *ConfigurationsServerTransport { + return NewConfigurationsServerTransport(&s.srv.ConfigurationsServer) + }) + resp, err = s.trConfigurationsServer.Do(req) + case "OperationsClient": + initServer(&s.trMu, &s.trOperationsServer, func() *OperationsServerTransport { + return NewOperationsServerTransport(&s.srv.OperationsServer) + }) + resp, err = s.trOperationsServer.Do(req) + case "RecommendationMetadataClient": + initServer(&s.trMu, &s.trRecommendationMetadataServer, func() *RecommendationMetadataServerTransport { + return NewRecommendationMetadataServerTransport(&s.srv.RecommendationMetadataServer) + }) + resp, err = s.trRecommendationMetadataServer.Do(req) + case "RecommendationsClient": + initServer(&s.trMu, &s.trRecommendationsServer, func() *RecommendationsServerTransport { + return NewRecommendationsServerTransport(&s.srv.RecommendationsServer) + }) + resp, err = s.trRecommendationsServer.Do(req) + case "ResiliencyReviewsClient": + initServer(&s.trMu, &s.trResiliencyReviewsServer, func() *ResiliencyReviewsServerTransport { + return NewResiliencyReviewsServerTransport(&s.srv.ResiliencyReviewsServer) + }) + resp, err = s.trResiliencyReviewsServer.Do(req) + case "ScoresClient": + initServer(&s.trMu, &s.trScoresServer, func() *ScoresServerTransport { + return NewScoresServerTransport(&s.srv.ScoresServer) + }) + resp, err = s.trScoresServer.Do(req) + case "SuppressionsClient": + initServer(&s.trMu, &s.trSuppressionsServer, func() *SuppressionsServerTransport { + return NewSuppressionsServerTransport(&s.srv.SuppressionsServer) + }) + resp, err = s.trSuppressionsServer.Do(req) + case "TriageRecommendationsClient": + initServer(&s.trMu, &s.trTriageRecommendationsServer, func() *TriageRecommendationsServerTransport { + return NewTriageRecommendationsServerTransport(&s.srv.TriageRecommendationsServer) + }) + resp, err = s.trTriageRecommendationsServer.Do(req) + case "TriageResourcesClient": + initServer(&s.trMu, &s.trTriageResourcesServer, func() *TriageResourcesServerTransport { + return NewTriageResourcesServerTransport(&s.srv.TriageResourcesServer) + }) + resp, err = s.trTriageResourcesServer.Do(req) + case "WorkloadsClient": + initServer(&s.trMu, &s.trWorkloadsServer, func() *WorkloadsServerTransport { + return NewWorkloadsServerTransport(&s.srv.WorkloadsServer) + }) + resp, err = s.trWorkloadsServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + return resp, err +} + +func (s *ServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result) + defer close(resultChan) + + go func() { + var intercepted bool + var res result + if serverTransportInterceptor != nil { + res.resp, res.err, intercepted = serverTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "Client.Predict": + res.resp, res.err = s.dispatchPredict(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + select { + case resultChan <- res: + case <-req.Context().Done(): + } + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *ServerTransport) dispatchPredict(req *http.Request) (*http.Response, error) { + if s.srv.Predict == nil { + return nil, &nonRetriableError{errors.New("fake for method Predict not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Advisor/predict` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armadvisor.PredictionRequest](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Predict(req.Context(), 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).PredictionResponse, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ServerTransport +var serverTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/sdk/resourcemanager/advisor/armadvisor/fake/server_factory.go b/sdk/resourcemanager/advisor/armadvisor/fake/server_factory.go index 0d1ce5d40faf..1ed3cd67c45f 100644 --- a/sdk/resourcemanager/advisor/armadvisor/fake/server_factory.go +++ b/sdk/resourcemanager/advisor/armadvisor/fake/server_factory.go @@ -1,7 +1,6 @@ // 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. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package fake @@ -16,11 +15,44 @@ import ( // ServerFactory is a fake server for instances of the armadvisor.ClientFactory type. type ServerFactory struct { - ConfigurationsServer ConfigurationsServer - OperationsServer OperationsServer + // AssessmentTypesServer contains the fakes for client AssessmentTypesClient + AssessmentTypesServer AssessmentTypesServer + + // AssessmentsServer contains the fakes for client AssessmentsClient + AssessmentsServer AssessmentsServer + + // Server contains the fakes for client Client + Server Server + + // ConfigurationsServer contains the fakes for client ConfigurationsClient + ConfigurationsServer ConfigurationsServer + + // OperationsServer contains the fakes for client OperationsClient + OperationsServer OperationsServer + + // RecommendationMetadataServer contains the fakes for client RecommendationMetadataClient RecommendationMetadataServer RecommendationMetadataServer - RecommendationsServer RecommendationsServer - SuppressionsServer SuppressionsServer + + // RecommendationsServer contains the fakes for client RecommendationsClient + RecommendationsServer RecommendationsServer + + // ResiliencyReviewsServer contains the fakes for client ResiliencyReviewsClient + ResiliencyReviewsServer ResiliencyReviewsServer + + // ScoresServer contains the fakes for client ScoresClient + ScoresServer ScoresServer + + // SuppressionsServer contains the fakes for client SuppressionsClient + SuppressionsServer SuppressionsServer + + // TriageRecommendationsServer contains the fakes for client TriageRecommendationsClient + TriageRecommendationsServer TriageRecommendationsServer + + // TriageResourcesServer contains the fakes for client TriageResourcesClient + TriageResourcesServer TriageResourcesServer + + // WorkloadsServer contains the fakes for client WorkloadsClient + WorkloadsServer WorkloadsServer } // NewServerFactoryTransport creates a new instance of ServerFactoryTransport with the provided implementation. @@ -37,11 +69,19 @@ func NewServerFactoryTransport(srv *ServerFactory) *ServerFactoryTransport { type ServerFactoryTransport struct { srv *ServerFactory trMu sync.Mutex + trAssessmentTypesServer *AssessmentTypesServerTransport + trAssessmentsServer *AssessmentsServerTransport + trServer *ServerTransport trConfigurationsServer *ConfigurationsServerTransport trOperationsServer *OperationsServerTransport trRecommendationMetadataServer *RecommendationMetadataServerTransport trRecommendationsServer *RecommendationsServerTransport + trResiliencyReviewsServer *ResiliencyReviewsServerTransport + trScoresServer *ScoresServerTransport trSuppressionsServer *SuppressionsServerTransport + trTriageRecommendationsServer *TriageRecommendationsServerTransport + trTriageResourcesServer *TriageResourcesServerTransport + trWorkloadsServer *WorkloadsServerTransport } // Do implements the policy.Transporter interface for ServerFactoryTransport. @@ -57,27 +97,59 @@ func (s *ServerFactoryTransport) Do(req *http.Request) (*http.Response, error) { var err error switch client { + case "AssessmentTypesClient": + initServer(&s.trMu, &s.trAssessmentTypesServer, func() *AssessmentTypesServerTransport { + return NewAssessmentTypesServerTransport(&s.srv.AssessmentTypesServer) + }) + resp, err = s.trAssessmentTypesServer.Do(req) + case "AssessmentsClient": + initServer(&s.trMu, &s.trAssessmentsServer, func() *AssessmentsServerTransport { return NewAssessmentsServerTransport(&s.srv.AssessmentsServer) }) + resp, err = s.trAssessmentsServer.Do(req) + case "Client": + initServer(&s.trMu, &s.trServer, func() *ServerTransport { return NewServerTransport(&s.srv.Server) }) + resp, err = s.trServer.Do(req) case "ConfigurationsClient": - initServer(s, &s.trConfigurationsServer, func() *ConfigurationsServerTransport { + initServer(&s.trMu, &s.trConfigurationsServer, func() *ConfigurationsServerTransport { return NewConfigurationsServerTransport(&s.srv.ConfigurationsServer) }) resp, err = s.trConfigurationsServer.Do(req) case "OperationsClient": - initServer(s, &s.trOperationsServer, func() *OperationsServerTransport { return NewOperationsServerTransport(&s.srv.OperationsServer) }) + initServer(&s.trMu, &s.trOperationsServer, func() *OperationsServerTransport { return NewOperationsServerTransport(&s.srv.OperationsServer) }) resp, err = s.trOperationsServer.Do(req) case "RecommendationMetadataClient": - initServer(s, &s.trRecommendationMetadataServer, func() *RecommendationMetadataServerTransport { + initServer(&s.trMu, &s.trRecommendationMetadataServer, func() *RecommendationMetadataServerTransport { return NewRecommendationMetadataServerTransport(&s.srv.RecommendationMetadataServer) }) resp, err = s.trRecommendationMetadataServer.Do(req) case "RecommendationsClient": - initServer(s, &s.trRecommendationsServer, func() *RecommendationsServerTransport { + initServer(&s.trMu, &s.trRecommendationsServer, func() *RecommendationsServerTransport { return NewRecommendationsServerTransport(&s.srv.RecommendationsServer) }) resp, err = s.trRecommendationsServer.Do(req) + case "ResiliencyReviewsClient": + initServer(&s.trMu, &s.trResiliencyReviewsServer, func() *ResiliencyReviewsServerTransport { + return NewResiliencyReviewsServerTransport(&s.srv.ResiliencyReviewsServer) + }) + resp, err = s.trResiliencyReviewsServer.Do(req) + case "ScoresClient": + initServer(&s.trMu, &s.trScoresServer, func() *ScoresServerTransport { return NewScoresServerTransport(&s.srv.ScoresServer) }) + resp, err = s.trScoresServer.Do(req) case "SuppressionsClient": - initServer(s, &s.trSuppressionsServer, func() *SuppressionsServerTransport { return NewSuppressionsServerTransport(&s.srv.SuppressionsServer) }) + initServer(&s.trMu, &s.trSuppressionsServer, func() *SuppressionsServerTransport { return NewSuppressionsServerTransport(&s.srv.SuppressionsServer) }) resp, err = s.trSuppressionsServer.Do(req) + case "TriageRecommendationsClient": + initServer(&s.trMu, &s.trTriageRecommendationsServer, func() *TriageRecommendationsServerTransport { + return NewTriageRecommendationsServerTransport(&s.srv.TriageRecommendationsServer) + }) + resp, err = s.trTriageRecommendationsServer.Do(req) + case "TriageResourcesClient": + initServer(&s.trMu, &s.trTriageResourcesServer, func() *TriageResourcesServerTransport { + return NewTriageResourcesServerTransport(&s.srv.TriageResourcesServer) + }) + resp, err = s.trTriageResourcesServer.Do(req) + case "WorkloadsClient": + initServer(&s.trMu, &s.trWorkloadsServer, func() *WorkloadsServerTransport { return NewWorkloadsServerTransport(&s.srv.WorkloadsServer) }) + resp, err = s.trWorkloadsServer.Do(req) default: err = fmt.Errorf("unhandled client %s", client) } @@ -88,11 +160,3 @@ func (s *ServerFactoryTransport) Do(req *http.Request) (*http.Response, error) { return resp, nil } - -func initServer[T any](s *ServerFactoryTransport, dst **T, src func() *T) { - s.trMu.Lock() - if *dst == nil { - *dst = src() - } - s.trMu.Unlock() -} diff --git a/sdk/resourcemanager/advisor/armadvisor/fake/suppressions_server.go b/sdk/resourcemanager/advisor/armadvisor/fake/suppressions_server.go index 4fe77b1224f0..58fefa060c37 100644 --- a/sdk/resourcemanager/advisor/armadvisor/fake/suppressions_server.go +++ b/sdk/resourcemanager/advisor/armadvisor/fake/suppressions_server.go @@ -1,7 +1,6 @@ // 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. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package fake @@ -13,7 +12,7 @@ import ( "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/advisor/armadvisor" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/advisor/armadvisor/v2" "net/http" "net/url" "regexp" @@ -64,27 +63,46 @@ func (s *SuppressionsServerTransport) Do(req *http.Request) (*http.Response, err return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} } - var resp *http.Response - var err error + return s.dispatchToMethodFake(req, method) +} - switch method { - case "SuppressionsClient.Create": - resp, err = s.dispatchCreate(req) - case "SuppressionsClient.Delete": - resp, err = s.dispatchDelete(req) - case "SuppressionsClient.Get": - resp, err = s.dispatchGet(req) - case "SuppressionsClient.NewListPager": - resp, err = s.dispatchNewListPager(req) - default: - err = fmt.Errorf("unhandled API %s", method) - } +func (s *SuppressionsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result) + defer close(resultChan) - if err != nil { - return nil, err - } + go func() { + var intercepted bool + var res result + if suppressionsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = suppressionsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "SuppressionsClient.Create": + res.resp, res.err = s.dispatchCreate(req) + case "SuppressionsClient.Delete": + res.resp, res.err = s.dispatchDelete(req) + case "SuppressionsClient.Get": + res.resp, res.err = s.dispatchGet(req) + case "SuppressionsClient.NewListPager": + res.resp, res.err = s.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } - return resp, nil + } + select { + case resultChan <- res: + case <-req.Context().Done(): + } + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } } func (s *SuppressionsServerTransport) dispatchCreate(req *http.Request) (*http.Response, error) { @@ -94,7 +112,7 @@ func (s *SuppressionsServerTransport) dispatchCreate(req *http.Request) (*http.R const regexStr = `/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Advisor/recommendations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/suppressions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` regex := regexp.MustCompile(regexStr) matches := regex.FindStringSubmatch(req.URL.EscapedPath()) - if matches == nil || len(matches) < 3 { + if len(matches) < 4 { return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) } body, err := server.UnmarshalRequestAsJSON[armadvisor.SuppressionContract](req) @@ -135,7 +153,7 @@ func (s *SuppressionsServerTransport) dispatchDelete(req *http.Request) (*http.R const regexStr = `/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Advisor/recommendations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/suppressions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` regex := regexp.MustCompile(regexStr) matches := regex.FindStringSubmatch(req.URL.EscapedPath()) - if matches == nil || len(matches) < 3 { + if len(matches) < 4 { return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) } resourceURIParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceUri")]) @@ -172,7 +190,7 @@ func (s *SuppressionsServerTransport) dispatchGet(req *http.Request) (*http.Resp const regexStr = `/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Advisor/recommendations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/suppressions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` regex := regexp.MustCompile(regexStr) matches := regex.FindStringSubmatch(req.URL.EscapedPath()) - if matches == nil || len(matches) < 3 { + if len(matches) < 4 { return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) } resourceURIParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceUri")]) @@ -211,7 +229,7 @@ func (s *SuppressionsServerTransport) dispatchNewListPager(req *http.Request) (* const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Advisor/suppressions` regex := regexp.MustCompile(regexStr) matches := regex.FindStringSubmatch(req.URL.EscapedPath()) - if matches == nil || len(matches) < 1 { + if len(matches) < 2 { return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) } qp := req.URL.Query() @@ -261,3 +279,9 @@ func (s *SuppressionsServerTransport) dispatchNewListPager(req *http.Request) (* } return resp, nil } + +// set this to conditionally intercept incoming requests to SuppressionsServerTransport +var suppressionsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/sdk/resourcemanager/advisor/armadvisor/fake/time_rfc3339.go b/sdk/resourcemanager/advisor/armadvisor/fake/time_rfc3339.go deleted file mode 100644 index b98c0b0402be..000000000000 --- a/sdk/resourcemanager/advisor/armadvisor/fake/time_rfc3339.go +++ /dev/null @@ -1,83 +0,0 @@ -// 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 ( - "encoding/json" - "fmt" - "github.com/Azure/azure-sdk-for-go/sdk/azcore" - "reflect" - "regexp" - "strings" - "time" -) - -// 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+)*"*$`) - -const ( - utcDateTimeJSON = `"2006-01-02T15:04:05.999999999"` - utcDateTime = "2006-01-02T15:04:05.999999999" - dateTimeJSON = `"` + time.RFC3339Nano + `"` -) - -type dateTimeRFC3339 time.Time - -func (t dateTimeRFC3339) MarshalJSON() ([]byte, error) { - tt := time.Time(t) - return tt.MarshalJSON() -} - -func (t dateTimeRFC3339) MarshalText() ([]byte, error) { - tt := time.Time(t) - return tt.MarshalText() -} - -func (t *dateTimeRFC3339) UnmarshalJSON(data []byte) error { - layout := utcDateTimeJSON - if tzOffsetRegex.Match(data) { - layout = dateTimeJSON - } - return t.Parse(layout, string(data)) -} - -func (t *dateTimeRFC3339) UnmarshalText(data []byte) error { - layout := utcDateTime - if tzOffsetRegex.Match(data) { - layout = time.RFC3339Nano - } - return t.Parse(layout, string(data)) -} - -func (t *dateTimeRFC3339) Parse(layout, value string) error { - p, err := time.Parse(layout, strings.ToUpper(value)) - *t = dateTimeRFC3339(p) - return err -} - -func populateDateTimeRFC3339(m map[string]any, k string, t *time.Time) { - if t == nil { - return - } else if azcore.IsNullValue(t) { - m[k] = nil - return - } else if reflect.ValueOf(t).IsNil() { - return - } - m[k] = (*dateTimeRFC3339)(t) -} - -func unpopulateDateTimeRFC3339(data json.RawMessage, fn string, t **time.Time) error { - if data == nil || strings.EqualFold(string(data), "null") { - return nil - } - var aux dateTimeRFC3339 - if err := json.Unmarshal(data, &aux); err != nil { - return fmt.Errorf("struct field %s: %v", fn, err) - } - *t = (*time.Time)(&aux) - return nil -} diff --git a/sdk/resourcemanager/advisor/armadvisor/fake/triagerecommendations_server.go b/sdk/resourcemanager/advisor/armadvisor/fake/triagerecommendations_server.go new file mode 100644 index 000000000000..ea19046e3b9e --- /dev/null +++ b/sdk/resourcemanager/advisor/armadvisor/fake/triagerecommendations_server.go @@ -0,0 +1,327 @@ +// 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) Go Code Generator. DO NOT EDIT. + +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/advisor/armadvisor/v2" + "net/http" + "net/url" + "regexp" + "strconv" +) + +// TriageRecommendationsServer is a fake server for instances of the armadvisor.TriageRecommendationsClient type. +type TriageRecommendationsServer struct { + // ApproveTriageRecommendation is the fake for method TriageRecommendationsClient.ApproveTriageRecommendation + // HTTP status codes to indicate success: http.StatusOK + ApproveTriageRecommendation func(ctx context.Context, reviewID string, recommendationID string, options *armadvisor.TriageRecommendationsClientApproveTriageRecommendationOptions) (resp azfake.Responder[armadvisor.TriageRecommendationsClientApproveTriageRecommendationResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method TriageRecommendationsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, reviewID string, recommendationID string, options *armadvisor.TriageRecommendationsClientGetOptions) (resp azfake.Responder[armadvisor.TriageRecommendationsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListPager is the fake for method TriageRecommendationsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(reviewID string, options *armadvisor.TriageRecommendationsClientListOptions) (resp azfake.PagerResponder[armadvisor.TriageRecommendationsClientListResponse]) + + // RejectTriageRecommendation is the fake for method TriageRecommendationsClient.RejectTriageRecommendation + // HTTP status codes to indicate success: http.StatusOK + RejectTriageRecommendation func(ctx context.Context, reviewID string, recommendationID string, recommendationRejectBody armadvisor.RecommendationRejectBody, options *armadvisor.TriageRecommendationsClientRejectTriageRecommendationOptions) (resp azfake.Responder[armadvisor.TriageRecommendationsClientRejectTriageRecommendationResponse], errResp azfake.ErrorResponder) + + // ResetTriageRecommendation is the fake for method TriageRecommendationsClient.ResetTriageRecommendation + // HTTP status codes to indicate success: http.StatusOK + ResetTriageRecommendation func(ctx context.Context, reviewID string, recommendationID string, options *armadvisor.TriageRecommendationsClientResetTriageRecommendationOptions) (resp azfake.Responder[armadvisor.TriageRecommendationsClientResetTriageRecommendationResponse], errResp azfake.ErrorResponder) +} + +// NewTriageRecommendationsServerTransport creates a new instance of TriageRecommendationsServerTransport with the provided implementation. +// The returned TriageRecommendationsServerTransport instance is connected to an instance of armadvisor.TriageRecommendationsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewTriageRecommendationsServerTransport(srv *TriageRecommendationsServer) *TriageRecommendationsServerTransport { + return &TriageRecommendationsServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[armadvisor.TriageRecommendationsClientListResponse]](), + } +} + +// TriageRecommendationsServerTransport connects instances of armadvisor.TriageRecommendationsClient to instances of TriageRecommendationsServer. +// Don't use this type directly, use NewTriageRecommendationsServerTransport instead. +type TriageRecommendationsServerTransport struct { + srv *TriageRecommendationsServer + newListPager *tracker[azfake.PagerResponder[armadvisor.TriageRecommendationsClientListResponse]] +} + +// Do implements the policy.Transporter interface for TriageRecommendationsServerTransport. +func (t *TriageRecommendationsServerTransport) 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")} + } + + return t.dispatchToMethodFake(req, method) +} + +func (t *TriageRecommendationsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result) + defer close(resultChan) + + go func() { + var intercepted bool + var res result + if triageRecommendationsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = triageRecommendationsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "TriageRecommendationsClient.ApproveTriageRecommendation": + res.resp, res.err = t.dispatchApproveTriageRecommendation(req) + case "TriageRecommendationsClient.Get": + res.resp, res.err = t.dispatchGet(req) + case "TriageRecommendationsClient.NewListPager": + res.resp, res.err = t.dispatchNewListPager(req) + case "TriageRecommendationsClient.RejectTriageRecommendation": + res.resp, res.err = t.dispatchRejectTriageRecommendation(req) + case "TriageRecommendationsClient.ResetTriageRecommendation": + res.resp, res.err = t.dispatchResetTriageRecommendation(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + select { + case resultChan <- res: + case <-req.Context().Done(): + } + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (t *TriageRecommendationsServerTransport) dispatchApproveTriageRecommendation(req *http.Request) (*http.Response, error) { + if t.srv.ApproveTriageRecommendation == nil { + return nil, &nonRetriableError{errors.New("fake for method ApproveTriageRecommendation not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Advisor/resiliencyReviews/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Advisor/triageRecommendations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/approve` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + reviewIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("reviewId")]) + if err != nil { + return nil, err + } + recommendationIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("recommendationId")]) + if err != nil { + return nil, err + } + respr, errRespr := t.srv.ApproveTriageRecommendation(req.Context(), reviewIDParam, recommendationIDParam, 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.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (t *TriageRecommendationsServerTransport) 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 = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Advisor/resiliencyReviews/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Advisor/triageRecommendations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + reviewIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("reviewId")]) + if err != nil { + return nil, err + } + recommendationIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("recommendationId")]) + if err != nil { + return nil, err + } + respr, errRespr := t.srv.Get(req.Context(), reviewIDParam, recommendationIDParam, 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).TriageRecommendation, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (t *TriageRecommendationsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if t.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := t.newListPager.get(req) + if newListPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Advisor/resiliencyReviews/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Advisor/triageRecommendations` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + qp := req.URL.Query() + reviewIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("reviewId")]) + if err != nil { + return nil, err + } + topUnescaped, err := url.QueryUnescape(qp.Get("$top")) + if err != nil { + return nil, err + } + topParam, err := parseOptional(topUnescaped, func(v string) (int32, error) { + p, parseErr := strconv.ParseInt(v, 10, 32) + if parseErr != nil { + return 0, parseErr + } + return int32(p), nil + }) + if err != nil { + return nil, err + } + skipUnescaped, err := url.QueryUnescape(qp.Get("$skip")) + if err != nil { + return nil, err + } + skipParam, err := parseOptional(skipUnescaped, func(v string) (int32, error) { + p, parseErr := strconv.ParseInt(v, 10, 32) + if parseErr != nil { + return 0, parseErr + } + return int32(p), nil + }) + if err != nil { + return nil, err + } + var options *armadvisor.TriageRecommendationsClientListOptions + if topParam != nil || skipParam != nil { + options = &armadvisor.TriageRecommendationsClientListOptions{ + Top: topParam, + Skip: skipParam, + } + } + resp := t.srv.NewListPager(reviewIDParam, options) + newListPager = &resp + t.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armadvisor.TriageRecommendationsClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !contains([]int{http.StatusOK}, resp.StatusCode) { + t.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + t.newListPager.remove(req) + } + return resp, nil +} + +func (t *TriageRecommendationsServerTransport) dispatchRejectTriageRecommendation(req *http.Request) (*http.Response, error) { + if t.srv.RejectTriageRecommendation == nil { + return nil, &nonRetriableError{errors.New("fake for method RejectTriageRecommendation not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Advisor/resiliencyReviews/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Advisor/triageRecommendations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/reject` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armadvisor.RecommendationRejectBody](req) + if err != nil { + return nil, err + } + reviewIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("reviewId")]) + if err != nil { + return nil, err + } + recommendationIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("recommendationId")]) + if err != nil { + return nil, err + } + respr, errRespr := t.srv.RejectTriageRecommendation(req.Context(), reviewIDParam, recommendationIDParam, 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.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (t *TriageRecommendationsServerTransport) dispatchResetTriageRecommendation(req *http.Request) (*http.Response, error) { + if t.srv.ResetTriageRecommendation == nil { + return nil, &nonRetriableError{errors.New("fake for method ResetTriageRecommendation not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Advisor/resiliencyReviews/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Advisor/triageRecommendations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/reset` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + reviewIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("reviewId")]) + if err != nil { + return nil, err + } + recommendationIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("recommendationId")]) + if err != nil { + return nil, err + } + respr, errRespr := t.srv.ResetTriageRecommendation(req.Context(), reviewIDParam, recommendationIDParam, 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.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to TriageRecommendationsServerTransport +var triageRecommendationsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/sdk/resourcemanager/advisor/armadvisor/fake/triageresources_server.go b/sdk/resourcemanager/advisor/armadvisor/fake/triageresources_server.go new file mode 100644 index 000000000000..a3a2a0d03bb9 --- /dev/null +++ b/sdk/resourcemanager/advisor/armadvisor/fake/triageresources_server.go @@ -0,0 +1,177 @@ +// 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) Go Code Generator. DO NOT EDIT. + +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/advisor/armadvisor/v2" + "net/http" + "net/url" + "regexp" +) + +// TriageResourcesServer is a fake server for instances of the armadvisor.TriageResourcesClient type. +type TriageResourcesServer struct { + // Get is the fake for method TriageResourcesClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, reviewID string, recommendationID string, recommendationResourceID string, options *armadvisor.TriageResourcesClientGetOptions) (resp azfake.Responder[armadvisor.TriageResourcesClientGetResponse], errResp azfake.ErrorResponder) + + // NewListPager is the fake for method TriageResourcesClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(reviewID string, recommendationID string, options *armadvisor.TriageResourcesClientListOptions) (resp azfake.PagerResponder[armadvisor.TriageResourcesClientListResponse]) +} + +// NewTriageResourcesServerTransport creates a new instance of TriageResourcesServerTransport with the provided implementation. +// The returned TriageResourcesServerTransport instance is connected to an instance of armadvisor.TriageResourcesClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewTriageResourcesServerTransport(srv *TriageResourcesServer) *TriageResourcesServerTransport { + return &TriageResourcesServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[armadvisor.TriageResourcesClientListResponse]](), + } +} + +// TriageResourcesServerTransport connects instances of armadvisor.TriageResourcesClient to instances of TriageResourcesServer. +// Don't use this type directly, use NewTriageResourcesServerTransport instead. +type TriageResourcesServerTransport struct { + srv *TriageResourcesServer + newListPager *tracker[azfake.PagerResponder[armadvisor.TriageResourcesClientListResponse]] +} + +// Do implements the policy.Transporter interface for TriageResourcesServerTransport. +func (t *TriageResourcesServerTransport) 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")} + } + + return t.dispatchToMethodFake(req, method) +} + +func (t *TriageResourcesServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result) + defer close(resultChan) + + go func() { + var intercepted bool + var res result + if triageResourcesServerTransportInterceptor != nil { + res.resp, res.err, intercepted = triageResourcesServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "TriageResourcesClient.Get": + res.resp, res.err = t.dispatchGet(req) + case "TriageResourcesClient.NewListPager": + res.resp, res.err = t.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + select { + case resultChan <- res: + case <-req.Context().Done(): + } + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (t *TriageResourcesServerTransport) 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 = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Advisor/resiliencyReviews/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Advisor/triageRecommendations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Advisor/triageResources/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + reviewIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("reviewId")]) + if err != nil { + return nil, err + } + recommendationIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("recommendationId")]) + if err != nil { + return nil, err + } + recommendationResourceIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("recommendationResourceId")]) + if err != nil { + return nil, err + } + respr, errRespr := t.srv.Get(req.Context(), reviewIDParam, recommendationIDParam, recommendationResourceIDParam, 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).TriageResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (t *TriageResourcesServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if t.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := t.newListPager.get(req) + if newListPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Advisor/resiliencyReviews/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Advisor/triageRecommendations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Advisor/triageResources` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + reviewIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("reviewId")]) + if err != nil { + return nil, err + } + recommendationIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("recommendationId")]) + if err != nil { + return nil, err + } + resp := t.srv.NewListPager(reviewIDParam, recommendationIDParam, nil) + newListPager = &resp + t.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armadvisor.TriageResourcesClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !contains([]int{http.StatusOK}, resp.StatusCode) { + t.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + t.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to TriageResourcesServerTransport +var triageResourcesServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/sdk/resourcemanager/advisor/armadvisor/fake/workloads_server.go b/sdk/resourcemanager/advisor/armadvisor/fake/workloads_server.go new file mode 100644 index 000000000000..1bb167d3d158 --- /dev/null +++ b/sdk/resourcemanager/advisor/armadvisor/fake/workloads_server.go @@ -0,0 +1,124 @@ +// 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) Go Code Generator. DO NOT EDIT. + +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/advisor/armadvisor/v2" + "net/http" + "regexp" +) + +// WorkloadsServer is a fake server for instances of the armadvisor.WorkloadsClient type. +type WorkloadsServer struct { + // NewListPager is the fake for method WorkloadsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(options *armadvisor.WorkloadsClientListOptions) (resp azfake.PagerResponder[armadvisor.WorkloadsClientListResponse]) +} + +// NewWorkloadsServerTransport creates a new instance of WorkloadsServerTransport with the provided implementation. +// The returned WorkloadsServerTransport instance is connected to an instance of armadvisor.WorkloadsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewWorkloadsServerTransport(srv *WorkloadsServer) *WorkloadsServerTransport { + return &WorkloadsServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[armadvisor.WorkloadsClientListResponse]](), + } +} + +// WorkloadsServerTransport connects instances of armadvisor.WorkloadsClient to instances of WorkloadsServer. +// Don't use this type directly, use NewWorkloadsServerTransport instead. +type WorkloadsServerTransport struct { + srv *WorkloadsServer + newListPager *tracker[azfake.PagerResponder[armadvisor.WorkloadsClientListResponse]] +} + +// Do implements the policy.Transporter interface for WorkloadsServerTransport. +func (w *WorkloadsServerTransport) 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")} + } + + return w.dispatchToMethodFake(req, method) +} + +func (w *WorkloadsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result) + defer close(resultChan) + + go func() { + var intercepted bool + var res result + if workloadsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = workloadsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "WorkloadsClient.NewListPager": + res.resp, res.err = w.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + select { + case resultChan <- res: + case <-req.Context().Done(): + } + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (w *WorkloadsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if w.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := w.newListPager.get(req) + if newListPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Advisor/workloads` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resp := w.srv.NewListPager(nil) + newListPager = &resp + w.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armadvisor.WorkloadsClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !contains([]int{http.StatusOK}, resp.StatusCode) { + w.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + w.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to WorkloadsServerTransport +var workloadsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/sdk/resourcemanager/advisor/armadvisor/go.mod b/sdk/resourcemanager/advisor/armadvisor/go.mod index 8e82712c0918..1193e2a1f929 100644 --- a/sdk/resourcemanager/advisor/armadvisor/go.mod +++ b/sdk/resourcemanager/advisor/armadvisor/go.mod @@ -1,9 +1,9 @@ -module github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/advisor/armadvisor +module github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/advisor/armadvisor/v2 go 1.24.0 require ( - github.com/Azure/azure-sdk-for-go/sdk/azcore v1.20.0 + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.21.0 github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.13.1 github.com/Azure/azure-sdk-for-go/sdk/internal v1.11.2 github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/internal/v3 v3.1.0 @@ -19,9 +19,9 @@ require ( github.com/kylelemons/godebug v1.1.0 // indirect github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect github.com/pmezard/go-difflib v1.0.0 // indirect - golang.org/x/crypto v0.45.0 // indirect - golang.org/x/net v0.47.0 // indirect - golang.org/x/sys v0.38.0 // indirect - golang.org/x/text v0.31.0 // indirect + golang.org/x/crypto v0.47.0 // indirect + golang.org/x/net v0.49.0 // indirect + golang.org/x/sys v0.40.0 // indirect + golang.org/x/text v0.33.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/sdk/resourcemanager/advisor/armadvisor/go.sum b/sdk/resourcemanager/advisor/armadvisor/go.sum index cc236fb92e86..f4450ac568ee 100644 --- a/sdk/resourcemanager/advisor/armadvisor/go.sum +++ b/sdk/resourcemanager/advisor/armadvisor/go.sum @@ -1,5 +1,5 @@ -github.com/Azure/azure-sdk-for-go/sdk/azcore v1.20.0 h1:JXg2dwJUmPB9JmtVmdEB16APJ7jurfbY5jnfXpJoRMc= -github.com/Azure/azure-sdk-for-go/sdk/azcore v1.20.0/go.mod h1:YD5h/ldMsG0XiIw7PdyNhLxaM317eFh5yNLccNfGdyw= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.21.0 h1:fou+2+WFTib47nS+nz/ozhEBnvU96bKHy6LjRsY4E28= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.21.0/go.mod h1:t76Ruy8AHvUAC8GfMWJMa0ElSbuIcO03NLpynfbgsPA= github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.13.1 h1:Hk5QBxZQC1jb2Fwj6mpzme37xbCDdNTxU7O9eb5+LB4= github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.13.1/go.mod h1:IYus9qsFobWIc2YVwe/WPjcnyCkPKtnHAqUYeebc8z0= github.com/Azure/azure-sdk-for-go/sdk/azidentity/cache v0.3.2 h1:yz1bePFlP5Vws5+8ez6T3HWXPmwOK7Yvq8QxDBD3SKY= @@ -40,15 +40,15 @@ github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= -golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q= -golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4= -golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY= -golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU= +golang.org/x/crypto v0.47.0 h1:V6e3FRj+n4dbpw86FJ8Fv7XVOql7TEwpHapKoMJ/GO8= +golang.org/x/crypto v0.47.0/go.mod h1:ff3Y9VzzKbwSSEzWqJsJVBnWmRwRSHt/6Op5n9bQc4A= +golang.org/x/net v0.49.0 h1:eeHFmOGUTtaaPSGNmjBKpbng9MulQsJURQUAfUwY++o= +golang.org/x/net v0.49.0/go.mod h1:/ysNB2EvaqvesRkuLAyjI1ycPZlQHM3q01F02UY/MV8= golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc= -golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= -golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM= -golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM= +golang.org/x/sys v0.40.0 h1:DBZZqJ2Rkml6QMQsZywtnjnnGvHza6BTfYFWY9kjEWQ= +golang.org/x/sys v0.40.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +golang.org/x/text v0.33.0 h1:B3njUFyqtHDUI5jMn1YIr5B0IE2U0qck04r6d4KPAxE= +golang.org/x/text v0.33.0/go.mod h1:LuMebE6+rBincTi9+xWTY8TztLzKHc/9C1uBCG27+q8= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= diff --git a/sdk/resourcemanager/advisor/armadvisor/models.go b/sdk/resourcemanager/advisor/armadvisor/models.go index 2e97db890ff7..87b42486fdf2 100644 --- a/sdk/resourcemanager/advisor/armadvisor/models.go +++ b/sdk/resourcemanager/advisor/armadvisor/models.go @@ -1,7 +1,6 @@ // 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. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package armadvisor @@ -21,18 +20,108 @@ type ArmErrorResponse struct { Error *ARMErrorResponseBody } +// AssessmentListResult - Paged collection of AssessmentResult items +type AssessmentListResult struct { + // REQUIRED; The AssessmentResult items on this page + Value []*AssessmentResult + + // The link to the next page of items + NextLink *string +} + +// AssessmentResult - The Advisor assessment result data structure. +type AssessmentResult struct { + // The Advisor assessment result properties structure. + Properties *AssessmentResultProperties + + // 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 +} + +// AssessmentResultProperties - Assessment result properties. +type AssessmentResultProperties struct { + // Assessment Type Locale. + Locale *string + + // Assessment Type Id. + TypeID *string + + // Workload Id. + WorkloadID *string + + // READ-ONLY; Assessment Id. + AssessmentID *string + + // READ-ONLY; Assessment Type Description. + Description *string + + // READ-ONLY; Assessment Score. + Score *int32 + + // READ-ONLY; Assessment State. + State *string + + // READ-ONLY; Assessment Type. + Type *string + + // READ-ONLY; Assessment Type Version. + TypeVersion *string + + // READ-ONLY; Workload Name. + WorkloadName *string +} + +// AssessmentTypeListResult - The Advisor assessment type list result data structure. +type AssessmentTypeListResult struct { + // REQUIRED; The AssessmentTypeResult items on this page + Value []*AssessmentTypeResult + + // The link to the next page of items + NextLink *string +} + +// AssessmentTypeResult - The Advisor assessment type result data structure. +type AssessmentTypeResult struct { + // Assessment Type Description + Description *string + + // Assessment Type Id + ID *string + + // Assessment Type Locale + Locale *string + + // Assessment Type Title + Title *string + + // Assessment Type Version + Version *string +} + // ConfigData - The Advisor configuration data structure. type ConfigData struct { // The Advisor configuration data structure. Properties *ConfigDataProperties - // READ-ONLY; The resource ID. + // 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. + // READ-ONLY; The name of the resource Name *string - // READ-ONLY; The type of the resource. + // 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 } @@ -41,6 +130,10 @@ type ConfigDataProperties struct { // Advisor digest configuration. Valid only for subscriptions Digests []*DigestConfig + // Minimum duration for Advisor low CPU utilization evaluation. Valid only for subscriptions. Valid values: 7 (default), 14, + // 21, 30, 60 or 90. + Duration *Duration + // Exclude the resource from Advisor evaluations. Valid values: False (default) or True. Exclude *bool @@ -49,13 +142,13 @@ type ConfigDataProperties struct { LowCPUThreshold *CPUThreshold } -// ConfigurationListResult - The list of Advisor configurations. +// ConfigurationListResult - Paged collection of ConfigData items type ConfigurationListResult struct { - // The link used to get the next page of configurations. - NextLink *string - - // The list of configurations. + // REQUIRED; The ConfigData items on this page Value []*ConfigData + + // The link to the next page of items + NextLink *string } // DigestConfig - Advisor Digest configuration entity @@ -82,26 +175,29 @@ type DigestConfig struct { // MetadataEntity - The metadata entity contract. type MetadataEntity struct { - // The resource Id of the metadata entity. + // The metadata entity properties. + Properties *MetadataEntityProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} ID *string - // The name of the metadata entity. + // READ-ONLY; The name of the resource Name *string - // The metadata entity properties. - Properties *MetadataEntityProperties + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData - // The type of the metadata entity. + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" Type *string } -// MetadataEntityListResult - The list of metadata entities +// MetadataEntityListResult - The response of a MetadataEntity list operation. type MetadataEntityListResult struct { - // The link used to get the next page of metadata. - NextLink *string - - // The list of metadata entities. + // REQUIRED; The MetadataEntity items on this page Value []*MetadataEntity + + // The link to the next page of items + NextLink *string } // MetadataEntityProperties - The metadata entity properties @@ -152,13 +248,58 @@ type OperationEntity struct { Name *string } -// OperationEntityListResult - The list of Advisor operations. +// OperationEntityListResult - Paged collection of OperationEntity items type OperationEntityListResult struct { - // The link used to get the next page of operations. + // REQUIRED; The OperationEntity items on this page + Value []*OperationEntity + + // The link to the next page of items NextLink *string +} - // The list of operations. - Value []*OperationEntity +// PredictionRequest - Parameters for predict recommendation. +type PredictionRequest struct { + // Request properties for prediction recommendation. + Properties *PredictionRequestProperties +} + +// PredictionRequestProperties - Properties given for the predictor. +type PredictionRequestProperties struct { + // Extended properties are arguments specific for each prediction type. + ExtendedProperties any + + // Type of the prediction. + PredictionType *PredictionType +} + +// PredictionResponse - Response used by predictions. +type PredictionResponse struct { + // The properties of the prediction. + Properties *PredictionResponseProperties +} + +// PredictionResponseProperties - Properties of the prediction +type PredictionResponseProperties struct { + // The category of the recommendation. + Category *Category + + // Extended properties + ExtendedProperties any + + // The business impact of the recommendation. + Impact *Impact + + // The resource type identified by Advisor. + ImpactedField *string + + // The most recent time that Advisor checked the validity of the recommendation. + LastUpdated *time.Time + + // Type of the prediction. + PredictionType *PredictionType + + // A summary of the recommendation. + ShortDescription *ShortDescription } // RecommendationProperties - The properties of the recommendation. @@ -169,6 +310,9 @@ type RecommendationProperties struct { // The category of the recommendation. Category *Category + // The sub-category of the recommendation. + Control *Control + // The detailed description of recommendation. Description *string @@ -199,6 +343,9 @@ type RecommendationProperties struct { // The recommendation metadata. Metadata map[string]any + // Additional notes for the Recommendation + Notes *string + // The potential benefit of implementing recommendation. PotentialBenefits *string @@ -211,28 +358,103 @@ type RecommendationProperties struct { // Metadata of resource that was assessed ResourceMetadata *ResourceMetadata + // The Workload that this Resource belongs to. + ResourceWorkload *RecommendationPropertiesResourceWorkload + + // The Review that this Recommendation belongs to. + Review *RecommendationPropertiesReview + // The potential risk of not implementing the recommendation. Risk *Risk // A summary of the recommendation. ShortDescription *ShortDescription + // The Source System that this Recommendation originated from. + SourceSystem *string + // The list of snoozed and dismissed rules for the recommendation. SuppressionIDs []*string + + // If the Recommendation has Tracking enabled. + Tracked *bool + + // The properties of a tracked recommendation. + TrackedProperties *TrackedRecommendationProperties +} + +// RecommendationPropertiesResourceWorkload - The Workload that this Resource belongs to. +type RecommendationPropertiesResourceWorkload struct { + // The Id of the Workload + ID *string + + // The Name of the Workload + Name *string } -// Resource - An Azure resource. -type Resource struct { - // READ-ONLY; The resource ID. +// RecommendationPropertiesReview - The Review that this Recommendation belongs to. +type RecommendationPropertiesReview struct { + // The ARM Resource Id of the Review ID *string - // READ-ONLY; The name of the resource. + // The Name of the Review Name *string +} + +// RecommendationRejectBody - Recommendation reject body. +type RecommendationRejectBody struct { + // Reason for rejecting recommendation. + ReasonForRejection *ReasonForRejectionName +} + +// ResiliencyReview - The Advisor resiliency review data structure. +type ResiliencyReview struct { + // Advisor resiliency review properties. + Properties *ResiliencyReviewProperties - // READ-ONLY; The type of the resource. + // 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 } +// ResiliencyReviewCollection - Collection of Resiliency Reviews. +type ResiliencyReviewCollection struct { + // REQUIRED; The ResiliencyReview items on this page + Value []*ResiliencyReview + + // The link to the next page of items + NextLink *string +} + +// ResiliencyReviewProperties - Resiliency review properties. +type ResiliencyReviewProperties struct { + // READ-ONLY; Review last updated timestamp. + PublishedAt *string + + // READ-ONLY; Review recommendations count. + RecommendationsCount *int32 + + // READ-ONLY; Review name. + ReviewName *string + + // READ-ONLY; Review status. + ReviewStatus *ReviewStatus + + // READ-ONLY; Review last updated timestamp. + UpdatedAt *string + + // READ-ONLY; Workload Name. + WorkloadName *string +} + // ResourceMetadata - Recommendation resource metadata type ResourceMetadata struct { // The action to view resource. @@ -256,31 +478,87 @@ type ResourceRecommendationBase struct { // The properties of the recommendation. Properties *RecommendationProperties - // READ-ONLY; The resource ID. + // 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. + // READ-ONLY; The name of the resource Name *string - // READ-ONLY; The type of the resource. + // 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 } -// ResourceRecommendationBaseListResult - The list of Advisor recommendations. +// ResourceRecommendationBaseListResult - The response of a ResourceRecommendationBase list operation. type ResourceRecommendationBaseListResult struct { - // The link used to get the next page of recommendations. + // REQUIRED; The ResourceRecommendationBase items on this page + Value []*ResourceRecommendationBase + + // The link to the next page of items NextLink *string +} - // The list of recommendations. - Value []*ResourceRecommendationBase +// ScoreEntity - The details of Advisor Score +type ScoreEntity struct { + // The consumption units for the score. + ConsumptionUnits *float32 + + // The date score was calculated. + Date *string + + // The number of impacted resources. + ImpactedResourceCount *float32 + + // The potential percentage increase in overall score at subscription level once all recommendations in this scope are implemented. + PotentialScoreIncrease *float32 + + // The percentage score. + Score *float32 + + // READ-ONLY; The count of impacted categories. + CategoryCount *float32 +} + +// ScoreEntityForAdvisor - The details of Advisor score for a single category. +type ScoreEntityForAdvisor struct { + // The Advisor score data. + Properties *ScoreEntityProperties + + // 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 +} + +// ScoreEntityProperties - The Advisor score data. +type ScoreEntityProperties struct { + // The details of latest available score. + LastRefreshedScore *ScoreEntity + + // The historic Advisor score data. + TimeSeries []*TimeSeriesEntity +} + +type ScoreResponse struct { + // The list of operations. + Value []*ScoreEntityForAdvisor } // ShortDescription - A summary of the recommendation. type ShortDescription struct { - // The issue or opportunity identified by the recommendation. + // The issue or opportunity identified by the recommendation and proposed solution. Problem *string - // The remediation action suggested by the recommendation. + // The issue or opportunity identified by the recommendation and proposed solution. Solution *string } @@ -290,23 +568,26 @@ type SuppressionContract struct { // The properties of the suppression. Properties *SuppressionProperties - // READ-ONLY; The resource ID. + // 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. + // READ-ONLY; The name of the resource Name *string - // READ-ONLY; The type of the resource. + // 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 } -// SuppressionContractListResult - The list of Advisor suppressions. +// SuppressionContractListResult - The response of a SuppressionContract list operation. type SuppressionContractListResult struct { - // The link used to get the next page of suppressions. - NextLink *string - - // The list of suppressions. + // REQUIRED; The SuppressionContract items on this page Value []*SuppressionContract + + // The link to the next page of items + NextLink *string } // SuppressionProperties - The properties of the suppression. @@ -320,3 +601,192 @@ type SuppressionProperties struct { // READ-ONLY; Gets or sets the expiration time stamp. ExpirationTimeStamp *time.Time } + +// SystemData - Metadata pertaining to creation and last modification of the resource. +type SystemData struct { + // The timestamp of resource creation (UTC). + CreatedAt *time.Time + + // The identity that created the resource. + CreatedBy *string + + // The type of identity that created the resource. + CreatedByType *CreatedByType + + // The timestamp of resource last modification (UTC) + LastModifiedAt *time.Time + + // The identity that last modified the resource. + LastModifiedBy *string + + // The type of identity that last modified the resource. + LastModifiedByType *CreatedByType +} + +// TimeSeriesEntity - The historic data at different aggregation levels. +type TimeSeriesEntity struct { + // The aggregation level of the score. + AggregationLevel *Aggregated + + // The past score data + ScoreHistory []*ScoreEntity +} + +// TrackedRecommendationProperties - The tracked properties of a Recommendation +type TrackedRecommendationProperties struct { + // The time the Recommendation was postponed until. + PostponedTime *time.Time + + // The Priority of the Recommendation. + Priority *Priority + + // The reason the state of the Recommendation was changed. + Reason *Reason + + // The state of the Recommendation + State *State +} + +type TrackedRecommendationPropertiesPayload struct { + Properties *TrackedRecommendationPropertiesPayloadProperties +} + +type TrackedRecommendationPropertiesPayloadProperties struct { + // The tracked properties of a Recommendation + TrackedProperties *TrackedRecommendationProperties +} + +// TriageRecommendation - Triage recommendation data structure. +type TriageRecommendation struct { + // Advisor resiliency review properties. + Properties *TriageRecommendationProperties + + // 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 +} + +// TriageRecommendationCollection - Collection of Advisor triage recommendations. +type TriageRecommendationCollection struct { + // REQUIRED; List of triage recommendations. + Value []*TriageRecommendation + + // The URL to get the next set of triage recommendations, if there are any. + NextLink *string +} + +// TriageRecommendationProperties - Triage recommendation properties. +type TriageRecommendationProperties struct { + // READ-ONLY; List of subscription ids. + AppliesToSubscriptions []*string + + // READ-ONLY; Recommendation description. + Description *string + + // READ-ONLY; Recommendation notes. + Notes *string + + // READ-ONLY; Recommendation potential benefit. + PotentialBenefits *string + + // READ-ONLY; Recommendation priority. + Priority *PriorityName + + // READ-ONLY; Recommendation status. + RecommendationStatus *RecommendationStatusName + + // READ-ONLY; Recommendation rejection reason. + RejectReason *string + + // READ-ONLY; Review id. + ReviewID *string + + // READ-ONLY; Recommendation label. + Title *string + + // READ-ONLY; Recommendation potential benefit. + UpdatedAt *string +} + +// TriageResource - Triage resource data structure. +type TriageResource struct { + // Triage resource properties. + Properties *TriageResourceProperties + + // 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 +} + +// TriageResourceCollection - Collection of Advisor triage resources. +type TriageResourceCollection struct { + // REQUIRED; The TriageResource items on this page + Value []*TriageResource + + // The link to the next page of items + NextLink *string +} + +// TriageResourceProperties - Triage resource properties. +type TriageResourceProperties struct { + // READ-ONLY; Unique identifier for the recommendation resource this triageResource belongs to. + RecommendationID *string + + // READ-ONLY; Name of the resource group this triageResource belongs to. + ResourceGroup *string + + // READ-ONLY; Full Azure resource id path of the resource this triageResource corresponds to. + ResourceID *string + + // READ-ONLY; Name of the resource this triageResource corresponds to. + ResourceName *string + + // READ-ONLY; Type of resource this triageResource corresponds to e.g. "Cosmos DB". + ResourceType *string + + // READ-ONLY; Unique identifier for the review resource this triageResource belongs to. + ReviewID *string + + // READ-ONLY; Unique identifier for the subscription resource this triageResource belongs to. + SubscriptionID *string +} + +// WorkloadListResult - The Workload list result data structure. +type WorkloadListResult struct { + // REQUIRED; List of WorkloadListResult items on this page. + Value []*WorkloadResult + + // Url to get the next Page of WorkloadListResult items. + NextLink *string +} + +// WorkloadResult - The Workload result data structure. +type WorkloadResult struct { + // Workload Id + ID *string + + // Workload Name + Name *string + + // Subscription Id + SubscriptionID *string + + // Subscription Name + SubscriptionName *string +} diff --git a/sdk/resourcemanager/advisor/armadvisor/models_serde.go b/sdk/resourcemanager/advisor/armadvisor/models_serde.go index dc42d2186207..c6397d0bb7e0 100644 --- a/sdk/resourcemanager/advisor/armadvisor/models_serde.go +++ b/sdk/resourcemanager/advisor/armadvisor/models_serde.go @@ -1,7 +1,6 @@ // 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. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package armadvisor @@ -9,7 +8,9 @@ import ( "encoding/json" "fmt" "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime" "reflect" + "time" ) // MarshalJSON implements the json.Marshaller interface for type ARMErrorResponseBody. @@ -70,12 +71,224 @@ func (a *ArmErrorResponse) UnmarshalJSON(data []byte) error { return nil } +// MarshalJSON implements the json.Marshaller interface for type AssessmentListResult. +func (a AssessmentListResult) 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 AssessmentListResult. +func (a *AssessmentListResult) 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 AssessmentResult. +func (a AssessmentResult) 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 AssessmentResult. +func (a *AssessmentResult) 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 AssessmentResultProperties. +func (a AssessmentResultProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "assessmentId", a.AssessmentID) + populate(objectMap, "description", a.Description) + populate(objectMap, "locale", a.Locale) + populate(objectMap, "score", a.Score) + populate(objectMap, "state", a.State) + populate(objectMap, "type", a.Type) + populate(objectMap, "typeId", a.TypeID) + populate(objectMap, "typeVersion", a.TypeVersion) + populate(objectMap, "workloadId", a.WorkloadID) + populate(objectMap, "workloadName", a.WorkloadName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AssessmentResultProperties. +func (a *AssessmentResultProperties) 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 "assessmentId": + err = unpopulate(val, "AssessmentID", &a.AssessmentID) + delete(rawMsg, key) + case "description": + err = unpopulate(val, "Description", &a.Description) + delete(rawMsg, key) + case "locale": + err = unpopulate(val, "Locale", &a.Locale) + delete(rawMsg, key) + case "score": + err = unpopulate(val, "Score", &a.Score) + delete(rawMsg, key) + case "state": + err = unpopulate(val, "State", &a.State) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &a.Type) + delete(rawMsg, key) + case "typeId": + err = unpopulate(val, "TypeID", &a.TypeID) + delete(rawMsg, key) + case "typeVersion": + err = unpopulate(val, "TypeVersion", &a.TypeVersion) + delete(rawMsg, key) + case "workloadId": + err = unpopulate(val, "WorkloadID", &a.WorkloadID) + delete(rawMsg, key) + case "workloadName": + err = unpopulate(val, "WorkloadName", &a.WorkloadName) + 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 AssessmentTypeListResult. +func (a AssessmentTypeListResult) 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 AssessmentTypeListResult. +func (a *AssessmentTypeListResult) 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 AssessmentTypeResult. +func (a AssessmentTypeResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", a.Description) + populate(objectMap, "id", a.ID) + populate(objectMap, "locale", a.Locale) + populate(objectMap, "title", a.Title) + populate(objectMap, "version", a.Version) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AssessmentTypeResult. +func (a *AssessmentTypeResult) 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 "description": + err = unpopulate(val, "Description", &a.Description) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &a.ID) + delete(rawMsg, key) + case "locale": + err = unpopulate(val, "Locale", &a.Locale) + delete(rawMsg, key) + case "title": + err = unpopulate(val, "Title", &a.Title) + delete(rawMsg, key) + case "version": + err = unpopulate(val, "Version", &a.Version) + 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 ConfigData. func (c ConfigData) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) populate(objectMap, "id", c.ID) populate(objectMap, "name", c.Name) populate(objectMap, "properties", c.Properties) + populate(objectMap, "systemData", c.SystemData) populate(objectMap, "type", c.Type) return json.Marshal(objectMap) } @@ -98,6 +311,9 @@ func (c *ConfigData) UnmarshalJSON(data []byte) error { case "properties": err = unpopulate(val, "Properties", &c.Properties) delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &c.SystemData) + delete(rawMsg, key) case "type": err = unpopulate(val, "Type", &c.Type) delete(rawMsg, key) @@ -113,6 +329,7 @@ func (c *ConfigData) UnmarshalJSON(data []byte) error { func (c ConfigDataProperties) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) populate(objectMap, "digests", c.Digests) + populate(objectMap, "duration", c.Duration) populate(objectMap, "exclude", c.Exclude) populate(objectMap, "lowCpuThreshold", c.LowCPUThreshold) return json.Marshal(objectMap) @@ -130,6 +347,9 @@ func (c *ConfigDataProperties) UnmarshalJSON(data []byte) error { case "digests": err = unpopulate(val, "Digests", &c.Digests) delete(rawMsg, key) + case "duration": + err = unpopulate(val, "Duration", &c.Duration) + delete(rawMsg, key) case "exclude": err = unpopulate(val, "Exclude", &c.Exclude) delete(rawMsg, key) @@ -228,6 +448,7 @@ func (m MetadataEntity) MarshalJSON() ([]byte, error) { populate(objectMap, "id", m.ID) populate(objectMap, "name", m.Name) populate(objectMap, "properties", m.Properties) + populate(objectMap, "systemData", m.SystemData) populate(objectMap, "type", m.Type) return json.Marshal(objectMap) } @@ -250,6 +471,9 @@ func (m *MetadataEntity) UnmarshalJSON(data []byte) error { case "properties": err = unpopulate(val, "Properties", &m.Properties) delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &m.SystemData) + delete(rawMsg, key) case "type": err = unpopulate(val, "Type", &m.Type) delete(rawMsg, key) @@ -463,11 +687,148 @@ func (o *OperationEntityListResult) UnmarshalJSON(data []byte) error { return nil } +// MarshalJSON implements the json.Marshaller interface for type PredictionRequest. +func (p PredictionRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", p.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PredictionRequest. +func (p *PredictionRequest) 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) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PredictionRequestProperties. +func (p PredictionRequestProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateAny(objectMap, "extendedProperties", p.ExtendedProperties) + populate(objectMap, "predictionType", p.PredictionType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PredictionRequestProperties. +func (p *PredictionRequestProperties) 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 "extendedProperties": + err = unpopulate(val, "ExtendedProperties", &p.ExtendedProperties) + delete(rawMsg, key) + case "predictionType": + err = unpopulate(val, "PredictionType", &p.PredictionType) + 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 PredictionResponse. +func (p PredictionResponse) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", p.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PredictionResponse. +func (p *PredictionResponse) 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) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PredictionResponseProperties. +func (p PredictionResponseProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "category", p.Category) + populateAny(objectMap, "extendedProperties", p.ExtendedProperties) + populate(objectMap, "impact", p.Impact) + populate(objectMap, "impactedField", p.ImpactedField) + populateTime[datetime.RFC3339](objectMap, "lastUpdated", p.LastUpdated) + populate(objectMap, "predictionType", p.PredictionType) + populate(objectMap, "shortDescription", p.ShortDescription) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PredictionResponseProperties. +func (p *PredictionResponseProperties) 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 "category": + err = unpopulate(val, "Category", &p.Category) + delete(rawMsg, key) + case "extendedProperties": + err = unpopulate(val, "ExtendedProperties", &p.ExtendedProperties) + delete(rawMsg, key) + case "impact": + err = unpopulate(val, "Impact", &p.Impact) + delete(rawMsg, key) + case "impactedField": + err = unpopulate(val, "ImpactedField", &p.ImpactedField) + delete(rawMsg, key) + case "lastUpdated": + err = unpopulateTime[datetime.RFC3339](val, "LastUpdated", &p.LastUpdated) + delete(rawMsg, key) + case "predictionType": + err = unpopulate(val, "PredictionType", &p.PredictionType) + delete(rawMsg, key) + case "shortDescription": + err = unpopulate(val, "ShortDescription", &p.ShortDescription) + 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 RecommendationProperties. func (r RecommendationProperties) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) populate(objectMap, "actions", r.Actions) populate(objectMap, "category", r.Category) + populate(objectMap, "control", r.Control) populate(objectMap, "description", r.Description) populate(objectMap, "exposedMetadataProperties", r.ExposedMetadataProperties) populate(objectMap, "extendedProperties", r.ExtendedProperties) @@ -475,16 +836,22 @@ func (r RecommendationProperties) MarshalJSON() ([]byte, error) { populate(objectMap, "impactedField", r.ImpactedField) populate(objectMap, "impactedValue", r.ImpactedValue) populate(objectMap, "label", r.Label) - populateDateTimeRFC3339(objectMap, "lastUpdated", r.LastUpdated) + populateTime[datetime.RFC3339](objectMap, "lastUpdated", r.LastUpdated) populate(objectMap, "learnMoreLink", r.LearnMoreLink) populate(objectMap, "metadata", r.Metadata) + populate(objectMap, "notes", r.Notes) populate(objectMap, "potentialBenefits", r.PotentialBenefits) populate(objectMap, "recommendationTypeId", r.RecommendationTypeID) populate(objectMap, "remediation", r.Remediation) populate(objectMap, "resourceMetadata", r.ResourceMetadata) + populate(objectMap, "resourceWorkload", r.ResourceWorkload) + populate(objectMap, "review", r.Review) populate(objectMap, "risk", r.Risk) populate(objectMap, "shortDescription", r.ShortDescription) + populate(objectMap, "sourceSystem", r.SourceSystem) populate(objectMap, "suppressionIds", r.SuppressionIDs) + populate(objectMap, "tracked", r.Tracked) + populate(objectMap, "trackedProperties", r.TrackedProperties) return json.Marshal(objectMap) } @@ -503,6 +870,9 @@ func (r *RecommendationProperties) UnmarshalJSON(data []byte) error { case "category": err = unpopulate(val, "Category", &r.Category) delete(rawMsg, key) + case "control": + err = unpopulate(val, "Control", &r.Control) + delete(rawMsg, key) case "description": err = unpopulate(val, "Description", &r.Description) delete(rawMsg, key) @@ -525,7 +895,7 @@ func (r *RecommendationProperties) UnmarshalJSON(data []byte) error { err = unpopulate(val, "Label", &r.Label) delete(rawMsg, key) case "lastUpdated": - err = unpopulateDateTimeRFC3339(val, "LastUpdated", &r.LastUpdated) + err = unpopulateTime[datetime.RFC3339](val, "LastUpdated", &r.LastUpdated) delete(rawMsg, key) case "learnMoreLink": err = unpopulate(val, "LearnMoreLink", &r.LearnMoreLink) @@ -533,6 +903,9 @@ func (r *RecommendationProperties) UnmarshalJSON(data []byte) error { case "metadata": err = unpopulate(val, "Metadata", &r.Metadata) delete(rawMsg, key) + case "notes": + err = unpopulate(val, "Notes", &r.Notes) + delete(rawMsg, key) case "potentialBenefits": err = unpopulate(val, "PotentialBenefits", &r.PotentialBenefits) delete(rawMsg, key) @@ -545,15 +918,30 @@ func (r *RecommendationProperties) UnmarshalJSON(data []byte) error { case "resourceMetadata": err = unpopulate(val, "ResourceMetadata", &r.ResourceMetadata) delete(rawMsg, key) + case "resourceWorkload": + err = unpopulate(val, "ResourceWorkload", &r.ResourceWorkload) + delete(rawMsg, key) + case "review": + err = unpopulate(val, "Review", &r.Review) + delete(rawMsg, key) case "risk": err = unpopulate(val, "Risk", &r.Risk) delete(rawMsg, key) case "shortDescription": err = unpopulate(val, "ShortDescription", &r.ShortDescription) delete(rawMsg, key) + case "sourceSystem": + err = unpopulate(val, "SourceSystem", &r.SourceSystem) + delete(rawMsg, key) case "suppressionIds": err = unpopulate(val, "SuppressionIDs", &r.SuppressionIDs) delete(rawMsg, key) + case "tracked": + err = unpopulate(val, "Tracked", &r.Tracked) + delete(rawMsg, key) + case "trackedProperties": + err = unpopulate(val, "TrackedProperties", &r.TrackedProperties) + delete(rawMsg, key) } if err != nil { return fmt.Errorf("unmarshalling type %T: %v", r, err) @@ -562,17 +950,16 @@ func (r *RecommendationProperties) 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 RecommendationPropertiesResourceWorkload. +func (r RecommendationPropertiesResourceWorkload) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) populate(objectMap, "id", r.ID) populate(objectMap, "name", r.Name) - populate(objectMap, "type", r.Type) 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 RecommendationPropertiesResourceWorkload. +func (r *RecommendationPropertiesResourceWorkload) 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) @@ -586,9 +973,6 @@ func (r *Resource) UnmarshalJSON(data []byte) error { case "name": err = unpopulate(val, "Name", &r.Name) delete(rawMsg, key) - case "type": - err = unpopulate(val, "Type", &r.Type) - delete(rawMsg, key) } if err != nil { return fmt.Errorf("unmarshalling type %T: %v", r, err) @@ -597,19 +981,16 @@ func (r *Resource) UnmarshalJSON(data []byte) error { return nil } -// MarshalJSON implements the json.Marshaller interface for type ResourceMetadata. -func (r ResourceMetadata) MarshalJSON() ([]byte, error) { +// MarshalJSON implements the json.Marshaller interface for type RecommendationPropertiesReview. +func (r RecommendationPropertiesReview) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) - populate(objectMap, "action", r.Action) - populate(objectMap, "plural", r.Plural) - populate(objectMap, "resourceId", r.ResourceID) - populate(objectMap, "singular", r.Singular) - populate(objectMap, "source", r.Source) + populate(objectMap, "id", r.ID) + populate(objectMap, "name", r.Name) return json.Marshal(objectMap) } -// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceMetadata. -func (r *ResourceMetadata) UnmarshalJSON(data []byte) error { +// UnmarshalJSON implements the json.Unmarshaller interface for type RecommendationPropertiesReview. +func (r *RecommendationPropertiesReview) 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) @@ -617,14 +998,196 @@ func (r *ResourceMetadata) UnmarshalJSON(data []byte) error { for key, val := range rawMsg { var err error switch key { - case "action": - err = unpopulate(val, "Action", &r.Action) - delete(rawMsg, key) - case "plural": - err = unpopulate(val, "Plural", &r.Plural) + case "id": + err = unpopulate(val, "ID", &r.ID) delete(rawMsg, key) - case "resourceId": - err = unpopulate(val, "ResourceID", &r.ResourceID) + case "name": + err = unpopulate(val, "Name", &r.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RecommendationRejectBody. +func (r RecommendationRejectBody) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "reasonForRejection", r.ReasonForRejection) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RecommendationRejectBody. +func (r *RecommendationRejectBody) 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) + } + for key, val := range rawMsg { + var err error + switch key { + case "reasonForRejection": + err = unpopulate(val, "ReasonForRejection", &r.ReasonForRejection) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ResiliencyReview. +func (r ResiliencyReview) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", r.ID) + populate(objectMap, "name", r.Name) + populate(objectMap, "properties", r.Properties) + populate(objectMap, "systemData", r.SystemData) + populate(objectMap, "type", r.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResiliencyReview. +func (r *ResiliencyReview) 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) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &r.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &r.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &r.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &r.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &r.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ResiliencyReviewCollection. +func (r ResiliencyReviewCollection) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", r.NextLink) + populate(objectMap, "value", r.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResiliencyReviewCollection. +func (r *ResiliencyReviewCollection) 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) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &r.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &r.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ResiliencyReviewProperties. +func (r ResiliencyReviewProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "publishedAt", r.PublishedAt) + populate(objectMap, "recommendationsCount", r.RecommendationsCount) + populate(objectMap, "reviewName", r.ReviewName) + populate(objectMap, "reviewStatus", r.ReviewStatus) + populate(objectMap, "updatedAt", r.UpdatedAt) + populate(objectMap, "workloadName", r.WorkloadName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResiliencyReviewProperties. +func (r *ResiliencyReviewProperties) 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) + } + for key, val := range rawMsg { + var err error + switch key { + case "publishedAt": + err = unpopulate(val, "PublishedAt", &r.PublishedAt) + delete(rawMsg, key) + case "recommendationsCount": + err = unpopulate(val, "RecommendationsCount", &r.RecommendationsCount) + delete(rawMsg, key) + case "reviewName": + err = unpopulate(val, "ReviewName", &r.ReviewName) + delete(rawMsg, key) + case "reviewStatus": + err = unpopulate(val, "ReviewStatus", &r.ReviewStatus) + delete(rawMsg, key) + case "updatedAt": + err = unpopulate(val, "UpdatedAt", &r.UpdatedAt) + delete(rawMsg, key) + case "workloadName": + err = unpopulate(val, "WorkloadName", &r.WorkloadName) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ResourceMetadata. +func (r ResourceMetadata) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "action", r.Action) + populate(objectMap, "plural", r.Plural) + populate(objectMap, "resourceId", r.ResourceID) + populate(objectMap, "singular", r.Singular) + populate(objectMap, "source", r.Source) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceMetadata. +func (r *ResourceMetadata) 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) + } + for key, val := range rawMsg { + var err error + switch key { + case "action": + err = unpopulate(val, "Action", &r.Action) + delete(rawMsg, key) + case "plural": + err = unpopulate(val, "Plural", &r.Plural) + delete(rawMsg, key) + case "resourceId": + err = unpopulate(val, "ResourceID", &r.ResourceID) delete(rawMsg, key) case "singular": err = unpopulate(val, "Singular", &r.Singular) @@ -646,6 +1209,7 @@ func (r ResourceRecommendationBase) MarshalJSON() ([]byte, error) { populate(objectMap, "id", r.ID) populate(objectMap, "name", r.Name) populate(objectMap, "properties", r.Properties) + populate(objectMap, "systemData", r.SystemData) populate(objectMap, "type", r.Type) return json.Marshal(objectMap) } @@ -668,6 +1232,9 @@ func (r *ResourceRecommendationBase) UnmarshalJSON(data []byte) error { case "properties": err = unpopulate(val, "Properties", &r.Properties) delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &r.SystemData) + delete(rawMsg, key) case "type": err = unpopulate(val, "Type", &r.Type) delete(rawMsg, key) @@ -710,6 +1277,154 @@ func (r *ResourceRecommendationBaseListResult) UnmarshalJSON(data []byte) error return nil } +// MarshalJSON implements the json.Marshaller interface for type ScoreEntity. +func (s ScoreEntity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "categoryCount", s.CategoryCount) + populate(objectMap, "consumptionUnits", s.ConsumptionUnits) + populate(objectMap, "date", s.Date) + populate(objectMap, "impactedResourceCount", s.ImpactedResourceCount) + populate(objectMap, "potentialScoreIncrease", s.PotentialScoreIncrease) + populate(objectMap, "score", s.Score) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ScoreEntity. +func (s *ScoreEntity) 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", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "categoryCount": + err = unpopulate(val, "CategoryCount", &s.CategoryCount) + delete(rawMsg, key) + case "consumptionUnits": + err = unpopulate(val, "ConsumptionUnits", &s.ConsumptionUnits) + delete(rawMsg, key) + case "date": + err = unpopulate(val, "Date", &s.Date) + delete(rawMsg, key) + case "impactedResourceCount": + err = unpopulate(val, "ImpactedResourceCount", &s.ImpactedResourceCount) + delete(rawMsg, key) + case "potentialScoreIncrease": + err = unpopulate(val, "PotentialScoreIncrease", &s.PotentialScoreIncrease) + delete(rawMsg, key) + case "score": + err = unpopulate(val, "Score", &s.Score) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ScoreEntityForAdvisor. +func (s ScoreEntityForAdvisor) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", s.ID) + populate(objectMap, "name", s.Name) + populate(objectMap, "properties", s.Properties) + populate(objectMap, "systemData", s.SystemData) + populate(objectMap, "type", s.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ScoreEntityForAdvisor. +func (s *ScoreEntityForAdvisor) 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", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &s.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &s.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &s.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &s.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &s.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ScoreEntityProperties. +func (s ScoreEntityProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "lastRefreshedScore", s.LastRefreshedScore) + populate(objectMap, "timeSeries", s.TimeSeries) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ScoreEntityProperties. +func (s *ScoreEntityProperties) 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", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "lastRefreshedScore": + err = unpopulate(val, "LastRefreshedScore", &s.LastRefreshedScore) + delete(rawMsg, key) + case "timeSeries": + err = unpopulate(val, "TimeSeries", &s.TimeSeries) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ScoreResponse. +func (s ScoreResponse) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", s.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ScoreResponse. +func (s *ScoreResponse) 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", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + err = unpopulate(val, "Value", &s.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + // MarshalJSON implements the json.Marshaller interface for type ShortDescription. func (s ShortDescription) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) @@ -747,6 +1462,7 @@ func (s SuppressionContract) MarshalJSON() ([]byte, error) { populate(objectMap, "id", s.ID) populate(objectMap, "name", s.Name) populate(objectMap, "properties", s.Properties) + populate(objectMap, "systemData", s.SystemData) populate(objectMap, "type", s.Type) return json.Marshal(objectMap) } @@ -769,6 +1485,9 @@ func (s *SuppressionContract) UnmarshalJSON(data []byte) error { case "properties": err = unpopulate(val, "Properties", &s.Properties) delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &s.SystemData) + delete(rawMsg, key) case "type": err = unpopulate(val, "Type", &s.Type) delete(rawMsg, key) @@ -814,7 +1533,7 @@ func (s *SuppressionContractListResult) UnmarshalJSON(data []byte) error { // MarshalJSON implements the json.Marshaller interface for type SuppressionProperties. func (s SuppressionProperties) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) - populateDateTimeRFC3339(objectMap, "expirationTimeStamp", s.ExpirationTimeStamp) + populateTime[datetime.RFC3339](objectMap, "expirationTimeStamp", s.ExpirationTimeStamp) populate(objectMap, "suppressionId", s.SuppressionID) populate(objectMap, "ttl", s.TTL) return json.Marshal(objectMap) @@ -830,7 +1549,7 @@ func (s *SuppressionProperties) UnmarshalJSON(data []byte) error { var err error switch key { case "expirationTimeStamp": - err = unpopulateDateTimeRFC3339(val, "ExpirationTimeStamp", &s.ExpirationTimeStamp) + err = unpopulateTime[datetime.RFC3339](val, "ExpirationTimeStamp", &s.ExpirationTimeStamp) delete(rawMsg, key) case "suppressionId": err = unpopulate(val, "SuppressionID", &s.SuppressionID) @@ -846,18 +1565,542 @@ func (s *SuppressionProperties) UnmarshalJSON(data []byte) error { return nil } -func populate(m map[string]any, k string, v any) { - if v == nil { - return - } else if azcore.IsNullValue(v) { +// MarshalJSON implements the json.Marshaller interface for type SystemData. +func (s SystemData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTime[datetime.RFC3339](objectMap, "createdAt", s.CreatedAt) + populate(objectMap, "createdBy", s.CreatedBy) + populate(objectMap, "createdByType", s.CreatedByType) + populateTime[datetime.RFC3339](objectMap, "lastModifiedAt", s.LastModifiedAt) + populate(objectMap, "lastModifiedBy", s.LastModifiedBy) + populate(objectMap, "lastModifiedByType", s.LastModifiedByType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SystemData. +func (s *SystemData) 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", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "createdAt": + err = unpopulateTime[datetime.RFC3339](val, "CreatedAt", &s.CreatedAt) + delete(rawMsg, key) + case "createdBy": + err = unpopulate(val, "CreatedBy", &s.CreatedBy) + delete(rawMsg, key) + case "createdByType": + err = unpopulate(val, "CreatedByType", &s.CreatedByType) + delete(rawMsg, key) + case "lastModifiedAt": + err = unpopulateTime[datetime.RFC3339](val, "LastModifiedAt", &s.LastModifiedAt) + delete(rawMsg, key) + case "lastModifiedBy": + err = unpopulate(val, "LastModifiedBy", &s.LastModifiedBy) + delete(rawMsg, key) + case "lastModifiedByType": + err = unpopulate(val, "LastModifiedByType", &s.LastModifiedByType) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type TimeSeriesEntity. +func (t TimeSeriesEntity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "aggregationLevel", t.AggregationLevel) + populate(objectMap, "scoreHistory", t.ScoreHistory) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TimeSeriesEntity. +func (t *TimeSeriesEntity) 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 "aggregationLevel": + err = unpopulate(val, "AggregationLevel", &t.AggregationLevel) + delete(rawMsg, key) + case "scoreHistory": + err = unpopulate(val, "ScoreHistory", &t.ScoreHistory) + 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 TrackedRecommendationProperties. +func (t TrackedRecommendationProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTime[datetime.RFC3339](objectMap, "postponedTime", t.PostponedTime) + populate(objectMap, "priority", t.Priority) + populate(objectMap, "reason", t.Reason) + populate(objectMap, "state", t.State) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TrackedRecommendationProperties. +func (t *TrackedRecommendationProperties) 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 "postponedTime": + err = unpopulateTime[datetime.RFC3339](val, "PostponedTime", &t.PostponedTime) + delete(rawMsg, key) + case "priority": + err = unpopulate(val, "Priority", &t.Priority) + delete(rawMsg, key) + case "reason": + err = unpopulate(val, "Reason", &t.Reason) + delete(rawMsg, key) + case "state": + err = unpopulate(val, "State", &t.State) + 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 TrackedRecommendationPropertiesPayload. +func (t TrackedRecommendationPropertiesPayload) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", t.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TrackedRecommendationPropertiesPayload. +func (t *TrackedRecommendationPropertiesPayload) 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) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type TrackedRecommendationPropertiesPayloadProperties. +func (t TrackedRecommendationPropertiesPayloadProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "trackedProperties", t.TrackedProperties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TrackedRecommendationPropertiesPayloadProperties. +func (t *TrackedRecommendationPropertiesPayloadProperties) 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 "trackedProperties": + err = unpopulate(val, "TrackedProperties", &t.TrackedProperties) + 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 TriageRecommendation. +func (t TriageRecommendation) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", t.ID) + populate(objectMap, "name", t.Name) + populate(objectMap, "properties", t.Properties) + populate(objectMap, "systemData", t.SystemData) + populate(objectMap, "type", t.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TriageRecommendation. +func (t *TriageRecommendation) 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 "name": + err = unpopulate(val, "Name", &t.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &t.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &t.SystemData) + 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 TriageRecommendationCollection. +func (t TriageRecommendationCollection) 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 TriageRecommendationCollection. +func (t *TriageRecommendationCollection) 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 TriageRecommendationProperties. +func (t TriageRecommendationProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "appliesToSubscriptions", t.AppliesToSubscriptions) + populate(objectMap, "description", t.Description) + populate(objectMap, "notes", t.Notes) + populate(objectMap, "potentialBenefits", t.PotentialBenefits) + populate(objectMap, "priority", t.Priority) + populate(objectMap, "recommendationStatus", t.RecommendationStatus) + populate(objectMap, "rejectReason", t.RejectReason) + populate(objectMap, "reviewId", t.ReviewID) + populate(objectMap, "title", t.Title) + populate(objectMap, "updatedAt", t.UpdatedAt) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TriageRecommendationProperties. +func (t *TriageRecommendationProperties) 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 "appliesToSubscriptions": + err = unpopulate(val, "AppliesToSubscriptions", &t.AppliesToSubscriptions) + delete(rawMsg, key) + case "description": + err = unpopulate(val, "Description", &t.Description) + delete(rawMsg, key) + case "notes": + err = unpopulate(val, "Notes", &t.Notes) + delete(rawMsg, key) + case "potentialBenefits": + err = unpopulate(val, "PotentialBenefits", &t.PotentialBenefits) + delete(rawMsg, key) + case "priority": + err = unpopulate(val, "Priority", &t.Priority) + delete(rawMsg, key) + case "recommendationStatus": + err = unpopulate(val, "RecommendationStatus", &t.RecommendationStatus) + delete(rawMsg, key) + case "rejectReason": + err = unpopulate(val, "RejectReason", &t.RejectReason) + delete(rawMsg, key) + case "reviewId": + err = unpopulate(val, "ReviewID", &t.ReviewID) + delete(rawMsg, key) + case "title": + err = unpopulate(val, "Title", &t.Title) + delete(rawMsg, key) + case "updatedAt": + err = unpopulate(val, "UpdatedAt", &t.UpdatedAt) + 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 TriageResource. +func (t TriageResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", t.ID) + populate(objectMap, "name", t.Name) + populate(objectMap, "properties", t.Properties) + populate(objectMap, "systemData", t.SystemData) + populate(objectMap, "type", t.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TriageResource. +func (t *TriageResource) 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 "name": + err = unpopulate(val, "Name", &t.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &t.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &t.SystemData) + 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 TriageResourceCollection. +func (t TriageResourceCollection) 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 TriageResourceCollection. +func (t *TriageResourceCollection) 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 TriageResourceProperties. +func (t TriageResourceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "recommendationId", t.RecommendationID) + populate(objectMap, "resourceGroup", t.ResourceGroup) + populate(objectMap, "resourceId", t.ResourceID) + populate(objectMap, "resourceName", t.ResourceName) + populate(objectMap, "resourceType", t.ResourceType) + populate(objectMap, "reviewId", t.ReviewID) + populate(objectMap, "subscriptionId", t.SubscriptionID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TriageResourceProperties. +func (t *TriageResourceProperties) 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 "recommendationId": + err = unpopulate(val, "RecommendationID", &t.RecommendationID) + delete(rawMsg, key) + case "resourceGroup": + err = unpopulate(val, "ResourceGroup", &t.ResourceGroup) + delete(rawMsg, key) + case "resourceId": + err = unpopulate(val, "ResourceID", &t.ResourceID) + delete(rawMsg, key) + case "resourceName": + err = unpopulate(val, "ResourceName", &t.ResourceName) + delete(rawMsg, key) + case "resourceType": + err = unpopulate(val, "ResourceType", &t.ResourceType) + delete(rawMsg, key) + case "reviewId": + err = unpopulate(val, "ReviewID", &t.ReviewID) + delete(rawMsg, key) + case "subscriptionId": + err = unpopulate(val, "SubscriptionID", &t.SubscriptionID) + 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 WorkloadListResult. +func (w WorkloadListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", w.NextLink) + populate(objectMap, "value", w.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type WorkloadListResult. +func (w *WorkloadListResult) 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", w, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &w.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &w.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type WorkloadResult. +func (w WorkloadResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", w.ID) + populate(objectMap, "name", w.Name) + populate(objectMap, "subscriptionId", w.SubscriptionID) + populate(objectMap, "subscriptionName", w.SubscriptionName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type WorkloadResult. +func (w *WorkloadResult) 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", w, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &w.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &w.Name) + delete(rawMsg, key) + case "subscriptionId": + err = unpopulate(val, "SubscriptionID", &w.SubscriptionID) + delete(rawMsg, key) + case "subscriptionName": + err = unpopulate(val, "SubscriptionName", &w.SubscriptionName) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { m[k] = nil } else if !reflect.ValueOf(v).IsNil() { m[k] = v } } +func populateTime[T dateTimeConstraints](m map[string]any, k string, t *time.Time) { + if t == nil { + return + } else if azcore.IsNullValue(t) { + m[k] = nil + } else if !reflect.ValueOf(t).IsNil() { + newTime := T(*t) + m[k] = (*T)(&newTime) + } +} + +func populateAny(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else { + m[k] = v + } +} + 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 { @@ -865,3 +2108,20 @@ func unpopulate(data json.RawMessage, fn string, v any) error { } return nil } + +func unpopulateTime[T dateTimeConstraints](data json.RawMessage, fn string, t **time.Time) error { + if data == nil || string(data) == "null" { + return nil + } + var aux T + if err := json.Unmarshal(data, &aux); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + newTime := time.Time(aux) + *t = &newTime + return nil +} + +type dateTimeConstraints interface { + datetime.PlainDate | datetime.PlainTime | datetime.RFC1123 | datetime.RFC3339 | datetime.Unix +} diff --git a/sdk/resourcemanager/advisor/armadvisor/operations_client.go b/sdk/resourcemanager/advisor/armadvisor/operations_client.go index 05d648e41bf6..2eb40328ab43 100644 --- a/sdk/resourcemanager/advisor/armadvisor/operations_client.go +++ b/sdk/resourcemanager/advisor/armadvisor/operations_client.go @@ -1,7 +1,6 @@ // 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. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package armadvisor @@ -22,7 +21,7 @@ type OperationsClient struct { // NewOperationsClient creates a new instance of OperationsClient with the specified values. // - credential - used to authorize requests. Usually a credential from azidentity. -// - options - pass nil to accept the default values. +// - options - Contains optional client configuration. Pass nil to accept the default values. func NewOperationsClient(credential azcore.TokenCredential, options *arm.ClientOptions) (*OperationsClient, error) { cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) if err != nil { @@ -34,9 +33,9 @@ func NewOperationsClient(credential azcore.TokenCredential, options *arm.ClientO return client, nil } -// NewListPager - Lists all the available Advisor REST API operations. +// NewListPager - List the operations for the provider // -// Generated from API version 2020-01-01 +// Generated from API version 2025-05-01-preview // - options - OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. func (client *OperationsClient) NewListPager(options *OperationsClientListOptions) *runtime.Pager[OperationsClientListResponse] { return runtime.NewPager(runtime.PagingHandler[OperationsClientListResponse]{ @@ -62,14 +61,14 @@ func (client *OperationsClient) NewListPager(options *OperationsClientListOption } // listCreateRequest creates the List request. -func (client *OperationsClient) listCreateRequest(ctx context.Context, options *OperationsClientListOptions) (*policy.Request, error) { +func (client *OperationsClient) listCreateRequest(ctx context.Context, _ *OperationsClientListOptions) (*policy.Request, error) { urlPath := "/providers/Microsoft.Advisor/operations" 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", "2020-01-01") + reqQP.Set("api-version", "2025-05-01-preview") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil diff --git a/sdk/resourcemanager/advisor/armadvisor/operations_client_example_test.go b/sdk/resourcemanager/advisor/armadvisor/operations_client_example_test.go new file mode 100644 index 000000000000..045f52251518 --- /dev/null +++ b/sdk/resourcemanager/advisor/armadvisor/operations_client_example_test.go @@ -0,0 +1,51 @@ +// 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) Go Code Generator. DO NOT EDIT. + +package armadvisor_test + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/advisor/armadvisor/v2" + "log" +) + +// Generated from example definition: 2025-05-01-preview/OperationsList.json +func ExampleOperationsClient_NewListPager() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armadvisor.NewClientFactory("", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + pager := clientFactory.NewOperationsClient().NewListPager(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 = armadvisor.OperationsClientListResponse{ + // OperationEntityListResult: armadvisor.OperationEntityListResult{ + // Value: []*armadvisor.OperationEntity{ + // { + // Name: to.Ptr("Microsoft.Advisor/prediction"), + // Display: &armadvisor.OperationDisplayInfo{ + // Provider: to.Ptr("Microsoft Advisor"), + // Resource: to.Ptr("Prediction"), + // Description: to.Ptr("Predicts a recommendation."), + // }, + // }, + // }, + // }, + // } + } +} diff --git a/sdk/resourcemanager/advisor/armadvisor/options.go b/sdk/resourcemanager/advisor/armadvisor/options.go index fa171d6a483e..6ffb6474f35d 100644 --- a/sdk/resourcemanager/advisor/armadvisor/options.go +++ b/sdk/resourcemanager/advisor/armadvisor/options.go @@ -1,10 +1,43 @@ // 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. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package armadvisor +// AssessmentTypesClientListOptions contains the optional parameters for the AssessmentTypesClient.NewListPager method. +type AssessmentTypesClientListOptions struct { + // placeholder for future optional parameters +} + +// AssessmentsClientDeleteOptions contains the optional parameters for the AssessmentsClient.Delete method. +type AssessmentsClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// AssessmentsClientGetOptions contains the optional parameters for the AssessmentsClient.Get method. +type AssessmentsClientGetOptions struct { + // placeholder for future optional parameters +} + +// AssessmentsClientListOptions contains the optional parameters for the AssessmentsClient.NewListPager method. +type AssessmentsClientListOptions struct { + // The page-continuation token to use with a paged version of this API. + Skiptoken *string + + // Limit the result to the specified number of rows. + Top *string +} + +// AssessmentsClientPutOptions contains the optional parameters for the AssessmentsClient.Put method. +type AssessmentsClientPutOptions struct { + // placeholder for future optional parameters +} + +// ClientPredictOptions contains the optional parameters for the Client.Predict method. +type ClientPredictOptions struct { + // placeholder for future optional parameters +} + // ConfigurationsClientCreateInResourceGroupOptions contains the optional parameters for the ConfigurationsClient.CreateInResourceGroup // method. type ConfigurationsClientCreateInResourceGroupOptions struct { @@ -61,13 +94,26 @@ type RecommendationsClientGetOptions struct { // placeholder for future optional parameters } +// RecommendationsClientListByTenantOptions contains the optional parameters for the RecommendationsClient.NewListByTenantPager +// method. +type RecommendationsClientListByTenantOptions struct { + // The filter to apply to the recommendations.
Filter can be applied to properties ['ResourceId', 'ResourceGroup', 'RecommendationTypeGuid', + // '[Category](#category)'] with operators ['eq', 'and', 'or'].
Example:
- $filter=Category eq 'Cost' and ResourceGroup + // eq 'MyResourceGroup' + Filter *string + + // The page-continuation token to use with a paged version of this API. + SkipToken *string + + // The number of recommendations per page if a paged version of this API is being used. + Top *int32 +} + // RecommendationsClientListOptions contains the optional parameters for the RecommendationsClient.NewListPager method. type RecommendationsClientListOptions struct { - // The filter to apply to the recommendations. - // Filter can be applied to properties ['ResourceId', 'ResourceGroup', 'RecommendationTypeGuid', 'Category'] with operators - // ['eq', 'and', 'or']. - // Example: - // - $filter=Category eq 'Cost' and ResourceGroup eq 'MyResourceGroup' + // The filter to apply to the recommendations.
Filter can be applied to properties ['ResourceId', 'ResourceGroup', 'RecommendationTypeGuid', + // '[Category](#category)'] with operators ['eq', 'and', 'or'].
Example:
- $filter=Category eq 'Cost' and ResourceGroup + // eq 'MyResourceGroup' Filter *string // The page-continuation token to use with a paged version of this API. @@ -77,6 +123,39 @@ type RecommendationsClientListOptions struct { Top *int32 } +// RecommendationsClientPatchOptions contains the optional parameters for the RecommendationsClient.Patch method. +type RecommendationsClientPatchOptions struct { + // placeholder for future optional parameters +} + +// ResiliencyReviewsClientGetOptions contains the optional parameters for the ResiliencyReviewsClient.Get method. +type ResiliencyReviewsClientGetOptions struct { + // placeholder for future optional parameters +} + +// ResiliencyReviewsClientListOptions contains the optional parameters for the ResiliencyReviewsClient.NewListPager method. +type ResiliencyReviewsClientListOptions struct { + // The filter to apply.
Filter can be applied to properties ['reviewStatus', 'reviewId'] with operators ['eq', 'and', 'or'].
Example:
- + // $filter=reviewStatus eq 'New' + Filter *string + + // The number of items to skip before starting to collect the result set. + Skip *int32 + + // The number of items to be included in the result. + Top *int32 +} + +// ScoresClientGetOptions contains the optional parameters for the ScoresClient.Get method. +type ScoresClientGetOptions struct { + // placeholder for future optional parameters +} + +// ScoresClientListOptions contains the optional parameters for the ScoresClient.NewListPager method. +type ScoresClientListOptions struct { + // placeholder for future optional parameters +} + // SuppressionsClientCreateOptions contains the optional parameters for the SuppressionsClient.Create method. type SuppressionsClientCreateOptions struct { // placeholder for future optional parameters @@ -100,3 +179,51 @@ type SuppressionsClientListOptions struct { // The number of suppressions per page if a paged version of this API is being used. Top *int32 } + +// TriageRecommendationsClientApproveTriageRecommendationOptions contains the optional parameters for the TriageRecommendationsClient.ApproveTriageRecommendation +// method. +type TriageRecommendationsClientApproveTriageRecommendationOptions struct { + // placeholder for future optional parameters +} + +// TriageRecommendationsClientGetOptions contains the optional parameters for the TriageRecommendationsClient.Get method. +type TriageRecommendationsClientGetOptions struct { + // placeholder for future optional parameters +} + +// TriageRecommendationsClientListOptions contains the optional parameters for the TriageRecommendationsClient.NewListPager +// method. +type TriageRecommendationsClientListOptions struct { + // The number of items to skip before starting to collect the result set. + Skip *int32 + + // The number of items to be included in the result. + Top *int32 +} + +// TriageRecommendationsClientRejectTriageRecommendationOptions contains the optional parameters for the TriageRecommendationsClient.RejectTriageRecommendation +// method. +type TriageRecommendationsClientRejectTriageRecommendationOptions struct { + // placeholder for future optional parameters +} + +// TriageRecommendationsClientResetTriageRecommendationOptions contains the optional parameters for the TriageRecommendationsClient.ResetTriageRecommendation +// method. +type TriageRecommendationsClientResetTriageRecommendationOptions struct { + // placeholder for future optional parameters +} + +// TriageResourcesClientGetOptions contains the optional parameters for the TriageResourcesClient.Get method. +type TriageResourcesClientGetOptions struct { + // placeholder for future optional parameters +} + +// TriageResourcesClientListOptions contains the optional parameters for the TriageResourcesClient.NewListPager method. +type TriageResourcesClientListOptions struct { + // placeholder for future optional parameters +} + +// WorkloadsClientListOptions contains the optional parameters for the WorkloadsClient.NewListPager method. +type WorkloadsClientListOptions struct { + // placeholder for future optional parameters +} diff --git a/sdk/resourcemanager/advisor/armadvisor/recommendationmetadata_client.go b/sdk/resourcemanager/advisor/armadvisor/recommendationmetadata_client.go index 427480ad8c29..84676dc36367 100644 --- a/sdk/resourcemanager/advisor/armadvisor/recommendationmetadata_client.go +++ b/sdk/resourcemanager/advisor/armadvisor/recommendationmetadata_client.go @@ -1,7 +1,6 @@ // 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. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package armadvisor @@ -25,7 +24,7 @@ type RecommendationMetadataClient struct { // NewRecommendationMetadataClient creates a new instance of RecommendationMetadataClient with the specified values. // - credential - used to authorize requests. Usually a credential from azidentity. -// - options - pass nil to accept the default values. +// - options - Contains optional client configuration. Pass nil to accept the default values. func NewRecommendationMetadataClient(credential azcore.TokenCredential, options *arm.ClientOptions) (*RecommendationMetadataClient, error) { cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) if err != nil { @@ -40,7 +39,7 @@ func NewRecommendationMetadataClient(credential azcore.TokenCredential, options // Get - Gets the metadata entity. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2020-01-01 +// Generated from API version 2025-05-01-preview // - name - Name of metadata entity. // - options - RecommendationMetadataClientGetOptions contains the optional parameters for the RecommendationMetadataClient.Get // method. @@ -67,7 +66,7 @@ func (client *RecommendationMetadataClient) Get(ctx context.Context, name string } // getCreateRequest creates the Get request. -func (client *RecommendationMetadataClient) getCreateRequest(ctx context.Context, name string, options *RecommendationMetadataClientGetOptions) (*policy.Request, error) { +func (client *RecommendationMetadataClient) getCreateRequest(ctx context.Context, name string, _ *RecommendationMetadataClientGetOptions) (*policy.Request, error) { urlPath := "/providers/Microsoft.Advisor/metadata/{name}" if name == "" { return nil, errors.New("parameter name cannot be empty") @@ -78,7 +77,7 @@ func (client *RecommendationMetadataClient) getCreateRequest(ctx context.Context return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2020-01-01") + reqQP.Set("api-version", "2025-05-01-preview") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -95,7 +94,7 @@ func (client *RecommendationMetadataClient) getHandleResponse(resp *http.Respons // NewListPager - Gets the list of metadata entities. // -// Generated from API version 2020-01-01 +// Generated from API version 2025-05-01-preview // - options - RecommendationMetadataClientListOptions contains the optional parameters for the RecommendationMetadataClient.NewListPager // method. func (client *RecommendationMetadataClient) NewListPager(options *RecommendationMetadataClientListOptions) *runtime.Pager[RecommendationMetadataClientListResponse] { @@ -122,14 +121,14 @@ func (client *RecommendationMetadataClient) NewListPager(options *Recommendation } // listCreateRequest creates the List request. -func (client *RecommendationMetadataClient) listCreateRequest(ctx context.Context, options *RecommendationMetadataClientListOptions) (*policy.Request, error) { +func (client *RecommendationMetadataClient) listCreateRequest(ctx context.Context, _ *RecommendationMetadataClientListOptions) (*policy.Request, error) { urlPath := "/providers/Microsoft.Advisor/metadata" 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", "2020-01-01") + reqQP.Set("api-version", "2025-05-01-preview") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil diff --git a/sdk/resourcemanager/advisor/armadvisor/recommendationmetadata_client_example_test.go b/sdk/resourcemanager/advisor/armadvisor/recommendationmetadata_client_example_test.go index 676c2547462c..55d41b060847 100644 --- a/sdk/resourcemanager/advisor/armadvisor/recommendationmetadata_client_example_test.go +++ b/sdk/resourcemanager/advisor/armadvisor/recommendationmetadata_client_example_test.go @@ -1,27 +1,24 @@ // 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. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package armadvisor_test import ( "context" - "log" - "github.com/Azure/azure-sdk-for-go/sdk/azidentity" - "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/advisor/armadvisor" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/advisor/armadvisor/v2" + "log" ) -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/7a2ac91de424f271cf91cc8009f3fe9ee8249086/specification/advisor/resource-manager/Microsoft.Advisor/stable/2020-01-01/examples/GetRecommendationMetadataEntity.json +// Generated from example definition: 2025-05-01-preview/GetRecommendationMetadataEntity.json func ExampleRecommendationMetadataClient_Get() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() - clientFactory, err := armadvisor.NewClientFactory("", cred, nil) + clientFactory, err := armadvisor.NewClientFactory("", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } @@ -32,38 +29,43 @@ func ExampleRecommendationMetadataClient_Get() { // 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.MetadataEntity = armadvisor.MetadataEntity{ - // Name: to.Ptr("recommendationType"), - // Type: to.Ptr("Microsoft.Advisor/metadata"), - // ID: to.Ptr("providers/Microsoft.Advisor/metadata/recommendationType"), - // Properties: &armadvisor.MetadataEntityProperties{ - // ApplicableScenarios: []*armadvisor.Scenario{ - // to.Ptr(armadvisor.ScenarioAlerts)}, + // res = armadvisor.RecommendationMetadataClientGetResponse{ + // MetadataEntity: &armadvisor.MetadataEntity{ + // ID: to.Ptr("/providers/Microsoft.Advisor/metadata/recommendationType"), + // Name: to.Ptr("recommendationType"), + // Type: to.Ptr("Microsoft.Advisor/metadata"), + // Properties: &armadvisor.MetadataEntityProperties{ + // DisplayName: to.Ptr("Recommendation Type"), // DependsOn: []*string{ // to.Ptr("category"), - // to.Ptr("impact")}, - // DisplayName: to.Ptr("Recommendation Type"), - // SupportedValues: []*armadvisor.MetadataSupportedValueDetail{ - // { - // DisplayName: to.Ptr("Upgrade your SKU or add more instances to ensure fault tolerance"), - // ID: to.Ptr("6a2b1e70-bd4c-4163-86de-5243d7ac05ee"), - // }, - // { - // DisplayName: to.Ptr("Delete ExpressRoute circuits in the provider status of Not Provisioned"), - // ID: to.Ptr("da6630fb-4286-4996-92a3-a43f5f26dd34"), - // }}, + // to.Ptr("impact"), + // }, + // ApplicableScenarios: []*armadvisor.Scenario{ + // to.Ptr(armadvisor.ScenarioAlerts), // }, - // } + // SupportedValues: []*armadvisor.MetadataSupportedValueDetail{ + // { + // ID: to.Ptr("6a2b1e70-bd4c-4163-86de-5243d7ac05ee"), + // DisplayName: to.Ptr("Upgrade your SKU or add more instances to ensure fault tolerance"), + // }, + // { + // ID: to.Ptr("da6630fb-4286-4996-92a3-a43f5f26dd34"), + // DisplayName: to.Ptr("Delete ExpressRoute circuits in the provider status of Not Provisioned"), + // }, + // }, + // }, + // }, + // } } -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/7a2ac91de424f271cf91cc8009f3fe9ee8249086/specification/advisor/resource-manager/Microsoft.Advisor/stable/2020-01-01/examples/ListRecommendationMetadata.json +// Generated from example definition: 2025-05-01-preview/ListRecommendationMetadata.json func ExampleRecommendationMetadataClient_NewListPager() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() - clientFactory, err := armadvisor.NewClientFactory("", cred, nil) + clientFactory, err := armadvisor.NewClientFactory("", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } @@ -78,70 +80,80 @@ func ExampleRecommendationMetadataClient_NewListPager() { _ = 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.MetadataEntityListResult = armadvisor.MetadataEntityListResult{ - // Value: []*armadvisor.MetadataEntity{ - // { - // Name: to.Ptr("recommendationType"), - // Type: to.Ptr("Microsoft.Advisor/metadata"), - // ID: to.Ptr("providers/Microsoft.Advisor/metadata/recommendationType"), - // Properties: &armadvisor.MetadataEntityProperties{ - // ApplicableScenarios: []*armadvisor.Scenario{ - // to.Ptr(armadvisor.ScenarioAlerts)}, + // page = armadvisor.RecommendationMetadataClientListResponse{ + // MetadataEntityListResult: armadvisor.MetadataEntityListResult{ + // NextLink: to.Ptr("https://management.azure.com/providers/Microsoft.Advisor/metadata?api-version=2025-05-01-preview&$skipToken=abc123"), + // Value: []*armadvisor.MetadataEntity{ + // { + // ID: to.Ptr("/providers/Microsoft.Advisor/metadata/recommendationType"), + // Name: to.Ptr("recommendationType"), + // Type: to.Ptr("Microsoft.Advisor/metadata"), + // Properties: &armadvisor.MetadataEntityProperties{ + // DisplayName: to.Ptr("Recommendation Type"), // DependsOn: []*string{ // to.Ptr("category"), - // to.Ptr("impact")}, - // DisplayName: to.Ptr("Recommendation Type"), - // SupportedValues: []*armadvisor.MetadataSupportedValueDetail{ - // { - // DisplayName: to.Ptr("Upgrade your SKU or add more instances to ensure fault tolerance"), - // ID: to.Ptr("6a2b1e70-bd4c-4163-86de-5243d7ac05ee"), - // }, - // { - // DisplayName: to.Ptr("Delete ExpressRoute circuits in the provider status of Not Provisioned"), - // ID: to.Ptr("da6630fb-4286-4996-92a3-a43f5f26dd34"), - // }}, + // to.Ptr("impact"), + // }, + // ApplicableScenarios: []*armadvisor.Scenario{ + // to.Ptr(armadvisor.ScenarioAlerts), + // }, + // SupportedValues: []*armadvisor.MetadataSupportedValueDetail{ + // { + // ID: to.Ptr("6a2b1e70-bd4c-4163-86de-5243d7ac05ee"), + // DisplayName: to.Ptr("Upgrade your SKU or add more instances to ensure fault tolerance"), + // }, + // { + // ID: to.Ptr("da6630fb-4286-4996-92a3-a43f5f26dd34"), + // DisplayName: to.Ptr("Delete ExpressRoute circuits in the provider status of Not Provisioned"), + // }, // }, // }, - // { - // Name: to.Ptr("recommendationCategory"), - // Type: to.Ptr("Microsoft.Advisor/metadata"), - // ID: to.Ptr("providers/Microsoft.Advisor/metadata/recommendationCategory"), - // Properties: &armadvisor.MetadataEntityProperties{ - // ApplicableScenarios: []*armadvisor.Scenario{ - // to.Ptr(armadvisor.ScenarioAlerts)}, - // DisplayName: to.Ptr("Category"), - // SupportedValues: []*armadvisor.MetadataSupportedValueDetail{ - // { - // DisplayName: to.Ptr("Cost"), - // ID: to.Ptr("Cost"), - // }, - // { - // DisplayName: to.Ptr("Performance"), - // ID: to.Ptr("Performance"), - // }}, + // }, + // { + // ID: to.Ptr("/providers/Microsoft.Advisor/metadata/recommendationCategory"), + // Name: to.Ptr("recommendationCategory"), + // Type: to.Ptr("Microsoft.Advisor/metadata"), + // Properties: &armadvisor.MetadataEntityProperties{ + // DisplayName: to.Ptr("Category"), + // ApplicableScenarios: []*armadvisor.Scenario{ + // to.Ptr(armadvisor.ScenarioAlerts), + // }, + // SupportedValues: []*armadvisor.MetadataSupportedValueDetail{ + // { + // ID: to.Ptr("Cost"), + // DisplayName: to.Ptr("Cost"), + // }, + // { + // ID: to.Ptr("Performance"), + // DisplayName: to.Ptr("Performance"), // }, // }, - // { - // Name: to.Ptr("recommendationImpact"), - // Type: to.Ptr("Microsoft.Advisor/metadata"), - // ID: to.Ptr("providers/Microsoft.Advisor/metadata/recommendationImpact"), - // Properties: &armadvisor.MetadataEntityProperties{ - // DisplayName: to.Ptr("Impact"), - // SupportedValues: []*armadvisor.MetadataSupportedValueDetail{ - // { - // DisplayName: to.Ptr("High"), - // ID: to.Ptr("High"), - // }, - // { - // DisplayName: to.Ptr("Medium"), - // ID: to.Ptr("Medium"), - // }, - // { - // DisplayName: to.Ptr("Low"), - // ID: to.Ptr("Low"), - // }}, + // }, + // }, + // { + // ID: to.Ptr("/providers/Microsoft.Advisor/metadata/recommendationImpact"), + // Name: to.Ptr("recommendationImpact"), + // Type: to.Ptr("Microsoft.Advisor/metadata"), + // Properties: &armadvisor.MetadataEntityProperties{ + // DisplayName: to.Ptr("Impact"), + // SupportedValues: []*armadvisor.MetadataSupportedValueDetail{ + // { + // ID: to.Ptr("High"), + // DisplayName: to.Ptr("High"), // }, - // }}, - // } + // { + // ID: to.Ptr("Medium"), + // DisplayName: to.Ptr("Medium"), + // }, + // { + // ID: to.Ptr("Low"), + // DisplayName: to.Ptr("Low"), + // }, + // }, + // }, + // }, + // }, + // }, + // } } } diff --git a/sdk/resourcemanager/advisor/armadvisor/recommendations_client.go b/sdk/resourcemanager/advisor/armadvisor/recommendations_client.go index c6677b4a7dae..04ef9bb1c8d4 100644 --- a/sdk/resourcemanager/advisor/armadvisor/recommendations_client.go +++ b/sdk/resourcemanager/advisor/armadvisor/recommendations_client.go @@ -1,7 +1,6 @@ // 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. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package armadvisor @@ -26,9 +25,9 @@ type RecommendationsClient struct { } // NewRecommendationsClient creates a new instance of RecommendationsClient with the specified values. -// - subscriptionID - The Azure subscription ID. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. // - credential - used to authorize requests. Usually a credential from azidentity. -// - options - pass nil to accept the default values. +// - options - Contains optional client configuration. Pass nil to accept the default values. func NewRecommendationsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*RecommendationsClient, error) { cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) if err != nil { @@ -43,9 +42,12 @@ func NewRecommendationsClient(subscriptionID string, credential azcore.TokenCred // Generate - Initiates the recommendation generation or computation process for a subscription. This operation is asynchronous. // The generated recommendations are stored in a cache in the Advisor service. +// +// Initiates the recommendation generation or computation process for a subscription. This operation is asynchronous. The +// generated recommendations are stored in a cache in the Advisor service. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2020-01-01 +// Generated from API version 2025-05-01-preview // - options - RecommendationsClientGenerateOptions contains the optional parameters for the RecommendationsClient.Generate // method. func (client *RecommendationsClient) Generate(ctx context.Context, options *RecommendationsClientGenerateOptions) (RecommendationsClientGenerateResponse, error) { @@ -71,7 +73,7 @@ func (client *RecommendationsClient) Generate(ctx context.Context, options *Reco } // generateCreateRequest creates the Generate request. -func (client *RecommendationsClient) generateCreateRequest(ctx context.Context, options *RecommendationsClientGenerateOptions) (*policy.Request, error) { +func (client *RecommendationsClient) generateCreateRequest(ctx context.Context, _ *RecommendationsClientGenerateOptions) (*policy.Request, error) { urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Advisor/generateRecommendations" if client.subscriptionID == "" { return nil, errors.New("parameter client.subscriptionID cannot be empty") @@ -82,9 +84,8 @@ func (client *RecommendationsClient) generateCreateRequest(ctx context.Context, return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2020-01-01") + reqQP.Set("api-version", "2025-05-01-preview") req.Raw().URL.RawQuery = reqQP.Encode() - req.Raw().Header["Accept"] = []string{"application/json"} return req, nil } @@ -95,7 +96,12 @@ func (client *RecommendationsClient) generateHandleResponse(resp *http.Response) result.Location = &val } if val := resp.Header.Get("Retry-After"); val != "" { - result.RetryAfter = &val + retryAfter32, err := strconv.ParseInt(val, 10, 32) + retryAfter := int32(retryAfter32) + if err != nil { + return RecommendationsClientGenerateResponse{}, err + } + result.RetryAfter = &retryAfter } return result, nil } @@ -103,8 +109,8 @@ func (client *RecommendationsClient) generateHandleResponse(resp *http.Response) // Get - Obtains details of a cached recommendation. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2020-01-01 -// - resourceURI - The fully qualified Azure Resource Manager identifier of the resource to which the recommendation applies. +// Generated from API version 2025-05-01-preview +// - resourceURI - The fully qualified Azure Resource manager identifier of the resource. // - recommendationID - The recommendation ID. // - options - RecommendationsClientGetOptions contains the optional parameters for the RecommendationsClient.Get method. func (client *RecommendationsClient) Get(ctx context.Context, resourceURI string, recommendationID string, options *RecommendationsClientGetOptions) (RecommendationsClientGetResponse, error) { @@ -130,12 +136,12 @@ func (client *RecommendationsClient) Get(ctx context.Context, resourceURI string } // getCreateRequest creates the Get request. -func (client *RecommendationsClient) getCreateRequest(ctx context.Context, resourceURI string, recommendationID string, options *RecommendationsClientGetOptions) (*policy.Request, error) { +func (client *RecommendationsClient) getCreateRequest(ctx context.Context, resourceURI string, recommendationID string, _ *RecommendationsClientGetOptions) (*policy.Request, error) { urlPath := "/{resourceUri}/providers/Microsoft.Advisor/recommendations/{recommendationId}" if resourceURI == "" { return nil, errors.New("parameter resourceURI cannot be empty") } - urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", url.PathEscape(resourceURI)) + urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", resourceURI) if recommendationID == "" { return nil, errors.New("parameter recommendationID cannot be empty") } @@ -145,7 +151,7 @@ func (client *RecommendationsClient) getCreateRequest(ctx context.Context, resou return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2020-01-01") + reqQP.Set("api-version", "2025-05-01-preview") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -161,11 +167,13 @@ func (client *RecommendationsClient) getHandleResponse(resp *http.Response) (Rec } // GetGenerateStatus - Retrieves the status of the recommendation computation or generation process. Invoke this API after -// calling the generation recommendation. The URI of this API is returned in the Location field of the -// response header. +// calling the generation recommendation. The URI of this API is returned in the Location field of the response header. +// +// Retrieves the status of the recommendation computation or generation process. Invoke this API after calling the generation +// recommendation. The URI of this API is returned in the Location field of the response header. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2020-01-01 +// Generated from API version 2025-05-01-preview // - operationID - The operation ID, which can be found from the Location field in the generate recommendation response header. // - options - RecommendationsClientGetGenerateStatusOptions contains the optional parameters for the RecommendationsClient.GetGenerateStatus // method. @@ -187,11 +195,12 @@ func (client *RecommendationsClient) GetGenerateStatus(ctx context.Context, oper err = runtime.NewResponseError(httpResp) return RecommendationsClientGetGenerateStatusResponse{}, err } - return RecommendationsClientGetGenerateStatusResponse{}, nil + resp, err := client.getGenerateStatusHandleResponse(httpResp) + return resp, err } // getGenerateStatusCreateRequest creates the GetGenerateStatus request. -func (client *RecommendationsClient) getGenerateStatusCreateRequest(ctx context.Context, operationID string, options *RecommendationsClientGetGenerateStatusOptions) (*policy.Request, error) { +func (client *RecommendationsClient) getGenerateStatusCreateRequest(ctx context.Context, operationID string, _ *RecommendationsClientGetGenerateStatusOptions) (*policy.Request, error) { urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Advisor/generateRecommendations/{operationId}" if client.subscriptionID == "" { return nil, errors.New("parameter client.subscriptionID cannot be empty") @@ -206,16 +215,29 @@ func (client *RecommendationsClient) getGenerateStatusCreateRequest(ctx context. return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2020-01-01") + reqQP.Set("api-version", "2025-05-01-preview") req.Raw().URL.RawQuery = reqQP.Encode() - req.Raw().Header["Accept"] = []string{"application/json"} return req, nil } +// getGenerateStatusHandleResponse handles the GetGenerateStatus response. +func (client *RecommendationsClient) getGenerateStatusHandleResponse(resp *http.Response) (RecommendationsClientGetGenerateStatusResponse, error) { + result := RecommendationsClientGetGenerateStatusResponse{} + if val := resp.Header.Get("Retry-After"); val != "" { + retryAfter32, err := strconv.ParseInt(val, 10, 32) + retryAfter := int32(retryAfter32) + if err != nil { + return RecommendationsClientGetGenerateStatusResponse{}, err + } + result.RetryAfter = &retryAfter + } + return result, nil +} + // NewListPager - Obtains cached recommendations for a subscription. The recommendations are generated or computed by invoking // generateRecommendations. // -// Generated from API version 2020-01-01 +// Generated from API version 2025-05-01-preview // - options - RecommendationsClientListOptions contains the optional parameters for the RecommendationsClient.NewListPager // method. func (client *RecommendationsClient) NewListPager(options *RecommendationsClientListOptions) *runtime.Pager[RecommendationsClientListResponse] { @@ -253,16 +275,16 @@ func (client *RecommendationsClient) listCreateRequest(ctx context.Context, opti return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2020-01-01") if options != nil && options.Filter != nil { reqQP.Set("$filter", *options.Filter) } - if options != nil && options.Top != nil { - reqQP.Set("$top", strconv.FormatInt(int64(*options.Top), 10)) - } if options != nil && options.SkipToken != nil { reqQP.Set("$skipToken", *options.SkipToken) } + if options != nil && options.Top != nil { + reqQP.Set("$top", strconv.FormatInt(int64(*options.Top), 10)) + } + reqQP.Set("api-version", "2025-05-01-preview") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -276,3 +298,134 @@ func (client *RecommendationsClient) listHandleResponse(resp *http.Response) (Re } return result, nil } + +// NewListByTenantPager - Obtains cached recommendations for a subscription. The recommendations are generated or computed +// by invoking generateRecommendations. +// +// Generated from API version 2025-05-01-preview +// - resourceURI - The fully qualified Azure Resource manager identifier of the resource. +// - options - RecommendationsClientListByTenantOptions contains the optional parameters for the RecommendationsClient.NewListByTenantPager +// method. +func (client *RecommendationsClient) NewListByTenantPager(resourceURI string, options *RecommendationsClientListByTenantOptions) *runtime.Pager[RecommendationsClientListByTenantResponse] { + return runtime.NewPager(runtime.PagingHandler[RecommendationsClientListByTenantResponse]{ + More: func(page RecommendationsClientListByTenantResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *RecommendationsClientListByTenantResponse) (RecommendationsClientListByTenantResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "RecommendationsClient.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, resourceURI, options) + }, nil) + if err != nil { + return RecommendationsClientListByTenantResponse{}, err + } + return client.listByTenantHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByTenantCreateRequest creates the ListByTenant request. +func (client *RecommendationsClient) listByTenantCreateRequest(ctx context.Context, resourceURI string, options *RecommendationsClientListByTenantOptions) (*policy.Request, error) { + urlPath := "/{resourceUri}/providers/Microsoft.Advisor/recommendations" + if resourceURI == "" { + return nil, errors.New("parameter resourceURI cannot be empty") + } + 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() + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + if options != nil && options.SkipToken != nil { + reqQP.Set("$skipToken", *options.SkipToken) + } + if options != nil && options.Top != nil { + reqQP.Set("$top", strconv.FormatInt(int64(*options.Top), 10)) + } + reqQP.Set("api-version", "2025-05-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 *RecommendationsClient) listByTenantHandleResponse(resp *http.Response) (RecommendationsClientListByTenantResponse, error) { + result := RecommendationsClientListByTenantResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ResourceRecommendationBaseListResult); err != nil { + return RecommendationsClientListByTenantResponse{}, err + } + return result, nil +} + +// Patch - Update the tracked properties of a Recommendation. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-05-01-preview +// - resourceURI - The fully qualified Azure Resource manager identifier of the resource. +// - recommendationID - The recommendation ID. +// - trackedProperties - The properties to update on the recommendation. +// - options - RecommendationsClientPatchOptions contains the optional parameters for the RecommendationsClient.Patch method. +func (client *RecommendationsClient) Patch(ctx context.Context, resourceURI string, recommendationID string, trackedProperties TrackedRecommendationPropertiesPayload, options *RecommendationsClientPatchOptions) (RecommendationsClientPatchResponse, error) { + var err error + const operationName = "RecommendationsClient.Patch" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.patchCreateRequest(ctx, resourceURI, recommendationID, trackedProperties, options) + if err != nil { + return RecommendationsClientPatchResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return RecommendationsClientPatchResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return RecommendationsClientPatchResponse{}, err + } + resp, err := client.patchHandleResponse(httpResp) + return resp, err +} + +// patchCreateRequest creates the Patch request. +func (client *RecommendationsClient) patchCreateRequest(ctx context.Context, resourceURI string, recommendationID string, trackedProperties TrackedRecommendationPropertiesPayload, _ *RecommendationsClientPatchOptions) (*policy.Request, error) { + urlPath := "/{resourceUri}/providers/Microsoft.Advisor/recommendations/{recommendationId}" + if resourceURI == "" { + return nil, errors.New("parameter resourceURI cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", resourceURI) + if recommendationID == "" { + return nil, errors.New("parameter recommendationID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{recommendationId}", url.PathEscape(recommendationID)) + 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", "2025-05-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, trackedProperties); err != nil { + return nil, err + } + return req, nil +} + +// patchHandleResponse handles the Patch response. +func (client *RecommendationsClient) patchHandleResponse(resp *http.Response) (RecommendationsClientPatchResponse, error) { + result := RecommendationsClientPatchResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ResourceRecommendationBase); err != nil { + return RecommendationsClientPatchResponse{}, err + } + return result, nil +} diff --git a/sdk/resourcemanager/advisor/armadvisor/recommendations_client_example_test.go b/sdk/resourcemanager/advisor/armadvisor/recommendations_client_example_test.go index e2702bfb4609..05f49f954a23 100644 --- a/sdk/resourcemanager/advisor/armadvisor/recommendations_client_example_test.go +++ b/sdk/resourcemanager/advisor/armadvisor/recommendations_client_example_test.go @@ -1,28 +1,26 @@ // 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. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package armadvisor_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/advisor/armadvisor" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/advisor/armadvisor/v2" + "log" + "time" ) -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/7a2ac91de424f271cf91cc8009f3fe9ee8249086/specification/advisor/resource-manager/Microsoft.Advisor/stable/2020-01-01/examples/GenerateRecommendations.json +// Generated from example definition: 2025-05-01-preview/GenerateRecommendations.json func ExampleRecommendationsClient_Generate() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() - clientFactory, err := armadvisor.NewClientFactory("", cred, nil) + clientFactory, err := armadvisor.NewClientFactory("12345678-1234-1234-1234-123456789012", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } @@ -32,38 +30,190 @@ func ExampleRecommendationsClient_Generate() { } } -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/7a2ac91de424f271cf91cc8009f3fe9ee8249086/specification/advisor/resource-manager/Microsoft.Advisor/stable/2020-01-01/examples/EmptyResponse.json +// Generated from example definition: 2025-05-01-preview/GetRecommendationDetailServiceGroupResourceUri.json +func ExampleRecommendationsClient_Get_getRecommendationDetailServiceGroupResourceUri() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armadvisor.NewClientFactory("", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewRecommendationsClient().Get(ctx, "providers/microsoft.management/serviceGroup/serviceGroupXYZ", "37c93209-4bfb-4f3b-8874-ccc718f7a467", 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 = armadvisor.RecommendationsClientGetResponse{ + // ResourceRecommendationBase: &armadvisor.ResourceRecommendationBase{ + // ID: to.Ptr("/providers/microsoft.management/serviceGroup/serviceGroupXYZ/providers/Microsoft.Advisor/recommendations/37c93209-4bfb-4f3b-8874-ccc718f7a467"), + // Name: to.Ptr("37c93209-4bfb-4f3b-8874-ccc718f7a467"), + // Properties: &armadvisor.RecommendationProperties{ + // Category: to.Ptr(armadvisor.CategoryHighAvailability), + // Impact: to.Ptr(armadvisor.ImpactMedium), + // ImpactedField: to.Ptr("Microsoft.Management/serviceGroup"), + // ImpactedValue: to.Ptr("serviceGroupXYZ"), + // LastUpdated: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2025-04-24T22:24:43.3216408Z"); return t}()), + // Risk: to.Ptr(armadvisor.RiskWarning), + // ShortDescription: &armadvisor.ShortDescription{ + // Problem: to.Ptr("To ensure high availability add one or more virtual machines to this availability set"), + // Solution: to.Ptr("To ensure high availability add one or more virtual machines to this availability set"), + // }, + // ResourceMetadata: &armadvisor.ResourceMetadata{ + // ResourceID: to.Ptr("/providers/microsoft.management/serviceGroup/serviceGroupXYZ"), + // Action: map[string]any{ + // "additionalProperties": map[string]any{ + // "actionType": "Document", + // "link": "https://link3", + // "caption": "Enable Soft Delete to protect blob data", + // "description": "Enable Soft Delete to protect blob data", + // }, + // "metadata": map[string]any{ + // "id": "/providers/microsoft.management/serviceGroup/serviceGroupXYZ", + // }, + // }, + // Singular: to.Ptr("Availability set"), + // Plural: to.Ptr("Availability sets"), + // }, + // Actions: []map[string]any{ + // map[string]any{ + // "additionalProperties": map[string]any{ + // "actionType": "Document", + // "link": "https://link1", + // "caption": "Enable Soft Delete to protect blob data", + // "description": "Enable Soft Delete to protect blob data", + // }, + // "metadata": map[string]any{ + // "id": "/providers/microsoft.management/serviceGroup/serviceGroupXYZ", + // }, + // }, + // }, + // Description: to.Ptr("After enabling Soft Delete, deleted data transitions to a soft deleted state instead of being permanently deleted. When data is overwritten, a soft deleted snapshot is generated to save the state of the overwritten data. You can configure the amount of time soft deleted data is recoverable before it permanently expires."), + // Label: to.Ptr("Enable Soft Delete"), + // LearnMoreLink: to.Ptr("https://link2"), + // PotentialBenefits: to.Ptr("Save and recover your data when blobs or blob snapshots are accidentally overwritten or deleted"), + // Tracked: to.Ptr(false), + // }, + // Type: to.Ptr("Microsoft.Advisor/recommendations"), + // }, + // } +} + +// Generated from example definition: 2025-05-01-preview/GetRecommendationDetailSubscriptionResourceUri.json +func ExampleRecommendationsClient_Get_getRecommendationDetailSubscriptionResourceUri() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armadvisor.NewClientFactory("", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewRecommendationsClient().Get(ctx, "subscriptions/a5481ee1-95df-47d0-85d4-dd3f0dfa19bc/resourceGroups/resourceGroup/providers/Microsoft.Compute/availabilitysets/armavset", "bd27ddc6-1312-4067-b4af-cbb45e32cfd7", 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 = armadvisor.RecommendationsClientGetResponse{ + // ResourceRecommendationBase: &armadvisor.ResourceRecommendationBase{ + // ID: to.Ptr("/subscriptions/a5481ee1-95df-47d0-85d4-dd3f0dfa19bc/resourceGroups/resourceGroup/providers/Microsoft.Compute/availabilitysets/armavset/providers/Microsoft.Advisor/recommendations/bd27ddc6-1312-4067-b4af-cbb45e32cfd7"), + // Name: to.Ptr("bd27ddc6-1312-4067-b4af-cbb45e32cfd7"), + // Properties: &armadvisor.RecommendationProperties{ + // Category: to.Ptr(armadvisor.CategorySecurity), + // Impact: to.Ptr(armadvisor.ImpactMedium), + // ImpactedField: to.Ptr("Microsoft.Compute/availabilitysets"), + // ImpactedValue: to.Ptr("armavset"), + // LastUpdated: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2017-02-24T22:24:43.3216408Z"); return t}()), + // Risk: to.Ptr(armadvisor.RiskWarning), + // ShortDescription: &armadvisor.ShortDescription{ + // Problem: to.Ptr("Monitoring agent should be installed on your machines"), + // Solution: to.Ptr("Monitoring agent should be installed on your machines"), + // }, + // Remediation: map[string]any{ + // "additionalProperties": map[string]any{ + // "httpMethod": "POST", + // "uri": "uri", + // "details": "link to document", + // }, + // }, + // ResourceMetadata: &armadvisor.ResourceMetadata{ + // ResourceID: to.Ptr("/subscriptions/a5481ee1-95df-47d0-85d4-dd3f0dfa19bc/resourceGroups/resourceGroup/providers/Microsoft.Compute/availabilitysets/armavset"), + // Source: to.Ptr("/subscriptions/a5481ee1-95df-47d0-85d4-dd3f0dfa19bc/resourceGroups/resourceGroup/providers/Microsoft.Compute/availabilitysets/armavset/providers/Microsoft.Security/assessments/15e912ef-221a-4efe-80d2-df5671cdd5f5"), + // Action: map[string]any{ + // "additionalProperties": map[string]any{ + // "actionType": "Document", + // "link": "https://link3", + // "caption": "Enable Soft Delete to protect blob data", + // "description": "Enable Soft Delete to protect blob data", + // }, + // "metadata": map[string]any{ + // "id": "/subscriptions/a5481ee1-95df-47d0-85d4-dd3f0dfa19bc/resourceGroups/resourceGroup/providers/Microsoft.Compute/availabilitysets/armavset", + // }, + // }, + // Singular: to.Ptr("Availability set"), + // Plural: to.Ptr("Availability sets"), + // }, + // Actions: []map[string]any{ + // map[string]any{ + // "additionalProperties": map[string]any{ + // "actionType": "Document", + // "link": "https://link1", + // "caption": "Enable Soft Delete to protect blob data", + // "description": "Enable Soft Delete to protect blob data", + // }, + // "metadata": map[string]any{ + // "id": "/subscriptions/a5481ee1-95df-47d0-85d4-dd3f0dfa19bc", + // }, + // }, + // }, + // Description: to.Ptr("After enabling Soft Delete, deleted data transitions to a soft deleted state instead of being permanently deleted. When data is overwritten, a soft deleted snapshot is generated to save the state of the overwritten data. You can configure the amount of time soft deleted data is recoverable before it permanently expires."), + // Label: to.Ptr("Enable Soft Delete"), + // LearnMoreLink: to.Ptr("https://link2"), + // PotentialBenefits: to.Ptr("Save and recover your data when blobs or blob snapshots are accidentally overwritten or deleted"), + // Tracked: to.Ptr(false), + // }, + // Type: to.Ptr("Microsoft.Advisor/recommendations"), + // }, + // } +} + +// Generated from example definition: 2025-05-01-preview/EmptyResponse.json func ExampleRecommendationsClient_GetGenerateStatus() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() - clientFactory, err := armadvisor.NewClientFactory("", cred, nil) + clientFactory, err := armadvisor.NewClientFactory("12345678-1234-1234-1234-123456789012", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } - _, err = clientFactory.NewRecommendationsClient().GetGenerateStatus(ctx, "operationGUID", nil) + _, err = clientFactory.NewRecommendationsClient().GetGenerateStatus(ctx, "123e4567-e89b-12d3-a456-426614174000", 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/7a2ac91de424f271cf91cc8009f3fe9ee8249086/specification/advisor/resource-manager/Microsoft.Advisor/stable/2020-01-01/examples/ListRecommendations.json +// Generated from example definition: 2025-05-01-preview/ListRecommendationsSubscriptionResourceUri.json func ExampleRecommendationsClient_NewListPager() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() - clientFactory, err := armadvisor.NewClientFactory("", cred, nil) + clientFactory, err := armadvisor.NewClientFactory("a5481ee1-95df-47d0-85d4-dd3f0dfa19bc", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } - pager := clientFactory.NewRecommendationsClient().NewListPager(&armadvisor.RecommendationsClientListOptions{Filter: nil, - Top: to.Ptr[int32](10), - SkipToken: nil, - }) + pager := clientFactory.NewRecommendationsClient().NewListPager(&armadvisor.RecommendationsClientListOptions{ + Top: to.Ptr[int32](10)}) for pager.More() { page, err := pager.NextPage(ctx) if err != nil { @@ -74,174 +224,375 @@ func ExampleRecommendationsClient_NewListPager() { _ = 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.ResourceRecommendationBaseListResult = armadvisor.ResourceRecommendationBaseListResult{ - // Value: []*armadvisor.ResourceRecommendationBase{ - // { - // Name: to.Ptr("recGUID1"), - // Type: to.Ptr("Microsoft.Advisor/recommendations"), - // ID: to.Ptr("/resourceUri/providers/Microsoft.Advisor/recommendations/recGUID1"), - // Properties: &armadvisor.RecommendationProperties{ - // Description: to.Ptr("After enabling Soft Delete, deleted data transitions to a soft deleted state instead of being permanently deleted. When data is overwritten, a soft deleted snapshot is generated to save the state of the overwritten data. You can configure the amount of time soft deleted data is recoverable before it permanently expires."), - // Actions: []map[string]any{ - // map[string]any{ - // "description": "Enable Soft Delete to protect blob data", - // "actionType": "Document", - // "caption": "Enable Soft Delete to protect blob data", - // "link": "https://link1", - // "metadata": map[string]any{ - // "id": "/subscriptions/subscriptionId", + // page = armadvisor.RecommendationsClientListResponse{ + // ResourceRecommendationBaseListResult: armadvisor.ResourceRecommendationBaseListResult{ + // NextLink: to.Ptr("https://management.azure.com/subscriptions/a5481ee1-95df-47d0-85d4-dd3f0dfa19bc/providers/Microsoft.Advisor/recommendations?api-version=2025-05-01-preview&$top=10&$skiptoken=skiptoken"), + // Value: []*armadvisor.ResourceRecommendationBase{ + // { + // ID: to.Ptr("/subscriptions/a5481ee1-95df-47d0-85d4-dd3f0dfa19bc/resourceGroups/resourceGroup/providers/Microsoft.Compute/availabilitysets/armavset/providers/Microsoft.Advisor/recommendations/bd27ddc6-1312-4067-b4af-cbb45e32cfd7"), + // Name: to.Ptr("bd27ddc6-1312-4067-b4af-cbb45e32cfd7"), + // Type: to.Ptr("Microsoft.Advisor/recommendations"), + // Properties: &armadvisor.RecommendationProperties{ + // Category: to.Ptr(armadvisor.CategoryHighAvailability), + // Impact: to.Ptr(armadvisor.ImpactMedium), + // ImpactedField: to.Ptr("Microsoft.Compute/availabilitySets"), + // ImpactedValue: to.Ptr("armavset"), + // LastUpdated: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2017-02-24T22:24:43.3216408Z"); return t}()), + // Risk: to.Ptr(armadvisor.RiskWarning), + // Remediation: map[string]any{ + // "additionalProperties": map[string]any{ + // "httpMethod": "POST", + // "uri": "uri", + // "details": "link to document", // }, - // }}, - // Category: to.Ptr(armadvisor.CategoryHighAvailability), - // Impact: to.Ptr(armadvisor.ImpactMedium), - // ImpactedField: to.Ptr("Microsoft.Compute/availabilitySets"), - // ImpactedValue: to.Ptr("armavset"), - // Label: to.Ptr("Enable Soft Delete"), - // LastUpdated: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2017-02-24T22:24:43.321Z"); return t}()), - // LearnMoreLink: to.Ptr("https://link2"), - // PotentialBenefits: to.Ptr("Save and recover your data when blobs or blob snapshots are accidentally overwritten or deleted"), - // Remediation: map[string]any{ - // "httpMethod": "POST", - // "uri": "uri", - // "details": "link to document", - // }, - // ResourceMetadata: &armadvisor.ResourceMetadata{ - // Action: map[string]any{ - // "description": "Enable Soft Delete to protect blob data", - // "actionType": "Document", - // "caption": "Enable Soft Delete to protect blob data", - // "link": "https://link3", - // "metadata": map[string]any{ - // "id": "/subscriptions/subscriptionId", + // }, + // ShortDescription: &armadvisor.ShortDescription{ + // Problem: to.Ptr("To ensure high availability add one or more virtual machines to this availability set"), + // Solution: to.Ptr("To ensure high availability add one or more virtual machines to this availability set"), + // }, + // ResourceMetadata: &armadvisor.ResourceMetadata{ + // ResourceID: to.Ptr("/subscriptions/a5481ee1-95df-47d0-85d4-dd3f0dfa19bc/resourceGroups/resourceGroup/providers/Microsoft.Compute/availabilitysets/armavset"), + // Action: map[string]any{ + // "additionalProperties": map[string]any{ + // "actionType": "Document", + // "link": "https://link3", + // "caption": "Enable Soft Delete to protect blob data", + // "description": "Enable Soft Delete to protect blob data", + // }, + // "metadata": map[string]any{ + // "id": "/subscriptions/a5481ee1-95df-47d0-85d4-dd3f0dfa19bc", + // }, + // }, + // Singular: to.Ptr("Availability set"), + // Plural: to.Ptr("Availability sets"), + // }, + // Actions: []map[string]any{ + // map[string]any{ + // "additionalProperties": map[string]any{ + // "actionType": "Document", + // "link": "https://link1", + // "caption": "Enable Soft Delete to protect blob data", + // "description": "Enable Soft Delete to protect blob data", + // }, + // "metadata": map[string]any{ + // "id": "/subscriptions/a5481ee1-95df-47d0-85d4-dd3f0dfa19bc", + // }, // }, // }, - // Plural: to.Ptr("Availability sets"), - // ResourceID: to.Ptr("/subscriptions/subscriptionId/resourceGroups/resourceGroup/providers/Microsoft.Compute/availabilitysets/abc"), - // Singular: to.Ptr("Availability set"), + // Description: to.Ptr("After enabling Soft Delete, deleted data transitions to a soft deleted state instead of being permanently deleted. When data is overwritten, a soft deleted snapshot is generated to save the state of the overwritten data. You can configure the amount of time soft deleted data is recoverable before it permanently expires."), + // Label: to.Ptr("Enable Soft Delete"), + // LearnMoreLink: to.Ptr("https://link2"), + // PotentialBenefits: to.Ptr("Save and recover your data when blobs or blob snapshots are accidentally overwritten or deleted"), + // Tracked: to.Ptr(false), // }, - // Risk: to.Ptr(armadvisor.RiskWarning), - // ShortDescription: &armadvisor.ShortDescription{ - // Problem: to.Ptr("This availability set is not configured for fault tolerance"), - // Solution: to.Ptr("To ensure high availability add one or more virtual machines to this availability set"), + // }, + // { + // ID: to.Ptr("/subscriptions/a5481ee1-95df-47d0-85d4-dd3f0dfa19bc/resourceGroups/resourceGroup/providers/Microsoft.Compute/virtualMachines/xyz/providers/Microsoft.Advisor/recommendations/1b266c91-3a92-4423-8aa2-ee13a6d90f47"), + // Name: to.Ptr("1b266c91-3a92-4423-8aa2-ee13a6d90f47"), + // Type: to.Ptr("Microsoft.Advisor/recommendations"), + // Properties: &armadvisor.RecommendationProperties{ + // Category: to.Ptr(armadvisor.CategorySecurity), + // Impact: to.Ptr(armadvisor.ImpactMedium), + // ImpactedField: to.Ptr("Microsoft.Compute/virtualMachines"), + // ImpactedValue: to.Ptr("xyz"), + // LastUpdated: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2017-02-24T22:24:43.3216408Z"); return t}()), + // Risk: to.Ptr(armadvisor.RiskWarning), + // ShortDescription: &armadvisor.ShortDescription{ + // Problem: to.Ptr("Monitoring agent should be installed on your machines"), + // Solution: to.Ptr("Monitoring agent should be installed on your machines"), + // }, + // ResourceMetadata: &armadvisor.ResourceMetadata{ + // ResourceID: to.Ptr("/subscriptions/a5481ee1-95df-47d0-85d4-dd3f0dfa19bc/resourceGroups/resourceGroup/providers/Microsoft.Compute/virtualMachines/xyz"), + // Source: to.Ptr("/subscriptions/a5481ee1-95df-47d0-85d4-dd3f0dfa19bc/resourceGroups/resourceGroup/providers/Microsoft.Compute/virtualMachines/xyz/providers/Microsoft.Security/assessments/15e912ef-221a-4efe-80d2-df5671cdd5f5"), + // Action: map[string]any{ + // "additionalProperties": map[string]any{ + // "actionType": "Document", + // "link": "https://link3", + // "caption": "Enable Soft Delete to protect blob data", + // "description": "Enable Soft Delete to protect blob data", + // }, + // "metadata": map[string]any{ + // "id": "/subscriptions/a5481ee1-95df-47d0-85d4-dd3f0dfa19bc", + // }, + // }, + // Singular: to.Ptr("Virtual machine"), + // Plural: to.Ptr("Virtual machines"), + // }, + // Actions: []map[string]any{ + // map[string]any{ + // "additionalProperties": map[string]any{ + // "actionType": "Document", + // "link": "https://link1", + // "caption": "Enable Soft Delete to protect blob data", + // "description": "Enable Soft Delete to protect blob data", + // }, + // "metadata": map[string]any{ + // "id": "/subscriptions/a5481ee1-95df-47d0-85d4-dd3f0dfa19bc", + // }, + // }, + // }, + // Description: to.Ptr("Monitoring agent should be installed on your machines."), + // Label: to.Ptr("Enable monitoring agent"), + // LearnMoreLink: to.Ptr("https://link2"), + // PotentialBenefits: to.Ptr("Protect and monitor machine"), + // Tracked: to.Ptr(true), + // TrackedProperties: &armadvisor.TrackedRecommendationProperties{ + // State: to.Ptr(armadvisor.StatePostponed), + // PostponedTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-10-01T00:00:00Z"); return t}()), + // Reason: to.Ptr(armadvisor.ReasonRiskAccepted), + // Priority: to.Ptr(armadvisor.PriorityHigh), + // }, + // ResourceWorkload: &armadvisor.RecommendationPropertiesResourceWorkload{ + // ID: to.Ptr("0560dbdb-f207-4690-b4ba-1fc0c3a0f082"), + // Name: to.Ptr("Critical VM Workload"), + // }, + // Review: &armadvisor.RecommendationPropertiesReview{ + // ID: to.Ptr("/subscriptions/a5481ee1-95df-47d0-85d4-dd3f0dfa19bc/providers/Microsoft.Advisor/assessments/MCWAR1"), + // Name: to.Ptr("Monthly WAF Review 09/23"), + // }, + // SourceSystem: to.Ptr("CxObserve"), + // Notes: to.Ptr("This is a note"), // }, // }, // }, - // { - // Name: to.Ptr("recGUID2"), - // Type: to.Ptr("Microsoft.Advisor/recommendations"), - // ID: to.Ptr("/resourceUri/providers/Microsoft.Advisor/recommendations/recGUID2"), - // Properties: &armadvisor.RecommendationProperties{ - // Description: to.Ptr("Monitoring agent should be installed on your machines."), - // Actions: []map[string]any{ - // map[string]any{ - // "description": "Enable Soft Delete to protect blob data", - // "actionType": "Document", - // "caption": "Enable Soft Delete to protect blob data", - // "link": "https://link1", - // "metadata": map[string]any{ - // "id": "/subscriptions/subscriptionId", + // }, + // } + } +} + +// Generated from example definition: 2025-05-01-preview/ListRecommendationsServiceGroupResourceUri.json +func ExampleRecommendationsClient_NewListByTenantPager() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armadvisor.NewClientFactory("", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + pager := clientFactory.NewRecommendationsClient().NewListByTenantPager("providers/microsoft.management/serviceGroups/serviceGroupXYZ", &armadvisor.RecommendationsClientListByTenantOptions{ + Top: to.Ptr[int32](10)}) + 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 = armadvisor.RecommendationsClientListByTenantResponse{ + // ResourceRecommendationBaseListResult: armadvisor.ResourceRecommendationBaseListResult{ + // NextLink: to.Ptr("https://management.azure.com/providers/microsoft.management/serviceGroup/serviceGroupXYZ/providers/Microsoft.Advisor/recommendations?api-version=2025-05-01-preview&$top=10&$skiptoken=skiptoken"), + // Value: []*armadvisor.ResourceRecommendationBase{ + // { + // ID: to.Ptr("/providers/microsoft.management/serviceGroup/serviceGroupXYZ/providers/Microsoft.Advisor/recommendations/37c93209-4bfb-4f3b-8874-ccc718f7a467"), + // Name: to.Ptr("37c93209-4bfb-4f3b-8874-ccc718f7a467"), + // Type: to.Ptr("Microsoft.Advisor/recommendations"), + // Properties: &armadvisor.RecommendationProperties{ + // Category: to.Ptr(armadvisor.CategoryHighAvailability), + // Impact: to.Ptr(armadvisor.ImpactMedium), + // ImpactedField: to.Ptr("Microsoft.Management/serviceGroup"), + // ImpactedValue: to.Ptr("serviceGroupXYZ"), + // LastUpdated: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2025-04-24T22:24:43.3216408Z"); return t}()), + // Risk: to.Ptr(armadvisor.RiskWarning), + // ShortDescription: &armadvisor.ShortDescription{ + // Problem: to.Ptr("To ensure high availability add one or more virtual machines to this availability set"), + // Solution: to.Ptr("To ensure high availability add one or more virtual machines to this availability set"), + // }, + // ResourceMetadata: &armadvisor.ResourceMetadata{ + // ResourceID: to.Ptr("/providers/microsoft.management/serviceGroup/serviceGroupXYZ"), + // Action: map[string]any{ + // "additionalProperties": map[string]any{ + // "actionType": "Document", + // "link": "https://link3", + // "caption": "Enable Soft Delete to protect blob data", + // "description": "Enable Soft Delete to protect blob data", + // }, + // "metadata": map[string]any{ + // "id": "/providers/microsoft.management/serviceGroup/serviceGroupXYZ", + // }, // }, - // }}, - // Category: to.Ptr(armadvisor.CategorySecurity), - // Impact: to.Ptr(armadvisor.ImpactMedium), - // ImpactedField: to.Ptr("Microsoft.Compute/virtualMachines"), - // ImpactedValue: to.Ptr("armavset"), - // Label: to.Ptr("Enable monitoring agent"), - // LastUpdated: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2017-02-24T22:24:43.321Z"); return t}()), - // LearnMoreLink: to.Ptr("https://link2"), - // PotentialBenefits: to.Ptr("Protect and monitor machine"), - // ResourceMetadata: &armadvisor.ResourceMetadata{ - // Action: map[string]any{ - // "description": "Enable Soft Delete to protect blob data", - // "actionType": "Document", - // "caption": "Enable Soft Delete to protect blob data", - // "link": "https://link3", - // "metadata": map[string]any{ - // "id": "/subscriptions/subscriptionId", + // Singular: to.Ptr("Availability set"), + // Plural: to.Ptr("Availability sets"), + // }, + // Actions: []map[string]any{ + // map[string]any{ + // "additionalProperties": map[string]any{ + // "actionType": "Document", + // "link": "https://link1", + // "caption": "Enable Soft Delete to protect blob data", + // "description": "Enable Soft Delete to protect blob data", + // }, + // "metadata": map[string]any{ + // "id": "/providers/microsoft.management/serviceGroup/serviceGroupXYZ", + // }, // }, // }, - // Plural: to.Ptr("Virtual machines"), - // ResourceID: to.Ptr("/subscriptions/subscriptionId/resourceGroups/resourceGroup/providers/Microsoft.Compute/virtualMachines/xyz"), - // Singular: to.Ptr("Virtual machine"), - // Source: to.Ptr("/subscriptions/subscriptionId/resourceGroups/resourceGroup/providers/Microsoft.Compute/virtualMachines/xyz/providers/Microsoft.Security/assessments/assessmentGuid"), + // Description: to.Ptr("After enabling Soft Delete, deleted data transitions to a soft deleted state instead of being permanently deleted. When data is overwritten, a soft deleted snapshot is generated to save the state of the overwritten data. You can configure the amount of time soft deleted data is recoverable before it permanently expires."), + // Label: to.Ptr("Enable Soft Delete"), + // LearnMoreLink: to.Ptr("https://link2"), + // PotentialBenefits: to.Ptr("Save and recover your data when blobs or blob snapshots are accidentally overwritten or deleted"), + // Tracked: to.Ptr(false), // }, - // Risk: to.Ptr(armadvisor.RiskWarning), - // ShortDescription: &armadvisor.ShortDescription{ - // Problem: to.Ptr("Monitoring agent is not installed on your machines"), - // Solution: to.Ptr("Monitoring agent should be installed on your machines"), + // }, + // { + // ID: to.Ptr("/providers/microsoft.management/serviceGroup/serviceGroupXYZ/providers/Microsoft.Advisor/recommendations/de0eb863-583e-ac10-eb7f-cb0f6b570e2b"), + // Name: to.Ptr("de0eb863-583e-ac10-eb7f-cb0f6b570e2b"), + // Type: to.Ptr("Microsoft.Advisor/recommendations"), + // Properties: &armadvisor.RecommendationProperties{ + // Category: to.Ptr(armadvisor.CategoryHighAvailability), + // Impact: to.Ptr(armadvisor.ImpactMedium), + // ImpactedField: to.Ptr("Microsoft.Management/serviceGroup"), + // ImpactedValue: to.Ptr("serviceGroupXYZ"), + // LastUpdated: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2025-04-24T22:24:43.3216408Z"); return t}()), + // Risk: to.Ptr(armadvisor.RiskWarning), + // ShortDescription: &armadvisor.ShortDescription{ + // Problem: to.Ptr("To ensure high availability add one or more virtual machines to this availability set"), + // Solution: to.Ptr("To ensure high availability add one or more virtual machines to this availability set"), + // }, + // ResourceMetadata: &armadvisor.ResourceMetadata{ + // ResourceID: to.Ptr("/providers/microsoft.management/serviceGroup/serviceGroupXYZ"), + // Action: map[string]any{ + // "additionalProperties": map[string]any{ + // "actionType": "Document", + // "link": "https://link3", + // "caption": "Enable Soft Delete to protect blob data", + // "description": "Enable Soft Delete to protect blob data", + // }, + // "metadata": map[string]any{ + // "id": "/providers/microsoft.management/serviceGroup/serviceGroupXYZ", + // }, + // }, + // Singular: to.Ptr("Availability set"), + // Plural: to.Ptr("Availability sets"), + // }, + // Actions: []map[string]any{ + // map[string]any{ + // "additionalProperties": map[string]any{ + // "actionType": "Document", + // "link": "https://link1", + // "caption": "Enable Soft Delete to protect blob data", + // "description": "Enable Soft Delete to protect blob data", + // }, + // "metadata": map[string]any{ + // "id": "/providers/microsoft.management/serviceGroup/serviceGroupXYZ", + // }, + // }, + // }, + // Description: to.Ptr("After enabling Soft Delete, deleted data transitions to a soft deleted state instead of being permanently deleted. When data is overwritten, a soft deleted snapshot is generated to save the state of the overwritten data. You can configure the amount of time soft deleted data is recoverable before it permanently expires."), + // Label: to.Ptr("Enable Soft Delete"), + // LearnMoreLink: to.Ptr("https://link2"), + // PotentialBenefits: to.Ptr("Save and recover your data when blobs or blob snapshots are accidentally overwritten or deleted"), + // Tracked: to.Ptr(false), // }, // }, - // }}, + // }, + // }, // } } } -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/7a2ac91de424f271cf91cc8009f3fe9ee8249086/specification/advisor/resource-manager/Microsoft.Advisor/stable/2020-01-01/examples/GetRecommendationDetail.json -func ExampleRecommendationsClient_Get() { +// Generated from example definition: 2025-05-01-preview/UpdateTrackedRecommendation.json +func ExampleRecommendationsClient_Patch() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() - clientFactory, err := armadvisor.NewClientFactory("", cred, nil) + clientFactory, err := armadvisor.NewClientFactory("", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } - res, err := clientFactory.NewRecommendationsClient().Get(ctx, "resourceUri", "recommendationId", nil) + res, err := clientFactory.NewRecommendationsClient().Patch(ctx, "subscriptions/00000000-1111-2222-3333-444444444444/resourceGroups/resourceGroupName/providers/Microsoft.Compute/virtualMachines/xyz", "c5532a76-8605-4328-ad27-f37ae87c086c", armadvisor.TrackedRecommendationPropertiesPayload{ + Properties: &armadvisor.TrackedRecommendationPropertiesPayloadProperties{ + TrackedProperties: &armadvisor.TrackedRecommendationProperties{ + State: to.Ptr(armadvisor.StatePostponed), + PostponedTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-10-01T00:00:00Z"); return t }()), + }, + }, + }, 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.ResourceRecommendationBase = armadvisor.ResourceRecommendationBase{ - // Name: to.Ptr("recommendationId"), - // Type: to.Ptr("Microsoft.Advisor/recommendations"), - // ID: to.Ptr("/resourceUri/providers/Microsoft.Advisor/recommendations/recommendationId"), - // Properties: &armadvisor.RecommendationProperties{ - // Description: to.Ptr("After enabling Soft Delete, deleted data transitions to a soft deleted state instead of being permanently deleted. When data is overwritten, a soft deleted snapshot is generated to save the state of the overwritten data. You can configure the amount of time soft deleted data is recoverable before it permanently expires."), - // Actions: []map[string]any{ - // map[string]any{ - // "description": "Enable Soft Delete to protect blob data", - // "actionType": "Document", - // "caption": "Enable Soft Delete to protect blob data", - // "link": "https://link1", - // "metadata": map[string]any{ - // "id": "/subscriptions/subscriptionId", + // res = armadvisor.RecommendationsClientPatchResponse{ + // ResourceRecommendationBase: &armadvisor.ResourceRecommendationBase{ + // ID: to.Ptr("/subscriptions/00000000-1111-2222-3333-444444444444/resourceGroups/resourceGroupName/providers/Microsoft.Compute/virtualMachines/xyz/providers/Microsoft.Advisor/recommendations/c5532a76-8605-4328-ad27-f37ae87c086c"), + // Name: to.Ptr("c5532a76-8605-4328-ad27-f37ae87c086c"), + // Type: to.Ptr("Microsoft.Advisor/recommendations"), + // Properties: &armadvisor.RecommendationProperties{ + // Category: to.Ptr(armadvisor.CategorySecurity), + // Impact: to.Ptr(armadvisor.ImpactMedium), + // ImpactedField: to.Ptr("Microsoft.Compute/virtualMachines"), + // ImpactedValue: to.Ptr("armavset"), + // LastUpdated: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2017-02-24T22:24:43.3216408Z"); return t}()), + // Risk: to.Ptr(armadvisor.RiskWarning), + // ShortDescription: &armadvisor.ShortDescription{ + // Problem: to.Ptr("Monitoring agent should be installed on your machines"), + // Solution: to.Ptr("Monitoring agent should be installed on your machines"), + // }, + // Remediation: map[string]any{ + // "additionalProperties": map[string]any{ + // "httpMethod": "POST", + // "uri": "uri", + // "details": "link to document", // }, - // }}, - // Category: to.Ptr(armadvisor.CategorySecurity), - // Impact: to.Ptr(armadvisor.ImpactMedium), - // ImpactedField: to.Ptr("Microsoft.Compute/virtualMachines"), - // ImpactedValue: to.Ptr("armavset"), - // Label: to.Ptr("Enable Soft Delete"), - // LastUpdated: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2017-02-24T22:24:43.321Z"); return t}()), - // LearnMoreLink: to.Ptr("https://link2"), - // PotentialBenefits: to.Ptr("Save and recover your data when blobs or blob snapshots are accidentally overwritten or deleted"), - // Remediation: map[string]any{ - // "httpMethod": "POST", - // "uri": "uri", - // "details": "link to document", - // }, - // ResourceMetadata: &armadvisor.ResourceMetadata{ - // Action: map[string]any{ - // "description": "Enable Soft Delete to protect blob data", - // "actionType": "Document", - // "caption": "Enable Soft Delete to protect blob data", - // "link": "https://link3", - // "metadata": map[string]any{ - // "id": "/subscriptions/subscriptionId/resourceGroups/resourceGroup/providers/Microsoft.Compute/virtualMachines/xyz", + // }, + // ResourceMetadata: &armadvisor.ResourceMetadata{ + // ResourceID: to.Ptr("/subscriptions/00000000-1111-2222-3333-444444444444/resourceGroups/resourceGroupName/providers/Microsoft.Compute/virtualMachines/xyz"), + // Source: to.Ptr("/subscriptions/00000000-1111-2222-3333-444444444444/resourceGroups/resourceGroupName/providers/Microsoft.Compute/virtualMachines/xyz/providers/Microsoft.Security/assessments/7d5f6ba5-307e-452e-b3c4-7d636f722055"), + // Action: map[string]any{ + // "additionalProperties": map[string]any{ + // "actionType": "Document", + // "link": "https://link3", + // "caption": "Enable Soft Delete to protect blob data", + // "description": "Enable Soft Delete to protect blob data", + // }, + // "metadata": map[string]any{ + // "id": "/subscriptions/00000000-1111-2222-3333-444444444444/resourceGroups/resourceGroupName/providers/Microsoft.Compute/virtualMachines/xyz", + // }, // }, + // Singular: to.Ptr("Virtual machine"), + // Plural: to.Ptr("Virtual machines"), // }, - // Plural: to.Ptr("Virtual machines"), - // ResourceID: to.Ptr("/subscriptions/subscriptionId/resourceGroups/resourceGroup/providers/Microsoft.Compute/virtualMachines/xyz"), - // Singular: to.Ptr("Virtual machine"), - // Source: to.Ptr("/subscriptions/subscriptionId/resourceGroups/resourceGroup/providers/Microsoft.Compute/virtualMachines/xyz/providers/Microsoft.Security/assessments/assessmentGuid"), - // }, - // Risk: to.Ptr(armadvisor.RiskWarning), - // ShortDescription: &armadvisor.ShortDescription{ - // Problem: to.Ptr("Monitoring agent is not installed on your machines"), - // Solution: to.Ptr("Monitoring agent should be installed on your machines"), + // Actions: []map[string]any{ + // map[string]any{ + // "additionalProperties": map[string]any{ + // "actionType": "Document", + // "link": "https://link1", + // "caption": "Enable Soft Delete to protect blob data", + // "description": "Enable Soft Delete to protect blob data", + // }, + // "metadata": map[string]any{ + // "id": "/subscriptions/00000000-1111-2222-3333-444444444444", + // }, + // }, + // }, + // Description: to.Ptr("After enabling Soft Delete, deleted data transitions to a soft deleted state instead of being permanently deleted. When data is overwritten, a soft deleted snapshot is generated to save the state of the overwritten data. You can configure the amount of time soft deleted data is recoverable before it permanently expires."), + // Label: to.Ptr("Enable Soft Delete"), + // LearnMoreLink: to.Ptr("https://link2"), + // PotentialBenefits: to.Ptr("Save and recover your data when blobs or blob snapshots are accidentally overwritten or deleted"), + // Tracked: to.Ptr(true), + // TrackedProperties: &armadvisor.TrackedRecommendationProperties{ + // State: to.Ptr(armadvisor.StatePostponed), + // PostponedTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-10-01T00:00:00Z"); return t}()), + // Priority: to.Ptr(armadvisor.PriorityHigh), + // }, + // ResourceWorkload: &armadvisor.RecommendationPropertiesResourceWorkload{ + // ID: to.Ptr("0560dbdb-f207-4690-b4ba-1fc0c3a0f082"), + // Name: to.Ptr("Critical VM Workload"), + // }, + // Review: &armadvisor.RecommendationPropertiesReview{ + // ID: to.Ptr("/subscriptions/a5481ee1-95df-47d0-85d4-dd3f0dfa19bc/providers/Microsoft.Advisor/assessments/MCWAR1"), + // Name: to.Ptr("Monthly WAF Review 09/23"), + // }, + // SourceSystem: to.Ptr("CxObserve"), + // Notes: to.Ptr("This is a note"), // }, // }, // } diff --git a/sdk/resourcemanager/advisor/armadvisor/resiliencyreviews_client.go b/sdk/resourcemanager/advisor/armadvisor/resiliencyreviews_client.go new file mode 100644 index 000000000000..dbad08ed2ec8 --- /dev/null +++ b/sdk/resourcemanager/advisor/armadvisor/resiliencyreviews_client.go @@ -0,0 +1,168 @@ +// 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) Go Code Generator. DO NOT EDIT. + +package armadvisor + +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" + "strconv" + "strings" +) + +// ResiliencyReviewsClient contains the methods for the ResiliencyReviews group. +// Don't use this type directly, use NewResiliencyReviewsClient() instead. +type ResiliencyReviewsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewResiliencyReviewsClient creates a new instance of ResiliencyReviewsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewResiliencyReviewsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ResiliencyReviewsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ResiliencyReviewsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Get - Get existing resiliency review. +// +// Get existing Azure Advisor resiliency review by id. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-05-01-preview +// - reviewID - Existing review id. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). +// - options - ResiliencyReviewsClientGetOptions contains the optional parameters for the ResiliencyReviewsClient.Get method. +func (client *ResiliencyReviewsClient) Get(ctx context.Context, reviewID string, options *ResiliencyReviewsClientGetOptions) (ResiliencyReviewsClientGetResponse, error) { + var err error + const operationName = "ResiliencyReviewsClient.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, reviewID, options) + if err != nil { + return ResiliencyReviewsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ResiliencyReviewsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ResiliencyReviewsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ResiliencyReviewsClient) getCreateRequest(ctx context.Context, reviewID string, _ *ResiliencyReviewsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Advisor/resiliencyReviews/{reviewId}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if reviewID == "" { + return nil, errors.New("parameter reviewID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{reviewId}", url.PathEscape(reviewID)) + 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", "2025-05-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 *ResiliencyReviewsClient) getHandleResponse(resp *http.Response) (ResiliencyReviewsClientGetResponse, error) { + result := ResiliencyReviewsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ResiliencyReview); err != nil { + return ResiliencyReviewsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Get list of resiliency reviews. +// +// Get list of Azure Advisor resiliency reviews. +// +// Generated from API version 2025-05-01-preview +// - options - ResiliencyReviewsClientListOptions contains the optional parameters for the ResiliencyReviewsClient.NewListPager +// method. +func (client *ResiliencyReviewsClient) NewListPager(options *ResiliencyReviewsClientListOptions) *runtime.Pager[ResiliencyReviewsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[ResiliencyReviewsClientListResponse]{ + More: func(page ResiliencyReviewsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ResiliencyReviewsClientListResponse) (ResiliencyReviewsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ResiliencyReviewsClient.NewListPager") + 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.listCreateRequest(ctx, options) + }, nil) + if err != nil { + return ResiliencyReviewsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *ResiliencyReviewsClient) listCreateRequest(ctx context.Context, options *ResiliencyReviewsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Advisor/resiliencyReviews" + 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() + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + if options != nil && options.Skip != nil { + reqQP.Set("$skip", strconv.FormatInt(int64(*options.Skip), 10)) + } + if options != nil && options.Top != nil { + reqQP.Set("$top", strconv.FormatInt(int64(*options.Top), 10)) + } + reqQP.Set("api-version", "2025-05-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *ResiliencyReviewsClient) listHandleResponse(resp *http.Response) (ResiliencyReviewsClientListResponse, error) { + result := ResiliencyReviewsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ResiliencyReviewCollection); err != nil { + return ResiliencyReviewsClientListResponse{}, err + } + return result, nil +} diff --git a/sdk/resourcemanager/advisor/armadvisor/resiliencyreviews_client_example_test.go b/sdk/resourcemanager/advisor/armadvisor/resiliencyreviews_client_example_test.go new file mode 100644 index 000000000000..bf87365d4af7 --- /dev/null +++ b/sdk/resourcemanager/advisor/armadvisor/resiliencyreviews_client_example_test.go @@ -0,0 +1,129 @@ +// 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) Go Code Generator. DO NOT EDIT. + +package armadvisor_test + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/advisor/armadvisor/v2" + "log" +) + +// Generated from example definition: 2025-05-01-preview/ResiliencyReviewsGet.json +func ExampleResiliencyReviewsClient_Get() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armadvisor.NewClientFactory("00000000-1111-2222-3333-444444444444", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewResiliencyReviewsClient().Get(ctx, "11111111-1111-2222-3333-444444444444", 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 = armadvisor.ResiliencyReviewsClientGetResponse{ + // ResiliencyReview: &armadvisor.ResiliencyReview{ + // ID: to.Ptr("/subscriptions/00000000-1111-2222-3333-444444444444/providers/Microsoft.Advisor/ResiliencyReview/11111111-1111-2222-3333-444444444444"), + // Name: to.Ptr("11111111-1111-2222-3333-444444444444"), + // Type: to.Ptr("Microsoft.Advisor/ResiliencyReview"), + // SystemData: &armadvisor.SystemData{ + // CreatedBy: to.Ptr("user-identity"), + // CreatedByType: to.Ptr(armadvisor.CreatedByTypeUser), + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-06-30T09:41:00Z"); return t}()), + // LastModifiedBy: to.Ptr("user-identity"), + // LastModifiedByType: to.Ptr(armadvisor.CreatedByTypeUser), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-06-30T09:41:00Z"); return t}()), + // }, + // Properties: &armadvisor.ResiliencyReviewProperties{ + // ReviewName: to.Ptr("review name xyz"), + // WorkloadName: to.Ptr("workload name xyz"), + // ReviewStatus: to.Ptr(armadvisor.ReviewStatusTriaged), + // RecommendationsCount: to.Ptr[int32](4), + // PublishedAt: to.Ptr("2023-06-30T09:41:00Z"), + // UpdatedAt: to.Ptr("2023-06-30T09:41:00Z"), + // }, + // }, + // } +} + +// Generated from example definition: 2025-05-01-preview/ResiliencyReviewsList.json +func ExampleResiliencyReviewsClient_NewListPager() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armadvisor.NewClientFactory("00000000-1111-2222-3333-444444444444", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + pager := clientFactory.NewResiliencyReviewsClient().NewListPager(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 = armadvisor.ResiliencyReviewsClientListResponse{ + // ResiliencyReviewCollection: armadvisor.ResiliencyReviewCollection{ + // Value: []*armadvisor.ResiliencyReview{ + // { + // ID: to.Ptr("/subscriptions/00000000-1111-2222-3333-444444444444/providers/Microsoft.Advisor/ResiliencyReview/11111111-1111-2222-3333-444444444444"), + // Name: to.Ptr("11111111-1111-2222-3333-444444444444"), + // Type: to.Ptr("Microsoft.Advisor/ResiliencyReview"), + // SystemData: &armadvisor.SystemData{ + // CreatedBy: to.Ptr("user-identity"), + // CreatedByType: to.Ptr(armadvisor.CreatedByTypeUser), + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-06-30T09:41:00Z"); return t}()), + // LastModifiedBy: to.Ptr("user-identity"), + // LastModifiedByType: to.Ptr(armadvisor.CreatedByTypeUser), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-06-30T09:41:00Z"); return t}()), + // }, + // Properties: &armadvisor.ResiliencyReviewProperties{ + // ReviewName: to.Ptr("review name xyz"), + // WorkloadName: to.Ptr("workload name xyz"), + // ReviewStatus: to.Ptr(armadvisor.ReviewStatusTriaged), + // RecommendationsCount: to.Ptr[int32](4), + // PublishedAt: to.Ptr("2023-06-30T09:41:00Z"), + // UpdatedAt: to.Ptr("2023-06-30T09:41:00Z"), + // }, + // }, + // { + // ID: to.Ptr("/subscriptions/00000000-1111-2222-3333-444444444444/providers/Microsoft.Advisor/ResiliencyReview/11111111-1111-2222-3333-555555555555"), + // Name: to.Ptr("11111111-1111-2222-3333-555555555555"), + // Type: to.Ptr("Microsoft.Advisor/ResiliencyReview"), + // SystemData: &armadvisor.SystemData{ + // CreatedBy: to.Ptr("user-identity"), + // CreatedByType: to.Ptr(armadvisor.CreatedByTypeUser), + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-06-30T09:41:00Z"); return t}()), + // LastModifiedBy: to.Ptr("user-identity"), + // LastModifiedByType: to.Ptr(armadvisor.CreatedByTypeUser), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-06-30T09:41:00Z"); return t}()), + // }, + // Properties: &armadvisor.ResiliencyReviewProperties{ + // ReviewName: to.Ptr("review name abc"), + // WorkloadName: to.Ptr("workload name abc"), + // ReviewStatus: to.Ptr(armadvisor.ReviewStatusTriaged), + // RecommendationsCount: to.Ptr[int32](5), + // PublishedAt: to.Ptr("2023-06-30T09:41:00Z"), + // UpdatedAt: to.Ptr("2023-06-30T09:41:00Z"), + // }, + // }, + // }, + // NextLink: to.Ptr("https://management.azure.com/subscriptions/00000000-1111-2222-3333-444444444444/providers/Microsoft.Advisor/resiliencyReviews?api-version=2025-05-01-preview&$skipToken=abc123"), + // }, + // } + } +} diff --git a/sdk/resourcemanager/advisor/armadvisor/response_types.go b/sdk/resourcemanager/advisor/armadvisor/response_types.go deleted file mode 100644 index f240a49d8bea..000000000000 --- a/sdk/resourcemanager/advisor/armadvisor/response_types.go +++ /dev/null @@ -1,97 +0,0 @@ -// 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 armadvisor - -// ConfigurationsClientCreateInResourceGroupResponse contains the response from method ConfigurationsClient.CreateInResourceGroup. -type ConfigurationsClientCreateInResourceGroupResponse struct { - // The Advisor configuration data structure. - ConfigData -} - -// ConfigurationsClientCreateInSubscriptionResponse contains the response from method ConfigurationsClient.CreateInSubscription. -type ConfigurationsClientCreateInSubscriptionResponse struct { - // The Advisor configuration data structure. - ConfigData -} - -// ConfigurationsClientListByResourceGroupResponse contains the response from method ConfigurationsClient.NewListByResourceGroupPager. -type ConfigurationsClientListByResourceGroupResponse struct { - // The list of Advisor configurations. - ConfigurationListResult -} - -// ConfigurationsClientListBySubscriptionResponse contains the response from method ConfigurationsClient.NewListBySubscriptionPager. -type ConfigurationsClientListBySubscriptionResponse struct { - // The list of Advisor configurations. - ConfigurationListResult -} - -// OperationsClientListResponse contains the response from method OperationsClient.NewListPager. -type OperationsClientListResponse struct { - // The list of Advisor operations. - OperationEntityListResult -} - -// RecommendationMetadataClientGetResponse contains the response from method RecommendationMetadataClient.Get. -type RecommendationMetadataClientGetResponse struct { - // The metadata entity contract. - MetadataEntity -} - -// RecommendationMetadataClientListResponse contains the response from method RecommendationMetadataClient.NewListPager. -type RecommendationMetadataClientListResponse struct { - // The list of metadata entities - MetadataEntityListResult -} - -// RecommendationsClientGenerateResponse contains the response from method RecommendationsClient.Generate. -type RecommendationsClientGenerateResponse struct { - // Location contains the information returned from the Location header response. - Location *string - - // RetryAfter contains the information returned from the Retry-After header response. - RetryAfter *string -} - -// RecommendationsClientGetGenerateStatusResponse contains the response from method RecommendationsClient.GetGenerateStatus. -type RecommendationsClientGetGenerateStatusResponse struct { - // placeholder for future response values -} - -// RecommendationsClientGetResponse contains the response from method RecommendationsClient.Get. -type RecommendationsClientGetResponse struct { - // Advisor Recommendation. - ResourceRecommendationBase -} - -// RecommendationsClientListResponse contains the response from method RecommendationsClient.NewListPager. -type RecommendationsClientListResponse struct { - // The list of Advisor recommendations. - ResourceRecommendationBaseListResult -} - -// SuppressionsClientCreateResponse contains the response from method SuppressionsClient.Create. -type SuppressionsClientCreateResponse struct { - // The details of the snoozed or dismissed rule; for example, the duration, name, and GUID associated with the rule. - SuppressionContract -} - -// SuppressionsClientDeleteResponse contains the response from method SuppressionsClient.Delete. -type SuppressionsClientDeleteResponse struct { - // placeholder for future response values -} - -// SuppressionsClientGetResponse contains the response from method SuppressionsClient.Get. -type SuppressionsClientGetResponse struct { - // The details of the snoozed or dismissed rule; for example, the duration, name, and GUID associated with the rule. - SuppressionContract -} - -// SuppressionsClientListResponse contains the response from method SuppressionsClient.NewListPager. -type SuppressionsClientListResponse struct { - // The list of Advisor suppressions. - SuppressionContractListResult -} diff --git a/sdk/resourcemanager/advisor/armadvisor/responses.go b/sdk/resourcemanager/advisor/armadvisor/responses.go new file mode 100644 index 000000000000..e2cf04716825 --- /dev/null +++ b/sdk/resourcemanager/advisor/armadvisor/responses.go @@ -0,0 +1,212 @@ +// 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) Go Code Generator. DO NOT EDIT. + +package armadvisor + +// AssessmentTypesClientListResponse contains the response from method AssessmentTypesClient.NewListPager. +type AssessmentTypesClientListResponse struct { + // The Advisor assessment type list result data structure. + AssessmentTypeListResult +} + +// AssessmentsClientDeleteResponse contains the response from method AssessmentsClient.Delete. +type AssessmentsClientDeleteResponse struct { + // placeholder for future response values +} + +// AssessmentsClientGetResponse contains the response from method AssessmentsClient.Get. +type AssessmentsClientGetResponse struct { + // The Advisor assessment result data structure. + AssessmentResult +} + +// AssessmentsClientListResponse contains the response from method AssessmentsClient.NewListPager. +type AssessmentsClientListResponse struct { + // Paged collection of AssessmentResult items + AssessmentListResult +} + +// AssessmentsClientPutResponse contains the response from method AssessmentsClient.Put. +type AssessmentsClientPutResponse struct { + // The Advisor assessment result data structure. + AssessmentResult +} + +// ClientPredictResponse contains the response from method Client.Predict. +type ClientPredictResponse struct { + // Response used by predictions. + PredictionResponse +} + +// ConfigurationsClientCreateInResourceGroupResponse contains the response from method ConfigurationsClient.CreateInResourceGroup. +type ConfigurationsClientCreateInResourceGroupResponse struct { + // The Advisor configuration data structure. + ConfigData +} + +// ConfigurationsClientCreateInSubscriptionResponse contains the response from method ConfigurationsClient.CreateInSubscription. +type ConfigurationsClientCreateInSubscriptionResponse struct { + // The Advisor configuration data structure. + ConfigData +} + +// ConfigurationsClientListByResourceGroupResponse contains the response from method ConfigurationsClient.NewListByResourceGroupPager. +type ConfigurationsClientListByResourceGroupResponse struct { + // Paged collection of ConfigData items + ConfigurationListResult +} + +// ConfigurationsClientListBySubscriptionResponse contains the response from method ConfigurationsClient.NewListBySubscriptionPager. +type ConfigurationsClientListBySubscriptionResponse struct { + // Paged collection of ConfigData items + ConfigurationListResult +} + +// OperationsClientListResponse contains the response from method OperationsClient.NewListPager. +type OperationsClientListResponse struct { + // Paged collection of OperationEntity items + OperationEntityListResult +} + +// RecommendationMetadataClientGetResponse contains the response from method RecommendationMetadataClient.Get. +type RecommendationMetadataClientGetResponse struct { + // The metadata entity contract. + MetadataEntity +} + +// RecommendationMetadataClientListResponse contains the response from method RecommendationMetadataClient.NewListPager. +type RecommendationMetadataClientListResponse struct { + // The response of a MetadataEntity list operation. + MetadataEntityListResult +} + +// RecommendationsClientGenerateResponse contains the response from method RecommendationsClient.Generate. +type RecommendationsClientGenerateResponse struct { + // The URL where the status of the asynchronous operation can be checked. + Location *string + + // The Retry-After header can indicate how long the client should wait before polling the operation status. + RetryAfter *int32 +} + +// RecommendationsClientGetGenerateStatusResponse contains the response from method RecommendationsClient.GetGenerateStatus. +type RecommendationsClientGetGenerateStatusResponse struct { + // The Retry-After header can indicate how long the client should wait before polling the operation status. + RetryAfter *int32 +} + +// RecommendationsClientGetResponse contains the response from method RecommendationsClient.Get. +type RecommendationsClientGetResponse struct { + // Advisor Recommendation. + ResourceRecommendationBase +} + +// RecommendationsClientListByTenantResponse contains the response from method RecommendationsClient.NewListByTenantPager. +type RecommendationsClientListByTenantResponse struct { + // The response of a ResourceRecommendationBase list operation. + ResourceRecommendationBaseListResult +} + +// RecommendationsClientListResponse contains the response from method RecommendationsClient.NewListPager. +type RecommendationsClientListResponse struct { + // The response of a ResourceRecommendationBase list operation. + ResourceRecommendationBaseListResult +} + +// RecommendationsClientPatchResponse contains the response from method RecommendationsClient.Patch. +type RecommendationsClientPatchResponse struct { + // Advisor Recommendation. + ResourceRecommendationBase +} + +// ResiliencyReviewsClientGetResponse contains the response from method ResiliencyReviewsClient.Get. +type ResiliencyReviewsClientGetResponse struct { + // The Advisor resiliency review data structure. + ResiliencyReview +} + +// ResiliencyReviewsClientListResponse contains the response from method ResiliencyReviewsClient.NewListPager. +type ResiliencyReviewsClientListResponse struct { + // Collection of Resiliency Reviews. + ResiliencyReviewCollection +} + +// ScoresClientGetResponse contains the response from method ScoresClient.Get. +type ScoresClientGetResponse struct { + // The details of Advisor score for a single category. + ScoreEntityForAdvisor +} + +// ScoresClientListResponse contains the response from method ScoresClient.NewListPager. +type ScoresClientListResponse struct { + ScoreResponse +} + +// SuppressionsClientCreateResponse contains the response from method SuppressionsClient.Create. +type SuppressionsClientCreateResponse struct { + // The details of the snoozed or dismissed rule; for example, the duration, name, and GUID associated with the rule. + SuppressionContract +} + +// SuppressionsClientDeleteResponse contains the response from method SuppressionsClient.Delete. +type SuppressionsClientDeleteResponse struct { + // placeholder for future response values +} + +// SuppressionsClientGetResponse contains the response from method SuppressionsClient.Get. +type SuppressionsClientGetResponse struct { + // The details of the snoozed or dismissed rule; for example, the duration, name, and GUID associated with the rule. + SuppressionContract +} + +// SuppressionsClientListResponse contains the response from method SuppressionsClient.NewListPager. +type SuppressionsClientListResponse struct { + // The response of a SuppressionContract list operation. + SuppressionContractListResult +} + +// TriageRecommendationsClientApproveTriageRecommendationResponse contains the response from method TriageRecommendationsClient.ApproveTriageRecommendation. +type TriageRecommendationsClientApproveTriageRecommendationResponse struct { + // placeholder for future response values +} + +// TriageRecommendationsClientGetResponse contains the response from method TriageRecommendationsClient.Get. +type TriageRecommendationsClientGetResponse struct { + // Triage recommendation data structure. + TriageRecommendation +} + +// TriageRecommendationsClientListResponse contains the response from method TriageRecommendationsClient.NewListPager. +type TriageRecommendationsClientListResponse struct { + // Collection of Advisor triage recommendations. + TriageRecommendationCollection +} + +// TriageRecommendationsClientRejectTriageRecommendationResponse contains the response from method TriageRecommendationsClient.RejectTriageRecommendation. +type TriageRecommendationsClientRejectTriageRecommendationResponse struct { + // placeholder for future response values +} + +// TriageRecommendationsClientResetTriageRecommendationResponse contains the response from method TriageRecommendationsClient.ResetTriageRecommendation. +type TriageRecommendationsClientResetTriageRecommendationResponse struct { + // placeholder for future response values +} + +// TriageResourcesClientGetResponse contains the response from method TriageResourcesClient.Get. +type TriageResourcesClientGetResponse struct { + // Triage resource data structure. + TriageResource +} + +// TriageResourcesClientListResponse contains the response from method TriageResourcesClient.NewListPager. +type TriageResourcesClientListResponse struct { + // Collection of Advisor triage resources. + TriageResourceCollection +} + +// WorkloadsClientListResponse contains the response from method WorkloadsClient.NewListPager. +type WorkloadsClientListResponse struct { + // The Workload list result data structure. + WorkloadListResult +} diff --git a/sdk/resourcemanager/advisor/armadvisor/scores_client.go b/sdk/resourcemanager/advisor/armadvisor/scores_client.go new file mode 100644 index 000000000000..e6b0f2d258bd --- /dev/null +++ b/sdk/resourcemanager/advisor/armadvisor/scores_client.go @@ -0,0 +1,154 @@ +// 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) Go Code Generator. DO NOT EDIT. + +package armadvisor + +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" +) + +// ScoresClient contains the methods for the Scores group. +// Don't use this type directly, use NewScoresClient() instead. +type ScoresClient struct { + internal *arm.Client + subscriptionID string +} + +// NewScoresClient creates a new instance of ScoresClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewScoresClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ScoresClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ScoresClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Get - Gets the advisor score. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-05-01-preview +// - name - The scope of Advisor score entity. +// - options - ScoresClientGetOptions contains the optional parameters for the ScoresClient.Get method. +func (client *ScoresClient) Get(ctx context.Context, name string, options *ScoresClientGetOptions) (ScoresClientGetResponse, error) { + var err error + const operationName = "ScoresClient.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, name, options) + if err != nil { + return ScoresClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ScoresClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ScoresClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ScoresClient) getCreateRequest(ctx context.Context, name string, _ *ScoresClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Advisor/advisorScore/{name}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{name}", url.PathEscape(name)) + 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", "2025-05-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 *ScoresClient) getHandleResponse(resp *http.Response) (ScoresClientGetResponse, error) { + result := ScoresClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ScoreEntityForAdvisor); err != nil { + return ScoresClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Gets the list of advisor scores. +// +// Generated from API version 2025-05-01-preview +// - options - ScoresClientListOptions contains the optional parameters for the ScoresClient.NewListPager method. +func (client *ScoresClient) NewListPager(options *ScoresClientListOptions) *runtime.Pager[ScoresClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[ScoresClientListResponse]{ + More: func(page ScoresClientListResponse) bool { + return false + }, + Fetcher: func(ctx context.Context, page *ScoresClientListResponse) (ScoresClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ScoresClient.NewListPager") + req, err := client.listCreateRequest(ctx, options) + if err != nil { + return ScoresClientListResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ScoresClientListResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return ScoresClientListResponse{}, runtime.NewResponseError(resp) + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *ScoresClient) listCreateRequest(ctx context.Context, _ *ScoresClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Advisor/advisorScore" + 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", "2025-05-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *ScoresClient) listHandleResponse(resp *http.Response) (ScoresClientListResponse, error) { + result := ScoresClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ScoreResponse); err != nil { + return ScoresClientListResponse{}, err + } + return result, nil +} diff --git a/sdk/resourcemanager/advisor/armadvisor/scores_client_example_test.go b/sdk/resourcemanager/advisor/armadvisor/scores_client_example_test.go new file mode 100644 index 000000000000..bce8aff13d8a --- /dev/null +++ b/sdk/resourcemanager/advisor/armadvisor/scores_client_example_test.go @@ -0,0 +1,546 @@ +// 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) Go Code Generator. DO NOT EDIT. + +package armadvisor_test + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/advisor/armadvisor/v2" + "log" +) + +// Generated from example definition: 2025-05-01-preview/GetAdvisorScoreDetail.json +func ExampleScoresClient_Get() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armadvisor.NewClientFactory("a5481ee1-95df-47d0-85d4-dd3f0dfa19bc", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewScoresClient().Get(ctx, "Cost", 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 = armadvisor.ScoresClientGetResponse{ + // ScoreEntityForAdvisor: &armadvisor.ScoreEntityForAdvisor{ + // ID: to.Ptr("/subscriptions/a5481ee1-95df-47d0-85d4-dd3f0dfa19bc/providers/Microsoft.Advisor/advisorScore/Cost"), + // Name: to.Ptr("Cost"), + // Type: to.Ptr("Microsoft.Advisor/advisorScore"), + // Properties: &armadvisor.ScoreEntityProperties{ + // LastRefreshedScore: &armadvisor.ScoreEntity{ + // Date: to.Ptr("2020-06-25T00:00:00Z"), + // Score: to.Ptr[float32](1), + // ConsumptionUnits: to.Ptr[float32](12), + // ImpactedResourceCount: to.Ptr[float32](1), + // PotentialScoreIncrease: to.Ptr[float32](0), + // CategoryCount: to.Ptr[float32](1), + // }, + // TimeSeries: []*armadvisor.TimeSeriesEntity{ + // { + // AggregationLevel: to.Ptr(armadvisor.AggregatedDay), + // ScoreHistory: []*armadvisor.ScoreEntity{ + // { + // Date: to.Ptr("2020-06-25T00:00:00Z"), + // Score: to.Ptr[float32](1), + // ConsumptionUnits: to.Ptr[float32](12), + // ImpactedResourceCount: to.Ptr[float32](1), + // PotentialScoreIncrease: to.Ptr[float32](0), + // }, + // { + // Date: to.Ptr("2020-06-24T00:00:00Z"), + // Score: to.Ptr[float32](1), + // ConsumptionUnits: to.Ptr[float32](12), + // ImpactedResourceCount: to.Ptr[float32](1), + // PotentialScoreIncrease: to.Ptr[float32](0), + // }, + // { + // Date: to.Ptr("2020-06-23T00:00:00Z"), + // Score: to.Ptr[float32](1), + // ConsumptionUnits: to.Ptr[float32](12), + // ImpactedResourceCount: to.Ptr[float32](1), + // PotentialScoreIncrease: to.Ptr[float32](0), + // }, + // { + // Date: to.Ptr("2020-06-22T00:00:00Z"), + // Score: to.Ptr[float32](1), + // ConsumptionUnits: to.Ptr[float32](12), + // ImpactedResourceCount: to.Ptr[float32](1), + // PotentialScoreIncrease: to.Ptr[float32](0), + // }, + // { + // Date: to.Ptr("2020-06-21T00:00:00Z"), + // Score: to.Ptr[float32](1), + // ConsumptionUnits: to.Ptr[float32](12), + // ImpactedResourceCount: to.Ptr[float32](1), + // PotentialScoreIncrease: to.Ptr[float32](0), + // }, + // { + // Date: to.Ptr("2020-06-20T00:00:00Z"), + // Score: to.Ptr[float32](1), + // ConsumptionUnits: to.Ptr[float32](12), + // ImpactedResourceCount: to.Ptr[float32](1), + // PotentialScoreIncrease: to.Ptr[float32](0), + // }, + // { + // Date: to.Ptr("2020-06-19T00:00:00Z"), + // Score: to.Ptr[float32](1), + // ConsumptionUnits: to.Ptr[float32](12), + // ImpactedResourceCount: to.Ptr[float32](1), + // PotentialScoreIncrease: to.Ptr[float32](0), + // }, + // }, + // }, + // { + // AggregationLevel: to.Ptr(armadvisor.AggregatedMonth), + // ScoreHistory: []*armadvisor.ScoreEntity{ + // { + // Date: to.Ptr("2020-06-25T00:00:00Z"), + // Score: to.Ptr[float32](1), + // ConsumptionUnits: to.Ptr[float32](12), + // ImpactedResourceCount: to.Ptr[float32](1), + // PotentialScoreIncrease: to.Ptr[float32](0), + // }, + // { + // Date: to.Ptr("2020-05-30T00:00:00Z"), + // Score: to.Ptr[float32](1), + // ConsumptionUnits: to.Ptr[float32](12), + // ImpactedResourceCount: to.Ptr[float32](1), + // PotentialScoreIncrease: to.Ptr[float32](0), + // }, + // { + // Date: to.Ptr("2020-04-30T00:00:00Z"), + // Score: to.Ptr[float32](1), + // ConsumptionUnits: to.Ptr[float32](12), + // ImpactedResourceCount: to.Ptr[float32](1), + // PotentialScoreIncrease: to.Ptr[float32](0), + // }, + // }, + // }, + // { + // AggregationLevel: to.Ptr(armadvisor.AggregatedWeek), + // ScoreHistory: []*armadvisor.ScoreEntity{ + // { + // Date: to.Ptr("2020-06-25T00:00:00Z"), + // Score: to.Ptr[float32](1), + // ConsumptionUnits: to.Ptr[float32](12), + // ImpactedResourceCount: to.Ptr[float32](1), + // PotentialScoreIncrease: to.Ptr[float32](0), + // }, + // { + // Date: to.Ptr("2020-06-21T00:00:00Z"), + // Score: to.Ptr[float32](1), + // ConsumptionUnits: to.Ptr[float32](12), + // ImpactedResourceCount: to.Ptr[float32](1), + // PotentialScoreIncrease: to.Ptr[float32](0), + // }, + // { + // Date: to.Ptr("2020-06-14T00:00:00Z"), + // Score: to.Ptr[float32](1), + // ConsumptionUnits: to.Ptr[float32](12), + // ImpactedResourceCount: to.Ptr[float32](1), + // PotentialScoreIncrease: to.Ptr[float32](0), + // }, + // { + // Date: to.Ptr("2020-06-07T00:00:00Z"), + // Score: to.Ptr[float32](1), + // ConsumptionUnits: to.Ptr[float32](12), + // ImpactedResourceCount: to.Ptr[float32](1), + // PotentialScoreIncrease: to.Ptr[float32](0), + // }, + // { + // Date: to.Ptr("2020-05-31T00:00:00Z"), + // Score: to.Ptr[float32](1), + // ConsumptionUnits: to.Ptr[float32](12), + // ImpactedResourceCount: to.Ptr[float32](1), + // PotentialScoreIncrease: to.Ptr[float32](0), + // }, + // { + // Date: to.Ptr("2020-05-24T00:00:00Z"), + // Score: to.Ptr[float32](1), + // ConsumptionUnits: to.Ptr[float32](12), + // ImpactedResourceCount: to.Ptr[float32](1), + // PotentialScoreIncrease: to.Ptr[float32](0), + // }, + // }, + // }, + // }, + // }, + // }, + // } +} + +// Generated from example definition: 2025-05-01-preview/ListAdvisorScore.json +func ExampleScoresClient_NewListPager() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armadvisor.NewClientFactory("a5481ee1-95df-47d0-85d4-dd3f0dfa19bc", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + pager := clientFactory.NewScoresClient().NewListPager(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 = armadvisor.ScoresClientListResponse{ + // ScoreResponse: armadvisor.ScoreResponse{ + // Value: []*armadvisor.ScoreEntityForAdvisor{ + // { + // ID: to.Ptr("/subscriptions/a5481ee1-95df-47d0-85d4-dd3f0dfa19bc/providers/Microsoft.Advisor/advisorScore/Cost"), + // Name: to.Ptr("Cost"), + // Type: to.Ptr("Microsoft.Advisor/advisorScore"), + // Properties: &armadvisor.ScoreEntityProperties{ + // LastRefreshedScore: &armadvisor.ScoreEntity{ + // Date: to.Ptr("2020-06-25T00:00:00Z"), + // Score: to.Ptr[float32](1), + // ConsumptionUnits: to.Ptr[float32](12.24521), + // ImpactedResourceCount: to.Ptr[float32](1), + // PotentialScoreIncrease: to.Ptr[float32](0), + // CategoryCount: to.Ptr[float32](2), + // }, + // TimeSeries: []*armadvisor.TimeSeriesEntity{ + // { + // AggregationLevel: to.Ptr(armadvisor.AggregatedDay), + // ScoreHistory: []*armadvisor.ScoreEntity{ + // { + // Date: to.Ptr("2020-06-25T00:00:00Z"), + // Score: to.Ptr[float32](1), + // ConsumptionUnits: to.Ptr[float32](12.24521), + // ImpactedResourceCount: to.Ptr[float32](1), + // PotentialScoreIncrease: to.Ptr[float32](0), + // }, + // { + // Date: to.Ptr("2020-06-24T00:00:00Z"), + // Score: to.Ptr[float32](1), + // ConsumptionUnits: to.Ptr[float32](12.24521), + // ImpactedResourceCount: to.Ptr[float32](1), + // PotentialScoreIncrease: to.Ptr[float32](0), + // }, + // { + // Date: to.Ptr("2020-06-23T00:00:00Z"), + // Score: to.Ptr[float32](1), + // ConsumptionUnits: to.Ptr[float32](12.24521), + // ImpactedResourceCount: to.Ptr[float32](1), + // PotentialScoreIncrease: to.Ptr[float32](0), + // }, + // { + // Date: to.Ptr("2020-06-22T00:00:00Z"), + // Score: to.Ptr[float32](1), + // ConsumptionUnits: to.Ptr[float32](12.24521), + // ImpactedResourceCount: to.Ptr[float32](1), + // PotentialScoreIncrease: to.Ptr[float32](0), + // }, + // { + // Date: to.Ptr("2020-06-21T00:00:00Z"), + // Score: to.Ptr[float32](1), + // ConsumptionUnits: to.Ptr[float32](12.24521), + // ImpactedResourceCount: to.Ptr[float32](1), + // PotentialScoreIncrease: to.Ptr[float32](0), + // }, + // { + // Date: to.Ptr("2020-06-20T00:00:00Z"), + // Score: to.Ptr[float32](1), + // ConsumptionUnits: to.Ptr[float32](12.24521), + // ImpactedResourceCount: to.Ptr[float32](1), + // PotentialScoreIncrease: to.Ptr[float32](0), + // }, + // { + // Date: to.Ptr("2020-06-19T00:00:00Z"), + // Score: to.Ptr[float32](1), + // ConsumptionUnits: to.Ptr[float32](12.24521), + // ImpactedResourceCount: to.Ptr[float32](1), + // PotentialScoreIncrease: to.Ptr[float32](0), + // }, + // }, + // }, + // { + // AggregationLevel: to.Ptr(armadvisor.AggregatedMonth), + // ScoreHistory: []*armadvisor.ScoreEntity{ + // { + // Date: to.Ptr("2020-06-25T00:00:00Z"), + // Score: to.Ptr[float32](1), + // ConsumptionUnits: to.Ptr[float32](12.24521), + // ImpactedResourceCount: to.Ptr[float32](1), + // PotentialScoreIncrease: to.Ptr[float32](0), + // }, + // { + // Date: to.Ptr("2020-05-30T00:00:00Z"), + // Score: to.Ptr[float32](1), + // ConsumptionUnits: to.Ptr[float32](12.24521), + // ImpactedResourceCount: to.Ptr[float32](1), + // PotentialScoreIncrease: to.Ptr[float32](0), + // }, + // { + // Date: to.Ptr("2020-04-30T00:00:00Z"), + // Score: to.Ptr[float32](1), + // ConsumptionUnits: to.Ptr[float32](12.24521), + // ImpactedResourceCount: to.Ptr[float32](1), + // PotentialScoreIncrease: to.Ptr[float32](0), + // }, + // }, + // }, + // { + // AggregationLevel: to.Ptr(armadvisor.AggregatedWeek), + // ScoreHistory: []*armadvisor.ScoreEntity{ + // { + // Date: to.Ptr("2020-06-25T00:00:00Z"), + // Score: to.Ptr[float32](1), + // ConsumptionUnits: to.Ptr[float32](12.24521), + // ImpactedResourceCount: to.Ptr[float32](1), + // PotentialScoreIncrease: to.Ptr[float32](0), + // }, + // { + // Date: to.Ptr("2020-06-21T00:00:00Z"), + // Score: to.Ptr[float32](1), + // ConsumptionUnits: to.Ptr[float32](12.24521), + // ImpactedResourceCount: to.Ptr[float32](1), + // PotentialScoreIncrease: to.Ptr[float32](0), + // }, + // { + // Date: to.Ptr("2020-06-14T00:00:00Z"), + // Score: to.Ptr[float32](1), + // ConsumptionUnits: to.Ptr[float32](12.24521), + // ImpactedResourceCount: to.Ptr[float32](1), + // PotentialScoreIncrease: to.Ptr[float32](0), + // }, + // { + // Date: to.Ptr("2020-06-07T00:00:00Z"), + // Score: to.Ptr[float32](1), + // ConsumptionUnits: to.Ptr[float32](12.24521), + // ImpactedResourceCount: to.Ptr[float32](1), + // PotentialScoreIncrease: to.Ptr[float32](0), + // }, + // { + // Date: to.Ptr("2020-05-31T00:00:00Z"), + // Score: to.Ptr[float32](1), + // ConsumptionUnits: to.Ptr[float32](12.24521), + // ImpactedResourceCount: to.Ptr[float32](1), + // PotentialScoreIncrease: to.Ptr[float32](0), + // }, + // { + // Date: to.Ptr("2020-05-24T00:00:00Z"), + // Score: to.Ptr[float32](1), + // ConsumptionUnits: to.Ptr[float32](12.24521), + // ImpactedResourceCount: to.Ptr[float32](1), + // PotentialScoreIncrease: to.Ptr[float32](0), + // }, + // }, + // }, + // }, + // }, + // }, + // { + // ID: to.Ptr("/subscriptions/a5481ee1-95df-47d0-85d4-dd3f0dfa19bc/providers/Microsoft.Advisor/advisorScore/Performance"), + // Name: to.Ptr("Performance"), + // Type: to.Ptr("Microsoft.Advisor/advisorScore"), + // Properties: &armadvisor.ScoreEntityProperties{ + // LastRefreshedScore: &armadvisor.ScoreEntity{ + // Date: to.Ptr("2020-06-25T00:00:00Z"), + // Score: to.Ptr[float32](1), + // ConsumptionUnits: to.Ptr[float32](12.24521), + // ImpactedResourceCount: to.Ptr[float32](1), + // PotentialScoreIncrease: to.Ptr[float32](0), + // CategoryCount: to.Ptr[float32](2), + // }, + // TimeSeries: []*armadvisor.TimeSeriesEntity{ + // { + // AggregationLevel: to.Ptr(armadvisor.AggregatedDay), + // ScoreHistory: []*armadvisor.ScoreEntity{ + // { + // Date: to.Ptr("2020-06-25T00:00:00Z"), + // Score: to.Ptr[float32](1), + // ConsumptionUnits: to.Ptr[float32](12.24521), + // ImpactedResourceCount: to.Ptr[float32](1), + // PotentialScoreIncrease: to.Ptr[float32](0), + // }, + // }, + // }, + // { + // AggregationLevel: to.Ptr(armadvisor.AggregatedMonth), + // ScoreHistory: []*armadvisor.ScoreEntity{ + // { + // Date: to.Ptr("2020-05-30T00:00:00Z"), + // Score: to.Ptr[float32](1), + // ConsumptionUnits: to.Ptr[float32](12.24521), + // ImpactedResourceCount: to.Ptr[float32](1), + // PotentialScoreIncrease: to.Ptr[float32](0), + // }, + // }, + // }, + // { + // AggregationLevel: to.Ptr(armadvisor.AggregatedWeek), + // ScoreHistory: []*armadvisor.ScoreEntity{ + // { + // Date: to.Ptr("2020-06-25T00:00:00Z"), + // Score: to.Ptr[float32](1), + // ConsumptionUnits: to.Ptr[float32](12.24521), + // ImpactedResourceCount: to.Ptr[float32](1), + // PotentialScoreIncrease: to.Ptr[float32](0), + // }, + // }, + // }, + // }, + // }, + // }, + // { + // ID: to.Ptr("/subscriptions/a5481ee1-95df-47d0-85d4-dd3f0dfa19bc/providers/Microsoft.Advisor/advisorScore/Security"), + // Name: to.Ptr("Security"), + // Type: to.Ptr("Microsoft.Advisor/advisorScore"), + // Properties: &armadvisor.ScoreEntityProperties{ + // LastRefreshedScore: &armadvisor.ScoreEntity{ + // Date: to.Ptr("2020-06-25T00:00:00Z"), + // Score: to.Ptr[float32](1), + // ConsumptionUnits: to.Ptr[float32](12.24521), + // ImpactedResourceCount: to.Ptr[float32](1), + // PotentialScoreIncrease: to.Ptr[float32](0), + // CategoryCount: to.Ptr[float32](3), + // }, + // TimeSeries: []*armadvisor.TimeSeriesEntity{ + // { + // AggregationLevel: to.Ptr(armadvisor.AggregatedDay), + // ScoreHistory: []*armadvisor.ScoreEntity{ + // { + // Date: to.Ptr("2020-06-25T00:00:00Z"), + // Score: to.Ptr[float32](1), + // ConsumptionUnits: to.Ptr[float32](12.24521), + // ImpactedResourceCount: to.Ptr[float32](1), + // PotentialScoreIncrease: to.Ptr[float32](0), + // }, + // }, + // }, + // { + // AggregationLevel: to.Ptr(armadvisor.AggregatedMonth), + // ScoreHistory: []*armadvisor.ScoreEntity{ + // { + // Date: to.Ptr("2020-05-30T00:00:00Z"), + // Score: to.Ptr[float32](1), + // ConsumptionUnits: to.Ptr[float32](12.24521), + // ImpactedResourceCount: to.Ptr[float32](1), + // PotentialScoreIncrease: to.Ptr[float32](0), + // }, + // }, + // }, + // { + // AggregationLevel: to.Ptr(armadvisor.AggregatedWeek), + // ScoreHistory: []*armadvisor.ScoreEntity{ + // { + // Date: to.Ptr("2020-06-25T00:00:00Z"), + // Score: to.Ptr[float32](1), + // ConsumptionUnits: to.Ptr[float32](12.24521), + // ImpactedResourceCount: to.Ptr[float32](1), + // PotentialScoreIncrease: to.Ptr[float32](0), + // }, + // }, + // }, + // }, + // }, + // }, + // { + // ID: to.Ptr("/subscriptions/a5481ee1-95df-47d0-85d4-dd3f0dfa19bc/providers/Microsoft.Advisor/advisorScore/HighAvailability"), + // Name: to.Ptr("HighAvailability"), + // Type: to.Ptr("Microsoft.Advisor/advisorScore"), + // Properties: &armadvisor.ScoreEntityProperties{ + // LastRefreshedScore: &armadvisor.ScoreEntity{ + // Date: to.Ptr("2020-06-25T00:00:00Z"), + // Score: to.Ptr[float32](1), + // ConsumptionUnits: to.Ptr[float32](12.24521), + // ImpactedResourceCount: to.Ptr[float32](1), + // PotentialScoreIncrease: to.Ptr[float32](0), + // CategoryCount: to.Ptr[float32](2), + // }, + // TimeSeries: []*armadvisor.TimeSeriesEntity{ + // { + // AggregationLevel: to.Ptr(armadvisor.AggregatedDay), + // ScoreHistory: []*armadvisor.ScoreEntity{ + // { + // Date: to.Ptr("2020-06-25T00:00:00Z"), + // Score: to.Ptr[float32](1), + // ConsumptionUnits: to.Ptr[float32](12.24521), + // ImpactedResourceCount: to.Ptr[float32](1), + // PotentialScoreIncrease: to.Ptr[float32](0), + // }, + // }, + // }, + // }, + // }, + // }, + // { + // ID: to.Ptr("/subscriptions/a5481ee1-95df-47d0-85d4-dd3f0dfa19bc/providers/Microsoft.Advisor/advisorScore/OperationalExcellence"), + // Name: to.Ptr("OperationalExcellence"), + // Type: to.Ptr("Microsoft.Advisor/advisorScore"), + // Properties: &armadvisor.ScoreEntityProperties{ + // LastRefreshedScore: &armadvisor.ScoreEntity{ + // Date: to.Ptr("2020-06-25T00:00:00Z"), + // Score: to.Ptr[float32](1), + // ConsumptionUnits: to.Ptr[float32](12.24521), + // ImpactedResourceCount: to.Ptr[float32](1), + // PotentialScoreIncrease: to.Ptr[float32](0), + // CategoryCount: to.Ptr[float32](1), + // }, + // TimeSeries: []*armadvisor.TimeSeriesEntity{ + // { + // AggregationLevel: to.Ptr(armadvisor.AggregatedDay), + // ScoreHistory: []*armadvisor.ScoreEntity{ + // { + // Date: to.Ptr("2020-06-25T00:00:00Z"), + // Score: to.Ptr[float32](1), + // ConsumptionUnits: to.Ptr[float32](12.24521), + // ImpactedResourceCount: to.Ptr[float32](1), + // PotentialScoreIncrease: to.Ptr[float32](0), + // }, + // }, + // }, + // }, + // }, + // }, + // { + // ID: to.Ptr("/subscriptions/a5481ee1-95df-47d0-85d4-dd3f0dfa19bc/providers/Microsoft.Advisor/advisorScore/Advisor"), + // Name: to.Ptr("Advisor"), + // Type: to.Ptr("Microsoft.Advisor/advisorScore"), + // Properties: &armadvisor.ScoreEntityProperties{ + // LastRefreshedScore: &armadvisor.ScoreEntity{ + // Date: to.Ptr("2020-06-25T00:00:00Z"), + // Score: to.Ptr[float32](1), + // ConsumptionUnits: to.Ptr[float32](12.24521), + // ImpactedResourceCount: to.Ptr[float32](1), + // PotentialScoreIncrease: to.Ptr[float32](0), + // CategoryCount: to.Ptr[float32](1), + // }, + // TimeSeries: []*armadvisor.TimeSeriesEntity{ + // { + // AggregationLevel: to.Ptr(armadvisor.AggregatedDay), + // ScoreHistory: []*armadvisor.ScoreEntity{ + // { + // Date: to.Ptr("2020-06-25T00:00:00Z"), + // Score: to.Ptr[float32](1), + // ConsumptionUnits: to.Ptr[float32](12.24521), + // ImpactedResourceCount: to.Ptr[float32](1), + // PotentialScoreIncrease: to.Ptr[float32](0), + // }, + // }, + // }, + // }, + // }, + // }, + // }, + // }, + // } + } +} diff --git a/sdk/resourcemanager/advisor/armadvisor/suppressions_client.go b/sdk/resourcemanager/advisor/armadvisor/suppressions_client.go index 91ac2eae236f..0a1cf468b00c 100644 --- a/sdk/resourcemanager/advisor/armadvisor/suppressions_client.go +++ b/sdk/resourcemanager/advisor/armadvisor/suppressions_client.go @@ -1,7 +1,6 @@ // 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. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package armadvisor @@ -26,9 +25,9 @@ type SuppressionsClient struct { } // NewSuppressionsClient creates a new instance of SuppressionsClient with the specified values. -// - subscriptionID - The Azure subscription ID. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. // - credential - used to authorize requests. Usually a credential from azidentity. -// - options - pass nil to accept the default values. +// - options - Contains optional client configuration. Pass nil to accept the default values. func NewSuppressionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*SuppressionsClient, error) { cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) if err != nil { @@ -42,12 +41,11 @@ func NewSuppressionsClient(subscriptionID string, credential azcore.TokenCredent } // Create - Enables the snoozed or dismissed attribute of a recommendation. The snoozed or dismissed attribute is referred -// to as a suppression. Use this API to create or update the snoozed or dismissed status of -// a recommendation. +// to as a suppression. Use this API to create or update the snoozed or dismissed status of a recommendation. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2020-01-01 -// - resourceURI - The fully qualified Azure Resource Manager identifier of the resource to which the recommendation applies. +// Generated from API version 2025-05-01-preview +// - resourceURI - The fully qualified Azure Resource manager identifier of the resource. // - recommendationID - The recommendation ID. // - name - The name of the suppression. // - suppressionContract - The snoozed or dismissed attribute; for example, the snooze duration. @@ -75,12 +73,12 @@ func (client *SuppressionsClient) Create(ctx context.Context, resourceURI string } // createCreateRequest creates the Create request. -func (client *SuppressionsClient) createCreateRequest(ctx context.Context, resourceURI string, recommendationID string, name string, suppressionContract SuppressionContract, options *SuppressionsClientCreateOptions) (*policy.Request, error) { +func (client *SuppressionsClient) createCreateRequest(ctx context.Context, resourceURI string, recommendationID string, name string, suppressionContract SuppressionContract, _ *SuppressionsClientCreateOptions) (*policy.Request, error) { urlPath := "/{resourceUri}/providers/Microsoft.Advisor/recommendations/{recommendationId}/suppressions/{name}" if resourceURI == "" { return nil, errors.New("parameter resourceURI cannot be empty") } - urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", url.PathEscape(resourceURI)) + urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", resourceURI) if recommendationID == "" { return nil, errors.New("parameter recommendationID cannot be empty") } @@ -94,9 +92,10 @@ func (client *SuppressionsClient) createCreateRequest(ctx context.Context, resou return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2020-01-01") + reqQP.Set("api-version", "2025-05-01-preview") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, suppressionContract); err != nil { return nil, err } @@ -116,8 +115,8 @@ func (client *SuppressionsClient) createHandleResponse(resp *http.Response) (Sup // is referred to as a suppression. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2020-01-01 -// - resourceURI - The fully qualified Azure Resource Manager identifier of the resource to which the recommendation applies. +// Generated from API version 2025-05-01-preview +// - resourceURI - The fully qualified Azure Resource manager identifier of the resource. // - recommendationID - The recommendation ID. // - name - The name of the suppression. // - options - SuppressionsClientDeleteOptions contains the optional parameters for the SuppressionsClient.Delete method. @@ -143,12 +142,12 @@ func (client *SuppressionsClient) Delete(ctx context.Context, resourceURI string } // deleteCreateRequest creates the Delete request. -func (client *SuppressionsClient) deleteCreateRequest(ctx context.Context, resourceURI string, recommendationID string, name string, options *SuppressionsClientDeleteOptions) (*policy.Request, error) { +func (client *SuppressionsClient) deleteCreateRequest(ctx context.Context, resourceURI string, recommendationID string, name string, _ *SuppressionsClientDeleteOptions) (*policy.Request, error) { urlPath := "/{resourceUri}/providers/Microsoft.Advisor/recommendations/{recommendationId}/suppressions/{name}" if resourceURI == "" { return nil, errors.New("parameter resourceURI cannot be empty") } - urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", url.PathEscape(resourceURI)) + urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", resourceURI) if recommendationID == "" { return nil, errors.New("parameter recommendationID cannot be empty") } @@ -162,17 +161,16 @@ func (client *SuppressionsClient) deleteCreateRequest(ctx context.Context, resou return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2020-01-01") + reqQP.Set("api-version", "2025-05-01-preview") req.Raw().URL.RawQuery = reqQP.Encode() - req.Raw().Header["Accept"] = []string{"application/json"} return req, nil } // Get - Obtains the details of a suppression. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2020-01-01 -// - resourceURI - The fully qualified Azure Resource Manager identifier of the resource to which the recommendation applies. +// Generated from API version 2025-05-01-preview +// - resourceURI - The fully qualified Azure Resource manager identifier of the resource. // - recommendationID - The recommendation ID. // - name - The name of the suppression. // - options - SuppressionsClientGetOptions contains the optional parameters for the SuppressionsClient.Get method. @@ -199,12 +197,12 @@ func (client *SuppressionsClient) Get(ctx context.Context, resourceURI string, r } // getCreateRequest creates the Get request. -func (client *SuppressionsClient) getCreateRequest(ctx context.Context, resourceURI string, recommendationID string, name string, options *SuppressionsClientGetOptions) (*policy.Request, error) { +func (client *SuppressionsClient) getCreateRequest(ctx context.Context, resourceURI string, recommendationID string, name string, _ *SuppressionsClientGetOptions) (*policy.Request, error) { urlPath := "/{resourceUri}/providers/Microsoft.Advisor/recommendations/{recommendationId}/suppressions/{name}" if resourceURI == "" { return nil, errors.New("parameter resourceURI cannot be empty") } - urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", url.PathEscape(resourceURI)) + urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", resourceURI) if recommendationID == "" { return nil, errors.New("parameter recommendationID cannot be empty") } @@ -218,7 +216,7 @@ func (client *SuppressionsClient) getCreateRequest(ctx context.Context, resource return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2020-01-01") + reqQP.Set("api-version", "2025-05-01-preview") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -236,7 +234,7 @@ func (client *SuppressionsClient) getHandleResponse(resp *http.Response) (Suppre // NewListPager - Retrieves the list of snoozed or dismissed suppressions for a subscription. The snoozed or dismissed attribute // of a recommendation is referred to as a suppression. // -// Generated from API version 2020-01-01 +// Generated from API version 2025-05-01-preview // - options - SuppressionsClientListOptions contains the optional parameters for the SuppressionsClient.NewListPager method. func (client *SuppressionsClient) NewListPager(options *SuppressionsClientListOptions) *runtime.Pager[SuppressionsClientListResponse] { return runtime.NewPager(runtime.PagingHandler[SuppressionsClientListResponse]{ @@ -273,13 +271,13 @@ func (client *SuppressionsClient) listCreateRequest(ctx context.Context, options return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2020-01-01") - if options != nil && options.Top != nil { - reqQP.Set("$top", strconv.FormatInt(int64(*options.Top), 10)) - } if options != nil && options.SkipToken != nil { reqQP.Set("$skipToken", *options.SkipToken) } + if options != nil && options.Top != nil { + reqQP.Set("$top", strconv.FormatInt(int64(*options.Top), 10)) + } + reqQP.Set("api-version", "2025-05-01-preview") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil diff --git a/sdk/resourcemanager/advisor/armadvisor/suppressions_client_example_test.go b/sdk/resourcemanager/advisor/armadvisor/suppressions_client_example_test.go index e0a25bb20831..e701ff054c37 100644 --- a/sdk/resourcemanager/advisor/armadvisor/suppressions_client_example_test.go +++ b/sdk/resourcemanager/advisor/armadvisor/suppressions_client_example_test.go @@ -1,114 +1,113 @@ // 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. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package armadvisor_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/advisor/armadvisor" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/advisor/armadvisor/v2" + "log" ) -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/7a2ac91de424f271cf91cc8009f3fe9ee8249086/specification/advisor/resource-manager/Microsoft.Advisor/stable/2020-01-01/examples/GetSuppressionDetail.json -func ExampleSuppressionsClient_Get() { +// Generated from example definition: 2025-05-01-preview/CreateSuppression.json +func ExampleSuppressionsClient_Create() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() - clientFactory, err := armadvisor.NewClientFactory("", cred, nil) + clientFactory, err := armadvisor.NewClientFactory("", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } - res, err := clientFactory.NewSuppressionsClient().Get(ctx, "resourceUri", "recommendationId", "suppressionName1", nil) + res, err := clientFactory.NewSuppressionsClient().Create(ctx, "resourceUri", "recommendationId", "suppressionName1", armadvisor.SuppressionContract{ + Properties: &armadvisor.SuppressionProperties{ + TTL: to.Ptr("07:00:00:00"), + }, + }, 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.SuppressionContract = armadvisor.SuppressionContract{ - // Name: to.Ptr("suppressionName1"), - // Type: to.Ptr("Microsoft.Advisor/suppressions"), - // ID: to.Ptr("/resourceUri/providers/Microsoft.Advisor/recommendations/recommendationId/suppressions/suppressionName1"), - // Properties: &armadvisor.SuppressionProperties{ - // ExpirationTimeStamp: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2020-10-25T22:24:43.321Z"); return t}()), - // SuppressionID: to.Ptr("suppressionId1"), - // TTL: to.Ptr("7.00:00:00"), + // res = armadvisor.SuppressionsClientCreateResponse{ + // SuppressionContract: &armadvisor.SuppressionContract{ + // ID: to.Ptr("/subscriptions/a5481ee1-95df-47d0-85d4-dd3f0dfa19bc/resourceGroups/resourceGroup/providers/Microsoft.Compute/availabilitysets/armavset/providers/Microsoft.Advisor/recommendations/bd27ddc6-1312-4067-b4af-cbb45e32cfd7/suppressions/HardcodedSuppressionName"), + // Name: to.Ptr("suppressionName1"), + // Type: to.Ptr("Microsoft.Advisor/suppressions"), + // Properties: &armadvisor.SuppressionProperties{ + // SuppressionID: to.Ptr("suppressionId"), + // TTL: to.Ptr("07:00:00:00"), + // }, // }, // } } -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/7a2ac91de424f271cf91cc8009f3fe9ee8249086/specification/advisor/resource-manager/Microsoft.Advisor/stable/2020-01-01/examples/CreateSuppression.json -func ExampleSuppressionsClient_Create() { +// Generated from example definition: 2025-05-01-preview/DeleteSuppression.json +func ExampleSuppressionsClient_Delete() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() - clientFactory, err := armadvisor.NewClientFactory("", cred, nil) + clientFactory, err := armadvisor.NewClientFactory("", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } - res, err := clientFactory.NewSuppressionsClient().Create(ctx, "resourceUri", "recommendationId", "suppressionName1", armadvisor.SuppressionContract{ - Properties: &armadvisor.SuppressionProperties{ - TTL: to.Ptr("07:00:00:00"), - }, - }, nil) + _, err = clientFactory.NewSuppressionsClient().Delete(ctx, "resourceUri", "recommendationId", "suppressionName1", 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.SuppressionContract = armadvisor.SuppressionContract{ - // Name: to.Ptr("suppressionName1"), - // Type: to.Ptr("Microsoft.Advisor/suppressions"), - // ID: to.Ptr("/resourceUri/providers/Microsoft.Advisor/recommendations/recommendationId/suppressions/suppressionName1"), - // Properties: &armadvisor.SuppressionProperties{ - // SuppressionID: to.Ptr("suppressionId"), - // TTL: to.Ptr("07:00:00:00"), - // }, - // } } -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/7a2ac91de424f271cf91cc8009f3fe9ee8249086/specification/advisor/resource-manager/Microsoft.Advisor/stable/2020-01-01/examples/DeleteSuppression.json -func ExampleSuppressionsClient_Delete() { +// Generated from example definition: 2025-05-01-preview/GetSuppressionDetail.json +func ExampleSuppressionsClient_Get() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() - clientFactory, err := armadvisor.NewClientFactory("", cred, nil) + clientFactory, err := armadvisor.NewClientFactory("", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } - _, err = clientFactory.NewSuppressionsClient().Delete(ctx, "resourceUri", "recommendationId", "suppressionName1", nil) + res, err := clientFactory.NewSuppressionsClient().Get(ctx, "resourceUri", "recommendationId", "suppressionName1", 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 = armadvisor.SuppressionsClientGetResponse{ + // SuppressionContract: &armadvisor.SuppressionContract{ + // ID: to.Ptr("/subscriptions/a5481ee1-95df-47d0-85d4-dd3f0dfa19bc/resourceGroups/resourceGroup/providers/Microsoft.Compute/availabilitysets/armavset/providers/Microsoft.Advisor/recommendations/recommendationId/suppressions/suppressionName1"), + // Name: to.Ptr("suppressionName1"), + // Type: to.Ptr("Microsoft.Advisor/suppressions"), + // Properties: &armadvisor.SuppressionProperties{ + // SuppressionID: to.Ptr("suppressionId1"), + // TTL: to.Ptr("7.00:00:00"), + // ExpirationTimeStamp: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2020-10-25T22:24:43.3216408Z"); return t}()), + // }, + // }, + // } } -// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/7a2ac91de424f271cf91cc8009f3fe9ee8249086/specification/advisor/resource-manager/Microsoft.Advisor/stable/2020-01-01/examples/ListSuppressions.json +// Generated from example definition: 2025-05-01-preview/ListSuppressions.json func ExampleSuppressionsClient_NewListPager() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() - clientFactory, err := armadvisor.NewClientFactory("", cred, nil) + clientFactory, err := armadvisor.NewClientFactory("a5481ee1-95df-47d0-85d4-dd3f0dfa19bc", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } - pager := clientFactory.NewSuppressionsClient().NewListPager(&armadvisor.SuppressionsClientListOptions{Top: nil, - SkipToken: nil, - }) + pager := clientFactory.NewSuppressionsClient().NewListPager(nil) for pager.More() { page, err := pager.NextPage(ctx) if err != nil { @@ -119,28 +118,32 @@ func ExampleSuppressionsClient_NewListPager() { _ = 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.SuppressionContractListResult = armadvisor.SuppressionContractListResult{ - // Value: []*armadvisor.SuppressionContract{ - // { - // Name: to.Ptr("suppressionName1"), - // Type: to.Ptr("Microsoft.Advisor/suppressions"), - // ID: to.Ptr("/resourceUri/providers/Microsoft.Advisor/recommendations/recommendationId/suppressions/suppressionName1"), - // Properties: &armadvisor.SuppressionProperties{ - // ExpirationTimeStamp: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2020-10-24T22:24:43.321Z"); return t}()), - // SuppressionID: to.Ptr("suppressionId1"), - // TTL: to.Ptr("7.00:00:00"), + // page = armadvisor.SuppressionsClientListResponse{ + // SuppressionContractListResult: armadvisor.SuppressionContractListResult{ + // NextLink: to.Ptr("https://management.azure.com/subscriptions/a5481ee1-95df-47d0-85d4-dd3f0dfa19bc/providers/microsoft.Advisor/suppressions?api-version=2025-05-01-preview&$top=3&$skiptoken=skiptoken"), + // Value: []*armadvisor.SuppressionContract{ + // { + // ID: to.Ptr("/subscriptions/a5481ee1-95df-47d0-85d4-dd3f0dfa19bc/resourceGroups/resourceGroup/providers/Microsoft.Compute/availabilitysets/armavset/providers/Microsoft.Advisor/recommendations/1b266c91-3a92-4423-8aa2-ee13a6d90f47/suppressions/HardcodedSuppressionName"), + // Name: to.Ptr("HardcodedSuppressionName"), + // Type: to.Ptr("Microsoft.Advisor/suppressions"), + // Properties: &armadvisor.SuppressionProperties{ + // SuppressionID: to.Ptr("58403b0e-113b-e428-d6f7-2a524380b955"), + // TTL: to.Ptr("7.00:00:00"), + // ExpirationTimeStamp: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2022-10-24T22:24:43.3216408Z"); return t}()), + // }, // }, - // }, - // { - // Name: to.Ptr("suppressionName2"), - // Type: to.Ptr("Microsoft.Advisor/suppressions"), - // ID: to.Ptr("/resourceUri/providers/Microsoft.Advisor/recommendations/recommendationId/suppressions/suppressionName2"), - // Properties: &armadvisor.SuppressionProperties{ - // ExpirationTimeStamp: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2020-10-25T22:24:43.321Z"); return t}()), - // SuppressionID: to.Ptr("suppressionId2"), - // TTL: to.Ptr("7.00:00:00"), + // { + // ID: to.Ptr("/subscriptions/a5481ee1-95df-47d0-85d4-dd3f0dfa19bc/resourceGroups/resourceGroup/providers/Microsoft.Compute/virtualMachines/xyz/providers/Microsoft.Advisor/recommendations/3385b5d0-b8cc-bdcf-0e0d-b5a3d1e9b93b/suppressions/HardcodedSuppressionName"), + // Name: to.Ptr("HardcodedSuppressionName"), + // Type: to.Ptr("Microsoft.Advisor/suppressions"), + // Properties: &armadvisor.SuppressionProperties{ + // SuppressionID: to.Ptr("72a23574-d49a-84d0-0a7d-fb3fe6cba16b"), + // TTL: to.Ptr("7.00:00:00"), + // ExpirationTimeStamp: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2022-10-25T22:24:43.3216408Z"); return t}()), + // }, // }, - // }}, + // }, + // }, // } } } diff --git a/sdk/resourcemanager/advisor/armadvisor/testdata/_metadata.json b/sdk/resourcemanager/advisor/armadvisor/testdata/_metadata.json new file mode 100644 index 000000000000..12fa52b1053c --- /dev/null +++ b/sdk/resourcemanager/advisor/armadvisor/testdata/_metadata.json @@ -0,0 +1,6 @@ +{ + "apiVersions": { + "Microsoft.Advisor": "2025-05-01-preview" + }, + "emitterVersion": "0.10.2" +} diff --git a/sdk/resourcemanager/advisor/armadvisor/time_rfc3339.go b/sdk/resourcemanager/advisor/armadvisor/time_rfc3339.go deleted file mode 100644 index 4691cbef22ca..000000000000 --- a/sdk/resourcemanager/advisor/armadvisor/time_rfc3339.go +++ /dev/null @@ -1,83 +0,0 @@ -// 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 armadvisor - -import ( - "encoding/json" - "fmt" - "github.com/Azure/azure-sdk-for-go/sdk/azcore" - "reflect" - "regexp" - "strings" - "time" -) - -// 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+)*"*$`) - -const ( - utcDateTimeJSON = `"2006-01-02T15:04:05.999999999"` - utcDateTime = "2006-01-02T15:04:05.999999999" - dateTimeJSON = `"` + time.RFC3339Nano + `"` -) - -type dateTimeRFC3339 time.Time - -func (t dateTimeRFC3339) MarshalJSON() ([]byte, error) { - tt := time.Time(t) - return tt.MarshalJSON() -} - -func (t dateTimeRFC3339) MarshalText() ([]byte, error) { - tt := time.Time(t) - return tt.MarshalText() -} - -func (t *dateTimeRFC3339) UnmarshalJSON(data []byte) error { - layout := utcDateTimeJSON - if tzOffsetRegex.Match(data) { - layout = dateTimeJSON - } - return t.Parse(layout, string(data)) -} - -func (t *dateTimeRFC3339) UnmarshalText(data []byte) error { - layout := utcDateTime - if tzOffsetRegex.Match(data) { - layout = time.RFC3339Nano - } - return t.Parse(layout, string(data)) -} - -func (t *dateTimeRFC3339) Parse(layout, value string) error { - p, err := time.Parse(layout, strings.ToUpper(value)) - *t = dateTimeRFC3339(p) - return err -} - -func populateDateTimeRFC3339(m map[string]any, k string, t *time.Time) { - if t == nil { - return - } else if azcore.IsNullValue(t) { - m[k] = nil - return - } else if reflect.ValueOf(t).IsNil() { - return - } - m[k] = (*dateTimeRFC3339)(t) -} - -func unpopulateDateTimeRFC3339(data json.RawMessage, fn string, t **time.Time) error { - if data == nil || strings.EqualFold(string(data), "null") { - return nil - } - var aux dateTimeRFC3339 - if err := json.Unmarshal(data, &aux); err != nil { - return fmt.Errorf("struct field %s: %v", fn, err) - } - *t = (*time.Time)(&aux) - return nil -} diff --git a/sdk/resourcemanager/advisor/armadvisor/triagerecommendations_client.go b/sdk/resourcemanager/advisor/armadvisor/triagerecommendations_client.go new file mode 100644 index 000000000000..d1f284e36460 --- /dev/null +++ b/sdk/resourcemanager/advisor/armadvisor/triagerecommendations_client.go @@ -0,0 +1,349 @@ +// 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) Go Code Generator. DO NOT EDIT. + +package armadvisor + +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" + "strconv" + "strings" +) + +// TriageRecommendationsClient contains the methods for the TriageRecommendations group. +// Don't use this type directly, use NewTriageRecommendationsClient() instead. +type TriageRecommendationsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewTriageRecommendationsClient creates a new instance of TriageRecommendationsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewTriageRecommendationsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*TriageRecommendationsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &TriageRecommendationsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// ApproveTriageRecommendation - Approve triage recommendation by id. +// +// Approve a triage recommendation for a given id. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-05-01-preview +// - reviewID - Existing review id. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). +// - recommendationID - Existing triage recommendation id. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). +// - options - TriageRecommendationsClientApproveTriageRecommendationOptions contains the optional parameters for the TriageRecommendationsClient.ApproveTriageRecommendation +// method. +func (client *TriageRecommendationsClient) ApproveTriageRecommendation(ctx context.Context, reviewID string, recommendationID string, options *TriageRecommendationsClientApproveTriageRecommendationOptions) (TriageRecommendationsClientApproveTriageRecommendationResponse, error) { + var err error + const operationName = "TriageRecommendationsClient.ApproveTriageRecommendation" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.approveTriageRecommendationCreateRequest(ctx, reviewID, recommendationID, options) + if err != nil { + return TriageRecommendationsClientApproveTriageRecommendationResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return TriageRecommendationsClientApproveTriageRecommendationResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return TriageRecommendationsClientApproveTriageRecommendationResponse{}, err + } + return TriageRecommendationsClientApproveTriageRecommendationResponse{}, nil +} + +// approveTriageRecommendationCreateRequest creates the ApproveTriageRecommendation request. +func (client *TriageRecommendationsClient) approveTriageRecommendationCreateRequest(ctx context.Context, reviewID string, recommendationID string, _ *TriageRecommendationsClientApproveTriageRecommendationOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Advisor/resiliencyReviews/{reviewId}/providers/Microsoft.Advisor/triageRecommendations/{recommendationId}/approve" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if reviewID == "" { + return nil, errors.New("parameter reviewID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{reviewId}", url.PathEscape(reviewID)) + if recommendationID == "" { + return nil, errors.New("parameter recommendationID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{recommendationId}", url.PathEscape(recommendationID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2025-05-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + return req, nil +} + +// Get - Get an existing recommendation by id for an existing Resiliency Review Id. +// +// Get an existing recommendation by id for an existing Azure Advisor Resiliency Review Id. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-05-01-preview +// - reviewID - Existing review id. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). +// - recommendationID - Existing triage recommendation id. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). +// - options - TriageRecommendationsClientGetOptions contains the optional parameters for the TriageRecommendationsClient.Get +// method. +func (client *TriageRecommendationsClient) Get(ctx context.Context, reviewID string, recommendationID string, options *TriageRecommendationsClientGetOptions) (TriageRecommendationsClientGetResponse, error) { + var err error + const operationName = "TriageRecommendationsClient.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, reviewID, recommendationID, options) + if err != nil { + return TriageRecommendationsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return TriageRecommendationsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return TriageRecommendationsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *TriageRecommendationsClient) getCreateRequest(ctx context.Context, reviewID string, recommendationID string, _ *TriageRecommendationsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Advisor/resiliencyReviews/{reviewId}/providers/Microsoft.Advisor/triageRecommendations/{recommendationId}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if reviewID == "" { + return nil, errors.New("parameter reviewID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{reviewId}", url.PathEscape(reviewID)) + if recommendationID == "" { + return nil, errors.New("parameter recommendationID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{recommendationId}", url.PathEscape(recommendationID)) + 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", "2025-05-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 *TriageRecommendationsClient) getHandleResponse(resp *http.Response) (TriageRecommendationsClientGetResponse, error) { + result := TriageRecommendationsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.TriageRecommendation); err != nil { + return TriageRecommendationsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Get list of recommendations for an existing Resiliency Review Id. +// +// Get list of recommendations for an existing Azure Advisor Resiliency Review Id. +// +// Generated from API version 2025-05-01-preview +// - reviewID - Existing review id. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). +// - options - TriageRecommendationsClientListOptions contains the optional parameters for the TriageRecommendationsClient.NewListPager +// method. +func (client *TriageRecommendationsClient) NewListPager(reviewID string, options *TriageRecommendationsClientListOptions) *runtime.Pager[TriageRecommendationsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[TriageRecommendationsClientListResponse]{ + More: func(page TriageRecommendationsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *TriageRecommendationsClientListResponse) (TriageRecommendationsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "TriageRecommendationsClient.NewListPager") + 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.listCreateRequest(ctx, reviewID, options) + }, nil) + if err != nil { + return TriageRecommendationsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *TriageRecommendationsClient) listCreateRequest(ctx context.Context, reviewID string, options *TriageRecommendationsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Advisor/resiliencyReviews/{reviewId}/providers/Microsoft.Advisor/triageRecommendations" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if reviewID == "" { + return nil, errors.New("parameter reviewID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{reviewId}", url.PathEscape(reviewID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Skip != nil { + reqQP.Set("$skip", strconv.FormatInt(int64(*options.Skip), 10)) + } + if options != nil && options.Top != nil { + reqQP.Set("$top", strconv.FormatInt(int64(*options.Top), 10)) + } + reqQP.Set("api-version", "2025-05-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *TriageRecommendationsClient) listHandleResponse(resp *http.Response) (TriageRecommendationsClientListResponse, error) { + result := TriageRecommendationsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.TriageRecommendationCollection); err != nil { + return TriageRecommendationsClientListResponse{}, err + } + return result, nil +} + +// RejectTriageRecommendation - Reject existing triage recommendation by id. +// +// Reject an existing triage recommendation for a given id. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-05-01-preview +// - reviewID - Existing review id. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). +// - recommendationID - Existing triage recommendation id. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). +// - recommendationRejectBody - JSON object that contains reason for rejecting triage recommendation. +// - options - TriageRecommendationsClientRejectTriageRecommendationOptions contains the optional parameters for the TriageRecommendationsClient.RejectTriageRecommendation +// method. +func (client *TriageRecommendationsClient) RejectTriageRecommendation(ctx context.Context, reviewID string, recommendationID string, recommendationRejectBody RecommendationRejectBody, options *TriageRecommendationsClientRejectTriageRecommendationOptions) (TriageRecommendationsClientRejectTriageRecommendationResponse, error) { + var err error + const operationName = "TriageRecommendationsClient.RejectTriageRecommendation" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.rejectTriageRecommendationCreateRequest(ctx, reviewID, recommendationID, recommendationRejectBody, options) + if err != nil { + return TriageRecommendationsClientRejectTriageRecommendationResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return TriageRecommendationsClientRejectTriageRecommendationResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return TriageRecommendationsClientRejectTriageRecommendationResponse{}, err + } + return TriageRecommendationsClientRejectTriageRecommendationResponse{}, nil +} + +// rejectTriageRecommendationCreateRequest creates the RejectTriageRecommendation request. +func (client *TriageRecommendationsClient) rejectTriageRecommendationCreateRequest(ctx context.Context, reviewID string, recommendationID string, recommendationRejectBody RecommendationRejectBody, _ *TriageRecommendationsClientRejectTriageRecommendationOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Advisor/resiliencyReviews/{reviewId}/providers/Microsoft.Advisor/triageRecommendations/{recommendationId}/reject" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if reviewID == "" { + return nil, errors.New("parameter reviewID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{reviewId}", url.PathEscape(reviewID)) + if recommendationID == "" { + return nil, errors.New("parameter recommendationID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{recommendationId}", url.PathEscape(recommendationID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2025-05-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, recommendationRejectBody); err != nil { + return nil, err + } + return req, nil +} + +// ResetTriageRecommendation - Reset existing triage recommendation by id. +// +// Reset an existing triage recommendation for a given id. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-05-01-preview +// - reviewID - Existing review id. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). +// - recommendationID - Existing triage recommendation id. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). +// - options - TriageRecommendationsClientResetTriageRecommendationOptions contains the optional parameters for the TriageRecommendationsClient.ResetTriageRecommendation +// method. +func (client *TriageRecommendationsClient) ResetTriageRecommendation(ctx context.Context, reviewID string, recommendationID string, options *TriageRecommendationsClientResetTriageRecommendationOptions) (TriageRecommendationsClientResetTriageRecommendationResponse, error) { + var err error + const operationName = "TriageRecommendationsClient.ResetTriageRecommendation" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.resetTriageRecommendationCreateRequest(ctx, reviewID, recommendationID, options) + if err != nil { + return TriageRecommendationsClientResetTriageRecommendationResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return TriageRecommendationsClientResetTriageRecommendationResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return TriageRecommendationsClientResetTriageRecommendationResponse{}, err + } + return TriageRecommendationsClientResetTriageRecommendationResponse{}, nil +} + +// resetTriageRecommendationCreateRequest creates the ResetTriageRecommendation request. +func (client *TriageRecommendationsClient) resetTriageRecommendationCreateRequest(ctx context.Context, reviewID string, recommendationID string, _ *TriageRecommendationsClientResetTriageRecommendationOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Advisor/resiliencyReviews/{reviewId}/providers/Microsoft.Advisor/triageRecommendations/{recommendationId}/reset" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if reviewID == "" { + return nil, errors.New("parameter reviewID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{reviewId}", url.PathEscape(reviewID)) + if recommendationID == "" { + return nil, errors.New("parameter recommendationID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{recommendationId}", url.PathEscape(recommendationID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2025-05-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + return req, nil +} diff --git a/sdk/resourcemanager/advisor/armadvisor/triagerecommendations_client_example_test.go b/sdk/resourcemanager/advisor/armadvisor/triagerecommendations_client_example_test.go new file mode 100644 index 000000000000..7c97358efb21 --- /dev/null +++ b/sdk/resourcemanager/advisor/armadvisor/triagerecommendations_client_example_test.go @@ -0,0 +1,251 @@ +// 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) Go Code Generator. DO NOT EDIT. + +package armadvisor_test + +import ( + "context" + "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/advisor/armadvisor/v2" + "log" +) + +// Generated from example definition: 2025-05-01-preview/TriageRecommendationsApprove.json +func ExampleTriageRecommendationsClient_ApproveTriageRecommendation() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armadvisor.NewClientFactory("00000000-1111-2222-3333-444444444444", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewTriageRecommendationsClient().ApproveTriageRecommendation(ctx, "11111111-1111-2222-3333-444444444444", "22222222-1111-2222-3333-444444444444", 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 = armadvisor.TriageRecommendationsClientApproveTriageRecommendationResponse{ + // } +} + +// Generated from example definition: 2025-05-01-preview/TriageRecommendationsGet.json +func ExampleTriageRecommendationsClient_Get() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armadvisor.NewClientFactory("00000000-1111-2222-3333-444444444444", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewTriageRecommendationsClient().Get(ctx, "11111111-1111-2222-3333-444444444444", "22222222-1111-2222-3333-444444444444", 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 = armadvisor.TriageRecommendationsClientGetResponse{ + // TriageRecommendation: &armadvisor.TriageRecommendation{ + // ID: to.Ptr("/subscriptions/00000000-1111-2222-3333-444444444444/providers/Microsoft.Advisor/ResiliencyReview/11111111-1111-2222-3333-444444444444/providers/Microsoft.Advisor/TriageRecommendations/22222222-1111-2222-3333-444444444444"), + // Name: to.Ptr("22222222-1111-2222-3333-444444444444"), + // Type: to.Ptr("Microsoft.Advisor/TriageRecommendations"), + // SystemData: &armadvisor.SystemData{ + // CreatedBy: to.Ptr("user-identity"), + // CreatedByType: to.Ptr(armadvisor.CreatedByTypeUser), + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-06-30T09:41:00Z"); return t}()), + // LastModifiedBy: to.Ptr("user-identity"), + // LastModifiedByType: to.Ptr(armadvisor.CreatedByTypeUser), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-06-30T09:41:00Z"); return t}()), + // }, + // Properties: &armadvisor.TriageRecommendationProperties{ + // ReviewID: to.Ptr("11111111-1111-2222-3333-444444444444"), + // Title: to.Ptr("Explore the scale-limits of each Azure resource"), + // Priority: to.Ptr(armadvisor.PriorityNameHigh), + // RecommendationStatus: to.Ptr(armadvisor.RecommendationStatusNamePending), + // UpdatedAt: to.Ptr("2023-06-30T10:51:00Z"), + // RejectReason: to.Ptr(""), + // AppliesToSubscriptions: []*string{ + // to.Ptr("00000000-1111-2222-3333-444444444444"), + // to.Ptr("00000000-1111-2222-3333-555555555555"), + // to.Ptr("00000000-1111-2222-3333-666666666666"), + // }, + // Description: to.Ptr("Azure resources have scale limits. If you are planning to deploy a large number of resources, you should be aware of these limits. This recommendation provides links to the scale limits for each Azure resource."), + // PotentialBenefits: to.Ptr("Avoid deployment failures due to scale limits."), + // Notes: to.Ptr("This recommendation is based on the scale limits for each Azure resource. For more information, see Azure subscription and service limits, quotas, and constraints."), + // }, + // }, + // } +} + +// Generated from example definition: 2025-05-01-preview/TriageRecommendationsList.json +func ExampleTriageRecommendationsClient_NewListPager() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armadvisor.NewClientFactory("00000000-1111-2222-3333-444444444444", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + pager := clientFactory.NewTriageRecommendationsClient().NewListPager("11111111-1111-2222-3333-444444444444", 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 = armadvisor.TriageRecommendationsClientListResponse{ + // TriageRecommendationCollection: armadvisor.TriageRecommendationCollection{ + // Value: []*armadvisor.TriageRecommendation{ + // { + // ID: to.Ptr("/subscriptions/00000000-1111-2222-3333-444444444444/providers/Microsoft.Advisor/ResiliencyReview/11111111-1111-2222-3333-444444444444/providers/Microsoft.Advisor/TriageRecommendations/22222222-1111-2222-3333-444444444444"), + // Name: to.Ptr("22222222-1111-2222-3333-444444444444"), + // Type: to.Ptr("Microsoft.Advisor/TriageRecommendations"), + // SystemData: &armadvisor.SystemData{ + // CreatedBy: to.Ptr("user-identity"), + // CreatedByType: to.Ptr(armadvisor.CreatedByTypeUser), + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-06-30T09:41:00Z"); return t}()), + // LastModifiedBy: to.Ptr("user-identity"), + // LastModifiedByType: to.Ptr(armadvisor.CreatedByTypeUser), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-06-30T09:41:00Z"); return t}()), + // }, + // Properties: &armadvisor.TriageRecommendationProperties{ + // ReviewID: to.Ptr("11111111-1111-2222-3333-444444444444"), + // Title: to.Ptr("Explore the scale-limits of each Azure resource"), + // Priority: to.Ptr(armadvisor.PriorityNameHigh), + // RecommendationStatus: to.Ptr(armadvisor.RecommendationStatusNamePending), + // UpdatedAt: to.Ptr("2023-06-30T10:51:00Z"), + // RejectReason: to.Ptr(""), + // AppliesToSubscriptions: []*string{ + // to.Ptr("00000000-1111-2222-3333-444444444444"), + // to.Ptr("00000000-1111-2222-3333-555555555555"), + // to.Ptr("00000000-1111-2222-3333-666666666666"), + // }, + // Description: to.Ptr("Azure resources have scale limits. If you are planning to deploy a large number of resources, you should be aware of these limits. This recommendation provides links to the scale limits for each Azure resource."), + // PotentialBenefits: to.Ptr("Avoid deployment failures due to scale limits."), + // Notes: to.Ptr("This recommendation is based on the scale limits for each Azure resource. For more information, see Azure subscription and service limits, quotas, and constraints."), + // }, + // }, + // { + // ID: to.Ptr("/subscriptions/00000000-1111-2222-3333-444444444444/providers/Microsoft.Advisor/ResiliencyReview/11111111-1111-2222-3333-444444444444/providers/Microsoft.Advisor/TriageRecommendations/22222222-1111-2222-3333-555555555555"), + // Name: to.Ptr("22222222-1111-2222-3333-555555555555"), + // Type: to.Ptr("Microsoft.Advisor/TriageRecommendations"), + // SystemData: &armadvisor.SystemData{ + // CreatedBy: to.Ptr("user-identity"), + // CreatedByType: to.Ptr(armadvisor.CreatedByTypeUser), + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-06-30T09:41:00Z"); return t}()), + // LastModifiedBy: to.Ptr("user-identity"), + // LastModifiedByType: to.Ptr(armadvisor.CreatedByTypeUser), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-06-30T09:41:00Z"); return t}()), + // }, + // Properties: &armadvisor.TriageRecommendationProperties{ + // ReviewID: to.Ptr("11111111-1111-2222-3333-444444444444"), + // Title: to.Ptr("Turn off unused resources"), + // Priority: to.Ptr(armadvisor.PriorityNameHigh), + // RecommendationStatus: to.Ptr(armadvisor.RecommendationStatusNameRejected), + // UpdatedAt: to.Ptr("2023-06-30T10:51:00Z"), + // RejectReason: to.Ptr("Not a risk"), + // AppliesToSubscriptions: []*string{ + // to.Ptr("00000000-1111-2222-3333-444444444444"), + // to.Ptr("00000000-1111-2222-3333-555555555555"), + // to.Ptr("00000000-1111-2222-3333-777777777777"), + // }, + // Description: to.Ptr("Azure resources have scale limits. If you are planning to deploy a large number of resources, you should be aware of these limits. This recommendation provides links to the scale limits for each Azure resource."), + // PotentialBenefits: to.Ptr("Avoid deployment failures due to scale limits."), + // Notes: to.Ptr("This recommendation is based on the scale limits for each Azure resource. For more information, see Azure subscription and service limits, quotas, and constraints."), + // }, + // }, + // { + // ID: to.Ptr("/subscriptions/00000000-1111-2222-3333-444444444444/providers/Microsoft.Advisor/ResiliencyReview/11111111-1111-2222-3333-444444444444/providers/Microsoft.Advisor/TriageRecommendations/22222222-1111-2222-3333-666666666666"), + // Name: to.Ptr("22222222-1111-2222-3333-666666666666"), + // Type: to.Ptr("Microsoft.Advisor/TriageRecommendations"), + // SystemData: &armadvisor.SystemData{ + // CreatedBy: to.Ptr("user-identity"), + // CreatedByType: to.Ptr(armadvisor.CreatedByTypeUser), + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-06-30T09:41:00Z"); return t}()), + // LastModifiedBy: to.Ptr("user-identity"), + // LastModifiedByType: to.Ptr(armadvisor.CreatedByTypeUser), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-06-30T09:41:00Z"); return t}()), + // }, + // Properties: &armadvisor.TriageRecommendationProperties{ + // ReviewID: to.Ptr("11111111-1111-2222-3333-444444444444"), + // Title: to.Ptr("Enabled HTTPS on all web apps"), + // Priority: to.Ptr(armadvisor.PriorityNameHigh), + // RecommendationStatus: to.Ptr(armadvisor.RecommendationStatusNameApproved), + // UpdatedAt: to.Ptr("2023-06-30T10:51:00Z"), + // RejectReason: to.Ptr(""), + // AppliesToSubscriptions: []*string{ + // to.Ptr("00000000-1111-2222-3333-888888888888"), + // to.Ptr("00000000-1111-2222-3333-555555555555"), + // to.Ptr("00000000-1111-2222-3333-777777777777"), + // }, + // Description: to.Ptr("Azure resources have scale limits. If you are planning to deploy a large number of resources, you should be aware of these limits. This recommendation provides links to the scale limits for each Azure resource."), + // PotentialBenefits: to.Ptr("Avoid deployment failures due to scale limits."), + // Notes: to.Ptr("This recommendation is based on the scale limits for each Azure resource. For more information, see Azure subscription and service limits, quotas, and constraints."), + // }, + // }, + // }, + // NextLink: to.Ptr("https://management.azure.com/subscriptions/12345678-1234-1234-1234-123456789012/providers/Microsoft.Advisor/resiliencyReviews/12345678-1234-1234-1234-123456789abc/providers/Microsoft.Advisor/triageRecommendations?api-version=2025-05-01-preview&$skipToken=abc123"), + // }, + // } + } +} + +// Generated from example definition: 2025-05-01-preview/TriageRecommendationsReject.json +func ExampleTriageRecommendationsClient_RejectTriageRecommendation() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armadvisor.NewClientFactory("00000000-1111-2222-3333-444444444444", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewTriageRecommendationsClient().RejectTriageRecommendation(ctx, "11111111-1111-2222-3333-444444444444", "22222222-1111-2222-3333-444444444444", armadvisor.RecommendationRejectBody{ + ReasonForRejection: to.Ptr(armadvisor.ReasonForRejectionNameNotARisk), + }, 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 = armadvisor.TriageRecommendationsClientRejectTriageRecommendationResponse{ + // } +} + +// Generated from example definition: 2025-05-01-preview/TriageRecommendationsReset.json +func ExampleTriageRecommendationsClient_ResetTriageRecommendation() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armadvisor.NewClientFactory("00000000-1111-2222-3333-444444444444", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewTriageRecommendationsClient().ResetTriageRecommendation(ctx, "11111111-1111-2222-3333-444444444444", "22222222-1111-2222-3333-444444444444", 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 = armadvisor.TriageRecommendationsClientResetTriageRecommendationResponse{ + // } +} diff --git a/sdk/resourcemanager/advisor/armadvisor/triageresources_client.go b/sdk/resourcemanager/advisor/armadvisor/triageresources_client.go new file mode 100644 index 000000000000..5644e0939dc4 --- /dev/null +++ b/sdk/resourcemanager/advisor/armadvisor/triageresources_client.go @@ -0,0 +1,179 @@ +// 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) Go Code Generator. DO NOT EDIT. + +package armadvisor + +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" +) + +// TriageResourcesClient contains the methods for the TriageResources group. +// Don't use this type directly, use NewTriageResourcesClient() instead. +type TriageResourcesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewTriageResourcesClient creates a new instance of TriageResourcesClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewTriageResourcesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*TriageResourcesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &TriageResourcesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Get - Get existing triage resource. +// +// Get a triage resource for a given review and recommendation. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2025-05-01-preview +// - reviewID - Existing review id. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). +// - recommendationID - Existing triage recommendation id. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). +// - recommendationResourceID - Existing recommendation triage resource associated with a triage recommendation. This is a GUID-formatted +// string (e.g. 00000000-0000-0000-0000-000000000000). +// - options - TriageResourcesClientGetOptions contains the optional parameters for the TriageResourcesClient.Get method. +func (client *TriageResourcesClient) Get(ctx context.Context, reviewID string, recommendationID string, recommendationResourceID string, options *TriageResourcesClientGetOptions) (TriageResourcesClientGetResponse, error) { + var err error + const operationName = "TriageResourcesClient.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, reviewID, recommendationID, recommendationResourceID, options) + if err != nil { + return TriageResourcesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return TriageResourcesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return TriageResourcesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *TriageResourcesClient) getCreateRequest(ctx context.Context, reviewID string, recommendationID string, recommendationResourceID string, _ *TriageResourcesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Advisor/resiliencyReviews/{reviewId}/providers/Microsoft.Advisor/triageRecommendations/{recommendationId}/providers/Microsoft.Advisor/triageResources/{recommendationResourceId}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if reviewID == "" { + return nil, errors.New("parameter reviewID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{reviewId}", url.PathEscape(reviewID)) + if recommendationID == "" { + return nil, errors.New("parameter recommendationID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{recommendationId}", url.PathEscape(recommendationID)) + if recommendationResourceID == "" { + return nil, errors.New("parameter recommendationResourceID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{recommendationResourceId}", url.PathEscape(recommendationResourceID)) + 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", "2025-05-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 *TriageResourcesClient) getHandleResponse(resp *http.Response) (TriageResourcesClientGetResponse, error) { + result := TriageResourcesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.TriageResource); err != nil { + return TriageResourcesClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - List triage resources based on a review and recommendation. +// +// List all triage resources that belong to a review and recommendation. +// +// Generated from API version 2025-05-01-preview +// - reviewID - Existing review id. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). +// - recommendationID - Existing triage recommendation id. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). +// - options - TriageResourcesClientListOptions contains the optional parameters for the TriageResourcesClient.NewListPager +// method. +func (client *TriageResourcesClient) NewListPager(reviewID string, recommendationID string, options *TriageResourcesClientListOptions) *runtime.Pager[TriageResourcesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[TriageResourcesClientListResponse]{ + More: func(page TriageResourcesClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *TriageResourcesClientListResponse) (TriageResourcesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "TriageResourcesClient.NewListPager") + 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.listCreateRequest(ctx, reviewID, recommendationID, options) + }, nil) + if err != nil { + return TriageResourcesClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *TriageResourcesClient) listCreateRequest(ctx context.Context, reviewID string, recommendationID string, _ *TriageResourcesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Advisor/resiliencyReviews/{reviewId}/providers/Microsoft.Advisor/triageRecommendations/{recommendationId}/providers/Microsoft.Advisor/triageResources" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if reviewID == "" { + return nil, errors.New("parameter reviewID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{reviewId}", url.PathEscape(reviewID)) + if recommendationID == "" { + return nil, errors.New("parameter recommendationID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{recommendationId}", url.PathEscape(recommendationID)) + 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", "2025-05-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *TriageResourcesClient) listHandleResponse(resp *http.Response) (TriageResourcesClientListResponse, error) { + result := TriageResourcesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.TriageResourceCollection); err != nil { + return TriageResourcesClientListResponse{}, err + } + return result, nil +} diff --git a/sdk/resourcemanager/advisor/armadvisor/triageresources_client_example_test.go b/sdk/resourcemanager/advisor/armadvisor/triageresources_client_example_test.go new file mode 100644 index 000000000000..8009cb9f5f07 --- /dev/null +++ b/sdk/resourcemanager/advisor/armadvisor/triageresources_client_example_test.go @@ -0,0 +1,131 @@ +// 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) Go Code Generator. DO NOT EDIT. + +package armadvisor_test + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/advisor/armadvisor/v2" + "log" +) + +// Generated from example definition: 2025-05-01-preview/TriageResourcesGet.json +func ExampleTriageResourcesClient_Get() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armadvisor.NewClientFactory("00000000-1111-2222-3333-444444444444", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + res, err := clientFactory.NewTriageResourcesClient().Get(ctx, "11111111-1111-2222-3333-444444444444", "22222222-1111-2222-3333-444444444444", "33333333-1111-2222-3333-444444444444", 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 = armadvisor.TriageResourcesClientGetResponse{ + // TriageResource: &armadvisor.TriageResource{ + // ID: to.Ptr("/subscriptions/00000000-1111-2222-3333-444444444444/providers/Microsoft.Advisor/ResiliencyReview/11111111-1111-2222-3333-444444444444/providers/Microsoft.Advisor/TriageRecommendations/22222222-1111-2222-3333-444444444444/providers/Microsoft.Advisor/triageResources/33333333-1111-2222-3333-444444444444"), + // Name: to.Ptr("22222222-1111-2222-3333-444444444444"), + // Type: to.Ptr("Microsoft.Advisor/triageResources"), + // SystemData: &armadvisor.SystemData{ + // CreatedBy: to.Ptr("user-identity"), + // CreatedByType: to.Ptr(armadvisor.CreatedByTypeUser), + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-06-30T09:41:00Z"); return t}()), + // LastModifiedBy: to.Ptr("user-identity"), + // LastModifiedByType: to.Ptr(armadvisor.CreatedByTypeUser), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-06-30T09:41:00Z"); return t}()), + // }, + // Properties: &armadvisor.TriageResourceProperties{ + // ReviewID: to.Ptr("68890cd7-36aa-0b52-3b12-d37bdd684ff4"), + // RecommendationID: to.Ptr("91b56499-13b1-49f8-d59c-5d269bd3a79f"), + // SubscriptionID: to.Ptr("5cc854d0-c65a-44b0-982e-120eabfe1027"), + // ResourceGroup: to.Ptr("rg-test-for-large-post"), + // ResourceType: to.Ptr("Cosmos DB"), + // ResourceName: to.Ptr("cdb-testresource-prod-wus3"), + // ResourceID: to.Ptr("/subscriptions/00000000-1111-2222-3333-444444444444/resourceGroups/rg-advisormanage-dev-wus3/providers/Microsoft.DocumentDB/databaseAccounts/cdb-testresource-prod-wus3"), + // }, + // }, + // } +} + +// Generated from example definition: 2025-05-01-preview/TriageResourcesList.json +func ExampleTriageResourcesClient_NewListPager() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armadvisor.NewClientFactory("00000000-1111-2222-3333-444444444444", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + pager := clientFactory.NewTriageResourcesClient().NewListPager("11111111-1111-2222-3333-444444444445", "22222222-1111-2222-3333-444444444444", 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 = armadvisor.TriageResourcesClientListResponse{ + // TriageResourceCollection: armadvisor.TriageResourceCollection{ + // Value: []*armadvisor.TriageResource{ + // { + // ID: to.Ptr("/subscriptions/00000000-1111-2222-3333-444444444444/providers/Microsoft.Advisor/ResiliencyReview/11111111-1111-2222-3333-444444444444/providers/Microsoft.Advisor/TriageRecommendations/22222222-1111-2222-3333-444444444444/providers/Microsoft.Advisor/triageResources/33333333-1111-2222-3333-444444444444"), + // Name: to.Ptr("22222222-1111-2222-3333-444444444444"), + // Type: to.Ptr("Microsoft.Advisor/triageResources"), + // SystemData: &armadvisor.SystemData{ + // CreatedBy: to.Ptr("user-identity"), + // CreatedByType: to.Ptr(armadvisor.CreatedByTypeUser), + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-06-30T09:41:00Z"); return t}()), + // LastModifiedBy: to.Ptr("user-identity"), + // LastModifiedByType: to.Ptr(armadvisor.CreatedByTypeUser), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-06-30T09:41:00Z"); return t}()), + // }, + // Properties: &armadvisor.TriageResourceProperties{ + // ReviewID: to.Ptr("68890cd7-36aa-0b52-3b12-d37bdd684ff4"), + // RecommendationID: to.Ptr("91b56499-13b1-49f8-d59c-5d269bd3a79f"), + // SubscriptionID: to.Ptr("5cc854d0-c65a-44b0-982e-120eabfe1027"), + // ResourceGroup: to.Ptr("rg-test-for-large-post"), + // ResourceType: to.Ptr("Cosmos DB"), + // ResourceName: to.Ptr("cdb-testresource-prod-wus3"), + // ResourceID: to.Ptr("/subscriptions/00000000-1111-2222-3333-444444444444/resourceGroups/rg-advisormanage-dev-wus3/providers/Microsoft.DocumentDB/databaseAccounts/cdb-testresource-prod-wus3"), + // }, + // }, + // { + // ID: to.Ptr("/subscriptions/00000000-1111-2222-3333-444444444444/providers/Microsoft.Advisor/ResiliencyReview/11111111-1111-2222-3333-444444444444/providers/Microsoft.Advisor/TriageRecommendations/22222222-1111-2222-3333-444444444444/providers/Microsoft.Advisor/triageResources/33333333-1111-2222-3333-444444444444"), + // Name: to.Ptr("22222222-1111-2222-3333-444444444444"), + // Type: to.Ptr("Microsoft.Advisor/triageResources"), + // SystemData: &armadvisor.SystemData{ + // CreatedBy: to.Ptr("user-identity"), + // CreatedByType: to.Ptr(armadvisor.CreatedByTypeUser), + // CreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-06-30T09:41:00Z"); return t}()), + // LastModifiedBy: to.Ptr("user-identity"), + // LastModifiedByType: to.Ptr(armadvisor.CreatedByTypeUser), + // LastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, "2023-06-30T09:41:00Z"); return t}()), + // }, + // Properties: &armadvisor.TriageResourceProperties{ + // ReviewID: to.Ptr("68890cd7-36aa-0b52-3b12-111111111111"), + // RecommendationID: to.Ptr("91b56499-13b1-49f8-d59c-111111111111"), + // SubscriptionID: to.Ptr("5cc854d0-c65a-44b0-982e-120eabfe1027"), + // ResourceGroup: to.Ptr("rg-test-for-small-post"), + // ResourceType: to.Ptr("Cosmos DB"), + // ResourceName: to.Ptr("cdb-testresource-prod-eus3"), + // ResourceID: to.Ptr("/subscriptions/00000000-1111-2222-3333-444444444444/resourceGroups/rg-advisormanage-dev-wus3/providers/Microsoft.DocumentDB/databaseAccounts/cdb-testresource-prod-eus3"), + // }, + // }, + // }, + // }, + // } + } +} diff --git a/sdk/resourcemanager/advisor/armadvisor/tsp-location.yaml b/sdk/resourcemanager/advisor/armadvisor/tsp-location.yaml new file mode 100644 index 000000000000..626fffaafb13 --- /dev/null +++ b/sdk/resourcemanager/advisor/armadvisor/tsp-location.yaml @@ -0,0 +1,4 @@ +directory: specification/advisor/resource-manager/Microsoft.Advisor/Advisor +commit: aa822c9c01b9e83fbc8ad8ec4c308203a3c29287 +repo: Azure/azure-rest-api-specs +additionalDirectories: diff --git a/sdk/resourcemanager/advisor/armadvisor/version.go b/sdk/resourcemanager/advisor/armadvisor/version.go new file mode 100644 index 000000000000..ecb37c5b5a22 --- /dev/null +++ b/sdk/resourcemanager/advisor/armadvisor/version.go @@ -0,0 +1,10 @@ +// 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) Go Code Generator. + +package armadvisor + +const ( + moduleName = "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/advisor/armadvisor" + moduleVersion = "v2.0.0-beta.1" +) diff --git a/sdk/resourcemanager/advisor/armadvisor/workloads_client.go b/sdk/resourcemanager/advisor/armadvisor/workloads_client.go new file mode 100644 index 000000000000..6aab13cc5859 --- /dev/null +++ b/sdk/resourcemanager/advisor/armadvisor/workloads_client.go @@ -0,0 +1,96 @@ +// 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) Go Code Generator. DO NOT EDIT. + +package armadvisor + +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" +) + +// WorkloadsClient contains the methods for the Workloads group. +// Don't use this type directly, use NewWorkloadsClient() instead. +type WorkloadsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewWorkloadsClient creates a new instance of WorkloadsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewWorkloadsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*WorkloadsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &WorkloadsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// NewListPager - Get Workloads list. +// +// Get list of Workloads. +// +// Generated from API version 2025-05-01-preview +// - options - WorkloadsClientListOptions contains the optional parameters for the WorkloadsClient.NewListPager method. +func (client *WorkloadsClient) NewListPager(options *WorkloadsClientListOptions) *runtime.Pager[WorkloadsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[WorkloadsClientListResponse]{ + More: func(page WorkloadsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *WorkloadsClientListResponse) (WorkloadsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "WorkloadsClient.NewListPager") + 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.listCreateRequest(ctx, options) + }, nil) + if err != nil { + return WorkloadsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *WorkloadsClient) listCreateRequest(ctx context.Context, _ *WorkloadsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Advisor/workloads" + 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", "2025-05-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *WorkloadsClient) listHandleResponse(resp *http.Response) (WorkloadsClientListResponse, error) { + result := WorkloadsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.WorkloadListResult); err != nil { + return WorkloadsClientListResponse{}, err + } + return result, nil +} diff --git a/sdk/resourcemanager/advisor/armadvisor/workloads_client_example_test.go b/sdk/resourcemanager/advisor/armadvisor/workloads_client_example_test.go new file mode 100644 index 000000000000..638d2abe1ffe --- /dev/null +++ b/sdk/resourcemanager/advisor/armadvisor/workloads_client_example_test.go @@ -0,0 +1,49 @@ +// 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) Go Code Generator. DO NOT EDIT. + +package armadvisor_test + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/advisor/armadvisor/v2" + "log" +) + +// Generated from example definition: 2025-05-01-preview/ListWorkloads.json +func ExampleWorkloadsClient_NewListPager() { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + log.Fatalf("failed to obtain a credential: %v", err) + } + ctx := context.Background() + clientFactory, err := armadvisor.NewClientFactory("00000000-1111-2222-3333-444444444444", cred, nil) + if err != nil { + log.Fatalf("failed to create client: %v", err) + } + pager := clientFactory.NewWorkloadsClient().NewListPager(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 = armadvisor.WorkloadsClientListResponse{ + // WorkloadListResult: armadvisor.WorkloadListResult{ + // Value: []*armadvisor.WorkloadResult{ + // { + // ID: to.Ptr("d8004ffb-de76-4bc4-b0bc-32880a031843"), + // Name: to.Ptr("Workload1"), + // SubscriptionID: to.Ptr("2f2edd23-bded-4c8d-bdef-1f32a9b83f84"), + // SubscriptionName: to.Ptr("Subscription1"), + // }, + // }, + // }, + // } + } +}