diff --git a/sdk/resourcemanager/advisor/armadvisor/CHANGELOG.md b/sdk/resourcemanager/advisor/armadvisor/CHANGELOG.md index 49967ccd50d3..eb364551b05c 100644 --- a/sdk/resourcemanager/advisor/armadvisor/CHANGELOG.md +++ b/sdk/resourcemanager/advisor/armadvisor/CHANGELOG.md @@ -1,5 +1,98 @@ # Release History +## 1.3.0-beta.1 (2025-04-24) +### Features Added + +- New enum type `Aggregated` with values `AggregatedDay`, `AggregatedMonth`, `AggregatedWeek` +- New enum type `CreatedByType` with values `CreatedByTypeApplication`, `CreatedByTypeKey`, `CreatedByTypeManagedIdentity`, `CreatedByTypeUser` +- New enum type `Duration` with values `DurationFourteen`, `DurationNinety`, `DurationSeven`, `DurationSixty`, `DurationThirty`, `DurationTwentyOne` +- 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(string, azcore.TokenCredential, *arm.ClientOptions) (*AssessmentTypesClient, error)` +- New function `*AssessmentTypesClient.NewListPager(*AssessmentTypesClientListOptions) *runtime.Pager[AssessmentTypesClientListResponse]` +- New function `NewAssessmentsClient(string, azcore.TokenCredential, *arm.ClientOptions) (*AssessmentsClient, error)` +- New function `*AssessmentsClient.Delete(context.Context, string, *AssessmentsClientDeleteOptions) (AssessmentsClientDeleteResponse, error)` +- New function `*AssessmentsClient.Get(context.Context, string, *AssessmentsClientGetOptions) (AssessmentsClientGetResponse, error)` +- New function `*AssessmentsClient.NewListPager(*AssessmentsClientListOptions) *runtime.Pager[AssessmentsClientListResponse]` +- New function `*AssessmentsClient.Put(context.Context, string, AssessmentResult, *AssessmentsClientPutOptions) (AssessmentsClientPutResponse, error)` +- New function `*ClientFactory.NewAssessmentTypesClient() *AssessmentTypesClient` +- New function `*ClientFactory.NewAssessmentsClient() *AssessmentsClient` +- New function `*ClientFactory.NewManagementClient() *ManagementClient` +- 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 `NewManagementClient(string, azcore.TokenCredential, *arm.ClientOptions) (*ManagementClient, error)` +- New function `*ManagementClient.Predict(context.Context, PredictionRequest, *ManagementClientPredictOptions) (ManagementClientPredictResponse, error)` +- New function `*RecommendationsClient.Patch(context.Context, string, string, TrackedRecommendationPropertiesPayload, *RecommendationsClientPatchOptions) (RecommendationsClientPatchResponse, error)` +- New function `NewResiliencyReviewsClient(string, azcore.TokenCredential, *arm.ClientOptions) (*ResiliencyReviewsClient, error)` +- New function `*ResiliencyReviewsClient.Get(context.Context, string, *ResiliencyReviewsClientGetOptions) (ResiliencyReviewsClientGetResponse, error)` +- New function `*ResiliencyReviewsClient.NewListPager(*ResiliencyReviewsClientListOptions) *runtime.Pager[ResiliencyReviewsClientListResponse]` +- New function `NewScoresClient(string, azcore.TokenCredential, *arm.ClientOptions) (*ScoresClient, error)` +- New function `*ScoresClient.Get(context.Context, string, *ScoresClientGetOptions) (ScoresClientGetResponse, error)` +- New function `*ScoresClient.List(context.Context, *ScoresClientListOptions) (ScoresClientListResponse, error)` +- New function `NewTriageRecommendationsClient(string, azcore.TokenCredential, *arm.ClientOptions) (*TriageRecommendationsClient, error)` +- New function `*TriageRecommendationsClient.ApproveTriageRecommendation(context.Context, string, string, *TriageRecommendationsClientApproveTriageRecommendationOptions) (TriageRecommendationsClientApproveTriageRecommendationResponse, error)` +- New function `*TriageRecommendationsClient.Get(context.Context, string, string, *TriageRecommendationsClientGetOptions) (TriageRecommendationsClientGetResponse, error)` +- New function `*TriageRecommendationsClient.NewListPager(string, *TriageRecommendationsClientListOptions) *runtime.Pager[TriageRecommendationsClientListResponse]` +- New function `*TriageRecommendationsClient.RejectTriageRecommendation(context.Context, string, string, RecommendationRejectBody, *TriageRecommendationsClientRejectTriageRecommendationOptions) (TriageRecommendationsClientRejectTriageRecommendationResponse, error)` +- New function `*TriageRecommendationsClient.ResetTriageRecommendation(context.Context, string, string, *TriageRecommendationsClientResetTriageRecommendationOptions) (TriageRecommendationsClientResetTriageRecommendationResponse, error)` +- New function `NewTriageResourcesClient(string, azcore.TokenCredential, *arm.ClientOptions) (*TriageResourcesClient, error)` +- New function `*TriageResourcesClient.Get(context.Context, string, string, string, *TriageResourcesClientGetOptions) (TriageResourcesClientGetResponse, error)` +- New function `*TriageResourcesClient.NewListPager(string, string, *TriageResourcesClientListOptions) *runtime.Pager[TriageResourcesClientListResponse]` +- New function `NewWorkloadsClient(string, azcore.TokenCredential, *arm.ClientOptions) (*WorkloadsClient, error)` +- New function `*WorkloadsClient.NewListPager(*WorkloadsClientListOptions) *runtime.Pager[WorkloadsClientListResponse]` +- New struct `AssessmentListResult` +- New struct `AssessmentResult` +- New struct `AssessmentResultProperties` +- New struct `AssessmentTypeListResult` +- New struct `AssessmentTypeResult` +- New struct `ErrorAdditionalInfo` +- New struct `ErrorDetail` +- New struct `ErrorResponse` +- New struct `PredictionRequest` +- New struct `PredictionRequestProperties` +- New struct `PredictionResponse` +- New struct `PredictionResponseProperties` +- New struct `ProxyResource` +- 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 `ScoreEntityForAdvisorProperties` +- New struct `ScoreResponse` +- New struct `SystemData` +- New struct `TimeSeriesEntityItem` +- 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 `Notes`, `ResourceWorkload`, `Review`, `SourceSystem`, `Tracked`, `TrackedProperties` in struct `RecommendationProperties` +- New field `SystemData` in struct `Resource` +- 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..b2cce6c52e14 100644 --- a/sdk/resourcemanager/advisor/armadvisor/README.md +++ b/sdk/resourcemanager/advisor/armadvisor/README.md @@ -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/assessments_client.go b/sdk/resourcemanager/advisor/armadvisor/assessments_client.go new file mode 100644 index 000000000000..71663a5644e7 --- /dev/null +++ b/sdk/resourcemanager/advisor/armadvisor/assessments_client.go @@ -0,0 +1,272 @@ +// 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 ( + "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 Azure subscription ID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - 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 a existing Azure Advisor assessment. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-11-18-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", "2024-11-18-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Get a existing Azure Advisor assessment. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-11-18-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", "2024-11-18-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 assessment. +// +// Generated from API version 2024-11-18-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", "2024-11-18-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 resource. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-11-18-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", "2024-11-18-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []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/assessmenttypes_client.go b/sdk/resourcemanager/advisor/armadvisor/assessmenttypes_client.go new file mode 100644 index 000000000000..2a3d4db0b669 --- /dev/null +++ b/sdk/resourcemanager/advisor/armadvisor/assessmenttypes_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) AutoRest Code Generator. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +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 Azure subscription ID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - 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 list of Azure Advisor assessment types. +// +// Generated from API version 2024-11-18-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", "2024-11-18-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/autorest.md b/sdk/resourcemanager/advisor/armadvisor/autorest.md index 582c1196e2a5..c5c37fe05bc9 100644 --- a/sdk/resourcemanager/advisor/armadvisor/autorest.md +++ b/sdk/resourcemanager/advisor/armadvisor/autorest.md @@ -5,8 +5,8 @@ ``` 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 +- /mnt/vss/_work/1/s/azure-rest-api-specs/specification/advisor/resource-manager/readme.md +- /mnt/vss/_work/1/s/azure-rest-api-specs/specification/advisor/resource-manager/readme.go.md license-header: MICROSOFT_MIT_NO_VERSION -module-version: 1.2.0 +module-version: 1.3.0-beta.1 ``` \ No newline at end of file diff --git a/sdk/resourcemanager/advisor/armadvisor/client_factory.go b/sdk/resourcemanager/advisor/armadvisor/client_factory.go index a0a8ce03d449..31c1794b694a 100644 --- a/sdk/resourcemanager/advisor/armadvisor/client_factory.go +++ b/sdk/resourcemanager/advisor/armadvisor/client_factory.go @@ -1,6 +1,3 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. @@ -17,8 +14,7 @@ import ( // Don't use this type directly, use NewClientFactory instead. type ClientFactory struct { subscriptionID string - credential azcore.TokenCredential - options *arm.ClientOptions + internal *arm.Client } // NewClientFactory creates a new instance of ClientFactory with the specified values. @@ -27,42 +23,114 @@ type ClientFactory struct { // - credential - used to authorize requests. Usually a credential from azidentity. // - options - pass nil to accept the default values. func NewClientFactory(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ClientFactory, error) { - _, err := arm.NewClient(moduleName, moduleVersion, credential, options) + internal, err := arm.NewClient(moduleName, moduleVersion, credential, options) if err != nil { return nil, err } return &ClientFactory{ - subscriptionID: subscriptionID, credential: credential, - options: options.Clone(), + subscriptionID: subscriptionID, + internal: internal, }, nil } +// 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, + } +} + // 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, + } +} + +// NewManagementClient creates a new instance of ManagementClient. +func (c *ClientFactory) NewManagementClient() *ManagementClient { + return &ManagementClient{ + 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 1cc233b23ad0..2997966e3051 100644 --- a/sdk/resourcemanager/advisor/armadvisor/configurations_client.go +++ b/sdk/resourcemanager/advisor/armadvisor/configurations_client.go @@ -1,6 +1,3 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. @@ -46,7 +43,7 @@ func NewConfigurationsClient(subscriptionID string, credential azcore.TokenCrede // CreateInResourceGroup - 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 2024-11-18-preview // - configurationName - Advisor configuration name. Value must be 'default' // - resourceGroup - The name of the Azure resource group. // - configContract - The Azure Advisor configuration data structure. @@ -75,7 +72,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") @@ -94,7 +91,7 @@ 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", "2024-11-18-preview") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, configContract); err != nil { @@ -116,7 +113,7 @@ func (client *ConfigurationsClient) createInResourceGroupHandleResponse(resp *ht // groups. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2020-01-01 +// Generated from API version 2024-11-18-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 @@ -144,7 +141,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") @@ -159,7 +156,7 @@ 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", "2024-11-18-preview") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, configContract); err != nil { @@ -179,7 +176,7 @@ func (client *ConfigurationsClient) createInSubscriptionHandleResponse(resp *htt // NewListByResourceGroupPager - Retrieve Azure Advisor configurations. // -// Generated from API version 2020-01-01 +// Generated from API version 2024-11-18-preview // - resourceGroup - The name of the Azure resource group. // - options - ConfigurationsClientListByResourceGroupOptions contains the optional parameters for the ConfigurationsClient.NewListByResourceGroupPager // method. @@ -208,7 +205,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") @@ -223,7 +220,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", "2024-11-18-preview") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -241,7 +238,7 @@ func (client *ConfigurationsClient) listByResourceGroupHandleResponse(resp *http // NewListBySubscriptionPager - Retrieve Azure Advisor configurations and also retrieve configurations of contained resource // groups. // -// Generated from API version 2020-01-01 +// Generated from API version 2024-11-18-preview // - options - ConfigurationsClientListBySubscriptionOptions contains the optional parameters for the ConfigurationsClient.NewListBySubscriptionPager // method. func (client *ConfigurationsClient) NewListBySubscriptionPager(options *ConfigurationsClientListBySubscriptionOptions) *runtime.Pager[ConfigurationsClientListBySubscriptionResponse] { @@ -268,7 +265,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") @@ -279,7 +276,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", "2024-11-18-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 deleted file mode 100644 index 4f8f0f0986d4..000000000000 --- a/sdk/resourcemanager/advisor/armadvisor/configurations_client_example_test.go +++ /dev/null @@ -1,132 +0,0 @@ -//go:build go1.18 -// +build go1.18 - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. -// DO NOT EDIT. - -package 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" -) - -// 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() { - 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.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), - // }, - // }}, - // } - } -} - -// 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 -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) - if err != nil { - log.Fatalf("failed to create client: %v", err) - } - res, err := clientFactory.NewConfigurationsClient().CreateInSubscription(ctx, armadvisor.ConfigurationNameDefault, armadvisor.ConfigData{ - 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(true), - LowCPUThreshold: to.Ptr(armadvisor.CPUThresholdFive), - }, - }, 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.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)}, - // Frequency: to.Ptr[int32](30), - // State: to.Ptr(armadvisor.DigestConfigStateActive), - // Language: to.Ptr("en"), - // }}, - // Exclude: to.Ptr(true), - // LowCPUThreshold: to.Ptr(armadvisor.CPUThresholdFive), - // }, - // } -} diff --git a/sdk/resourcemanager/advisor/armadvisor/constants.go b/sdk/resourcemanager/advisor/armadvisor/constants.go index 13a831a3d1d3..507da3b5fecb 100644 --- a/sdk/resourcemanager/advisor/armadvisor/constants.go +++ b/sdk/resourcemanager/advisor/armadvisor/constants.go @@ -1,6 +1,3 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. @@ -10,9 +7,27 @@ package armadvisor const ( moduleName = "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/advisor/armadvisor" - moduleVersion = "v1.2.0" + moduleVersion = "v1.3.0-beta.1" +) + +// Aggregated - The aggregation level of the score. +type Aggregated string + +const ( + 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 @@ -68,6 +83,26 @@ func PossibleConfigurationNameValues() []ConfigurationName { } } +// CreatedByType - The type of identity that created the resource. +type CreatedByType string + +const ( + CreatedByTypeApplication CreatedByType = "Application" + CreatedByTypeKey CreatedByType = "Key" + CreatedByTypeManagedIdentity CreatedByType = "ManagedIdentity" + 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 @@ -84,6 +119,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 ( + DurationFourteen Duration = "14" + DurationNinety Duration = "90" + DurationSeven Duration = "7" + DurationSixty Duration = "60" + DurationThirty Duration = "30" + DurationTwentyOne Duration = "21" +) + +// PossibleDurationValues returns the possible values for the Duration const type. +func PossibleDurationValues() []Duration { + return []Duration{ + DurationFourteen, + DurationNinety, + DurationSeven, + DurationSixty, + DurationThirty, + DurationTwentyOne, + } +} + // Impact - The business impact of the recommendation. type Impact string @@ -102,6 +162,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 string, returns the Reviews by the given status (e.g. 'New', 'Triaged', 'Completed'). +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 @@ -132,3 +336,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..8b3994084f2e --- /dev/null +++ b/sdk/resourcemanager/advisor/armadvisor/fake/assessments_server.go @@ -0,0 +1,254 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/advisor/armadvisor" + "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 matches == nil || len(matches) < 2 { + 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 matches == nil || len(matches) < 2 { + 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 matches == nil || len(matches) < 1 { + 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 matches == nil || len(matches) < 2 { + 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..a79575f67210 --- /dev/null +++ b/sdk/resourcemanager/advisor/armadvisor/fake/assessmenttypes_server.go @@ -0,0 +1,125 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package fake + +import ( + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/advisor/armadvisor" + "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 matches == nil || len(matches) < 1 { + 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 c611cdb9fbc9..9bb2026007ba 100644 --- a/sdk/resourcemanager/advisor/armadvisor/fake/configurations_server.go +++ b/sdk/resourcemanager/advisor/armadvisor/fake/configurations_server.go @@ -1,6 +1,3 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. @@ -68,27 +65,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) { @@ -239,3 +255,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 72f540f217a1..d186c1b38a18 100644 --- a/sdk/resourcemanager/advisor/armadvisor/fake/internal.go +++ b/sdk/resourcemanager/advisor/armadvisor/fake/internal.go @@ -1,6 +1,3 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. @@ -15,6 +12,11 @@ import ( "sync" ) +type result struct { + resp *http.Response + err error +} + type nonRetriableError struct { error } diff --git a/sdk/resourcemanager/advisor/armadvisor/fake/management_server.go b/sdk/resourcemanager/advisor/armadvisor/fake/management_server.go new file mode 100644 index 000000000000..0060c0e29007 --- /dev/null +++ b/sdk/resourcemanager/advisor/armadvisor/fake/management_server.go @@ -0,0 +1,117 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/advisor/armadvisor" + "net/http" + "regexp" +) + +// ManagementServer is a fake server for instances of the armadvisor.ManagementClient type. +type ManagementServer struct { + // Predict is the fake for method ManagementClient.Predict + // HTTP status codes to indicate success: http.StatusOK + Predict func(ctx context.Context, predictionRequest armadvisor.PredictionRequest, options *armadvisor.ManagementClientPredictOptions) (resp azfake.Responder[armadvisor.ManagementClientPredictResponse], errResp azfake.ErrorResponder) +} + +// NewManagementServerTransport creates a new instance of ManagementServerTransport with the provided implementation. +// The returned ManagementServerTransport instance is connected to an instance of armadvisor.ManagementClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewManagementServerTransport(srv *ManagementServer) *ManagementServerTransport { + return &ManagementServerTransport{srv: srv} +} + +// ManagementServerTransport connects instances of armadvisor.ManagementClient to instances of ManagementServer. +// Don't use this type directly, use NewManagementServerTransport instead. +type ManagementServerTransport struct { + srv *ManagementServer +} + +// Do implements the policy.Transporter interface for ManagementServerTransport. +func (m *ManagementServerTransport) 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 m.dispatchToMethodFake(req, method) +} + +func (m *ManagementServerTransport) 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 managementServerTransportInterceptor != nil { + res.resp, res.err, intercepted = managementServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ManagementClient.Predict": + res.resp, res.err = m.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 (m *ManagementServerTransport) dispatchPredict(req *http.Request) (*http.Response, error) { + if m.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 matches == nil || len(matches) < 1 { + 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 := m.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 ManagementServerTransport +var managementServerTransportInterceptor 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/operations_server.go b/sdk/resourcemanager/advisor/armadvisor/fake/operations_server.go index 267e70f372b6..28185be83bcb 100644 --- a/sdk/resourcemanager/advisor/armadvisor/fake/operations_server.go +++ b/sdk/resourcemanager/advisor/armadvisor/fake/operations_server.go @@ -1,6 +1,3 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. @@ -51,21 +48,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) { @@ -94,3 +110,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 ae9b09d9c6cd..10037a60a7e9 100644 --- a/sdk/resourcemanager/advisor/armadvisor/fake/recommendationmetadata_server.go +++ b/sdk/resourcemanager/advisor/armadvisor/fake/recommendationmetadata_server.go @@ -1,6 +1,3 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. @@ -58,23 +55,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) { @@ -132,3 +148,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 f89f48f27860..d240e304d47e 100644 --- a/sdk/resourcemanager/advisor/armadvisor/fake/recommendations_server.go +++ b/sdk/resourcemanager/advisor/armadvisor/fake/recommendations_server.go @@ -1,6 +1,3 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. @@ -40,6 +37,10 @@ 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]) + + // 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. @@ -67,27 +68,48 @@ 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.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) { @@ -248,3 +270,46 @@ func (r *RecommendationsServerTransport) dispatchNewListPager(req *http.Request) } 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 matches == nil || len(matches) < 2 { + 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..3bcd1038ab1b --- /dev/null +++ b/sdk/resourcemanager/advisor/armadvisor/fake/resiliencyreviews_server.go @@ -0,0 +1,205 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/advisor/armadvisor" + "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 matches == nil || len(matches) < 2 { + 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 matches == nil || len(matches) < 1 { + 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..76ee32ea61bb --- /dev/null +++ b/sdk/resourcemanager/advisor/armadvisor/fake/scores_server.go @@ -0,0 +1,149 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/advisor/armadvisor" + "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) + + // List is the fake for method ScoresClient.List + // HTTP status codes to indicate success: http.StatusOK + List func(ctx context.Context, options *armadvisor.ScoresClientListOptions) (resp azfake.Responder[armadvisor.ScoresClientListResponse], errResp azfake.ErrorResponder) +} + +// 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} +} + +// ScoresServerTransport connects instances of armadvisor.ScoresClient to instances of ScoresServer. +// Don't use this type directly, use NewScoresServerTransport instead. +type ScoresServerTransport struct { + srv *ScoresServer +} + +// 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.List": + res.resp, res.err = s.dispatchList(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 matches == nil || len(matches) < 2 { + 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) dispatchList(req *http.Request) (*http.Response, error) { + if s.srv.List == nil { + return nil, &nonRetriableError{errors.New("fake for method List not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Advisor/advisorScore` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 1 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + respr, errRespr := s.srv.List(req.Context(), 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).ScoreResponse, req) + if err != nil { + return nil, err + } + 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_factory.go b/sdk/resourcemanager/advisor/armadvisor/fake/server_factory.go index a712fe39be87..0d40524b5416 100644 --- a/sdk/resourcemanager/advisor/armadvisor/fake/server_factory.go +++ b/sdk/resourcemanager/advisor/armadvisor/fake/server_factory.go @@ -1,6 +1,3 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. @@ -19,11 +16,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 + + // ConfigurationsServer contains the fakes for client ConfigurationsClient + ConfigurationsServer ConfigurationsServer + + // ManagementServer contains the fakes for client ManagementClient + ManagementServer ManagementServer + + // 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. @@ -40,11 +70,19 @@ func NewServerFactoryTransport(srv *ServerFactory) *ServerFactoryTransport { type ServerFactoryTransport struct { srv *ServerFactory trMu sync.Mutex + trAssessmentTypesServer *AssessmentTypesServerTransport + trAssessmentsServer *AssessmentsServerTransport trConfigurationsServer *ConfigurationsServerTransport + trManagementServer *ManagementServerTransport 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. @@ -60,11 +98,22 @@ func (s *ServerFactoryTransport) Do(req *http.Request) (*http.Response, error) { var err error switch client { + case "AssessmentTypesClient": + initServer(s, &s.trAssessmentTypesServer, func() *AssessmentTypesServerTransport { + return NewAssessmentTypesServerTransport(&s.srv.AssessmentTypesServer) + }) + resp, err = s.trAssessmentTypesServer.Do(req) + case "AssessmentsClient": + initServer(s, &s.trAssessmentsServer, func() *AssessmentsServerTransport { return NewAssessmentsServerTransport(&s.srv.AssessmentsServer) }) + resp, err = s.trAssessmentsServer.Do(req) case "ConfigurationsClient": initServer(s, &s.trConfigurationsServer, func() *ConfigurationsServerTransport { return NewConfigurationsServerTransport(&s.srv.ConfigurationsServer) }) resp, err = s.trConfigurationsServer.Do(req) + case "ManagementClient": + initServer(s, &s.trManagementServer, func() *ManagementServerTransport { return NewManagementServerTransport(&s.srv.ManagementServer) }) + resp, err = s.trManagementServer.Do(req) case "OperationsClient": initServer(s, &s.trOperationsServer, func() *OperationsServerTransport { return NewOperationsServerTransport(&s.srv.OperationsServer) }) resp, err = s.trOperationsServer.Do(req) @@ -78,9 +127,30 @@ func (s *ServerFactoryTransport) Do(req *http.Request) (*http.Response, error) { return NewRecommendationsServerTransport(&s.srv.RecommendationsServer) }) resp, err = s.trRecommendationsServer.Do(req) + case "ResiliencyReviewsClient": + initServer(s, &s.trResiliencyReviewsServer, func() *ResiliencyReviewsServerTransport { + return NewResiliencyReviewsServerTransport(&s.srv.ResiliencyReviewsServer) + }) + resp, err = s.trResiliencyReviewsServer.Do(req) + case "ScoresClient": + initServer(s, &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) }) resp, err = s.trSuppressionsServer.Do(req) + case "TriageRecommendationsClient": + initServer(s, &s.trTriageRecommendationsServer, func() *TriageRecommendationsServerTransport { + return NewTriageRecommendationsServerTransport(&s.srv.TriageRecommendationsServer) + }) + resp, err = s.trTriageRecommendationsServer.Do(req) + case "TriageResourcesClient": + initServer(s, &s.trTriageResourcesServer, func() *TriageResourcesServerTransport { + return NewTriageResourcesServerTransport(&s.srv.TriageResourcesServer) + }) + resp, err = s.trTriageResourcesServer.Do(req) + case "WorkloadsClient": + initServer(s, &s.trWorkloadsServer, func() *WorkloadsServerTransport { return NewWorkloadsServerTransport(&s.srv.WorkloadsServer) }) + resp, err = s.trWorkloadsServer.Do(req) default: err = fmt.Errorf("unhandled client %s", client) } diff --git a/sdk/resourcemanager/advisor/armadvisor/fake/suppressions_server.go b/sdk/resourcemanager/advisor/armadvisor/fake/suppressions_server.go index f756d13e20f5..2a174ab34519 100644 --- a/sdk/resourcemanager/advisor/armadvisor/fake/suppressions_server.go +++ b/sdk/resourcemanager/advisor/armadvisor/fake/suppressions_server.go @@ -1,6 +1,3 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. @@ -67,27 +64,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) { @@ -264,3 +280,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 b0535a7b63e6..000000000000 --- a/sdk/resourcemanager/advisor/armadvisor/fake/time_rfc3339.go +++ /dev/null @@ -1,86 +0,0 @@ -//go:build go1.18 -// +build go1.18 - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -package fake - -import ( - "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..d5ddf054f598 --- /dev/null +++ b/sdk/resourcemanager/advisor/armadvisor/fake/triagerecommendations_server.go @@ -0,0 +1,328 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/advisor/armadvisor" + "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 matches == nil || 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 + } + 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 matches == nil || 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 + } + 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 matches == nil || len(matches) < 2 { + 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 matches == nil || len(matches) < 3 { + 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 matches == nil || 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 + } + 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..bcf1c0b9d71f --- /dev/null +++ b/sdk/resourcemanager/advisor/armadvisor/fake/triageresources_server.go @@ -0,0 +1,178 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/advisor/armadvisor" + "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 matches == nil || 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 + } + 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 matches == nil || 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 + } + 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..5a1245e6d508 --- /dev/null +++ b/sdk/resourcemanager/advisor/armadvisor/fake/workloads_server.go @@ -0,0 +1,125 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package fake + +import ( + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/advisor/armadvisor" + "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 matches == nil || len(matches) < 1 { + 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 55fbbb00e4a8..c66e9267b4a3 100644 --- a/sdk/resourcemanager/advisor/armadvisor/go.mod +++ b/sdk/resourcemanager/advisor/armadvisor/go.mod @@ -4,13 +4,13 @@ go 1.23.0 require ( github.com/Azure/azure-sdk-for-go/sdk/azcore v1.17.1 - github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.8.2 github.com/Azure/azure-sdk-for-go/sdk/internal v1.11.1 github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/internal/v3 v3.1.0 github.com/stretchr/testify v1.10.0 ) require ( + github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.8.2 // indirect github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armresources v1.2.0 // indirect github.com/AzureAD/microsoft-authentication-library-for-go v1.4.2 // indirect github.com/davecgh/go-spew v1.1.1 // indirect diff --git a/sdk/resourcemanager/advisor/armadvisor/management_client.go b/sdk/resourcemanager/advisor/armadvisor/management_client.go new file mode 100644 index 000000000000..fc38d0f5f50d --- /dev/null +++ b/sdk/resourcemanager/advisor/armadvisor/management_client.go @@ -0,0 +1,99 @@ +// 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 ( + "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" +) + +// ManagementClient contains the methods for the AdvisorManagementClient group. +// Don't use this type directly, use NewManagementClient() instead. +type ManagementClient struct { + internal *arm.Client + subscriptionID string +} + +// NewManagementClient creates a new instance of ManagementClient with the specified values. +// - subscriptionID - The Azure subscription ID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewManagementClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ManagementClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ManagementClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Predict - Predicts a recommendation. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-11-18-preview +// - predictionRequest - Parameters for predict recommendation. +// - options - ManagementClientPredictOptions contains the optional parameters for the ManagementClient.Predict method. +func (client *ManagementClient) Predict(ctx context.Context, predictionRequest PredictionRequest, options *ManagementClientPredictOptions) (ManagementClientPredictResponse, error) { + var err error + const operationName = "ManagementClient.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 ManagementClientPredictResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ManagementClientPredictResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ManagementClientPredictResponse{}, err + } + resp, err := client.predictHandleResponse(httpResp) + return resp, err +} + +// predictCreateRequest creates the Predict request. +func (client *ManagementClient) predictCreateRequest(ctx context.Context, predictionRequest PredictionRequest, _ *ManagementClientPredictOptions) (*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", "2024-11-18-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, predictionRequest); err != nil { + return nil, err + } + return req, nil +} + +// predictHandleResponse handles the Predict response. +func (client *ManagementClient) predictHandleResponse(resp *http.Response) (ManagementClientPredictResponse, error) { + result := ManagementClientPredictResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PredictionResponse); err != nil { + return ManagementClientPredictResponse{}, err + } + return result, nil +} diff --git a/sdk/resourcemanager/advisor/armadvisor/models.go b/sdk/resourcemanager/advisor/armadvisor/models.go index c52eab544f43..4196bd57eba5 100644 --- a/sdk/resourcemanager/advisor/armadvisor/models.go +++ b/sdk/resourcemanager/advisor/armadvisor/models.go @@ -1,6 +1,3 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. @@ -24,18 +21,108 @@ type ArmErrorResponse struct { Error *ARMErrorResponseBody } +// AssessmentListResult - The Advisor assessment list result data structure. +type AssessmentListResult struct { + // The URL to get the next set of Advisor assessments, if there are any. + NextLink *string + + // List of Assessments. + Value []*AssessmentResult +} + +// AssessmentResult - The Advisor assessment result data structure. +type AssessmentResult struct { + // The Advisor assessment result properties structure. + Properties *AssessmentResultProperties + + // READ-ONLY; Assessment Id + ID *string + + // READ-ONLY; Assessment Name + Name *string + + // READ-ONLY; Metadata pertaining to creation and last modification of the resource. + SystemData *SystemData + + // READ-ONLY; Resource Type + 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 { + // The URL to get the next set of Advisor assessments types, if there are any. + NextLink *string + + // List of Assessments Types. + Value []*AssessmentTypeResult +} + +// 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. E.g. "/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 } @@ -44,6 +131,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 @@ -83,6 +174,40 @@ type DigestConfig struct { State *DigestConfigState } +// ErrorAdditionalInfo - The resource management error additional info. +type ErrorAdditionalInfo struct { + // READ-ONLY; The additional info. + Info any + + // READ-ONLY; The additional info type. + Type *string +} + +// ErrorDetail - The error detail. +type ErrorDetail struct { + // READ-ONLY; The error additional info. + AdditionalInfo []*ErrorAdditionalInfo + + // READ-ONLY; The error code. + Code *string + + // READ-ONLY; The error details. + Details []*ErrorDetail + + // READ-ONLY; The error message. + Message *string + + // READ-ONLY; The error target. + Target *string +} + +// ErrorResponse - Common error response for all Azure Resource Manager APIs to return error details for failed operations. +// (This also follows the OData error response format.). +type ErrorResponse struct { + // The error object. + Error *ErrorDetail +} + // MetadataEntity - The metadata entity contract. type MetadataEntity struct { // The resource Id of the metadata entity. @@ -164,6 +289,67 @@ type OperationEntityListResult struct { 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 +} + +// ProxyResource - The resource model definition for a Azure Resource Manager proxy resource. It will not have tags and a +// location +type ProxyResource struct { + // READ-ONLY; Fully qualified resource ID for the resource. E.g. "/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 +} + // RecommendationProperties - The properties of the recommendation. type RecommendationProperties struct { // The list of recommended actions to implement recommendation. @@ -202,6 +388,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 @@ -214,25 +403,115 @@ 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 +} + +// RecommendationPropertiesReview - The Review that this Recommendation belongs to. +type RecommendationPropertiesReview struct { + // The ARM Resource Id of the Review + ID *string + + // 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; Fully qualified resource ID for the resource. E.g. "/subscriptions/{subscriptionId}/providers/Microsoft.Advisor/ResiliencyReviews/{reviewId}". + ID *string + + // READ-ONLY; Resource name E.g. "{guid}". + Name *string + + // READ-ONLY; Metadata pertaining to creation and last modification of the resource. + SystemData *SystemData + + // READ-ONLY; Resource type E.g. "Microsoft.Advisor/resiliencyReviews". + Type *string +} + +// ResiliencyReviewCollection - Collection of Resiliency Reviews. +type ResiliencyReviewCollection struct { + // REQUIRED; List of resiliency reviews. + Value []*ResiliencyReview + + // The URL to get the next set of Advisor resiliency reviews, if there are any. + NextLink *string } -// Resource - An Azure resource. +// 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 +} + +// Resource - Common fields that are returned in the response for all Azure Resource Manager resources type Resource struct { - // READ-ONLY; The resource ID. + // READ-ONLY; Fully qualified resource ID for the resource. E.g. "/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 } @@ -259,13 +538,16 @@ type ResourceRecommendationBase struct { // The properties of the recommendation. Properties *RecommendationProperties - // READ-ONLY; The resource ID. + // READ-ONLY; Fully qualified resource ID for the resource. E.g. "/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 } @@ -278,12 +560,65 @@ type ResourceRecommendationBaseListResult struct { 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 *ScoreEntityForAdvisorProperties + + // READ-ONLY; Fully qualified resource ID for the resource. E.g. "/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 +} + +// ScoreEntityForAdvisorProperties - The Advisor score data. +type ScoreEntityForAdvisorProperties struct { + // The details of latest available score. + LastRefreshedScore *ScoreEntity + + // The historic Advisor score data. + TimeSeries []*TimeSeriesEntityItem +} + +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 } @@ -293,13 +628,16 @@ type SuppressionContract struct { // The properties of the suppression. Properties *SuppressionProperties - // READ-ONLY; The resource ID. + // READ-ONLY; Fully qualified resource ID for the resource. E.g. "/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 } @@ -323,3 +661,193 @@ 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 +} + +// TimeSeriesEntityItem - The data from different aggregation levels. +type TimeSeriesEntityItem 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. E.g. + // "/subscriptions/{subscriptionId}/providers/Microsoft.Advisor/ResiliencyReviews/{reviewId}/providers/Microsoft.Advisor/triageRecommendation/{recommendationId}". + ID *string + + // READ-ONLY; Resource name E.g. "{guid}". + Name *string + + // READ-ONLY; Metadata pertaining to creation and last modification of the resource. + SystemData *SystemData + + // READ-ONLY; Resource type E.g. "Microsoft.Advisor/triageRecommendation". + 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. E.g. "/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; List of triage resources. + Value []*TriageResource + + // The URL to get the next set of triage resources, if there are any. + 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 { + // The URL to get the next set of Workloads, if there are any. + NextLink *string + + // List of Workload. + Value []*WorkloadResult +} + +// 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 b851e4e9882d..bab86f668476 100644 --- a/sdk/resourcemanager/advisor/armadvisor/models_serde.go +++ b/sdk/resourcemanager/advisor/armadvisor/models_serde.go @@ -1,6 +1,3 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. @@ -73,12 +70,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) } @@ -101,6 +310,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) @@ -116,6 +328,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) @@ -133,6 +346,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) @@ -225,6 +441,107 @@ func (d *DigestConfig) UnmarshalJSON(data []byte) error { return nil } +// MarshalJSON implements the json.Marshaller interface for type ErrorAdditionalInfo. +func (e ErrorAdditionalInfo) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateAny(objectMap, "info", e.Info) + populate(objectMap, "type", e.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ErrorAdditionalInfo. +func (e *ErrorAdditionalInfo) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "info": + err = unpopulate(val, "Info", &e.Info) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &e.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ErrorDetail. +func (e ErrorDetail) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "additionalInfo", e.AdditionalInfo) + populate(objectMap, "code", e.Code) + populate(objectMap, "details", e.Details) + populate(objectMap, "message", e.Message) + populate(objectMap, "target", e.Target) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ErrorDetail. +func (e *ErrorDetail) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "additionalInfo": + err = unpopulate(val, "AdditionalInfo", &e.AdditionalInfo) + delete(rawMsg, key) + case "code": + err = unpopulate(val, "Code", &e.Code) + delete(rawMsg, key) + case "details": + err = unpopulate(val, "Details", &e.Details) + delete(rawMsg, key) + case "message": + err = unpopulate(val, "Message", &e.Message) + delete(rawMsg, key) + case "target": + err = unpopulate(val, "Target", &e.Target) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ErrorResponse. +func (e ErrorResponse) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "error", e.Error) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ErrorResponse. +func (e *ErrorResponse) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "error": + err = unpopulate(val, "Error", &e.Error) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + // MarshalJSON implements the json.Marshaller interface for type MetadataEntity. func (m MetadataEntity) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) @@ -466,60 +783,241 @@ func (o *OperationEntityListResult) UnmarshalJSON(data []byte) error { return nil } -// MarshalJSON implements the json.Marshaller interface for type RecommendationProperties. -func (r RecommendationProperties) MarshalJSON() ([]byte, error) { +// MarshalJSON implements the json.Marshaller interface for type PredictionRequest. +func (p PredictionRequest) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) - populate(objectMap, "actions", r.Actions) - populate(objectMap, "category", r.Category) - populate(objectMap, "description", r.Description) - populate(objectMap, "exposedMetadataProperties", r.ExposedMetadataProperties) - populate(objectMap, "extendedProperties", r.ExtendedProperties) - populate(objectMap, "impact", r.Impact) - populate(objectMap, "impactedField", r.ImpactedField) - populate(objectMap, "impactedValue", r.ImpactedValue) - populate(objectMap, "label", r.Label) - populateDateTimeRFC3339(objectMap, "lastUpdated", r.LastUpdated) - populate(objectMap, "learnMoreLink", r.LearnMoreLink) - populate(objectMap, "metadata", r.Metadata) - populate(objectMap, "potentialBenefits", r.PotentialBenefits) - populate(objectMap, "recommendationTypeId", r.RecommendationTypeID) - populate(objectMap, "remediation", r.Remediation) - populate(objectMap, "resourceMetadata", r.ResourceMetadata) - populate(objectMap, "risk", r.Risk) - populate(objectMap, "shortDescription", r.ShortDescription) - populate(objectMap, "suppressionIds", r.SuppressionIDs) + populate(objectMap, "properties", p.Properties) return json.Marshal(objectMap) } -// UnmarshalJSON implements the json.Unmarshaller interface for type RecommendationProperties. -func (r *RecommendationProperties) UnmarshalJSON(data []byte) error { +// 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", r, err) + return fmt.Errorf("unmarshalling type %T: %v", p, err) } for key, val := range rawMsg { var err error switch key { - case "actions": - err = unpopulate(val, "Actions", &r.Actions) - delete(rawMsg, key) - case "category": - err = unpopulate(val, "Category", &r.Category) - delete(rawMsg, key) - case "description": - err = unpopulate(val, "Description", &r.Description) - delete(rawMsg, key) - case "exposedMetadataProperties": - err = unpopulate(val, "ExposedMetadataProperties", &r.ExposedMetadataProperties) + 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", &r.ExtendedProperties) + err = unpopulate(val, "ExtendedProperties", &p.ExtendedProperties) delete(rawMsg, key) - case "impact": - err = unpopulate(val, "Impact", &r.Impact) + case "predictionType": + err = unpopulate(val, "PredictionType", &p.PredictionType) delete(rawMsg, key) - case "impactedField": - err = unpopulate(val, "ImpactedField", &r.ImpactedField) + } + 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) + populateDateTimeRFC3339(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 = unpopulateDateTimeRFC3339(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 ProxyResource. +func (p ProxyResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", p.ID) + populate(objectMap, "name", p.Name) + populate(objectMap, "systemData", p.SystemData) + populate(objectMap, "type", p.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ProxyResource. +func (p *ProxyResource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &p.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &p.Name) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &p.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &p.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RecommendationProperties. +func (r RecommendationProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "actions", r.Actions) + populate(objectMap, "category", r.Category) + populate(objectMap, "description", r.Description) + populate(objectMap, "exposedMetadataProperties", r.ExposedMetadataProperties) + populate(objectMap, "extendedProperties", r.ExtendedProperties) + populate(objectMap, "impact", r.Impact) + populate(objectMap, "impactedField", r.ImpactedField) + populate(objectMap, "impactedValue", r.ImpactedValue) + populate(objectMap, "label", r.Label) + populateDateTimeRFC3339(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) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RecommendationProperties. +func (r *RecommendationProperties) 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 "actions": + err = unpopulate(val, "Actions", &r.Actions) + delete(rawMsg, key) + case "category": + err = unpopulate(val, "Category", &r.Category) + delete(rawMsg, key) + case "description": + err = unpopulate(val, "Description", &r.Description) + delete(rawMsg, key) + case "exposedMetadataProperties": + err = unpopulate(val, "ExposedMetadataProperties", &r.ExposedMetadataProperties) + delete(rawMsg, key) + case "extendedProperties": + err = unpopulate(val, "ExtendedProperties", &r.ExtendedProperties) + delete(rawMsg, key) + case "impact": + err = unpopulate(val, "Impact", &r.Impact) + delete(rawMsg, key) + case "impactedField": + err = unpopulate(val, "ImpactedField", &r.ImpactedField) delete(rawMsg, key) case "impactedValue": err = unpopulate(val, "ImpactedValue", &r.ImpactedValue) @@ -536,6 +1034,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) @@ -548,15 +1049,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) @@ -565,17 +1081,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) @@ -589,9 +1104,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) @@ -600,19 +1112,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) @@ -620,20 +1129,38 @@ 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) - delete(rawMsg, key) - case "resourceId": - err = unpopulate(val, "ResourceID", &r.ResourceID) + case "id": + err = unpopulate(val, "ID", &r.ID) delete(rawMsg, key) - case "singular": - err = unpopulate(val, "Singular", &r.Singular) + case "name": + err = unpopulate(val, "Name", &r.Name) delete(rawMsg, key) - case "source": - err = unpopulate(val, "Source", &r.Source) + } + 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 { @@ -643,18 +1170,19 @@ func (r *ResourceMetadata) UnmarshalJSON(data []byte) error { return nil } -// MarshalJSON implements the json.Marshaller interface for type ResourceRecommendationBase. -func (r ResourceRecommendationBase) MarshalJSON() ([]byte, error) { +// 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 ResourceRecommendationBase. -func (r *ResourceRecommendationBase) UnmarshalJSON(data []byte) error { +// 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) @@ -671,6 +1199,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) @@ -682,16 +1213,16 @@ func (r *ResourceRecommendationBase) UnmarshalJSON(data []byte) error { return nil } -// MarshalJSON implements the json.Marshaller interface for type ResourceRecommendationBaseListResult. -func (r ResourceRecommendationBaseListResult) MarshalJSON() ([]byte, error) { +// 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 ResourceRecommendationBaseListResult. -func (r *ResourceRecommendationBaseListResult) UnmarshalJSON(data []byte) error { +// 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) @@ -713,137 +1244,995 @@ func (r *ResourceRecommendationBaseListResult) UnmarshalJSON(data []byte) error return nil } -// MarshalJSON implements the json.Marshaller interface for type ShortDescription. -func (s ShortDescription) MarshalJSON() ([]byte, error) { +// MarshalJSON implements the json.Marshaller interface for type ResiliencyReviewProperties. +func (r ResiliencyReviewProperties) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) - populate(objectMap, "problem", s.Problem) - populate(objectMap, "solution", s.Solution) + 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 ShortDescription. -func (s *ShortDescription) UnmarshalJSON(data []byte) error { +// 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", s, err) + return fmt.Errorf("unmarshalling type %T: %v", r, err) } for key, val := range rawMsg { var err error switch key { - case "problem": - err = unpopulate(val, "Problem", &s.Problem) + case "publishedAt": + err = unpopulate(val, "PublishedAt", &r.PublishedAt) delete(rawMsg, key) - case "solution": - err = unpopulate(val, "Solution", &s.Solution) + 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", s, err) + return fmt.Errorf("unmarshalling type %T: %v", r, err) } } return nil } -// MarshalJSON implements the json.Marshaller interface for type SuppressionContract. -func (s SuppressionContract) MarshalJSON() ([]byte, error) { +// MarshalJSON implements the json.Marshaller interface for type Resource. +func (r Resource) 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, "type", s.Type) + populate(objectMap, "id", r.ID) + populate(objectMap, "name", r.Name) + populate(objectMap, "systemData", r.SystemData) + populate(objectMap, "type", r.Type) return json.Marshal(objectMap) } -// UnmarshalJSON implements the json.Unmarshaller interface for type SuppressionContract. -func (s *SuppressionContract) UnmarshalJSON(data []byte) error { +// UnmarshalJSON implements the json.Unmarshaller interface for type Resource. +func (r *Resource) 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) + 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", &s.ID) + err = unpopulate(val, "ID", &r.ID) delete(rawMsg, key) case "name": - err = unpopulate(val, "Name", &s.Name) + err = unpopulate(val, "Name", &r.Name) delete(rawMsg, key) - case "properties": - err = unpopulate(val, "Properties", &s.Properties) + case "systemData": + err = unpopulate(val, "SystemData", &r.SystemData) delete(rawMsg, key) case "type": - err = unpopulate(val, "Type", &s.Type) + err = unpopulate(val, "Type", &r.Type) delete(rawMsg, key) } if err != nil { - return fmt.Errorf("unmarshalling type %T: %v", s, err) + return fmt.Errorf("unmarshalling type %T: %v", r, err) } } return nil } -// MarshalJSON implements the json.Marshaller interface for type SuppressionContractListResult. -func (s SuppressionContractListResult) MarshalJSON() ([]byte, error) { +// MarshalJSON implements the json.Marshaller interface for type ResourceMetadata. +func (r ResourceMetadata) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) - populate(objectMap, "nextLink", s.NextLink) - populate(objectMap, "value", s.Value) - return json.Marshal(objectMap) -} + 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) + delete(rawMsg, key) + case "source": + err = unpopulate(val, "Source", &r.Source) + 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 ResourceRecommendationBase. +func (r ResourceRecommendationBase) 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 ResourceRecommendationBase. +func (r *ResourceRecommendationBase) 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 ResourceRecommendationBaseListResult. +func (r ResourceRecommendationBaseListResult) 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 ResourceRecommendationBaseListResult. +func (r *ResourceRecommendationBaseListResult) 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 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 ScoreEntityForAdvisorProperties. +func (s ScoreEntityForAdvisorProperties) 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 ScoreEntityForAdvisorProperties. +func (s *ScoreEntityForAdvisorProperties) 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) + populate(objectMap, "problem", s.Problem) + populate(objectMap, "solution", s.Solution) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ShortDescription. +func (s *ShortDescription) 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 "problem": + err = unpopulate(val, "Problem", &s.Problem) + delete(rawMsg, key) + case "solution": + err = unpopulate(val, "Solution", &s.Solution) + 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 SuppressionContract. +func (s SuppressionContract) 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 SuppressionContract. +func (s *SuppressionContract) 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 SuppressionContractListResult. +func (s SuppressionContractListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", s.NextLink) + populate(objectMap, "value", s.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SuppressionContractListResult. +func (s *SuppressionContractListResult) 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 "nextLink": + err = unpopulate(val, "NextLink", &s.NextLink) + delete(rawMsg, 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 SuppressionProperties. +func (s SuppressionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateDateTimeRFC3339(objectMap, "expirationTimeStamp", s.ExpirationTimeStamp) + populate(objectMap, "suppressionId", s.SuppressionID) + populate(objectMap, "ttl", s.TTL) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SuppressionProperties. +func (s *SuppressionProperties) 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 "expirationTimeStamp": + err = unpopulateDateTimeRFC3339(val, "ExpirationTimeStamp", &s.ExpirationTimeStamp) + delete(rawMsg, key) + case "suppressionId": + err = unpopulate(val, "SuppressionID", &s.SuppressionID) + delete(rawMsg, key) + case "ttl": + err = unpopulate(val, "TTL", &s.TTL) + 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 SystemData. +func (s SystemData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateDateTimeRFC3339(objectMap, "createdAt", s.CreatedAt) + populate(objectMap, "createdBy", s.CreatedBy) + populate(objectMap, "createdByType", s.CreatedByType) + populateDateTimeRFC3339(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 = unpopulateDateTimeRFC3339(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 = unpopulateDateTimeRFC3339(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 TimeSeriesEntityItem. +func (t TimeSeriesEntityItem) 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 TimeSeriesEntityItem. +func (t *TimeSeriesEntityItem) 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 +} -// UnmarshalJSON implements the json.Unmarshaller interface for type SuppressionContractListResult. -func (s *SuppressionContractListResult) UnmarshalJSON(data []byte) error { +// MarshalJSON implements the json.Marshaller interface for type TrackedRecommendationProperties. +func (t TrackedRecommendationProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateDateTimeRFC3339(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", s, err) + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "postponedTime": + err = unpopulateDateTimeRFC3339(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", &s.NextLink) + err = unpopulate(val, "NextLink", &t.NextLink) delete(rawMsg, key) case "value": - err = unpopulate(val, "Value", &s.Value) + err = unpopulate(val, "Value", &t.Value) delete(rawMsg, key) } if err != nil { - return fmt.Errorf("unmarshalling type %T: %v", s, err) + return fmt.Errorf("unmarshalling type %T: %v", t, err) } } return nil } -// MarshalJSON implements the json.Marshaller interface for type SuppressionProperties. -func (s SuppressionProperties) MarshalJSON() ([]byte, error) { +// MarshalJSON implements the json.Marshaller interface for type TriageRecommendationProperties. +func (t TriageRecommendationProperties) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) - populateDateTimeRFC3339(objectMap, "expirationTimeStamp", s.ExpirationTimeStamp) - populate(objectMap, "suppressionId", s.SuppressionID) - populate(objectMap, "ttl", s.TTL) + 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 SuppressionProperties. -func (s *SuppressionProperties) UnmarshalJSON(data []byte) error { +// 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", s, err) + return fmt.Errorf("unmarshalling type %T: %v", t, err) } for key, val := range rawMsg { var err error switch key { - case "expirationTimeStamp": - err = unpopulateDateTimeRFC3339(val, "ExpirationTimeStamp", &s.ExpirationTimeStamp) + case "appliesToSubscriptions": + err = unpopulate(val, "AppliesToSubscriptions", &t.AppliesToSubscriptions) delete(rawMsg, key) - case "suppressionId": - err = unpopulate(val, "SuppressionID", &s.SuppressionID) + case "description": + err = unpopulate(val, "Description", &t.Description) delete(rawMsg, key) - case "ttl": - err = unpopulate(val, "TTL", &s.TTL) + 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", s, err) + 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 @@ -859,8 +2248,18 @@ func populate(m map[string]any, k string, v any) { } } +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 { diff --git a/sdk/resourcemanager/advisor/armadvisor/operations_client.go b/sdk/resourcemanager/advisor/armadvisor/operations_client.go index 1f8a95a51b45..7eb4ea10eaaf 100644 --- a/sdk/resourcemanager/advisor/armadvisor/operations_client.go +++ b/sdk/resourcemanager/advisor/armadvisor/operations_client.go @@ -1,6 +1,3 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. @@ -39,7 +36,7 @@ func NewOperationsClient(credential azcore.TokenCredential, options *arm.ClientO // NewListPager - Lists all the available Advisor REST API operations. // -// Generated from API version 2020-01-01 +// Generated from API version 2024-11-18-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]{ @@ -65,14 +62,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", "2024-11-18-preview") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil diff --git a/sdk/resourcemanager/advisor/armadvisor/options.go b/sdk/resourcemanager/advisor/armadvisor/options.go index bb95021073cc..cae56e3c353f 100644 --- a/sdk/resourcemanager/advisor/armadvisor/options.go +++ b/sdk/resourcemanager/advisor/armadvisor/options.go @@ -1,6 +1,3 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. @@ -8,6 +5,35 @@ 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 +} + // ConfigurationsClientCreateInResourceGroupOptions contains the optional parameters for the ConfigurationsClient.CreateInResourceGroup // method. type ConfigurationsClientCreateInResourceGroupOptions struct { @@ -32,6 +58,11 @@ type ConfigurationsClientListBySubscriptionOptions struct { // placeholder for future optional parameters } +// ManagementClientPredictOptions contains the optional parameters for the ManagementClient.Predict method. +type ManagementClientPredictOptions struct { + // placeholder for future optional parameters +} + // OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. type OperationsClientListOptions struct { // placeholder for future optional parameters @@ -80,6 +111,41 @@ 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.List 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 @@ -103,3 +169,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 961f39a9d2a1..f49f05efb8f0 100644 --- a/sdk/resourcemanager/advisor/armadvisor/recommendationmetadata_client.go +++ b/sdk/resourcemanager/advisor/armadvisor/recommendationmetadata_client.go @@ -1,6 +1,3 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. @@ -43,7 +40,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 2024-11-18-preview // - name - Name of metadata entity. // - options - RecommendationMetadataClientGetOptions contains the optional parameters for the RecommendationMetadataClient.Get // method. @@ -70,7 +67,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") @@ -81,7 +78,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", "2024-11-18-preview") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -98,7 +95,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 2024-11-18-preview // - options - RecommendationMetadataClientListOptions contains the optional parameters for the RecommendationMetadataClient.NewListPager // method. func (client *RecommendationMetadataClient) NewListPager(options *RecommendationMetadataClientListOptions) *runtime.Pager[RecommendationMetadataClientListResponse] { @@ -125,14 +122,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", "2024-11-18-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 deleted file mode 100644 index 130734372a05..000000000000 --- a/sdk/resourcemanager/advisor/armadvisor/recommendationmetadata_client_example_test.go +++ /dev/null @@ -1,150 +0,0 @@ -//go:build go1.18 -// +build go1.18 - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. -// DO NOT EDIT. - -package 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" -) - -// 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 -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) - if err != nil { - log.Fatalf("failed to create client: %v", err) - } - res, err := clientFactory.NewRecommendationMetadataClient().Get(ctx, "types", 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.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)}, - // 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"), - // }}, - // }, - // } -} - -// 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 -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) - if err != nil { - log.Fatalf("failed to create client: %v", err) - } - pager := clientFactory.NewRecommendationMetadataClient().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.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)}, - // 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"), - // }}, - // }, - // }, - // { - // 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"), - // }}, - // }, - // }, - // { - // 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"), - // }}, - // }, - // }}, - // } - } -} diff --git a/sdk/resourcemanager/advisor/armadvisor/recommendations_client.go b/sdk/resourcemanager/advisor/armadvisor/recommendations_client.go index e59592f13667..17026e45934c 100644 --- a/sdk/resourcemanager/advisor/armadvisor/recommendations_client.go +++ b/sdk/resourcemanager/advisor/armadvisor/recommendations_client.go @@ -1,6 +1,3 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. @@ -48,7 +45,7 @@ func NewRecommendationsClient(subscriptionID string, credential azcore.TokenCred // 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 2024-11-18-preview // - options - RecommendationsClientGenerateOptions contains the optional parameters for the RecommendationsClient.Generate // method. func (client *RecommendationsClient) Generate(ctx context.Context, options *RecommendationsClientGenerateOptions) (RecommendationsClientGenerateResponse, error) { @@ -74,7 +71,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") @@ -85,7 +82,7 @@ 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", "2024-11-18-preview") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -106,7 +103,7 @@ 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 +// Generated from API version 2024-11-18-preview // - resourceURI - The fully qualified Azure Resource Manager identifier of the resource to which the recommendation applies. // - recommendationID - The recommendation ID. // - options - RecommendationsClientGetOptions contains the optional parameters for the RecommendationsClient.Get method. @@ -133,7 +130,7 @@ 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") @@ -148,7 +145,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", "2024-11-18-preview") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -168,7 +165,7 @@ func (client *RecommendationsClient) getHandleResponse(resp *http.Response) (Rec // response header. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2020-01-01 +// Generated from API version 2024-11-18-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. @@ -194,7 +191,7 @@ func (client *RecommendationsClient) GetGenerateStatus(ctx context.Context, oper } // 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") @@ -209,7 +206,7 @@ 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", "2024-11-18-preview") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -218,7 +215,7 @@ func (client *RecommendationsClient) getGenerateStatusCreateRequest(ctx context. // 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 2024-11-18-preview // - options - RecommendationsClientListOptions contains the optional parameters for the RecommendationsClient.NewListPager // method. func (client *RecommendationsClient) NewListPager(options *RecommendationsClientListOptions) *runtime.Pager[RecommendationsClientListResponse] { @@ -256,16 +253,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", "2024-11-18-preview") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -279,3 +276,68 @@ func (client *RecommendationsClient) listHandleResponse(resp *http.Response) (Re } 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 2024-11-18-preview +// - resourceURI - The fully qualified Azure Resource Manager identifier of the resource to which the tracked recommendation +// applies. +// - recommendationID - The RecommendationId 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}", url.PathEscape(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", "2024-11-18-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []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 deleted file mode 100644 index 76aa1f3b0a5c..000000000000 --- a/sdk/resourcemanager/advisor/armadvisor/recommendations_client_example_test.go +++ /dev/null @@ -1,251 +0,0 @@ -//go:build go1.18 -// +build go1.18 - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. -// DO NOT EDIT. - -package 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" -) - -// 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 -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) - if err != nil { - log.Fatalf("failed to create client: %v", err) - } - _, err = clientFactory.NewRecommendationsClient().Generate(ctx, 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/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) - if err != nil { - log.Fatalf("failed to create client: %v", err) - } - _, err = clientFactory.NewRecommendationsClient().GetGenerateStatus(ctx, "operationGUID", 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 -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) - 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, - }) - 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.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", - // }, - // }}, - // 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", - // }, - // }, - // Plural: to.Ptr("Availability sets"), - // ResourceID: to.Ptr("/subscriptions/subscriptionId/resourceGroups/resourceGroup/providers/Microsoft.Compute/availabilitysets/abc"), - // Singular: to.Ptr("Availability set"), - // }, - // 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"), - // }, - // }, - // }, - // { - // 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", - // }, - // }}, - // 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", - // }, - // }, - // 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"), - // }, - // }, - // }}, - // } - } -} - -// 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() { - 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, "resourceUri", "recommendationId", 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", - // }, - // }}, - // 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", - // }, - // }, - // 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"), - // }, - // }, - // } -} diff --git a/sdk/resourcemanager/advisor/armadvisor/resiliencyreviews_client.go b/sdk/resourcemanager/advisor/armadvisor/resiliencyreviews_client.go new file mode 100644 index 000000000000..2242d9964405 --- /dev/null +++ b/sdk/resourcemanager/advisor/armadvisor/resiliencyreviews_client.go @@ -0,0 +1,165 @@ +// 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 ( + "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 Azure subscription ID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - 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 Azure Advisor resiliency review by id. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-11-18-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", "2024-11-18-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 Azure Advisor resiliency reviews. +// +// Generated from API version 2024-11-18-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", "2024-11-18-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/response_types.go b/sdk/resourcemanager/advisor/armadvisor/response_types.go deleted file mode 100644 index 06f607940d54..000000000000 --- a/sdk/resourcemanager/advisor/armadvisor/response_types.go +++ /dev/null @@ -1,100 +0,0 @@ -//go:build go1.18 -// +build go1.18 - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -package 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..8631998d8f6c --- /dev/null +++ b/sdk/resourcemanager/advisor/armadvisor/responses.go @@ -0,0 +1,206 @@ +// 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 + +// 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 { + // The Advisor assessment list result data structure. + AssessmentListResult +} + +// AssessmentsClientPutResponse contains the response from method AssessmentsClient.Put. +type AssessmentsClientPutResponse struct { + // The Advisor assessment result data structure. + AssessmentResult +} + +// 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 +} + +// ManagementClientPredictResponse contains the response from method ManagementClient.Predict. +type ManagementClientPredictResponse struct { + // Response used by predictions. + PredictionResponse +} + +// 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 +} + +// 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.List. +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 list of Advisor suppressions. + 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..431b3bc30f83 --- /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) AutoRest Code Generator. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +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 AdvisorScores 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 Azure subscription ID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - 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 2024-11-18-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", "2024-11-18-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 +} + +// List - Gets the list of advisor scores. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-11-18-preview +// - options - ScoresClientListOptions contains the optional parameters for the ScoresClient.List method. +func (client *ScoresClient) List(ctx context.Context, options *ScoresClientListOptions) (ScoresClientListResponse, error) { + var err error + const operationName = "ScoresClient.List" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listCreateRequest(ctx, options) + if err != nil { + return ScoresClientListResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ScoresClientListResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ScoresClientListResponse{}, err + } + resp, err := client.listHandleResponse(httpResp) + return resp, err +} + +// 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", "2024-11-18-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/suppressions_client.go b/sdk/resourcemanager/advisor/armadvisor/suppressions_client.go index 5befe7330c01..5849e8ba0c41 100644 --- a/sdk/resourcemanager/advisor/armadvisor/suppressions_client.go +++ b/sdk/resourcemanager/advisor/armadvisor/suppressions_client.go @@ -1,6 +1,3 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. @@ -49,7 +46,7 @@ func NewSuppressionsClient(subscriptionID string, credential azcore.TokenCredent // a recommendation. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2020-01-01 +// Generated from API version 2024-11-18-preview // - resourceURI - The fully qualified Azure Resource Manager identifier of the resource to which the recommendation applies. // - recommendationID - The recommendation ID. // - name - The name of the suppression. @@ -78,7 +75,7 @@ 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") @@ -97,7 +94,7 @@ 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", "2024-11-18-preview") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, suppressionContract); err != nil { @@ -119,7 +116,7 @@ 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 +// Generated from API version 2024-11-18-preview // - resourceURI - The fully qualified Azure Resource Manager identifier of the resource to which the recommendation applies. // - recommendationID - The recommendation ID. // - name - The name of the suppression. @@ -146,7 +143,7 @@ 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") @@ -165,7 +162,7 @@ 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", "2024-11-18-preview") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -174,7 +171,7 @@ func (client *SuppressionsClient) deleteCreateRequest(ctx context.Context, resou // Get - Obtains the details of a suppression. // If the operation fails it returns an *azcore.ResponseError type. // -// Generated from API version 2020-01-01 +// Generated from API version 2024-11-18-preview // - resourceURI - The fully qualified Azure Resource Manager identifier of the resource to which the recommendation applies. // - recommendationID - The recommendation ID. // - name - The name of the suppression. @@ -202,7 +199,7 @@ 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") @@ -221,7 +218,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", "2024-11-18-preview") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -239,7 +236,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 2024-11-18-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]{ @@ -276,13 +273,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", "2024-11-18-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 deleted file mode 100644 index 11d9647f6658..000000000000 --- a/sdk/resourcemanager/advisor/armadvisor/suppressions_client_example_test.go +++ /dev/null @@ -1,149 +0,0 @@ -//go:build go1.18 -// +build go1.18 - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. -// DO NOT EDIT. - -package 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" -) - -// 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() { - 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.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.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"), - // }, - // } -} - -// 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() { - 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.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{ - // 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() { - 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) - } - _, err = clientFactory.NewSuppressionsClient().Delete(ctx, "resourceUri", "recommendationId", "suppressionName1", 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/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) - if err != nil { - log.Fatalf("failed to create client: %v", err) - } - pager := clientFactory.NewSuppressionsClient().NewListPager(&armadvisor.SuppressionsClientListOptions{Top: nil, - SkipToken: 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.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"), - // }, - // }, - // { - // 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"), - // }, - // }}, - // } - } -} diff --git a/sdk/resourcemanager/advisor/armadvisor/time_rfc3339.go b/sdk/resourcemanager/advisor/armadvisor/time_rfc3339.go index abdce9e90f2a..cf80d5a8980d 100644 --- a/sdk/resourcemanager/advisor/armadvisor/time_rfc3339.go +++ b/sdk/resourcemanager/advisor/armadvisor/time_rfc3339.go @@ -1,6 +1,3 @@ -//go:build go1.18 -// +build go1.18 - // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. @@ -19,12 +16,16 @@ import ( ) // Azure reports time in UTC but it doesn't include the 'Z' time zone suffix in some cases. -var tzOffsetRegex = regexp.MustCompile(`(Z|z|\+|-)(\d+:\d+)*"*$`) +var tzOffsetRegex = regexp.MustCompile(`(?:Z|z|\+|-)(?:\d+:\d+)*"*$`) const ( - utcDateTimeJSON = `"2006-01-02T15:04:05.999999999"` - utcDateTime = "2006-01-02T15:04:05.999999999" - dateTimeJSON = `"` + time.RFC3339Nano + `"` + utcDateTime = "2006-01-02T15:04:05.999999999" + utcDateTimeJSON = `"` + utcDateTime + `"` + utcDateTimeNoT = "2006-01-02 15:04:05.999999999" + utcDateTimeJSONNoT = `"` + utcDateTimeNoT + `"` + dateTimeNoT = `2006-01-02 15:04:05.999999999Z07:00` + dateTimeJSON = `"` + time.RFC3339Nano + `"` + dateTimeJSONNoT = `"` + dateTimeNoT + `"` ) type dateTimeRFC3339 time.Time @@ -40,17 +41,36 @@ func (t dateTimeRFC3339) MarshalText() ([]byte, error) { } func (t *dateTimeRFC3339) UnmarshalJSON(data []byte) error { - layout := utcDateTimeJSON - if tzOffsetRegex.Match(data) { + tzOffset := tzOffsetRegex.Match(data) + hasT := strings.Contains(string(data), "T") || strings.Contains(string(data), "t") + var layout string + if tzOffset && hasT { layout = dateTimeJSON + } else if tzOffset { + layout = dateTimeJSONNoT + } else if hasT { + layout = utcDateTimeJSON + } else { + layout = utcDateTimeJSONNoT } return t.Parse(layout, string(data)) } func (t *dateTimeRFC3339) UnmarshalText(data []byte) error { - layout := utcDateTime - if tzOffsetRegex.Match(data) { + if len(data) == 0 { + return nil + } + tzOffset := tzOffsetRegex.Match(data) + hasT := strings.Contains(string(data), "T") || strings.Contains(string(data), "t") + var layout string + if tzOffset && hasT { layout = time.RFC3339Nano + } else if tzOffset { + layout = dateTimeNoT + } else if hasT { + layout = utcDateTime + } else { + layout = utcDateTimeNoT } return t.Parse(layout, string(data)) } @@ -61,6 +81,10 @@ func (t *dateTimeRFC3339) Parse(layout, value string) error { return err } +func (t dateTimeRFC3339) String() string { + return time.Time(t).Format(time.RFC3339Nano) +} + func populateDateTimeRFC3339(m map[string]any, k string, t *time.Time) { if t == nil { return @@ -74,7 +98,7 @@ func populateDateTimeRFC3339(m map[string]any, k string, t *time.Time) { } func unpopulateDateTimeRFC3339(data json.RawMessage, fn string, t **time.Time) error { - if data == nil || strings.EqualFold(string(data), "null") { + if data == nil || string(data) == "null" { return nil } var aux dateTimeRFC3339 diff --git a/sdk/resourcemanager/advisor/armadvisor/triagerecommendations_client.go b/sdk/resourcemanager/advisor/armadvisor/triagerecommendations_client.go new file mode 100644 index 000000000000..6a6781dcf6bb --- /dev/null +++ b/sdk/resourcemanager/advisor/armadvisor/triagerecommendations_client.go @@ -0,0 +1,342 @@ +// 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 ( + "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 Azure subscription ID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - 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 a triage recommendation for a given id. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-11-18-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", "2024-11-18-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - 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 2024-11-18-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", "2024-11-18-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 Azure Advisor Resiliency Review Id. +// +// Generated from API version 2024-11-18-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", "2024-11-18-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 an existing triage recommendation for a given id. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-11-18-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", "2024-11-18-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, recommendationRejectBody); err != nil { + return nil, err + } + return req, nil +} + +// ResetTriageRecommendation - Reset an existing triage recommendation for a given id. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-11-18-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", "2024-11-18-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} diff --git a/sdk/resourcemanager/advisor/armadvisor/triageresources_client.go b/sdk/resourcemanager/advisor/armadvisor/triageresources_client.go new file mode 100644 index 000000000000..7d060d4dfade --- /dev/null +++ b/sdk/resourcemanager/advisor/armadvisor/triageresources_client.go @@ -0,0 +1,176 @@ +// 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 ( + "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 Azure subscription ID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - 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 a triage resource for a given review and recommendation. +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-11-18-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", "2024-11-18-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 all triage resources that belong to a review and recommendation. +// +// Generated from API version 2024-11-18-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", "2024-11-18-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/workloads_client.go b/sdk/resourcemanager/advisor/armadvisor/workloads_client.go new file mode 100644 index 000000000000..b776a3a6659f --- /dev/null +++ b/sdk/resourcemanager/advisor/armadvisor/workloads_client.go @@ -0,0 +1,95 @@ +// 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 ( + "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 Azure subscription ID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - 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 list of Workloads. +// +// Generated from API version 2024-11-18-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", "2024-11-18-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 +}