diff --git a/sdk/resourcemanager/advisor/armadvisor/CHANGELOG.md b/sdk/resourcemanager/advisor/armadvisor/CHANGELOG.md index 49967ccd50d3..14b92dc8879d 100644 --- a/sdk/resourcemanager/advisor/armadvisor/CHANGELOG.md +++ b/sdk/resourcemanager/advisor/armadvisor/CHANGELOG.md @@ -1,5 +1,37 @@ # Release History +## 1.3.0 (2024-10-04) +### 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 function `*ClientFactory.NewManagementClient() *ManagementClient` +- New function `*ClientFactory.NewScoresClient() *ScoresClient` +- New function `NewManagementClient(string, azcore.TokenCredential, *arm.ClientOptions) (*ManagementClient, error)` +- New function `*ManagementClient.Predict(context.Context, PredictionRequest, *ManagementClientPredictOptions) (ManagementClientPredictResponse, error)` +- 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 struct `PredictionRequest` +- New struct `PredictionRequestProperties` +- New struct `PredictionResponse` +- New struct `PredictionResponseProperties` +- New struct `ProxyResource` +- New struct `ScoreEntity` +- New struct `ScoreEntityForAdvisor` +- New struct `ScoreEntityForAdvisorProperties` +- New struct `ScoreResponse` +- New struct `SystemData` +- New struct `TimeSeriesEntityItem` +- New field `SystemData` in struct `ConfigData` +- New field `Duration` in struct `ConfigDataProperties` +- 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 71736113edf6..3e2efbaa38fb 100644 --- a/sdk/resourcemanager/advisor/armadvisor/README.md +++ b/sdk/resourcemanager/advisor/armadvisor/README.md @@ -57,7 +57,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.NewConfigurationsClient() ``` ## Fakes diff --git a/sdk/resourcemanager/advisor/armadvisor/autorest.md b/sdk/resourcemanager/advisor/armadvisor/autorest.md index 582c1196e2a5..76eee12b1ee5 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 ``` \ 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..3a5a8588848e 100644 --- a/sdk/resourcemanager/advisor/armadvisor/client_factory.go +++ b/sdk/resourcemanager/advisor/armadvisor/client_factory.go @@ -17,8 +17,7 @@ import ( // Don't use this type directly, use NewClientFactory instead. type ClientFactory struct { subscriptionID string - credential azcore.TokenCredential - options *arm.ClientOptions + internal *arm.Client } // NewClientFactory creates a new instance of ClientFactory with the specified values. @@ -27,42 +26,66 @@ type ClientFactory struct { // - credential - used to authorize requests. Usually a credential from azidentity. // - options - pass nil to accept the default values. func NewClientFactory(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ClientFactory, error) { - _, err := arm.NewClient(moduleName, moduleVersion, credential, options) + internal, err := arm.NewClient(moduleName, moduleVersion, credential, options) if err != nil { return nil, err } return &ClientFactory{ - subscriptionID: subscriptionID, credential: credential, - options: options.Clone(), + subscriptionID: subscriptionID, + internal: internal, }, nil } // 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, + } +} + +// 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, + } } diff --git a/sdk/resourcemanager/advisor/armadvisor/configurations_client.go b/sdk/resourcemanager/advisor/armadvisor/configurations_client.go index 1cc233b23ad0..f296a37e1e8b 100644 --- a/sdk/resourcemanager/advisor/armadvisor/configurations_client.go +++ b/sdk/resourcemanager/advisor/armadvisor/configurations_client.go @@ -46,7 +46,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 2023-01-01 // - configurationName - Advisor configuration name. Value must be 'default' // - resourceGroup - The name of the Azure resource group. // - configContract - The Azure Advisor configuration data structure. @@ -94,7 +94,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", "2023-01-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, configContract); err != nil { @@ -116,7 +116,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 2023-01-01 // - 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 @@ -159,7 +159,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", "2023-01-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, configContract); err != nil { @@ -179,7 +179,7 @@ func (client *ConfigurationsClient) createInSubscriptionHandleResponse(resp *htt // NewListByResourceGroupPager - Retrieve Azure Advisor configurations. // -// Generated from API version 2020-01-01 +// Generated from API version 2023-01-01 // - resourceGroup - The name of the Azure resource group. // - options - ConfigurationsClientListByResourceGroupOptions contains the optional parameters for the ConfigurationsClient.NewListByResourceGroupPager // method. @@ -223,7 +223,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", "2023-01-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -241,7 +241,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 2023-01-01 // - options - ConfigurationsClientListBySubscriptionOptions contains the optional parameters for the ConfigurationsClient.NewListBySubscriptionPager // method. func (client *ConfigurationsClient) NewListBySubscriptionPager(options *ConfigurationsClientListBySubscriptionOptions) *runtime.Pager[ConfigurationsClientListBySubscriptionResponse] { @@ -279,7 +279,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", "2023-01-01") 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..478eadf93227 100644 --- a/sdk/resourcemanager/advisor/armadvisor/constants.go +++ b/sdk/resourcemanager/advisor/armadvisor/constants.go @@ -10,9 +10,27 @@ package armadvisor const ( moduleName = "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/advisor/armadvisor" - moduleVersion = "v1.2.0" + moduleVersion = "v1.3.0" ) +// 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 +86,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 +122,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 +165,20 @@ 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, + } +} + // Risk - The potential risk of not implementing the recommendation. type Risk string 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..f2d3b9ab962d --- /dev/null +++ b/sdk/resourcemanager/advisor/armadvisor/fake/management_server.go @@ -0,0 +1,95 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/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")} + } + + var resp *http.Response + var err error + + switch method { + case "ManagementClient.Predict": + resp, err = m.dispatchPredict(req) + default: + err = fmt.Errorf("unhandled API %s", method) + } + + if err != nil { + return nil, err + } + + return resp, nil +} + +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 +} 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..c30d0a61311c --- /dev/null +++ b/sdk/resourcemanager/advisor/armadvisor/fake/scores_server.go @@ -0,0 +1,127 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/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")} + } + + var resp *http.Response + var err error + + switch method { + case "ScoresClient.Get": + resp, err = s.dispatchGet(req) + case "ScoresClient.List": + resp, err = s.dispatchList(req) + default: + err = fmt.Errorf("unhandled API %s", method) + } + + if err != nil { + return nil, err + } + + return resp, nil +} + +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 +} diff --git a/sdk/resourcemanager/advisor/armadvisor/fake/server_factory.go b/sdk/resourcemanager/advisor/armadvisor/fake/server_factory.go index a712fe39be87..46b1bc6f1566 100644 --- a/sdk/resourcemanager/advisor/armadvisor/fake/server_factory.go +++ b/sdk/resourcemanager/advisor/armadvisor/fake/server_factory.go @@ -20,9 +20,11 @@ import ( // ServerFactory is a fake server for instances of the armadvisor.ClientFactory type. type ServerFactory struct { ConfigurationsServer ConfigurationsServer + ManagementServer ManagementServer OperationsServer OperationsServer RecommendationMetadataServer RecommendationMetadataServer RecommendationsServer RecommendationsServer + ScoresServer ScoresServer SuppressionsServer SuppressionsServer } @@ -41,9 +43,11 @@ type ServerFactoryTransport struct { srv *ServerFactory trMu sync.Mutex trConfigurationsServer *ConfigurationsServerTransport + trManagementServer *ManagementServerTransport trOperationsServer *OperationsServerTransport trRecommendationMetadataServer *RecommendationMetadataServerTransport trRecommendationsServer *RecommendationsServerTransport + trScoresServer *ScoresServerTransport trSuppressionsServer *SuppressionsServerTransport } @@ -65,6 +69,9 @@ func (s *ServerFactoryTransport) Do(req *http.Request) (*http.Response, error) { 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,6 +85,9 @@ func (s *ServerFactoryTransport) Do(req *http.Request) (*http.Response, error) { return NewRecommendationsServerTransport(&s.srv.RecommendationsServer) }) resp, err = s.trRecommendationsServer.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) diff --git a/sdk/resourcemanager/advisor/armadvisor/fake/time_rfc3339.go b/sdk/resourcemanager/advisor/armadvisor/fake/time_rfc3339.go index b0535a7b63e6..81f308b0d343 100644 --- a/sdk/resourcemanager/advisor/armadvisor/fake/time_rfc3339.go +++ b/sdk/resourcemanager/advisor/armadvisor/fake/time_rfc3339.go @@ -19,12 +19,16 @@ import ( ) // Azure reports time in UTC but it doesn't include the 'Z' time zone suffix in some cases. -var tzOffsetRegex = regexp.MustCompile(`(Z|z|\+|-)(\d+:\d+)*"*$`) +var tzOffsetRegex = regexp.MustCompile(`(?:Z|z|\+|-)(?:\d+:\d+)*"*$`) const ( - utcDateTimeJSON = `"2006-01-02T15:04:05.999999999"` - utcDateTime = "2006-01-02T15:04:05.999999999" - dateTimeJSON = `"` + time.RFC3339Nano + `"` + utcDateTime = "2006-01-02T15:04:05.999999999" + utcDateTimeJSON = `"` + utcDateTime + `"` + utcDateTimeNoT = "2006-01-02 15:04:05.999999999" + utcDateTimeJSONNoT = `"` + utcDateTimeNoT + `"` + dateTimeNoT = `2006-01-02 15:04:05.999999999Z07:00` + dateTimeJSON = `"` + time.RFC3339Nano + `"` + dateTimeJSONNoT = `"` + dateTimeNoT + `"` ) type dateTimeRFC3339 time.Time @@ -40,17 +44,33 @@ func (t dateTimeRFC3339) MarshalText() ([]byte, error) { } func (t *dateTimeRFC3339) UnmarshalJSON(data []byte) error { - layout := utcDateTimeJSON - if tzOffsetRegex.Match(data) { + tzOffset := tzOffsetRegex.Match(data) + hasT := strings.Contains(string(data), "T") || strings.Contains(string(data), "t") + var layout string + if tzOffset && hasT { layout = dateTimeJSON + } else if tzOffset { + layout = dateTimeJSONNoT + } else if hasT { + layout = utcDateTimeJSON + } else { + layout = utcDateTimeJSONNoT } return t.Parse(layout, string(data)) } func (t *dateTimeRFC3339) UnmarshalText(data []byte) error { - layout := utcDateTime - if tzOffsetRegex.Match(data) { + tzOffset := tzOffsetRegex.Match(data) + hasT := strings.Contains(string(data), "T") || strings.Contains(string(data), "t") + var layout string + if tzOffset && hasT { layout = time.RFC3339Nano + } else if tzOffset { + layout = dateTimeNoT + } else if hasT { + layout = utcDateTime + } else { + layout = utcDateTimeNoT } return t.Parse(layout, string(data)) } @@ -61,6 +81,10 @@ func (t *dateTimeRFC3339) Parse(layout, value string) error { return err } +func (t dateTimeRFC3339) String() string { + return time.Time(t).Format(time.RFC3339Nano) +} + func populateDateTimeRFC3339(m map[string]any, k string, t *time.Time) { if t == nil { return @@ -74,7 +98,7 @@ func populateDateTimeRFC3339(m map[string]any, k string, t *time.Time) { } func unpopulateDateTimeRFC3339(data json.RawMessage, fn string, t **time.Time) error { - if data == nil || strings.EqualFold(string(data), "null") { + if data == nil || string(data) == "null" { return nil } var aux dateTimeRFC3339 diff --git a/sdk/resourcemanager/advisor/armadvisor/go.mod b/sdk/resourcemanager/advisor/armadvisor/go.mod index 64d464e1653e..2727eb8347ba 100644 --- a/sdk/resourcemanager/advisor/armadvisor/go.mod +++ b/sdk/resourcemanager/advisor/armadvisor/go.mod @@ -4,13 +4,13 @@ go 1.18 require ( github.com/Azure/azure-sdk-for-go/sdk/azcore v1.13.0 - github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.7.0 github.com/Azure/azure-sdk-for-go/sdk/internal v1.10.0 github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/internal/v3 v3.1.0 github.com/stretchr/testify v1.9.0 ) require ( + github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.7.0 // 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.2.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..1d2ad87bd2aa --- /dev/null +++ b/sdk/resourcemanager/advisor/armadvisor/management_client.go @@ -0,0 +1,102 @@ +//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 + +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 2023-01-01 +// - 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, options *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", "2023-01-01") + 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..125a5f3cbe5b 100644 --- a/sdk/resourcemanager/advisor/armadvisor/models.go +++ b/sdk/resourcemanager/advisor/armadvisor/models.go @@ -29,13 +29,16 @@ 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 +47,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 @@ -164,6 +171,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. @@ -224,15 +292,18 @@ type RecommendationProperties struct { SuppressionIDs []*string } -// Resource - An Azure resource. +// 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 +330,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 +352,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 +420,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 +453,33 @@ 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 +} diff --git a/sdk/resourcemanager/advisor/armadvisor/models_serde.go b/sdk/resourcemanager/advisor/armadvisor/models_serde.go index b851e4e9882d..10b9b8440ad1 100644 --- a/sdk/resourcemanager/advisor/armadvisor/models_serde.go +++ b/sdk/resourcemanager/advisor/armadvisor/models_serde.go @@ -79,6 +79,7 @@ func (c ConfigData) MarshalJSON() ([]byte, error) { 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 +102,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 +120,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 +138,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) @@ -466,6 +474,181 @@ func (o *OperationEntityListResult) UnmarshalJSON(data []byte) error { return nil } +// MarshalJSON implements the json.Marshaller interface for type PredictionRequest. +func (p PredictionRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", p.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PredictionRequest. +func (p *PredictionRequest) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, "Properties", &p.Properties) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PredictionRequestProperties. +func (p PredictionRequestProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateAny(objectMap, "extendedProperties", p.ExtendedProperties) + populate(objectMap, "predictionType", p.PredictionType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PredictionRequestProperties. +func (p *PredictionRequestProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "extendedProperties": + err = unpopulate(val, "ExtendedProperties", &p.ExtendedProperties) + delete(rawMsg, key) + case "predictionType": + err = unpopulate(val, "PredictionType", &p.PredictionType) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PredictionResponse. +func (p PredictionResponse) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", p.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PredictionResponse. +func (p *PredictionResponse) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, "Properties", &p.Properties) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PredictionResponseProperties. +func (p PredictionResponseProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "category", p.Category) + populateAny(objectMap, "extendedProperties", p.ExtendedProperties) + populate(objectMap, "impact", p.Impact) + populate(objectMap, "impactedField", p.ImpactedField) + 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) @@ -570,6 +753,7 @@ func (r Resource) MarshalJSON() ([]byte, error) { objectMap := make(map[string]any) populate(objectMap, "id", r.ID) populate(objectMap, "name", r.Name) + populate(objectMap, "systemData", r.SystemData) populate(objectMap, "type", r.Type) return json.Marshal(objectMap) } @@ -589,6 +773,9 @@ func (r *Resource) UnmarshalJSON(data []byte) error { case "name": err = unpopulate(val, "Name", &r.Name) 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) @@ -649,6 +836,7 @@ func (r ResourceRecommendationBase) MarshalJSON() ([]byte, error) { populate(objectMap, "id", r.ID) populate(objectMap, "name", r.Name) populate(objectMap, "properties", r.Properties) + populate(objectMap, "systemData", r.SystemData) populate(objectMap, "type", r.Type) return json.Marshal(objectMap) } @@ -671,6 +859,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) @@ -713,6 +904,154 @@ func (r *ResourceRecommendationBaseListResult) UnmarshalJSON(data []byte) error return nil } +// MarshalJSON implements the json.Marshaller interface for type ScoreEntity. +func (s ScoreEntity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "categoryCount", s.CategoryCount) + populate(objectMap, "consumptionUnits", s.ConsumptionUnits) + populate(objectMap, "date", s.Date) + populate(objectMap, "impactedResourceCount", s.ImpactedResourceCount) + populate(objectMap, "potentialScoreIncrease", s.PotentialScoreIncrease) + populate(objectMap, "score", s.Score) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ScoreEntity. +func (s *ScoreEntity) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "categoryCount": + err = unpopulate(val, "CategoryCount", &s.CategoryCount) + delete(rawMsg, key) + case "consumptionUnits": + err = unpopulate(val, "ConsumptionUnits", &s.ConsumptionUnits) + delete(rawMsg, key) + case "date": + err = unpopulate(val, "Date", &s.Date) + delete(rawMsg, key) + case "impactedResourceCount": + err = unpopulate(val, "ImpactedResourceCount", &s.ImpactedResourceCount) + delete(rawMsg, key) + case "potentialScoreIncrease": + err = unpopulate(val, "PotentialScoreIncrease", &s.PotentialScoreIncrease) + delete(rawMsg, key) + case "score": + err = unpopulate(val, "Score", &s.Score) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ScoreEntityForAdvisor. +func (s ScoreEntityForAdvisor) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", s.ID) + populate(objectMap, "name", s.Name) + populate(objectMap, "properties", s.Properties) + populate(objectMap, "systemData", s.SystemData) + populate(objectMap, "type", s.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ScoreEntityForAdvisor. +func (s *ScoreEntityForAdvisor) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &s.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &s.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &s.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &s.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &s.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type 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) @@ -750,6 +1089,7 @@ func (s SuppressionContract) MarshalJSON() ([]byte, error) { populate(objectMap, "id", s.ID) populate(objectMap, "name", s.Name) populate(objectMap, "properties", s.Properties) + populate(objectMap, "systemData", s.SystemData) populate(objectMap, "type", s.Type) return json.Marshal(objectMap) } @@ -772,6 +1112,9 @@ func (s *SuppressionContract) UnmarshalJSON(data []byte) error { case "properties": err = unpopulate(val, "Properties", &s.Properties) delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &s.SystemData) + delete(rawMsg, key) case "type": err = unpopulate(val, "Type", &s.Type) delete(rawMsg, key) @@ -849,6 +1192,84 @@ func (s *SuppressionProperties) UnmarshalJSON(data []byte) error { 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 +} + func populate(m map[string]any, k string, v any) { if v == nil { return @@ -859,8 +1280,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..6ed30b5832e5 100644 --- a/sdk/resourcemanager/advisor/armadvisor/operations_client.go +++ b/sdk/resourcemanager/advisor/armadvisor/operations_client.go @@ -39,7 +39,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 2023-01-01 // - 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]{ @@ -72,7 +72,7 @@ func (client *OperationsClient) listCreateRequest(ctx context.Context, options * return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2020-01-01") + reqQP.Set("api-version", "2023-01-01") 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..9ecaa980c5d2 100644 --- a/sdk/resourcemanager/advisor/armadvisor/options.go +++ b/sdk/resourcemanager/advisor/armadvisor/options.go @@ -32,6 +32,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 +85,16 @@ type RecommendationsClientListOptions struct { 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 diff --git a/sdk/resourcemanager/advisor/armadvisor/recommendationmetadata_client.go b/sdk/resourcemanager/advisor/armadvisor/recommendationmetadata_client.go index 961f39a9d2a1..f8b9bb303d59 100644 --- a/sdk/resourcemanager/advisor/armadvisor/recommendationmetadata_client.go +++ b/sdk/resourcemanager/advisor/armadvisor/recommendationmetadata_client.go @@ -43,7 +43,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 2023-01-01 // - name - Name of metadata entity. // - options - RecommendationMetadataClientGetOptions contains the optional parameters for the RecommendationMetadataClient.Get // method. @@ -81,7 +81,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", "2023-01-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -98,7 +98,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 2023-01-01 // - options - RecommendationMetadataClientListOptions contains the optional parameters for the RecommendationMetadataClient.NewListPager // method. func (client *RecommendationMetadataClient) NewListPager(options *RecommendationMetadataClientListOptions) *runtime.Pager[RecommendationMetadataClientListResponse] { @@ -132,7 +132,7 @@ func (client *RecommendationMetadataClient) listCreateRequest(ctx context.Contex return nil, err } reqQP := req.Raw().URL.Query() - reqQP.Set("api-version", "2020-01-01") + reqQP.Set("api-version", "2023-01-01") 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..f789d216393e 100644 --- a/sdk/resourcemanager/advisor/armadvisor/recommendations_client.go +++ b/sdk/resourcemanager/advisor/armadvisor/recommendations_client.go @@ -48,7 +48,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 2023-01-01 // - options - RecommendationsClientGenerateOptions contains the optional parameters for the RecommendationsClient.Generate // method. func (client *RecommendationsClient) Generate(ctx context.Context, options *RecommendationsClientGenerateOptions) (RecommendationsClientGenerateResponse, error) { @@ -85,7 +85,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", "2023-01-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -106,7 +106,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 2023-01-01 // - 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. @@ -148,7 +148,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", "2023-01-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -168,7 +168,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 2023-01-01 // - 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. @@ -209,7 +209,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", "2023-01-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -218,7 +218,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 2023-01-01 // - options - RecommendationsClientListOptions contains the optional parameters for the RecommendationsClient.NewListPager // method. func (client *RecommendationsClient) NewListPager(options *RecommendationsClientListOptions) *runtime.Pager[RecommendationsClientListResponse] { @@ -256,16 +256,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", "2023-01-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, 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/response_types.go b/sdk/resourcemanager/advisor/armadvisor/responses.go similarity index 88% rename from sdk/resourcemanager/advisor/armadvisor/response_types.go rename to sdk/resourcemanager/advisor/armadvisor/responses.go index 06f607940d54..9062935b5e16 100644 --- a/sdk/resourcemanager/advisor/armadvisor/response_types.go +++ b/sdk/resourcemanager/advisor/armadvisor/responses.go @@ -32,6 +32,12 @@ type ConfigurationsClientListBySubscriptionResponse struct { 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. @@ -76,6 +82,17 @@ type RecommendationsClientListResponse struct { ResourceRecommendationBaseListResult } +// 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. diff --git a/sdk/resourcemanager/advisor/armadvisor/scores_client.go b/sdk/resourcemanager/advisor/armadvisor/scores_client.go new file mode 100644 index 000000000000..cb900e6c9779 --- /dev/null +++ b/sdk/resourcemanager/advisor/armadvisor/scores_client.go @@ -0,0 +1,157 @@ +//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 + +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 2023-01-01 +// - 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, options *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", "2023-01-01") + 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 2023-01-01 +// - 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, options *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", "2023-01-01") + 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..d0e9a81a3747 100644 --- a/sdk/resourcemanager/advisor/armadvisor/suppressions_client.go +++ b/sdk/resourcemanager/advisor/armadvisor/suppressions_client.go @@ -49,7 +49,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 2023-01-01 // - 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. @@ -97,7 +97,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", "2023-01-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} if err := runtime.MarshalAsJSON(req, suppressionContract); err != nil { @@ -119,7 +119,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 2023-01-01 // - 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. @@ -165,7 +165,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", "2023-01-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -174,7 +174,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 2023-01-01 // - 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. @@ -221,7 +221,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", "2023-01-01") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil @@ -239,7 +239,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 2023-01-01 // - 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 +276,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", "2023-01-01") 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..dcaca8c4ddf0 100644 --- a/sdk/resourcemanager/advisor/armadvisor/time_rfc3339.go +++ b/sdk/resourcemanager/advisor/armadvisor/time_rfc3339.go @@ -19,12 +19,16 @@ import ( ) // Azure reports time in UTC but it doesn't include the 'Z' time zone suffix in some cases. -var tzOffsetRegex = regexp.MustCompile(`(Z|z|\+|-)(\d+:\d+)*"*$`) +var tzOffsetRegex = regexp.MustCompile(`(?:Z|z|\+|-)(?:\d+:\d+)*"*$`) const ( - utcDateTimeJSON = `"2006-01-02T15:04:05.999999999"` - utcDateTime = "2006-01-02T15:04:05.999999999" - dateTimeJSON = `"` + time.RFC3339Nano + `"` + utcDateTime = "2006-01-02T15:04:05.999999999" + utcDateTimeJSON = `"` + utcDateTime + `"` + utcDateTimeNoT = "2006-01-02 15:04:05.999999999" + utcDateTimeJSONNoT = `"` + utcDateTimeNoT + `"` + dateTimeNoT = `2006-01-02 15:04:05.999999999Z07:00` + dateTimeJSON = `"` + time.RFC3339Nano + `"` + dateTimeJSONNoT = `"` + dateTimeNoT + `"` ) type dateTimeRFC3339 time.Time @@ -40,17 +44,33 @@ func (t dateTimeRFC3339) MarshalText() ([]byte, error) { } func (t *dateTimeRFC3339) UnmarshalJSON(data []byte) error { - layout := utcDateTimeJSON - if tzOffsetRegex.Match(data) { + tzOffset := tzOffsetRegex.Match(data) + hasT := strings.Contains(string(data), "T") || strings.Contains(string(data), "t") + var layout string + if tzOffset && hasT { layout = dateTimeJSON + } else if tzOffset { + layout = dateTimeJSONNoT + } else if hasT { + layout = utcDateTimeJSON + } else { + layout = utcDateTimeJSONNoT } return t.Parse(layout, string(data)) } func (t *dateTimeRFC3339) UnmarshalText(data []byte) error { - layout := utcDateTime - if tzOffsetRegex.Match(data) { + tzOffset := tzOffsetRegex.Match(data) + hasT := strings.Contains(string(data), "T") || strings.Contains(string(data), "t") + var layout string + if tzOffset && hasT { layout = time.RFC3339Nano + } else if tzOffset { + layout = dateTimeNoT + } else if hasT { + layout = utcDateTime + } else { + layout = utcDateTimeNoT } return t.Parse(layout, string(data)) } @@ -61,6 +81,10 @@ func (t *dateTimeRFC3339) Parse(layout, value string) error { return err } +func (t dateTimeRFC3339) String() string { + return time.Time(t).Format(time.RFC3339Nano) +} + func populateDateTimeRFC3339(m map[string]any, k string, t *time.Time) { if t == nil { return @@ -74,7 +98,7 @@ func populateDateTimeRFC3339(m map[string]any, k string, t *time.Time) { } func unpopulateDateTimeRFC3339(data json.RawMessage, fn string, t **time.Time) error { - if data == nil || strings.EqualFold(string(data), "null") { + if data == nil || string(data) == "null" { return nil } var aux dateTimeRFC3339