diff --git a/sdk/resourcemanager/cloudhealth/armcloudhealth/CHANGELOG.md b/sdk/resourcemanager/cloudhealth/armcloudhealth/CHANGELOG.md new file mode 100644 index 000000000000..068c9fa202b6 --- /dev/null +++ b/sdk/resourcemanager/cloudhealth/armcloudhealth/CHANGELOG.md @@ -0,0 +1,8 @@ +# Release History + +## 0.1.0 (2025-05-08) +### Other Changes + +The package of `github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/cloudhealth/armcloudhealth` is using our [next generation design principles](https://azure.github.io/azure-sdk/general_introduction.html). + +To learn more, please refer to our documentation [Quick Start](https://aka.ms/azsdk/go/mgmt). \ No newline at end of file diff --git a/sdk/resourcemanager/cloudhealth/armcloudhealth/LICENSE.txt b/sdk/resourcemanager/cloudhealth/armcloudhealth/LICENSE.txt new file mode 100644 index 000000000000..dc0c2ffb3dc1 --- /dev/null +++ b/sdk/resourcemanager/cloudhealth/armcloudhealth/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/sdk/resourcemanager/cloudhealth/armcloudhealth/README.md b/sdk/resourcemanager/cloudhealth/armcloudhealth/README.md new file mode 100644 index 000000000000..efdec47ffe51 --- /dev/null +++ b/sdk/resourcemanager/cloudhealth/armcloudhealth/README.md @@ -0,0 +1,90 @@ +# Azure Cloudhealth Module for Go + +The `armcloudhealth` module provides operations for working with Azure Cloudhealth. + +[Source code](https://github.com/Azure/azure-sdk-for-go/tree/main/sdk/resourcemanager/cloudhealth/armcloudhealth) + +# Getting started + +## Prerequisites + +- an [Azure subscription](https://azure.microsoft.com/free/) +- Go 1.18 or above (You could download and install the latest version of Go from [here](https://go.dev/doc/install). It will replace the existing Go on your machine. If you want to install multiple Go versions on the same machine, you could refer this [doc](https://go.dev/doc/manage-install).) + +## Install the package + +This project uses [Go modules](https://github.com/golang/go/wiki/Modules) for versioning and dependency management. + +Install the Azure Cloudhealth module: + +```sh +go get github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/cloudhealth/armcloudhealth +``` + +## Authorization + +When creating a client, you will need to provide a credential for authenticating with Azure Cloudhealth. The `azidentity` module provides facilities for various ways of authenticating with Azure including client/secret, certificate, managed identity, and more. + +```go +cred, err := azidentity.NewDefaultAzureCredential(nil) +``` + +For more information on authentication, please see the documentation for `azidentity` at [pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity). + +## Client Factory + +Azure Cloudhealth module consists of one or more clients. We provide a client factory which could be used to create any client in this module. + +```go +clientFactory, err := armcloudhealth.NewClientFactory(, cred, nil) +``` + +You can use `ClientOptions` in package `github.com/Azure/azure-sdk-for-go/sdk/azcore/arm` to set endpoint to connect with public and sovereign clouds as well as Azure Stack. For more information, please see the documentation for `azcore` at [pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azcore](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azcore). + +```go +options := arm.ClientOptions { + ClientOptions: azcore.ClientOptions { + Cloud: cloud.AzureChina, + }, +} +clientFactory, err := armcloudhealth.NewClientFactory(, cred, &options) +``` + +## Clients + +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.NewAuthenticationSettingsClient() +``` + +## Fakes + +The fake package contains types used for constructing in-memory fake servers used in unit tests. +This allows writing tests to cover various success/error conditions without the need for connecting to a live service. + +Please see https://github.com/Azure/azure-sdk-for-go/tree/main/sdk/samples/fakes for details and examples on how to use fakes. + +## Provide Feedback + +If you encounter bugs or have suggestions, please +[open an issue](https://github.com/Azure/azure-sdk-for-go/issues) and assign the `Cloudhealth` label. + +# Contributing + +This project welcomes contributions and suggestions. Most contributions require +you to agree to a Contributor License Agreement (CLA) declaring that you have +the right to, and actually do, grant us the rights to use your contribution. +For details, visit [https://cla.microsoft.com](https://cla.microsoft.com). + +When you submit a pull request, a CLA-bot will automatically determine whether +you need to provide a CLA and decorate the PR appropriately (e.g., label, +comment). Simply follow the instructions provided by the bot. You will only +need to do this once across all repos using our CLA. + +This project has adopted the +[Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). +For more information, see the +[Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) +or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any +additional questions or comments. \ No newline at end of file diff --git a/sdk/resourcemanager/cloudhealth/armcloudhealth/authenticationsettings_client.go b/sdk/resourcemanager/cloudhealth/armcloudhealth/authenticationsettings_client.go new file mode 100644 index 000000000000..325c23b61580 --- /dev/null +++ b/sdk/resourcemanager/cloudhealth/armcloudhealth/authenticationsettings_client.go @@ -0,0 +1,310 @@ +// 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 armcloudhealth + +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" +) + +// AuthenticationSettingsClient contains the methods for the AuthenticationSettings group. +// Don't use this type directly, use NewAuthenticationSettingsClient() instead. +type AuthenticationSettingsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewAuthenticationSettingsClient creates a new instance of AuthenticationSettingsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewAuthenticationSettingsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*AuthenticationSettingsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &AuthenticationSettingsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CreateOrUpdate - Create a AuthenticationSetting +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-10-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - healthModelName - Name of health model resource +// - authenticationSettingName - Name of the authentication setting. Must be unique within a health model. +// - resource - Resource create parameters. +// - options - AuthenticationSettingsClientCreateOrUpdateOptions contains the optional parameters for the AuthenticationSettingsClient.CreateOrUpdate +// method. +func (client *AuthenticationSettingsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, healthModelName string, authenticationSettingName string, resource AuthenticationSetting, options *AuthenticationSettingsClientCreateOrUpdateOptions) (AuthenticationSettingsClientCreateOrUpdateResponse, error) { + var err error + const operationName = "AuthenticationSettingsClient.CreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, healthModelName, authenticationSettingName, resource, options) + if err != nil { + return AuthenticationSettingsClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AuthenticationSettingsClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return AuthenticationSettingsClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *AuthenticationSettingsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, healthModelName string, authenticationSettingName string, resource AuthenticationSetting, _ *AuthenticationSettingsClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/authenticationsettings/{authenticationSettingName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if healthModelName == "" { + return nil, errors.New("parameter healthModelName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{healthModelName}", url.PathEscape(healthModelName)) + if authenticationSettingName == "" { + return nil, errors.New("parameter authenticationSettingName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{authenticationSettingName}", url.PathEscape(authenticationSettingName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-10-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *AuthenticationSettingsClient) createOrUpdateHandleResponse(resp *http.Response) (AuthenticationSettingsClientCreateOrUpdateResponse, error) { + result := AuthenticationSettingsClientCreateOrUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AuthenticationSetting); err != nil { + return AuthenticationSettingsClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// Delete - Delete a AuthenticationSetting +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-10-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - healthModelName - Name of health model resource +// - authenticationSettingName - Name of the authentication setting. Must be unique within a health model. +// - options - AuthenticationSettingsClientDeleteOptions contains the optional parameters for the AuthenticationSettingsClient.Delete +// method. +func (client *AuthenticationSettingsClient) Delete(ctx context.Context, resourceGroupName string, healthModelName string, authenticationSettingName string, options *AuthenticationSettingsClientDeleteOptions) (AuthenticationSettingsClientDeleteResponse, error) { + var err error + const operationName = "AuthenticationSettingsClient.Delete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, healthModelName, authenticationSettingName, options) + if err != nil { + return AuthenticationSettingsClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AuthenticationSettingsClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return AuthenticationSettingsClientDeleteResponse{}, err + } + return AuthenticationSettingsClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *AuthenticationSettingsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, healthModelName string, authenticationSettingName string, _ *AuthenticationSettingsClientDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/authenticationsettings/{authenticationSettingName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if healthModelName == "" { + return nil, errors.New("parameter healthModelName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{healthModelName}", url.PathEscape(healthModelName)) + if authenticationSettingName == "" { + return nil, errors.New("parameter authenticationSettingName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{authenticationSettingName}", url.PathEscape(authenticationSettingName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-10-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Get a AuthenticationSetting +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-10-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - healthModelName - Name of health model resource +// - authenticationSettingName - Name of the authentication setting. Must be unique within a health model. +// - options - AuthenticationSettingsClientGetOptions contains the optional parameters for the AuthenticationSettingsClient.Get +// method. +func (client *AuthenticationSettingsClient) Get(ctx context.Context, resourceGroupName string, healthModelName string, authenticationSettingName string, options *AuthenticationSettingsClientGetOptions) (AuthenticationSettingsClientGetResponse, error) { + var err error + const operationName = "AuthenticationSettingsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, healthModelName, authenticationSettingName, options) + if err != nil { + return AuthenticationSettingsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AuthenticationSettingsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return AuthenticationSettingsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *AuthenticationSettingsClient) getCreateRequest(ctx context.Context, resourceGroupName string, healthModelName string, authenticationSettingName string, _ *AuthenticationSettingsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/authenticationsettings/{authenticationSettingName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if healthModelName == "" { + return nil, errors.New("parameter healthModelName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{healthModelName}", url.PathEscape(healthModelName)) + if authenticationSettingName == "" { + return nil, errors.New("parameter authenticationSettingName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{authenticationSettingName}", url.PathEscape(authenticationSettingName)) + 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-10-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *AuthenticationSettingsClient) getHandleResponse(resp *http.Response) (AuthenticationSettingsClientGetResponse, error) { + result := AuthenticationSettingsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AuthenticationSetting); err != nil { + return AuthenticationSettingsClientGetResponse{}, err + } + return result, nil +} + +// NewListByHealthModelPager - List AuthenticationSetting resources by HealthModel +// +// Generated from API version 2023-10-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - healthModelName - Name of health model resource +// - options - AuthenticationSettingsClientListByHealthModelOptions contains the optional parameters for the AuthenticationSettingsClient.NewListByHealthModelPager +// method. +func (client *AuthenticationSettingsClient) NewListByHealthModelPager(resourceGroupName string, healthModelName string, options *AuthenticationSettingsClientListByHealthModelOptions) *runtime.Pager[AuthenticationSettingsClientListByHealthModelResponse] { + return runtime.NewPager(runtime.PagingHandler[AuthenticationSettingsClientListByHealthModelResponse]{ + More: func(page AuthenticationSettingsClientListByHealthModelResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *AuthenticationSettingsClientListByHealthModelResponse) (AuthenticationSettingsClientListByHealthModelResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "AuthenticationSettingsClient.NewListByHealthModelPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByHealthModelCreateRequest(ctx, resourceGroupName, healthModelName, options) + }, nil) + if err != nil { + return AuthenticationSettingsClientListByHealthModelResponse{}, err + } + return client.listByHealthModelHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByHealthModelCreateRequest creates the ListByHealthModel request. +func (client *AuthenticationSettingsClient) listByHealthModelCreateRequest(ctx context.Context, resourceGroupName string, healthModelName string, _ *AuthenticationSettingsClientListByHealthModelOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/authenticationsettings" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if healthModelName == "" { + return nil, errors.New("parameter healthModelName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{healthModelName}", url.PathEscape(healthModelName)) + 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-10-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByHealthModelHandleResponse handles the ListByHealthModel response. +func (client *AuthenticationSettingsClient) listByHealthModelHandleResponse(resp *http.Response) (AuthenticationSettingsClientListByHealthModelResponse, error) { + result := AuthenticationSettingsClientListByHealthModelResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AuthenticationSettingListResult); err != nil { + return AuthenticationSettingsClientListByHealthModelResponse{}, err + } + return result, nil +} diff --git a/sdk/resourcemanager/cloudhealth/armcloudhealth/autorest.md b/sdk/resourcemanager/cloudhealth/armcloudhealth/autorest.md new file mode 100644 index 000000000000..3d009941c180 --- /dev/null +++ b/sdk/resourcemanager/cloudhealth/armcloudhealth/autorest.md @@ -0,0 +1,13 @@ +### AutoRest Configuration + +> see https://aka.ms/autorest + +``` yaml +azure-arm: true +require: +- /mnt/vss/_work/1/s/azure-rest-api-specs/specification/cloudhealth/resource-manager/readme.md +- /mnt/vss/_work/1/s/azure-rest-api-specs/specification/cloudhealth/resource-manager/readme.go.md +license-header: MICROSOFT_MIT_NO_VERSION +module-version: 0.1.0 + +``` \ No newline at end of file diff --git a/sdk/resourcemanager/cloudhealth/armcloudhealth/build.go b/sdk/resourcemanager/cloudhealth/armcloudhealth/build.go new file mode 100644 index 000000000000..34bb7dcf4d94 --- /dev/null +++ b/sdk/resourcemanager/cloudhealth/armcloudhealth/build.go @@ -0,0 +1,7 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +// This file enables 'go generate' to regenerate this specific SDK +//go:generate pwsh ../../../../eng/scripts/build.ps1 -skipBuild -cleanGenerated -format -tidy -generate -alwaysSetBodyParamRequired -removeUnreferencedTypes resourcemanager/cloudhealth/armcloudhealth + +package armcloudhealth diff --git a/sdk/resourcemanager/cloudhealth/armcloudhealth/ci.yml b/sdk/resourcemanager/cloudhealth/armcloudhealth/ci.yml new file mode 100644 index 000000000000..090330575ea1 --- /dev/null +++ b/sdk/resourcemanager/cloudhealth/armcloudhealth/ci.yml @@ -0,0 +1,27 @@ +# NOTE: Please refer to https://aka.ms/azsdk/engsys/ci-yaml before editing this file. +trigger: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/resourcemanager/cloudhealth/armcloudhealth/ + +pr: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/resourcemanager/cloudhealth/armcloudhealth/ + +extends: + template: /eng/pipelines/templates/jobs/archetype-sdk-client.yml + parameters: + ServiceDirectory: 'resourcemanager/cloudhealth/armcloudhealth' diff --git a/sdk/resourcemanager/cloudhealth/armcloudhealth/client_factory.go b/sdk/resourcemanager/cloudhealth/armcloudhealth/client_factory.go new file mode 100644 index 000000000000..2ef666340a91 --- /dev/null +++ b/sdk/resourcemanager/cloudhealth/armcloudhealth/client_factory.go @@ -0,0 +1,89 @@ +// 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 armcloudhealth + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" +) + +// ClientFactory is a client factory used to create any client in this module. +// Don't use this type directly, use NewClientFactory instead. +type ClientFactory struct { + subscriptionID string + internal *arm.Client +} + +// NewClientFactory creates a new instance of ClientFactory with the specified values. +// The parameter values will be propagated to any client created from this factory. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewClientFactory(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ClientFactory, error) { + internal, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + return &ClientFactory{ + subscriptionID: subscriptionID, + internal: internal, + }, nil +} + +// NewAuthenticationSettingsClient creates a new instance of AuthenticationSettingsClient. +func (c *ClientFactory) NewAuthenticationSettingsClient() *AuthenticationSettingsClient { + return &AuthenticationSettingsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewDiscoveryRulesClient creates a new instance of DiscoveryRulesClient. +func (c *ClientFactory) NewDiscoveryRulesClient() *DiscoveryRulesClient { + return &DiscoveryRulesClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewEntitiesClient creates a new instance of EntitiesClient. +func (c *ClientFactory) NewEntitiesClient() *EntitiesClient { + return &EntitiesClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewHealthModelsClient creates a new instance of HealthModelsClient. +func (c *ClientFactory) NewHealthModelsClient() *HealthModelsClient { + return &HealthModelsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewOperationsClient creates a new instance of OperationsClient. +func (c *ClientFactory) NewOperationsClient() *OperationsClient { + return &OperationsClient{ + internal: c.internal, + } +} + +// NewRelationshipsClient creates a new instance of RelationshipsClient. +func (c *ClientFactory) NewRelationshipsClient() *RelationshipsClient { + return &RelationshipsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewSignalDefinitionsClient creates a new instance of SignalDefinitionsClient. +func (c *ClientFactory) NewSignalDefinitionsClient() *SignalDefinitionsClient { + return &SignalDefinitionsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} diff --git a/sdk/resourcemanager/cloudhealth/armcloudhealth/constants.go b/sdk/resourcemanager/cloudhealth/armcloudhealth/constants.go new file mode 100644 index 000000000000..7936af27391c --- /dev/null +++ b/sdk/resourcemanager/cloudhealth/armcloudhealth/constants.go @@ -0,0 +1,387 @@ +// 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 armcloudhealth + +const ( + moduleName = "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/cloudhealth/armcloudhealth" + moduleVersion = "v0.1.0" +) + +// ActionType - Enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. +type ActionType string + +const ( + ActionTypeInternal ActionType = "Internal" +) + +// PossibleActionTypeValues returns the possible values for the ActionType const type. +func PossibleActionTypeValues() []ActionType { + return []ActionType{ + ActionTypeInternal, + } +} + +// AlertSeverity - Severity of an alert +type AlertSeverity string + +const ( + // AlertSeveritySev0 - Critical + AlertSeveritySev0 AlertSeverity = "Sev0" + // AlertSeveritySev1 - Error + AlertSeveritySev1 AlertSeverity = "Sev1" + // AlertSeveritySev2 - Warning + AlertSeveritySev2 AlertSeverity = "Sev2" + // AlertSeveritySev3 - Informational + AlertSeveritySev3 AlertSeverity = "Sev3" + // AlertSeveritySev4 - Verbose + AlertSeveritySev4 AlertSeverity = "Sev4" +) + +// PossibleAlertSeverityValues returns the possible values for the AlertSeverity const type. +func PossibleAlertSeverityValues() []AlertSeverity { + return []AlertSeverity{ + AlertSeveritySev0, + AlertSeveritySev1, + AlertSeveritySev2, + AlertSeveritySev3, + AlertSeveritySev4, + } +} + +// AuthenticationKind - Supported kinds of authentication settings as discriminator +type AuthenticationKind string + +const ( + AuthenticationKindManagedIdentity AuthenticationKind = "ManagedIdentity" +) + +// PossibleAuthenticationKindValues returns the possible values for the AuthenticationKind const type. +func PossibleAuthenticationKindValues() []AuthenticationKind { + return []AuthenticationKind{ + AuthenticationKindManagedIdentity, + } +} + +// 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, + } +} + +// DependenciesAggregationType - Aggregation type for child dependencies. +type DependenciesAggregationType string + +const ( + // DependenciesAggregationTypeThresholds - Based on configurable thresholds. + DependenciesAggregationTypeThresholds DependenciesAggregationType = "Thresholds" + // DependenciesAggregationTypeWorstOf - Default behavior: Worst child health state is propagated. + DependenciesAggregationTypeWorstOf DependenciesAggregationType = "WorstOf" +) + +// PossibleDependenciesAggregationTypeValues returns the possible values for the DependenciesAggregationType const type. +func PossibleDependenciesAggregationTypeValues() []DependenciesAggregationType { + return []DependenciesAggregationType{ + DependenciesAggregationTypeThresholds, + DependenciesAggregationTypeWorstOf, + } +} + +// DiscoveryRuleRecommendedSignalsBehavior - Discovery rule recommended signal behavior +type DiscoveryRuleRecommendedSignalsBehavior string + +const ( + // DiscoveryRuleRecommendedSignalsBehaviorDisabled - Do not automatically add recommended signals + DiscoveryRuleRecommendedSignalsBehaviorDisabled DiscoveryRuleRecommendedSignalsBehavior = "Disabled" + // DiscoveryRuleRecommendedSignalsBehaviorEnabled - Automatically add recommended signals + DiscoveryRuleRecommendedSignalsBehaviorEnabled DiscoveryRuleRecommendedSignalsBehavior = "Enabled" +) + +// PossibleDiscoveryRuleRecommendedSignalsBehaviorValues returns the possible values for the DiscoveryRuleRecommendedSignalsBehavior const type. +func PossibleDiscoveryRuleRecommendedSignalsBehaviorValues() []DiscoveryRuleRecommendedSignalsBehavior { + return []DiscoveryRuleRecommendedSignalsBehavior{ + DiscoveryRuleRecommendedSignalsBehaviorDisabled, + DiscoveryRuleRecommendedSignalsBehaviorEnabled, + } +} + +// DiscoveryRuleRelationshipDiscoveryBehavior - Discovery rule relationship discovery behavior +type DiscoveryRuleRelationshipDiscoveryBehavior string + +const ( + // DiscoveryRuleRelationshipDiscoveryBehaviorDisabled - Do not automatically attempt to discover relationships + DiscoveryRuleRelationshipDiscoveryBehaviorDisabled DiscoveryRuleRelationshipDiscoveryBehavior = "Disabled" + // DiscoveryRuleRelationshipDiscoveryBehaviorEnabled - Automatically attempt to discover relationships + DiscoveryRuleRelationshipDiscoveryBehaviorEnabled DiscoveryRuleRelationshipDiscoveryBehavior = "Enabled" +) + +// PossibleDiscoveryRuleRelationshipDiscoveryBehaviorValues returns the possible values for the DiscoveryRuleRelationshipDiscoveryBehavior const type. +func PossibleDiscoveryRuleRelationshipDiscoveryBehaviorValues() []DiscoveryRuleRelationshipDiscoveryBehavior { + return []DiscoveryRuleRelationshipDiscoveryBehavior{ + DiscoveryRuleRelationshipDiscoveryBehaviorDisabled, + DiscoveryRuleRelationshipDiscoveryBehaviorEnabled, + } +} + +// DynamicThresholdDirection - Threshold direction for dynamic thresholds +type DynamicThresholdDirection string + +const ( + // DynamicThresholdDirectionGreaterOrLowerThan - Greater or Lower Than + DynamicThresholdDirectionGreaterOrLowerThan DynamicThresholdDirection = "GreaterOrLowerThan" + // DynamicThresholdDirectionGreaterThan - Greater than + DynamicThresholdDirectionGreaterThan DynamicThresholdDirection = "GreaterThan" + // DynamicThresholdDirectionLowerThan - Lower than + DynamicThresholdDirectionLowerThan DynamicThresholdDirection = "LowerThan" +) + +// PossibleDynamicThresholdDirectionValues returns the possible values for the DynamicThresholdDirection const type. +func PossibleDynamicThresholdDirectionValues() []DynamicThresholdDirection { + return []DynamicThresholdDirection{ + DynamicThresholdDirectionGreaterOrLowerThan, + DynamicThresholdDirectionGreaterThan, + DynamicThresholdDirectionLowerThan, + } +} + +// DynamicThresholdModel - ML-based model variants +type DynamicThresholdModel string + +const ( + // DynamicThresholdModelAnomalyDetection - Anomaly detection model + DynamicThresholdModelAnomalyDetection DynamicThresholdModel = "AnomalyDetection" +) + +// PossibleDynamicThresholdModelValues returns the possible values for the DynamicThresholdModel const type. +func PossibleDynamicThresholdModelValues() []DynamicThresholdModel { + return []DynamicThresholdModel{ + DynamicThresholdModelAnomalyDetection, + } +} + +// EntityImpact - Impact of the entity in health state propagation +type EntityImpact string + +const ( + // EntityImpactLimited - Limited impact + EntityImpactLimited EntityImpact = "Limited" + // EntityImpactStandard - Standard impact + EntityImpactStandard EntityImpact = "Standard" + // EntityImpactSuppressed - Suppressed impact + EntityImpactSuppressed EntityImpact = "Suppressed" +) + +// PossibleEntityImpactValues returns the possible values for the EntityImpact const type. +func PossibleEntityImpactValues() []EntityImpact { + return []EntityImpact{ + EntityImpactLimited, + EntityImpactStandard, + EntityImpactSuppressed, + } +} + +// HealthModelProvisioningState - Health Model provisioning states +type HealthModelProvisioningState string + +const ( + // HealthModelProvisioningStateCanceled - Resource creation was canceled. + HealthModelProvisioningStateCanceled HealthModelProvisioningState = "Canceled" + HealthModelProvisioningStateCreating HealthModelProvisioningState = "Creating" + HealthModelProvisioningStateDeleting HealthModelProvisioningState = "Deleting" + // HealthModelProvisioningStateFailed - Resource creation failed. + HealthModelProvisioningStateFailed HealthModelProvisioningState = "Failed" + // HealthModelProvisioningStateSucceeded - Resource has been created. + HealthModelProvisioningStateSucceeded HealthModelProvisioningState = "Succeeded" +) + +// PossibleHealthModelProvisioningStateValues returns the possible values for the HealthModelProvisioningState const type. +func PossibleHealthModelProvisioningStateValues() []HealthModelProvisioningState { + return []HealthModelProvisioningState{ + HealthModelProvisioningStateCanceled, + HealthModelProvisioningStateCreating, + HealthModelProvisioningStateDeleting, + HealthModelProvisioningStateFailed, + HealthModelProvisioningStateSucceeded, + } +} + +// HealthState - Health state of an entity +type HealthState string + +const ( + // HealthStateDegraded - Degraded status + HealthStateDegraded HealthState = "Degraded" + // HealthStateDeleted - Deleted status + HealthStateDeleted HealthState = "Deleted" + // HealthStateError - Error status (Unhealthy) + HealthStateError HealthState = "Error" + // HealthStateHealthy - Healthy status + HealthStateHealthy HealthState = "Healthy" + // HealthStateUnknown - Unknown status + HealthStateUnknown HealthState = "Unknown" +) + +// PossibleHealthStateValues returns the possible values for the HealthState const type. +func PossibleHealthStateValues() []HealthState { + return []HealthState{ + HealthStateDegraded, + HealthStateDeleted, + HealthStateError, + HealthStateHealthy, + HealthStateUnknown, + } +} + +// ManagedServiceIdentityType - Type of managed service identity (where both SystemAssigned and UserAssigned types are allowed). +type ManagedServiceIdentityType string + +const ( + ManagedServiceIdentityTypeNone ManagedServiceIdentityType = "None" + ManagedServiceIdentityTypeSystemAssigned ManagedServiceIdentityType = "SystemAssigned" + ManagedServiceIdentityTypeSystemAssignedUserAssigned ManagedServiceIdentityType = "SystemAssigned,UserAssigned" + ManagedServiceIdentityTypeUserAssigned ManagedServiceIdentityType = "UserAssigned" +) + +// PossibleManagedServiceIdentityTypeValues returns the possible values for the ManagedServiceIdentityType const type. +func PossibleManagedServiceIdentityTypeValues() []ManagedServiceIdentityType { + return []ManagedServiceIdentityType{ + ManagedServiceIdentityTypeNone, + ManagedServiceIdentityTypeSystemAssigned, + ManagedServiceIdentityTypeSystemAssignedUserAssigned, + ManagedServiceIdentityTypeUserAssigned, + } +} + +// MetricAggregationType - Metric aggregation type +type MetricAggregationType string + +const ( + MetricAggregationTypeAverage MetricAggregationType = "Average" + MetricAggregationTypeCount MetricAggregationType = "Count" + MetricAggregationTypeMaximum MetricAggregationType = "Maximum" + MetricAggregationTypeMinimum MetricAggregationType = "Minimum" + MetricAggregationTypeNone MetricAggregationType = "None" + MetricAggregationTypeTotal MetricAggregationType = "Total" +) + +// PossibleMetricAggregationTypeValues returns the possible values for the MetricAggregationType const type. +func PossibleMetricAggregationTypeValues() []MetricAggregationType { + return []MetricAggregationType{ + MetricAggregationTypeAverage, + MetricAggregationTypeCount, + MetricAggregationTypeMaximum, + MetricAggregationTypeMinimum, + MetricAggregationTypeNone, + MetricAggregationTypeTotal, + } +} + +// Origin - The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default +// value is "user,system" +type Origin string + +const ( + OriginSystem Origin = "system" + OriginUser Origin = "user" + OriginUserSystem Origin = "user,system" +) + +// PossibleOriginValues returns the possible values for the Origin const type. +func PossibleOriginValues() []Origin { + return []Origin{ + OriginSystem, + OriginUser, + OriginUserSystem, + } +} + +// RefreshInterval - Interval in which the signal is being evaluated. Defaults to PT1M (1 minute). +type RefreshInterval string + +const ( + // RefreshIntervalPT10M - Ten Minutes + RefreshIntervalPT10M RefreshInterval = "PT10M" + // RefreshIntervalPT1H - One Hour + RefreshIntervalPT1H RefreshInterval = "PT1H" + // RefreshIntervalPT1M - One Minute + RefreshIntervalPT1M RefreshInterval = "PT1M" + // RefreshIntervalPT2H - Two Hours + RefreshIntervalPT2H RefreshInterval = "PT2H" + // RefreshIntervalPT30M - Thirty Minutes + RefreshIntervalPT30M RefreshInterval = "PT30M" + // RefreshIntervalPT5M - Five Minutes + RefreshIntervalPT5M RefreshInterval = "PT5M" +) + +// PossibleRefreshIntervalValues returns the possible values for the RefreshInterval const type. +func PossibleRefreshIntervalValues() []RefreshInterval { + return []RefreshInterval{ + RefreshIntervalPT10M, + RefreshIntervalPT1H, + RefreshIntervalPT1M, + RefreshIntervalPT2H, + RefreshIntervalPT30M, + RefreshIntervalPT5M, + } +} + +// SignalKind - Supported signal kinds as discriminator +type SignalKind string + +const ( + SignalKindAzureResourceMetric SignalKind = "AzureResourceMetric" + SignalKindLogAnalyticsQuery SignalKind = "LogAnalyticsQuery" + SignalKindPrometheusMetricsQuery SignalKind = "PrometheusMetricsQuery" +) + +// PossibleSignalKindValues returns the possible values for the SignalKind const type. +func PossibleSignalKindValues() []SignalKind { + return []SignalKind{ + SignalKindAzureResourceMetric, + SignalKindLogAnalyticsQuery, + SignalKindPrometheusMetricsQuery, + } +} + +// SignalOperator - Signal operator +type SignalOperator string + +const ( + // SignalOperatorEquals - Equal to + SignalOperatorEquals SignalOperator = "Equals" + // SignalOperatorGreaterOrEquals - Greater than or equal to + SignalOperatorGreaterOrEquals SignalOperator = "GreaterOrEquals" + // SignalOperatorGreaterThan - Greater than + SignalOperatorGreaterThan SignalOperator = "GreaterThan" + // SignalOperatorLowerOrEquals - Lower than or equal to + SignalOperatorLowerOrEquals SignalOperator = "LowerOrEquals" + // SignalOperatorLowerThan - Lower than + SignalOperatorLowerThan SignalOperator = "LowerThan" +) + +// PossibleSignalOperatorValues returns the possible values for the SignalOperator const type. +func PossibleSignalOperatorValues() []SignalOperator { + return []SignalOperator{ + SignalOperatorEquals, + SignalOperatorGreaterOrEquals, + SignalOperatorGreaterThan, + SignalOperatorLowerOrEquals, + SignalOperatorLowerThan, + } +} diff --git a/sdk/resourcemanager/cloudhealth/armcloudhealth/discoveryrules_client.go b/sdk/resourcemanager/cloudhealth/armcloudhealth/discoveryrules_client.go new file mode 100644 index 000000000000..90d89aa9ef38 --- /dev/null +++ b/sdk/resourcemanager/cloudhealth/armcloudhealth/discoveryrules_client.go @@ -0,0 +1,312 @@ +// 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 armcloudhealth + +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" + "time" +) + +// DiscoveryRulesClient contains the methods for the DiscoveryRules group. +// Don't use this type directly, use NewDiscoveryRulesClient() instead. +type DiscoveryRulesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewDiscoveryRulesClient creates a new instance of DiscoveryRulesClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewDiscoveryRulesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*DiscoveryRulesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &DiscoveryRulesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CreateOrUpdate - Create a DiscoveryRule +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-10-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - healthModelName - Name of health model resource +// - discoveryRuleName - Name of the discovery rule. Must be unique within a health model. +// - resource - Resource create parameters. +// - options - DiscoveryRulesClientCreateOrUpdateOptions contains the optional parameters for the DiscoveryRulesClient.CreateOrUpdate +// method. +func (client *DiscoveryRulesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, healthModelName string, discoveryRuleName string, resource DiscoveryRule, options *DiscoveryRulesClientCreateOrUpdateOptions) (DiscoveryRulesClientCreateOrUpdateResponse, error) { + var err error + const operationName = "DiscoveryRulesClient.CreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, healthModelName, discoveryRuleName, resource, options) + if err != nil { + return DiscoveryRulesClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DiscoveryRulesClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return DiscoveryRulesClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *DiscoveryRulesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, healthModelName string, discoveryRuleName string, resource DiscoveryRule, _ *DiscoveryRulesClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/discoveryrules/{discoveryRuleName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if healthModelName == "" { + return nil, errors.New("parameter healthModelName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{healthModelName}", url.PathEscape(healthModelName)) + if discoveryRuleName == "" { + return nil, errors.New("parameter discoveryRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{discoveryRuleName}", url.PathEscape(discoveryRuleName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-10-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *DiscoveryRulesClient) createOrUpdateHandleResponse(resp *http.Response) (DiscoveryRulesClientCreateOrUpdateResponse, error) { + result := DiscoveryRulesClientCreateOrUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DiscoveryRule); err != nil { + return DiscoveryRulesClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// Delete - Delete a DiscoveryRule +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-10-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - healthModelName - Name of health model resource +// - discoveryRuleName - Name of the discovery rule. Must be unique within a health model. +// - options - DiscoveryRulesClientDeleteOptions contains the optional parameters for the DiscoveryRulesClient.Delete method. +func (client *DiscoveryRulesClient) Delete(ctx context.Context, resourceGroupName string, healthModelName string, discoveryRuleName string, options *DiscoveryRulesClientDeleteOptions) (DiscoveryRulesClientDeleteResponse, error) { + var err error + const operationName = "DiscoveryRulesClient.Delete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, healthModelName, discoveryRuleName, options) + if err != nil { + return DiscoveryRulesClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DiscoveryRulesClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DiscoveryRulesClientDeleteResponse{}, err + } + return DiscoveryRulesClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *DiscoveryRulesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, healthModelName string, discoveryRuleName string, _ *DiscoveryRulesClientDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/discoveryrules/{discoveryRuleName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if healthModelName == "" { + return nil, errors.New("parameter healthModelName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{healthModelName}", url.PathEscape(healthModelName)) + if discoveryRuleName == "" { + return nil, errors.New("parameter discoveryRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{discoveryRuleName}", url.PathEscape(discoveryRuleName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-10-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Get a DiscoveryRule +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-10-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - healthModelName - Name of health model resource +// - discoveryRuleName - Name of the discovery rule. Must be unique within a health model. +// - options - DiscoveryRulesClientGetOptions contains the optional parameters for the DiscoveryRulesClient.Get method. +func (client *DiscoveryRulesClient) Get(ctx context.Context, resourceGroupName string, healthModelName string, discoveryRuleName string, options *DiscoveryRulesClientGetOptions) (DiscoveryRulesClientGetResponse, error) { + var err error + const operationName = "DiscoveryRulesClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, healthModelName, discoveryRuleName, options) + if err != nil { + return DiscoveryRulesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DiscoveryRulesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DiscoveryRulesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *DiscoveryRulesClient) getCreateRequest(ctx context.Context, resourceGroupName string, healthModelName string, discoveryRuleName string, _ *DiscoveryRulesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/discoveryrules/{discoveryRuleName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if healthModelName == "" { + return nil, errors.New("parameter healthModelName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{healthModelName}", url.PathEscape(healthModelName)) + if discoveryRuleName == "" { + return nil, errors.New("parameter discoveryRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{discoveryRuleName}", url.PathEscape(discoveryRuleName)) + 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-10-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *DiscoveryRulesClient) getHandleResponse(resp *http.Response) (DiscoveryRulesClientGetResponse, error) { + result := DiscoveryRulesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DiscoveryRule); err != nil { + return DiscoveryRulesClientGetResponse{}, err + } + return result, nil +} + +// NewListByHealthModelPager - List DiscoveryRule resources by HealthModel +// +// Generated from API version 2023-10-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - healthModelName - Name of health model resource +// - options - DiscoveryRulesClientListByHealthModelOptions contains the optional parameters for the DiscoveryRulesClient.NewListByHealthModelPager +// method. +func (client *DiscoveryRulesClient) NewListByHealthModelPager(resourceGroupName string, healthModelName string, options *DiscoveryRulesClientListByHealthModelOptions) *runtime.Pager[DiscoveryRulesClientListByHealthModelResponse] { + return runtime.NewPager(runtime.PagingHandler[DiscoveryRulesClientListByHealthModelResponse]{ + More: func(page DiscoveryRulesClientListByHealthModelResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *DiscoveryRulesClientListByHealthModelResponse) (DiscoveryRulesClientListByHealthModelResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DiscoveryRulesClient.NewListByHealthModelPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByHealthModelCreateRequest(ctx, resourceGroupName, healthModelName, options) + }, nil) + if err != nil { + return DiscoveryRulesClientListByHealthModelResponse{}, err + } + return client.listByHealthModelHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByHealthModelCreateRequest creates the ListByHealthModel request. +func (client *DiscoveryRulesClient) listByHealthModelCreateRequest(ctx context.Context, resourceGroupName string, healthModelName string, options *DiscoveryRulesClientListByHealthModelOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/discoveryrules" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if healthModelName == "" { + return nil, errors.New("parameter healthModelName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{healthModelName}", url.PathEscape(healthModelName)) + 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-10-01-preview") + if options != nil && options.Timestamp != nil { + reqQP.Set("timestamp", options.Timestamp.Format(time.RFC3339Nano)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByHealthModelHandleResponse handles the ListByHealthModel response. +func (client *DiscoveryRulesClient) listByHealthModelHandleResponse(resp *http.Response) (DiscoveryRulesClientListByHealthModelResponse, error) { + result := DiscoveryRulesClientListByHealthModelResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DiscoveryRuleListResult); err != nil { + return DiscoveryRulesClientListByHealthModelResponse{}, err + } + return result, nil +} diff --git a/sdk/resourcemanager/cloudhealth/armcloudhealth/entities_client.go b/sdk/resourcemanager/cloudhealth/armcloudhealth/entities_client.go new file mode 100644 index 000000000000..20f32617781d --- /dev/null +++ b/sdk/resourcemanager/cloudhealth/armcloudhealth/entities_client.go @@ -0,0 +1,311 @@ +// 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 armcloudhealth + +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" + "time" +) + +// EntitiesClient contains the methods for the Entities group. +// Don't use this type directly, use NewEntitiesClient() instead. +type EntitiesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewEntitiesClient creates a new instance of EntitiesClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewEntitiesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*EntitiesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &EntitiesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CreateOrUpdate - Create a Entity +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-10-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - healthModelName - Name of health model resource +// - entityName - Name of the entity. Must be unique within a health model. +// - resource - Resource create parameters. +// - options - EntitiesClientCreateOrUpdateOptions contains the optional parameters for the EntitiesClient.CreateOrUpdate method. +func (client *EntitiesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, healthModelName string, entityName string, resource Entity, options *EntitiesClientCreateOrUpdateOptions) (EntitiesClientCreateOrUpdateResponse, error) { + var err error + const operationName = "EntitiesClient.CreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, healthModelName, entityName, resource, options) + if err != nil { + return EntitiesClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return EntitiesClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return EntitiesClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *EntitiesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, healthModelName string, entityName string, resource Entity, _ *EntitiesClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/entities/{entityName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if healthModelName == "" { + return nil, errors.New("parameter healthModelName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{healthModelName}", url.PathEscape(healthModelName)) + if entityName == "" { + return nil, errors.New("parameter entityName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{entityName}", url.PathEscape(entityName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-10-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *EntitiesClient) createOrUpdateHandleResponse(resp *http.Response) (EntitiesClientCreateOrUpdateResponse, error) { + result := EntitiesClientCreateOrUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Entity); err != nil { + return EntitiesClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// Delete - Delete a Entity +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-10-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - healthModelName - Name of health model resource +// - entityName - Name of the entity. Must be unique within a health model. +// - options - EntitiesClientDeleteOptions contains the optional parameters for the EntitiesClient.Delete method. +func (client *EntitiesClient) Delete(ctx context.Context, resourceGroupName string, healthModelName string, entityName string, options *EntitiesClientDeleteOptions) (EntitiesClientDeleteResponse, error) { + var err error + const operationName = "EntitiesClient.Delete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, healthModelName, entityName, options) + if err != nil { + return EntitiesClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return EntitiesClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return EntitiesClientDeleteResponse{}, err + } + return EntitiesClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *EntitiesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, healthModelName string, entityName string, _ *EntitiesClientDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/entities/{entityName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if healthModelName == "" { + return nil, errors.New("parameter healthModelName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{healthModelName}", url.PathEscape(healthModelName)) + if entityName == "" { + return nil, errors.New("parameter entityName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{entityName}", url.PathEscape(entityName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-10-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Get a Entity +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-10-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - healthModelName - Name of health model resource +// - entityName - Name of the entity. Must be unique within a health model. +// - options - EntitiesClientGetOptions contains the optional parameters for the EntitiesClient.Get method. +func (client *EntitiesClient) Get(ctx context.Context, resourceGroupName string, healthModelName string, entityName string, options *EntitiesClientGetOptions) (EntitiesClientGetResponse, error) { + var err error + const operationName = "EntitiesClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, healthModelName, entityName, options) + if err != nil { + return EntitiesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return EntitiesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return EntitiesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *EntitiesClient) getCreateRequest(ctx context.Context, resourceGroupName string, healthModelName string, entityName string, _ *EntitiesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/entities/{entityName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if healthModelName == "" { + return nil, errors.New("parameter healthModelName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{healthModelName}", url.PathEscape(healthModelName)) + if entityName == "" { + return nil, errors.New("parameter entityName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{entityName}", url.PathEscape(entityName)) + 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-10-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *EntitiesClient) getHandleResponse(resp *http.Response) (EntitiesClientGetResponse, error) { + result := EntitiesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Entity); err != nil { + return EntitiesClientGetResponse{}, err + } + return result, nil +} + +// NewListByHealthModelPager - List Entity resources by HealthModel +// +// Generated from API version 2023-10-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - healthModelName - Name of health model resource +// - options - EntitiesClientListByHealthModelOptions contains the optional parameters for the EntitiesClient.NewListByHealthModelPager +// method. +func (client *EntitiesClient) NewListByHealthModelPager(resourceGroupName string, healthModelName string, options *EntitiesClientListByHealthModelOptions) *runtime.Pager[EntitiesClientListByHealthModelResponse] { + return runtime.NewPager(runtime.PagingHandler[EntitiesClientListByHealthModelResponse]{ + More: func(page EntitiesClientListByHealthModelResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *EntitiesClientListByHealthModelResponse) (EntitiesClientListByHealthModelResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "EntitiesClient.NewListByHealthModelPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByHealthModelCreateRequest(ctx, resourceGroupName, healthModelName, options) + }, nil) + if err != nil { + return EntitiesClientListByHealthModelResponse{}, err + } + return client.listByHealthModelHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByHealthModelCreateRequest creates the ListByHealthModel request. +func (client *EntitiesClient) listByHealthModelCreateRequest(ctx context.Context, resourceGroupName string, healthModelName string, options *EntitiesClientListByHealthModelOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/entities" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if healthModelName == "" { + return nil, errors.New("parameter healthModelName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{healthModelName}", url.PathEscape(healthModelName)) + 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-10-01-preview") + if options != nil && options.Timestamp != nil { + reqQP.Set("timestamp", options.Timestamp.Format(time.RFC3339Nano)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByHealthModelHandleResponse handles the ListByHealthModel response. +func (client *EntitiesClient) listByHealthModelHandleResponse(resp *http.Response) (EntitiesClientListByHealthModelResponse, error) { + result := EntitiesClientListByHealthModelResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.EntityListResult); err != nil { + return EntitiesClientListByHealthModelResponse{}, err + } + return result, nil +} diff --git a/sdk/resourcemanager/cloudhealth/armcloudhealth/fake/authenticationsettings_server.go b/sdk/resourcemanager/cloudhealth/armcloudhealth/fake/authenticationsettings_server.go new file mode 100644 index 000000000000..2cefe932647b --- /dev/null +++ b/sdk/resourcemanager/cloudhealth/armcloudhealth/fake/authenticationsettings_server.go @@ -0,0 +1,268 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/cloudhealth/armcloudhealth" + "net/http" + "net/url" + "regexp" +) + +// AuthenticationSettingsServer is a fake server for instances of the armcloudhealth.AuthenticationSettingsClient type. +type AuthenticationSettingsServer struct { + // CreateOrUpdate is the fake for method AuthenticationSettingsClient.CreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + CreateOrUpdate func(ctx context.Context, resourceGroupName string, healthModelName string, authenticationSettingName string, resource armcloudhealth.AuthenticationSetting, options *armcloudhealth.AuthenticationSettingsClientCreateOrUpdateOptions) (resp azfake.Responder[armcloudhealth.AuthenticationSettingsClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // Delete is the fake for method AuthenticationSettingsClient.Delete + // HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent + Delete func(ctx context.Context, resourceGroupName string, healthModelName string, authenticationSettingName string, options *armcloudhealth.AuthenticationSettingsClientDeleteOptions) (resp azfake.Responder[armcloudhealth.AuthenticationSettingsClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method AuthenticationSettingsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, healthModelName string, authenticationSettingName string, options *armcloudhealth.AuthenticationSettingsClientGetOptions) (resp azfake.Responder[armcloudhealth.AuthenticationSettingsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByHealthModelPager is the fake for method AuthenticationSettingsClient.NewListByHealthModelPager + // HTTP status codes to indicate success: http.StatusOK + NewListByHealthModelPager func(resourceGroupName string, healthModelName string, options *armcloudhealth.AuthenticationSettingsClientListByHealthModelOptions) (resp azfake.PagerResponder[armcloudhealth.AuthenticationSettingsClientListByHealthModelResponse]) +} + +// NewAuthenticationSettingsServerTransport creates a new instance of AuthenticationSettingsServerTransport with the provided implementation. +// The returned AuthenticationSettingsServerTransport instance is connected to an instance of armcloudhealth.AuthenticationSettingsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewAuthenticationSettingsServerTransport(srv *AuthenticationSettingsServer) *AuthenticationSettingsServerTransport { + return &AuthenticationSettingsServerTransport{ + srv: srv, + newListByHealthModelPager: newTracker[azfake.PagerResponder[armcloudhealth.AuthenticationSettingsClientListByHealthModelResponse]](), + } +} + +// AuthenticationSettingsServerTransport connects instances of armcloudhealth.AuthenticationSettingsClient to instances of AuthenticationSettingsServer. +// Don't use this type directly, use NewAuthenticationSettingsServerTransport instead. +type AuthenticationSettingsServerTransport struct { + srv *AuthenticationSettingsServer + newListByHealthModelPager *tracker[azfake.PagerResponder[armcloudhealth.AuthenticationSettingsClientListByHealthModelResponse]] +} + +// Do implements the policy.Transporter interface for AuthenticationSettingsServerTransport. +func (a *AuthenticationSettingsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return a.dispatchToMethodFake(req, method) +} + +func (a *AuthenticationSettingsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result) + defer close(resultChan) + + go func() { + var intercepted bool + var res result + if authenticationSettingsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = authenticationSettingsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "AuthenticationSettingsClient.CreateOrUpdate": + res.resp, res.err = a.dispatchCreateOrUpdate(req) + case "AuthenticationSettingsClient.Delete": + res.resp, res.err = a.dispatchDelete(req) + case "AuthenticationSettingsClient.Get": + res.resp, res.err = a.dispatchGet(req) + case "AuthenticationSettingsClient.NewListByHealthModelPager": + res.resp, res.err = a.dispatchNewListByHealthModelPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + select { + case resultChan <- res: + case <-req.Context().Done(): + } + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (a *AuthenticationSettingsServerTransport) dispatchCreateOrUpdate(req *http.Request) (*http.Response, error) { + if a.srv.CreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method CreateOrUpdate not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CloudHealth/healthmodels/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/authenticationsettings/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcloudhealth.AuthenticationSetting](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + healthModelNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("healthModelName")]) + if err != nil { + return nil, err + } + authenticationSettingNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("authenticationSettingName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.CreateOrUpdate(req.Context(), resourceGroupNameParam, healthModelNameParam, authenticationSettingNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK, http.StatusCreated}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).AuthenticationSetting, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *AuthenticationSettingsServerTransport) dispatchDelete(req *http.Request) (*http.Response, error) { + if a.srv.Delete == nil { + return nil, &nonRetriableError{errors.New("fake for method Delete not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CloudHealth/healthmodels/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/authenticationsettings/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + healthModelNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("healthModelName")]) + if err != nil { + return nil, err + } + authenticationSettingNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("authenticationSettingName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Delete(req.Context(), resourceGroupNameParam, healthModelNameParam, authenticationSettingNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK, http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *AuthenticationSettingsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if a.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CloudHealth/healthmodels/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/authenticationsettings/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + healthModelNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("healthModelName")]) + if err != nil { + return nil, err + } + authenticationSettingNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("authenticationSettingName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Get(req.Context(), resourceGroupNameParam, healthModelNameParam, authenticationSettingNameParam, 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).AuthenticationSetting, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *AuthenticationSettingsServerTransport) dispatchNewListByHealthModelPager(req *http.Request) (*http.Response, error) { + if a.srv.NewListByHealthModelPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByHealthModelPager not implemented")} + } + newListByHealthModelPager := a.newListByHealthModelPager.get(req) + if newListByHealthModelPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CloudHealth/healthmodels/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/authenticationsettings` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + healthModelNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("healthModelName")]) + if err != nil { + return nil, err + } + resp := a.srv.NewListByHealthModelPager(resourceGroupNameParam, healthModelNameParam, nil) + newListByHealthModelPager = &resp + a.newListByHealthModelPager.add(req, newListByHealthModelPager) + server.PagerResponderInjectNextLinks(newListByHealthModelPager, req, func(page *armcloudhealth.AuthenticationSettingsClientListByHealthModelResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByHealthModelPager, req) + if err != nil { + return nil, err + } + if !contains([]int{http.StatusOK}, resp.StatusCode) { + a.newListByHealthModelPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByHealthModelPager) { + a.newListByHealthModelPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to AuthenticationSettingsServerTransport +var authenticationSettingsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/sdk/resourcemanager/cloudhealth/armcloudhealth/fake/discoveryrules_server.go b/sdk/resourcemanager/cloudhealth/armcloudhealth/fake/discoveryrules_server.go new file mode 100644 index 000000000000..adce99328fd8 --- /dev/null +++ b/sdk/resourcemanager/cloudhealth/armcloudhealth/fake/discoveryrules_server.go @@ -0,0 +1,284 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/cloudhealth/armcloudhealth" + "net/http" + "net/url" + "regexp" + "time" +) + +// DiscoveryRulesServer is a fake server for instances of the armcloudhealth.DiscoveryRulesClient type. +type DiscoveryRulesServer struct { + // CreateOrUpdate is the fake for method DiscoveryRulesClient.CreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + CreateOrUpdate func(ctx context.Context, resourceGroupName string, healthModelName string, discoveryRuleName string, resource armcloudhealth.DiscoveryRule, options *armcloudhealth.DiscoveryRulesClientCreateOrUpdateOptions) (resp azfake.Responder[armcloudhealth.DiscoveryRulesClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // Delete is the fake for method DiscoveryRulesClient.Delete + // HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent + Delete func(ctx context.Context, resourceGroupName string, healthModelName string, discoveryRuleName string, options *armcloudhealth.DiscoveryRulesClientDeleteOptions) (resp azfake.Responder[armcloudhealth.DiscoveryRulesClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method DiscoveryRulesClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, healthModelName string, discoveryRuleName string, options *armcloudhealth.DiscoveryRulesClientGetOptions) (resp azfake.Responder[armcloudhealth.DiscoveryRulesClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByHealthModelPager is the fake for method DiscoveryRulesClient.NewListByHealthModelPager + // HTTP status codes to indicate success: http.StatusOK + NewListByHealthModelPager func(resourceGroupName string, healthModelName string, options *armcloudhealth.DiscoveryRulesClientListByHealthModelOptions) (resp azfake.PagerResponder[armcloudhealth.DiscoveryRulesClientListByHealthModelResponse]) +} + +// NewDiscoveryRulesServerTransport creates a new instance of DiscoveryRulesServerTransport with the provided implementation. +// The returned DiscoveryRulesServerTransport instance is connected to an instance of armcloudhealth.DiscoveryRulesClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewDiscoveryRulesServerTransport(srv *DiscoveryRulesServer) *DiscoveryRulesServerTransport { + return &DiscoveryRulesServerTransport{ + srv: srv, + newListByHealthModelPager: newTracker[azfake.PagerResponder[armcloudhealth.DiscoveryRulesClientListByHealthModelResponse]](), + } +} + +// DiscoveryRulesServerTransport connects instances of armcloudhealth.DiscoveryRulesClient to instances of DiscoveryRulesServer. +// Don't use this type directly, use NewDiscoveryRulesServerTransport instead. +type DiscoveryRulesServerTransport struct { + srv *DiscoveryRulesServer + newListByHealthModelPager *tracker[azfake.PagerResponder[armcloudhealth.DiscoveryRulesClientListByHealthModelResponse]] +} + +// Do implements the policy.Transporter interface for DiscoveryRulesServerTransport. +func (d *DiscoveryRulesServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return d.dispatchToMethodFake(req, method) +} + +func (d *DiscoveryRulesServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result) + defer close(resultChan) + + go func() { + var intercepted bool + var res result + if discoveryRulesServerTransportInterceptor != nil { + res.resp, res.err, intercepted = discoveryRulesServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "DiscoveryRulesClient.CreateOrUpdate": + res.resp, res.err = d.dispatchCreateOrUpdate(req) + case "DiscoveryRulesClient.Delete": + res.resp, res.err = d.dispatchDelete(req) + case "DiscoveryRulesClient.Get": + res.resp, res.err = d.dispatchGet(req) + case "DiscoveryRulesClient.NewListByHealthModelPager": + res.resp, res.err = d.dispatchNewListByHealthModelPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + select { + case resultChan <- res: + case <-req.Context().Done(): + } + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (d *DiscoveryRulesServerTransport) dispatchCreateOrUpdate(req *http.Request) (*http.Response, error) { + if d.srv.CreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method CreateOrUpdate not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CloudHealth/healthmodels/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/discoveryrules/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcloudhealth.DiscoveryRule](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + healthModelNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("healthModelName")]) + if err != nil { + return nil, err + } + discoveryRuleNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("discoveryRuleName")]) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.CreateOrUpdate(req.Context(), resourceGroupNameParam, healthModelNameParam, discoveryRuleNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK, http.StatusCreated}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).DiscoveryRule, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DiscoveryRulesServerTransport) dispatchDelete(req *http.Request) (*http.Response, error) { + if d.srv.Delete == nil { + return nil, &nonRetriableError{errors.New("fake for method Delete not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CloudHealth/healthmodels/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/discoveryrules/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + healthModelNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("healthModelName")]) + if err != nil { + return nil, err + } + discoveryRuleNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("discoveryRuleName")]) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Delete(req.Context(), resourceGroupNameParam, healthModelNameParam, discoveryRuleNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK, http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DiscoveryRulesServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if d.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CloudHealth/healthmodels/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/discoveryrules/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + healthModelNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("healthModelName")]) + if err != nil { + return nil, err + } + discoveryRuleNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("discoveryRuleName")]) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Get(req.Context(), resourceGroupNameParam, healthModelNameParam, discoveryRuleNameParam, 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).DiscoveryRule, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DiscoveryRulesServerTransport) dispatchNewListByHealthModelPager(req *http.Request) (*http.Response, error) { + if d.srv.NewListByHealthModelPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByHealthModelPager not implemented")} + } + newListByHealthModelPager := d.newListByHealthModelPager.get(req) + if newListByHealthModelPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CloudHealth/healthmodels/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/discoveryrules` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + qp := req.URL.Query() + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + timestampUnescaped, err := url.QueryUnescape(qp.Get("timestamp")) + if err != nil { + return nil, err + } + timestampParam, err := parseOptional(timestampUnescaped, func(v string) (time.Time, error) { return time.Parse(time.RFC3339Nano, v) }) + if err != nil { + return nil, err + } + healthModelNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("healthModelName")]) + if err != nil { + return nil, err + } + var options *armcloudhealth.DiscoveryRulesClientListByHealthModelOptions + if timestampParam != nil { + options = &armcloudhealth.DiscoveryRulesClientListByHealthModelOptions{ + Timestamp: timestampParam, + } + } + resp := d.srv.NewListByHealthModelPager(resourceGroupNameParam, healthModelNameParam, options) + newListByHealthModelPager = &resp + d.newListByHealthModelPager.add(req, newListByHealthModelPager) + server.PagerResponderInjectNextLinks(newListByHealthModelPager, req, func(page *armcloudhealth.DiscoveryRulesClientListByHealthModelResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByHealthModelPager, req) + if err != nil { + return nil, err + } + if !contains([]int{http.StatusOK}, resp.StatusCode) { + d.newListByHealthModelPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByHealthModelPager) { + d.newListByHealthModelPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to DiscoveryRulesServerTransport +var discoveryRulesServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/sdk/resourcemanager/cloudhealth/armcloudhealth/fake/entities_server.go b/sdk/resourcemanager/cloudhealth/armcloudhealth/fake/entities_server.go new file mode 100644 index 000000000000..ab34be27f1c5 --- /dev/null +++ b/sdk/resourcemanager/cloudhealth/armcloudhealth/fake/entities_server.go @@ -0,0 +1,284 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/cloudhealth/armcloudhealth" + "net/http" + "net/url" + "regexp" + "time" +) + +// EntitiesServer is a fake server for instances of the armcloudhealth.EntitiesClient type. +type EntitiesServer struct { + // CreateOrUpdate is the fake for method EntitiesClient.CreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + CreateOrUpdate func(ctx context.Context, resourceGroupName string, healthModelName string, entityName string, resource armcloudhealth.Entity, options *armcloudhealth.EntitiesClientCreateOrUpdateOptions) (resp azfake.Responder[armcloudhealth.EntitiesClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // Delete is the fake for method EntitiesClient.Delete + // HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent + Delete func(ctx context.Context, resourceGroupName string, healthModelName string, entityName string, options *armcloudhealth.EntitiesClientDeleteOptions) (resp azfake.Responder[armcloudhealth.EntitiesClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method EntitiesClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, healthModelName string, entityName string, options *armcloudhealth.EntitiesClientGetOptions) (resp azfake.Responder[armcloudhealth.EntitiesClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByHealthModelPager is the fake for method EntitiesClient.NewListByHealthModelPager + // HTTP status codes to indicate success: http.StatusOK + NewListByHealthModelPager func(resourceGroupName string, healthModelName string, options *armcloudhealth.EntitiesClientListByHealthModelOptions) (resp azfake.PagerResponder[armcloudhealth.EntitiesClientListByHealthModelResponse]) +} + +// NewEntitiesServerTransport creates a new instance of EntitiesServerTransport with the provided implementation. +// The returned EntitiesServerTransport instance is connected to an instance of armcloudhealth.EntitiesClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewEntitiesServerTransport(srv *EntitiesServer) *EntitiesServerTransport { + return &EntitiesServerTransport{ + srv: srv, + newListByHealthModelPager: newTracker[azfake.PagerResponder[armcloudhealth.EntitiesClientListByHealthModelResponse]](), + } +} + +// EntitiesServerTransport connects instances of armcloudhealth.EntitiesClient to instances of EntitiesServer. +// Don't use this type directly, use NewEntitiesServerTransport instead. +type EntitiesServerTransport struct { + srv *EntitiesServer + newListByHealthModelPager *tracker[azfake.PagerResponder[armcloudhealth.EntitiesClientListByHealthModelResponse]] +} + +// Do implements the policy.Transporter interface for EntitiesServerTransport. +func (e *EntitiesServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return e.dispatchToMethodFake(req, method) +} + +func (e *EntitiesServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result) + defer close(resultChan) + + go func() { + var intercepted bool + var res result + if entitiesServerTransportInterceptor != nil { + res.resp, res.err, intercepted = entitiesServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "EntitiesClient.CreateOrUpdate": + res.resp, res.err = e.dispatchCreateOrUpdate(req) + case "EntitiesClient.Delete": + res.resp, res.err = e.dispatchDelete(req) + case "EntitiesClient.Get": + res.resp, res.err = e.dispatchGet(req) + case "EntitiesClient.NewListByHealthModelPager": + res.resp, res.err = e.dispatchNewListByHealthModelPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + select { + case resultChan <- res: + case <-req.Context().Done(): + } + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (e *EntitiesServerTransport) dispatchCreateOrUpdate(req *http.Request) (*http.Response, error) { + if e.srv.CreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method CreateOrUpdate not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CloudHealth/healthmodels/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/entities/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcloudhealth.Entity](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + healthModelNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("healthModelName")]) + if err != nil { + return nil, err + } + entityNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("entityName")]) + if err != nil { + return nil, err + } + respr, errRespr := e.srv.CreateOrUpdate(req.Context(), resourceGroupNameParam, healthModelNameParam, entityNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK, http.StatusCreated}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Entity, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (e *EntitiesServerTransport) dispatchDelete(req *http.Request) (*http.Response, error) { + if e.srv.Delete == nil { + return nil, &nonRetriableError{errors.New("fake for method Delete not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CloudHealth/healthmodels/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/entities/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + healthModelNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("healthModelName")]) + if err != nil { + return nil, err + } + entityNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("entityName")]) + if err != nil { + return nil, err + } + respr, errRespr := e.srv.Delete(req.Context(), resourceGroupNameParam, healthModelNameParam, entityNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK, http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (e *EntitiesServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if e.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CloudHealth/healthmodels/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/entities/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + healthModelNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("healthModelName")]) + if err != nil { + return nil, err + } + entityNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("entityName")]) + if err != nil { + return nil, err + } + respr, errRespr := e.srv.Get(req.Context(), resourceGroupNameParam, healthModelNameParam, entityNameParam, 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).Entity, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (e *EntitiesServerTransport) dispatchNewListByHealthModelPager(req *http.Request) (*http.Response, error) { + if e.srv.NewListByHealthModelPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByHealthModelPager not implemented")} + } + newListByHealthModelPager := e.newListByHealthModelPager.get(req) + if newListByHealthModelPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CloudHealth/healthmodels/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/entities` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + qp := req.URL.Query() + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + timestampUnescaped, err := url.QueryUnescape(qp.Get("timestamp")) + if err != nil { + return nil, err + } + timestampParam, err := parseOptional(timestampUnescaped, func(v string) (time.Time, error) { return time.Parse(time.RFC3339Nano, v) }) + if err != nil { + return nil, err + } + healthModelNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("healthModelName")]) + if err != nil { + return nil, err + } + var options *armcloudhealth.EntitiesClientListByHealthModelOptions + if timestampParam != nil { + options = &armcloudhealth.EntitiesClientListByHealthModelOptions{ + Timestamp: timestampParam, + } + } + resp := e.srv.NewListByHealthModelPager(resourceGroupNameParam, healthModelNameParam, options) + newListByHealthModelPager = &resp + e.newListByHealthModelPager.add(req, newListByHealthModelPager) + server.PagerResponderInjectNextLinks(newListByHealthModelPager, req, func(page *armcloudhealth.EntitiesClientListByHealthModelResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByHealthModelPager, req) + if err != nil { + return nil, err + } + if !contains([]int{http.StatusOK}, resp.StatusCode) { + e.newListByHealthModelPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByHealthModelPager) { + e.newListByHealthModelPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to EntitiesServerTransport +var entitiesServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/sdk/resourcemanager/cloudhealth/armcloudhealth/fake/healthmodels_server.go b/sdk/resourcemanager/cloudhealth/armcloudhealth/fake/healthmodels_server.go new file mode 100644 index 000000000000..dde078187842 --- /dev/null +++ b/sdk/resourcemanager/cloudhealth/armcloudhealth/fake/healthmodels_server.go @@ -0,0 +1,375 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/cloudhealth/armcloudhealth" + "net/http" + "net/url" + "regexp" +) + +// HealthModelsServer is a fake server for instances of the armcloudhealth.HealthModelsClient type. +type HealthModelsServer struct { + // BeginCreate is the fake for method HealthModelsClient.BeginCreate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreate func(ctx context.Context, resourceGroupName string, healthModelName string, resource armcloudhealth.HealthModel, options *armcloudhealth.HealthModelsClientBeginCreateOptions) (resp azfake.PollerResponder[armcloudhealth.HealthModelsClientCreateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method HealthModelsClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, healthModelName string, options *armcloudhealth.HealthModelsClientBeginDeleteOptions) (resp azfake.PollerResponder[armcloudhealth.HealthModelsClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method HealthModelsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, healthModelName string, options *armcloudhealth.HealthModelsClientGetOptions) (resp azfake.Responder[armcloudhealth.HealthModelsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByResourceGroupPager is the fake for method HealthModelsClient.NewListByResourceGroupPager + // HTTP status codes to indicate success: http.StatusOK + NewListByResourceGroupPager func(resourceGroupName string, options *armcloudhealth.HealthModelsClientListByResourceGroupOptions) (resp azfake.PagerResponder[armcloudhealth.HealthModelsClientListByResourceGroupResponse]) + + // NewListBySubscriptionPager is the fake for method HealthModelsClient.NewListBySubscriptionPager + // HTTP status codes to indicate success: http.StatusOK + NewListBySubscriptionPager func(options *armcloudhealth.HealthModelsClientListBySubscriptionOptions) (resp azfake.PagerResponder[armcloudhealth.HealthModelsClientListBySubscriptionResponse]) + + // BeginUpdate is the fake for method HealthModelsClient.BeginUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginUpdate func(ctx context.Context, resourceGroupName string, healthModelName string, properties armcloudhealth.HealthModelUpdate, options *armcloudhealth.HealthModelsClientBeginUpdateOptions) (resp azfake.PollerResponder[armcloudhealth.HealthModelsClientUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewHealthModelsServerTransport creates a new instance of HealthModelsServerTransport with the provided implementation. +// The returned HealthModelsServerTransport instance is connected to an instance of armcloudhealth.HealthModelsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewHealthModelsServerTransport(srv *HealthModelsServer) *HealthModelsServerTransport { + return &HealthModelsServerTransport{ + srv: srv, + beginCreate: newTracker[azfake.PollerResponder[armcloudhealth.HealthModelsClientCreateResponse]](), + beginDelete: newTracker[azfake.PollerResponder[armcloudhealth.HealthModelsClientDeleteResponse]](), + newListByResourceGroupPager: newTracker[azfake.PagerResponder[armcloudhealth.HealthModelsClientListByResourceGroupResponse]](), + newListBySubscriptionPager: newTracker[azfake.PagerResponder[armcloudhealth.HealthModelsClientListBySubscriptionResponse]](), + beginUpdate: newTracker[azfake.PollerResponder[armcloudhealth.HealthModelsClientUpdateResponse]](), + } +} + +// HealthModelsServerTransport connects instances of armcloudhealth.HealthModelsClient to instances of HealthModelsServer. +// Don't use this type directly, use NewHealthModelsServerTransport instead. +type HealthModelsServerTransport struct { + srv *HealthModelsServer + beginCreate *tracker[azfake.PollerResponder[armcloudhealth.HealthModelsClientCreateResponse]] + beginDelete *tracker[azfake.PollerResponder[armcloudhealth.HealthModelsClientDeleteResponse]] + newListByResourceGroupPager *tracker[azfake.PagerResponder[armcloudhealth.HealthModelsClientListByResourceGroupResponse]] + newListBySubscriptionPager *tracker[azfake.PagerResponder[armcloudhealth.HealthModelsClientListBySubscriptionResponse]] + beginUpdate *tracker[azfake.PollerResponder[armcloudhealth.HealthModelsClientUpdateResponse]] +} + +// Do implements the policy.Transporter interface for HealthModelsServerTransport. +func (h *HealthModelsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return h.dispatchToMethodFake(req, method) +} + +func (h *HealthModelsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result) + defer close(resultChan) + + go func() { + var intercepted bool + var res result + if healthModelsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = healthModelsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "HealthModelsClient.BeginCreate": + res.resp, res.err = h.dispatchBeginCreate(req) + case "HealthModelsClient.BeginDelete": + res.resp, res.err = h.dispatchBeginDelete(req) + case "HealthModelsClient.Get": + res.resp, res.err = h.dispatchGet(req) + case "HealthModelsClient.NewListByResourceGroupPager": + res.resp, res.err = h.dispatchNewListByResourceGroupPager(req) + case "HealthModelsClient.NewListBySubscriptionPager": + res.resp, res.err = h.dispatchNewListBySubscriptionPager(req) + case "HealthModelsClient.BeginUpdate": + res.resp, res.err = h.dispatchBeginUpdate(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + select { + case resultChan <- res: + case <-req.Context().Done(): + } + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (h *HealthModelsServerTransport) dispatchBeginCreate(req *http.Request) (*http.Response, error) { + if h.srv.BeginCreate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreate not implemented")} + } + beginCreate := h.beginCreate.get(req) + if beginCreate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CloudHealth/healthmodels/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcloudhealth.HealthModel](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + healthModelNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("healthModelName")]) + if err != nil { + return nil, err + } + respr, errRespr := h.srv.BeginCreate(req.Context(), resourceGroupNameParam, healthModelNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreate = &respr + h.beginCreate.add(req, beginCreate) + } + + resp, err := server.PollerResponderNext(beginCreate, req) + if err != nil { + return nil, err + } + + if !contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + h.beginCreate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreate) { + h.beginCreate.remove(req) + } + + return resp, nil +} + +func (h *HealthModelsServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if h.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := h.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CloudHealth/healthmodels/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + healthModelNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("healthModelName")]) + if err != nil { + return nil, err + } + respr, errRespr := h.srv.BeginDelete(req.Context(), resourceGroupNameParam, healthModelNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + h.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + h.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + h.beginDelete.remove(req) + } + + return resp, nil +} + +func (h *HealthModelsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if h.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CloudHealth/healthmodels/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + healthModelNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("healthModelName")]) + if err != nil { + return nil, err + } + respr, errRespr := h.srv.Get(req.Context(), resourceGroupNameParam, healthModelNameParam, 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).HealthModel, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (h *HealthModelsServerTransport) dispatchNewListByResourceGroupPager(req *http.Request) (*http.Response, error) { + if h.srv.NewListByResourceGroupPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByResourceGroupPager not implemented")} + } + newListByResourceGroupPager := h.newListByResourceGroupPager.get(req) + if newListByResourceGroupPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CloudHealth/healthmodels` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + resp := h.srv.NewListByResourceGroupPager(resourceGroupNameParam, nil) + newListByResourceGroupPager = &resp + h.newListByResourceGroupPager.add(req, newListByResourceGroupPager) + server.PagerResponderInjectNextLinks(newListByResourceGroupPager, req, func(page *armcloudhealth.HealthModelsClientListByResourceGroupResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByResourceGroupPager, req) + if err != nil { + return nil, err + } + if !contains([]int{http.StatusOK}, resp.StatusCode) { + h.newListByResourceGroupPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByResourceGroupPager) { + h.newListByResourceGroupPager.remove(req) + } + return resp, nil +} + +func (h *HealthModelsServerTransport) dispatchNewListBySubscriptionPager(req *http.Request) (*http.Response, error) { + if h.srv.NewListBySubscriptionPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListBySubscriptionPager not implemented")} + } + newListBySubscriptionPager := h.newListBySubscriptionPager.get(req) + if newListBySubscriptionPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CloudHealth/healthmodels` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 1 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resp := h.srv.NewListBySubscriptionPager(nil) + newListBySubscriptionPager = &resp + h.newListBySubscriptionPager.add(req, newListBySubscriptionPager) + server.PagerResponderInjectNextLinks(newListBySubscriptionPager, req, func(page *armcloudhealth.HealthModelsClientListBySubscriptionResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListBySubscriptionPager, req) + if err != nil { + return nil, err + } + if !contains([]int{http.StatusOK}, resp.StatusCode) { + h.newListBySubscriptionPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListBySubscriptionPager) { + h.newListBySubscriptionPager.remove(req) + } + return resp, nil +} + +func (h *HealthModelsServerTransport) dispatchBeginUpdate(req *http.Request) (*http.Response, error) { + if h.srv.BeginUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginUpdate not implemented")} + } + beginUpdate := h.beginUpdate.get(req) + if beginUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CloudHealth/healthmodels/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcloudhealth.HealthModelUpdate](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + healthModelNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("healthModelName")]) + if err != nil { + return nil, err + } + respr, errRespr := h.srv.BeginUpdate(req.Context(), resourceGroupNameParam, healthModelNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginUpdate = &respr + h.beginUpdate.add(req, beginUpdate) + } + + resp, err := server.PollerResponderNext(beginUpdate, req) + if err != nil { + return nil, err + } + + if !contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + h.beginUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginUpdate) { + h.beginUpdate.remove(req) + } + + return resp, nil +} + +// set this to conditionally intercept incoming requests to HealthModelsServerTransport +var healthModelsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/sdk/resourcemanager/cloudhealth/armcloudhealth/fake/internal.go b/sdk/resourcemanager/cloudhealth/armcloudhealth/fake/internal.go new file mode 100644 index 000000000000..0e32a8018fe4 --- /dev/null +++ b/sdk/resourcemanager/cloudhealth/armcloudhealth/fake/internal.go @@ -0,0 +1,77 @@ +// 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 ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func contains[T comparable](s []T, v T) bool { + for _, vv := range s { + if vv == v { + return true + } + } + return false +} + +func parseOptional[T any](v string, parse func(v string) (T, error)) (*T, error) { + if v == "" { + return nil, nil + } + t, err := parse(v) + if err != nil { + return nil, err + } + return &t, err +} + +func newTracker[T any]() *tracker[T] { + return &tracker[T]{ + items: map[string]*T{}, + } +} + +type tracker[T any] struct { + items map[string]*T + mu sync.Mutex +} + +func (p *tracker[T]) get(req *http.Request) *T { + p.mu.Lock() + defer p.mu.Unlock() + if item, ok := p.items[server.SanitizePagerPollerPath(req.URL.Path)]; ok { + return item + } + return nil +} + +func (p *tracker[T]) add(req *http.Request, item *T) { + p.mu.Lock() + defer p.mu.Unlock() + p.items[server.SanitizePagerPollerPath(req.URL.Path)] = item +} + +func (p *tracker[T]) remove(req *http.Request) { + p.mu.Lock() + defer p.mu.Unlock() + delete(p.items, server.SanitizePagerPollerPath(req.URL.Path)) +} diff --git a/sdk/resourcemanager/cloudhealth/armcloudhealth/fake/operations_server.go b/sdk/resourcemanager/cloudhealth/armcloudhealth/fake/operations_server.go new file mode 100644 index 000000000000..b88bf16a3b29 --- /dev/null +++ b/sdk/resourcemanager/cloudhealth/armcloudhealth/fake/operations_server.go @@ -0,0 +1,118 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package fake + +import ( + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/cloudhealth/armcloudhealth" + "net/http" +) + +// OperationsServer is a fake server for instances of the armcloudhealth.OperationsClient type. +type OperationsServer struct { + // NewListPager is the fake for method OperationsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(options *armcloudhealth.OperationsClientListOptions) (resp azfake.PagerResponder[armcloudhealth.OperationsClientListResponse]) +} + +// NewOperationsServerTransport creates a new instance of OperationsServerTransport with the provided implementation. +// The returned OperationsServerTransport instance is connected to an instance of armcloudhealth.OperationsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewOperationsServerTransport(srv *OperationsServer) *OperationsServerTransport { + return &OperationsServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[armcloudhealth.OperationsClientListResponse]](), + } +} + +// OperationsServerTransport connects instances of armcloudhealth.OperationsClient to instances of OperationsServer. +// Don't use this type directly, use NewOperationsServerTransport instead. +type OperationsServerTransport struct { + srv *OperationsServer + newListPager *tracker[azfake.PagerResponder[armcloudhealth.OperationsClientListResponse]] +} + +// Do implements the policy.Transporter interface for OperationsServerTransport. +func (o *OperationsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return o.dispatchToMethodFake(req, method) +} + +func (o *OperationsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result) + defer close(resultChan) + + go func() { + var intercepted bool + var res result + if operationsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = operationsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "OperationsClient.NewListPager": + res.resp, res.err = o.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + select { + case resultChan <- res: + case <-req.Context().Done(): + } + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (o *OperationsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if o.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := o.newListPager.get(req) + if newListPager == nil { + resp := o.srv.NewListPager(nil) + newListPager = &resp + o.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armcloudhealth.OperationsClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !contains([]int{http.StatusOK}, resp.StatusCode) { + o.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + o.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to OperationsServerTransport +var operationsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/sdk/resourcemanager/cloudhealth/armcloudhealth/fake/relationships_server.go b/sdk/resourcemanager/cloudhealth/armcloudhealth/fake/relationships_server.go new file mode 100644 index 000000000000..369c5a988e4c --- /dev/null +++ b/sdk/resourcemanager/cloudhealth/armcloudhealth/fake/relationships_server.go @@ -0,0 +1,284 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/cloudhealth/armcloudhealth" + "net/http" + "net/url" + "regexp" + "time" +) + +// RelationshipsServer is a fake server for instances of the armcloudhealth.RelationshipsClient type. +type RelationshipsServer struct { + // CreateOrUpdate is the fake for method RelationshipsClient.CreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + CreateOrUpdate func(ctx context.Context, resourceGroupName string, healthModelName string, relationshipName string, resource armcloudhealth.Relationship, options *armcloudhealth.RelationshipsClientCreateOrUpdateOptions) (resp azfake.Responder[armcloudhealth.RelationshipsClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // Delete is the fake for method RelationshipsClient.Delete + // HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent + Delete func(ctx context.Context, resourceGroupName string, healthModelName string, relationshipName string, options *armcloudhealth.RelationshipsClientDeleteOptions) (resp azfake.Responder[armcloudhealth.RelationshipsClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method RelationshipsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, healthModelName string, relationshipName string, options *armcloudhealth.RelationshipsClientGetOptions) (resp azfake.Responder[armcloudhealth.RelationshipsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByHealthModelPager is the fake for method RelationshipsClient.NewListByHealthModelPager + // HTTP status codes to indicate success: http.StatusOK + NewListByHealthModelPager func(resourceGroupName string, healthModelName string, options *armcloudhealth.RelationshipsClientListByHealthModelOptions) (resp azfake.PagerResponder[armcloudhealth.RelationshipsClientListByHealthModelResponse]) +} + +// NewRelationshipsServerTransport creates a new instance of RelationshipsServerTransport with the provided implementation. +// The returned RelationshipsServerTransport instance is connected to an instance of armcloudhealth.RelationshipsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewRelationshipsServerTransport(srv *RelationshipsServer) *RelationshipsServerTransport { + return &RelationshipsServerTransport{ + srv: srv, + newListByHealthModelPager: newTracker[azfake.PagerResponder[armcloudhealth.RelationshipsClientListByHealthModelResponse]](), + } +} + +// RelationshipsServerTransport connects instances of armcloudhealth.RelationshipsClient to instances of RelationshipsServer. +// Don't use this type directly, use NewRelationshipsServerTransport instead. +type RelationshipsServerTransport struct { + srv *RelationshipsServer + newListByHealthModelPager *tracker[azfake.PagerResponder[armcloudhealth.RelationshipsClientListByHealthModelResponse]] +} + +// Do implements the policy.Transporter interface for RelationshipsServerTransport. +func (r *RelationshipsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return r.dispatchToMethodFake(req, method) +} + +func (r *RelationshipsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result) + defer close(resultChan) + + go func() { + var intercepted bool + var res result + if relationshipsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = relationshipsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "RelationshipsClient.CreateOrUpdate": + res.resp, res.err = r.dispatchCreateOrUpdate(req) + case "RelationshipsClient.Delete": + res.resp, res.err = r.dispatchDelete(req) + case "RelationshipsClient.Get": + res.resp, res.err = r.dispatchGet(req) + case "RelationshipsClient.NewListByHealthModelPager": + res.resp, res.err = r.dispatchNewListByHealthModelPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + select { + case resultChan <- res: + case <-req.Context().Done(): + } + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (r *RelationshipsServerTransport) dispatchCreateOrUpdate(req *http.Request) (*http.Response, error) { + if r.srv.CreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method CreateOrUpdate not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CloudHealth/healthmodels/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/relationships/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcloudhealth.Relationship](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + healthModelNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("healthModelName")]) + if err != nil { + return nil, err + } + relationshipNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("relationshipName")]) + if err != nil { + return nil, err + } + respr, errRespr := r.srv.CreateOrUpdate(req.Context(), resourceGroupNameParam, healthModelNameParam, relationshipNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK, http.StatusCreated}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Relationship, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (r *RelationshipsServerTransport) dispatchDelete(req *http.Request) (*http.Response, error) { + if r.srv.Delete == nil { + return nil, &nonRetriableError{errors.New("fake for method Delete not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CloudHealth/healthmodels/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/relationships/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + healthModelNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("healthModelName")]) + if err != nil { + return nil, err + } + relationshipNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("relationshipName")]) + if err != nil { + return nil, err + } + respr, errRespr := r.srv.Delete(req.Context(), resourceGroupNameParam, healthModelNameParam, relationshipNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK, http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (r *RelationshipsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if r.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CloudHealth/healthmodels/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/relationships/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + healthModelNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("healthModelName")]) + if err != nil { + return nil, err + } + relationshipNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("relationshipName")]) + if err != nil { + return nil, err + } + respr, errRespr := r.srv.Get(req.Context(), resourceGroupNameParam, healthModelNameParam, relationshipNameParam, 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).Relationship, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (r *RelationshipsServerTransport) dispatchNewListByHealthModelPager(req *http.Request) (*http.Response, error) { + if r.srv.NewListByHealthModelPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByHealthModelPager not implemented")} + } + newListByHealthModelPager := r.newListByHealthModelPager.get(req) + if newListByHealthModelPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CloudHealth/healthmodels/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/relationships` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + qp := req.URL.Query() + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + timestampUnescaped, err := url.QueryUnescape(qp.Get("timestamp")) + if err != nil { + return nil, err + } + timestampParam, err := parseOptional(timestampUnescaped, func(v string) (time.Time, error) { return time.Parse(time.RFC3339Nano, v) }) + if err != nil { + return nil, err + } + healthModelNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("healthModelName")]) + if err != nil { + return nil, err + } + var options *armcloudhealth.RelationshipsClientListByHealthModelOptions + if timestampParam != nil { + options = &armcloudhealth.RelationshipsClientListByHealthModelOptions{ + Timestamp: timestampParam, + } + } + resp := r.srv.NewListByHealthModelPager(resourceGroupNameParam, healthModelNameParam, options) + newListByHealthModelPager = &resp + r.newListByHealthModelPager.add(req, newListByHealthModelPager) + server.PagerResponderInjectNextLinks(newListByHealthModelPager, req, func(page *armcloudhealth.RelationshipsClientListByHealthModelResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByHealthModelPager, req) + if err != nil { + return nil, err + } + if !contains([]int{http.StatusOK}, resp.StatusCode) { + r.newListByHealthModelPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByHealthModelPager) { + r.newListByHealthModelPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to RelationshipsServerTransport +var relationshipsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/sdk/resourcemanager/cloudhealth/armcloudhealth/fake/server_factory.go b/sdk/resourcemanager/cloudhealth/armcloudhealth/fake/server_factory.go new file mode 100644 index 000000000000..3730f98911be --- /dev/null +++ b/sdk/resourcemanager/cloudhealth/armcloudhealth/fake/server_factory.go @@ -0,0 +1,123 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// ServerFactory is a fake server for instances of the armcloudhealth.ClientFactory type. +type ServerFactory struct { + // AuthenticationSettingsServer contains the fakes for client AuthenticationSettingsClient + AuthenticationSettingsServer AuthenticationSettingsServer + + // DiscoveryRulesServer contains the fakes for client DiscoveryRulesClient + DiscoveryRulesServer DiscoveryRulesServer + + // EntitiesServer contains the fakes for client EntitiesClient + EntitiesServer EntitiesServer + + // HealthModelsServer contains the fakes for client HealthModelsClient + HealthModelsServer HealthModelsServer + + // OperationsServer contains the fakes for client OperationsClient + OperationsServer OperationsServer + + // RelationshipsServer contains the fakes for client RelationshipsClient + RelationshipsServer RelationshipsServer + + // SignalDefinitionsServer contains the fakes for client SignalDefinitionsClient + SignalDefinitionsServer SignalDefinitionsServer +} + +// NewServerFactoryTransport creates a new instance of ServerFactoryTransport with the provided implementation. +// The returned ServerFactoryTransport instance is connected to an instance of armcloudhealth.ClientFactory via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewServerFactoryTransport(srv *ServerFactory) *ServerFactoryTransport { + return &ServerFactoryTransport{ + srv: srv, + } +} + +// ServerFactoryTransport connects instances of armcloudhealth.ClientFactory to instances of ServerFactory. +// Don't use this type directly, use NewServerFactoryTransport instead. +type ServerFactoryTransport struct { + srv *ServerFactory + trMu sync.Mutex + trAuthenticationSettingsServer *AuthenticationSettingsServerTransport + trDiscoveryRulesServer *DiscoveryRulesServerTransport + trEntitiesServer *EntitiesServerTransport + trHealthModelsServer *HealthModelsServerTransport + trOperationsServer *OperationsServerTransport + trRelationshipsServer *RelationshipsServerTransport + trSignalDefinitionsServer *SignalDefinitionsServerTransport +} + +// Do implements the policy.Transporter interface for ServerFactoryTransport. +func (s *ServerFactoryTransport) 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")} + } + + client := method[:strings.Index(method, ".")] + var resp *http.Response + var err error + + switch client { + case "AuthenticationSettingsClient": + initServer(s, &s.trAuthenticationSettingsServer, func() *AuthenticationSettingsServerTransport { + return NewAuthenticationSettingsServerTransport(&s.srv.AuthenticationSettingsServer) + }) + resp, err = s.trAuthenticationSettingsServer.Do(req) + case "DiscoveryRulesClient": + initServer(s, &s.trDiscoveryRulesServer, func() *DiscoveryRulesServerTransport { + return NewDiscoveryRulesServerTransport(&s.srv.DiscoveryRulesServer) + }) + resp, err = s.trDiscoveryRulesServer.Do(req) + case "EntitiesClient": + initServer(s, &s.trEntitiesServer, func() *EntitiesServerTransport { return NewEntitiesServerTransport(&s.srv.EntitiesServer) }) + resp, err = s.trEntitiesServer.Do(req) + case "HealthModelsClient": + initServer(s, &s.trHealthModelsServer, func() *HealthModelsServerTransport { return NewHealthModelsServerTransport(&s.srv.HealthModelsServer) }) + resp, err = s.trHealthModelsServer.Do(req) + case "OperationsClient": + initServer(s, &s.trOperationsServer, func() *OperationsServerTransport { return NewOperationsServerTransport(&s.srv.OperationsServer) }) + resp, err = s.trOperationsServer.Do(req) + case "RelationshipsClient": + initServer(s, &s.trRelationshipsServer, func() *RelationshipsServerTransport { + return NewRelationshipsServerTransport(&s.srv.RelationshipsServer) + }) + resp, err = s.trRelationshipsServer.Do(req) + case "SignalDefinitionsClient": + initServer(s, &s.trSignalDefinitionsServer, func() *SignalDefinitionsServerTransport { + return NewSignalDefinitionsServerTransport(&s.srv.SignalDefinitionsServer) + }) + resp, err = s.trSignalDefinitionsServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + if err != nil { + return nil, err + } + + return resp, nil +} + +func initServer[T any](s *ServerFactoryTransport, dst **T, src func() *T) { + s.trMu.Lock() + if *dst == nil { + *dst = src() + } + s.trMu.Unlock() +} diff --git a/sdk/resourcemanager/cloudhealth/armcloudhealth/fake/signaldefinitions_server.go b/sdk/resourcemanager/cloudhealth/armcloudhealth/fake/signaldefinitions_server.go new file mode 100644 index 000000000000..88999c1ebf64 --- /dev/null +++ b/sdk/resourcemanager/cloudhealth/armcloudhealth/fake/signaldefinitions_server.go @@ -0,0 +1,284 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/cloudhealth/armcloudhealth" + "net/http" + "net/url" + "regexp" + "time" +) + +// SignalDefinitionsServer is a fake server for instances of the armcloudhealth.SignalDefinitionsClient type. +type SignalDefinitionsServer struct { + // CreateOrUpdate is the fake for method SignalDefinitionsClient.CreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + CreateOrUpdate func(ctx context.Context, resourceGroupName string, healthModelName string, signalDefinitionName string, resource armcloudhealth.SignalDefinition, options *armcloudhealth.SignalDefinitionsClientCreateOrUpdateOptions) (resp azfake.Responder[armcloudhealth.SignalDefinitionsClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // Delete is the fake for method SignalDefinitionsClient.Delete + // HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent + Delete func(ctx context.Context, resourceGroupName string, healthModelName string, signalDefinitionName string, options *armcloudhealth.SignalDefinitionsClientDeleteOptions) (resp azfake.Responder[armcloudhealth.SignalDefinitionsClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method SignalDefinitionsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, healthModelName string, signalDefinitionName string, options *armcloudhealth.SignalDefinitionsClientGetOptions) (resp azfake.Responder[armcloudhealth.SignalDefinitionsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByHealthModelPager is the fake for method SignalDefinitionsClient.NewListByHealthModelPager + // HTTP status codes to indicate success: http.StatusOK + NewListByHealthModelPager func(resourceGroupName string, healthModelName string, options *armcloudhealth.SignalDefinitionsClientListByHealthModelOptions) (resp azfake.PagerResponder[armcloudhealth.SignalDefinitionsClientListByHealthModelResponse]) +} + +// NewSignalDefinitionsServerTransport creates a new instance of SignalDefinitionsServerTransport with the provided implementation. +// The returned SignalDefinitionsServerTransport instance is connected to an instance of armcloudhealth.SignalDefinitionsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewSignalDefinitionsServerTransport(srv *SignalDefinitionsServer) *SignalDefinitionsServerTransport { + return &SignalDefinitionsServerTransport{ + srv: srv, + newListByHealthModelPager: newTracker[azfake.PagerResponder[armcloudhealth.SignalDefinitionsClientListByHealthModelResponse]](), + } +} + +// SignalDefinitionsServerTransport connects instances of armcloudhealth.SignalDefinitionsClient to instances of SignalDefinitionsServer. +// Don't use this type directly, use NewSignalDefinitionsServerTransport instead. +type SignalDefinitionsServerTransport struct { + srv *SignalDefinitionsServer + newListByHealthModelPager *tracker[azfake.PagerResponder[armcloudhealth.SignalDefinitionsClientListByHealthModelResponse]] +} + +// Do implements the policy.Transporter interface for SignalDefinitionsServerTransport. +func (s *SignalDefinitionsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *SignalDefinitionsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result) + defer close(resultChan) + + go func() { + var intercepted bool + var res result + if signalDefinitionsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = signalDefinitionsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "SignalDefinitionsClient.CreateOrUpdate": + res.resp, res.err = s.dispatchCreateOrUpdate(req) + case "SignalDefinitionsClient.Delete": + res.resp, res.err = s.dispatchDelete(req) + case "SignalDefinitionsClient.Get": + res.resp, res.err = s.dispatchGet(req) + case "SignalDefinitionsClient.NewListByHealthModelPager": + res.resp, res.err = s.dispatchNewListByHealthModelPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + select { + case resultChan <- res: + case <-req.Context().Done(): + } + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *SignalDefinitionsServerTransport) dispatchCreateOrUpdate(req *http.Request) (*http.Response, error) { + if s.srv.CreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method CreateOrUpdate not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CloudHealth/healthmodels/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/signaldefinitions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcloudhealth.SignalDefinition](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + healthModelNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("healthModelName")]) + if err != nil { + return nil, err + } + signalDefinitionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("signalDefinitionName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.CreateOrUpdate(req.Context(), resourceGroupNameParam, healthModelNameParam, signalDefinitionNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK, http.StatusCreated}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).SignalDefinition, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SignalDefinitionsServerTransport) dispatchDelete(req *http.Request) (*http.Response, error) { + if s.srv.Delete == nil { + return nil, &nonRetriableError{errors.New("fake for method Delete not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CloudHealth/healthmodels/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/signaldefinitions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + healthModelNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("healthModelName")]) + if err != nil { + return nil, err + } + signalDefinitionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("signalDefinitionName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Delete(req.Context(), resourceGroupNameParam, healthModelNameParam, signalDefinitionNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK, http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SignalDefinitionsServerTransport) 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~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CloudHealth/healthmodels/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/signaldefinitions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + healthModelNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("healthModelName")]) + if err != nil { + return nil, err + } + signalDefinitionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("signalDefinitionName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Get(req.Context(), resourceGroupNameParam, healthModelNameParam, signalDefinitionNameParam, 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).SignalDefinition, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SignalDefinitionsServerTransport) dispatchNewListByHealthModelPager(req *http.Request) (*http.Response, error) { + if s.srv.NewListByHealthModelPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByHealthModelPager not implemented")} + } + newListByHealthModelPager := s.newListByHealthModelPager.get(req) + if newListByHealthModelPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CloudHealth/healthmodels/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/signaldefinitions` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + qp := req.URL.Query() + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + timestampUnescaped, err := url.QueryUnescape(qp.Get("timestamp")) + if err != nil { + return nil, err + } + timestampParam, err := parseOptional(timestampUnescaped, func(v string) (time.Time, error) { return time.Parse(time.RFC3339Nano, v) }) + if err != nil { + return nil, err + } + healthModelNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("healthModelName")]) + if err != nil { + return nil, err + } + var options *armcloudhealth.SignalDefinitionsClientListByHealthModelOptions + if timestampParam != nil { + options = &armcloudhealth.SignalDefinitionsClientListByHealthModelOptions{ + Timestamp: timestampParam, + } + } + resp := s.srv.NewListByHealthModelPager(resourceGroupNameParam, healthModelNameParam, options) + newListByHealthModelPager = &resp + s.newListByHealthModelPager.add(req, newListByHealthModelPager) + server.PagerResponderInjectNextLinks(newListByHealthModelPager, req, func(page *armcloudhealth.SignalDefinitionsClientListByHealthModelResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByHealthModelPager, req) + if err != nil { + return nil, err + } + if !contains([]int{http.StatusOK}, resp.StatusCode) { + s.newListByHealthModelPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByHealthModelPager) { + s.newListByHealthModelPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to SignalDefinitionsServerTransport +var signalDefinitionsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/sdk/resourcemanager/cloudhealth/armcloudhealth/go.mod b/sdk/resourcemanager/cloudhealth/armcloudhealth/go.mod new file mode 100644 index 000000000000..16583d83948c --- /dev/null +++ b/sdk/resourcemanager/cloudhealth/armcloudhealth/go.mod @@ -0,0 +1,13 @@ +module github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/cloudhealth/armcloudhealth + +go 1.23.0 + +toolchain go1.23.8 + +require github.com/Azure/azure-sdk-for-go/sdk/azcore v1.17.1 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.10.0 // indirect + golang.org/x/net v0.37.0 // indirect + golang.org/x/text v0.23.0 // indirect +) diff --git a/sdk/resourcemanager/cloudhealth/armcloudhealth/go.sum b/sdk/resourcemanager/cloudhealth/armcloudhealth/go.sum new file mode 100644 index 000000000000..cfff861c9769 --- /dev/null +++ b/sdk/resourcemanager/cloudhealth/armcloudhealth/go.sum @@ -0,0 +1,16 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.17.1 h1:DSDNVxqkoXJiko6x8a90zidoYqnYYa6c1MTzDKzKkTo= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.17.1/go.mod h1:zGqV2R4Cr/k8Uye5w+dgQ06WJtEcbQG/8J7BB6hnCr4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.10.0 h1:ywEEhmNahHBihViHepv3xPBn1663uRv2t2q/ESv9seY= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.10.0/go.mod h1:iZDifYGJTIgIIkYRNWPENUnqx6bJ2xnSDFI2tjwZNuY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= +github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +golang.org/x/net v0.37.0 h1:1zLorHbz+LYj7MQlSf1+2tPIIgibq2eL5xkrGk6f+2c= +golang.org/x/net v0.37.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8= +golang.org/x/text v0.23.0 h1:D71I7dUrlY+VX0gQShAThNGHFxZ13dGLBHQLVl1mJlY= +golang.org/x/text v0.23.0/go.mod h1:/BLNzu4aZCJ1+kcD0DNRotWKage4q2rGVAg4o22unh4= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/sdk/resourcemanager/cloudhealth/armcloudhealth/healthmodels_client.go b/sdk/resourcemanager/cloudhealth/armcloudhealth/healthmodels_client.go new file mode 100644 index 000000000000..3fa5098a4797 --- /dev/null +++ b/sdk/resourcemanager/cloudhealth/armcloudhealth/healthmodels_client.go @@ -0,0 +1,459 @@ +// 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 armcloudhealth + +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" +) + +// HealthModelsClient contains the methods for the HealthModels group. +// Don't use this type directly, use NewHealthModelsClient() instead. +type HealthModelsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewHealthModelsClient creates a new instance of HealthModelsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewHealthModelsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*HealthModelsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &HealthModelsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreate - Create a HealthModel +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-10-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - healthModelName - Name of health model resource +// - resource - Resource create parameters. +// - options - HealthModelsClientBeginCreateOptions contains the optional parameters for the HealthModelsClient.BeginCreate +// method. +func (client *HealthModelsClient) BeginCreate(ctx context.Context, resourceGroupName string, healthModelName string, resource HealthModel, options *HealthModelsClientBeginCreateOptions) (*runtime.Poller[HealthModelsClientCreateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.create(ctx, resourceGroupName, healthModelName, resource, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[HealthModelsClientCreateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[HealthModelsClientCreateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Create - Create a HealthModel +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-10-01-preview +func (client *HealthModelsClient) create(ctx context.Context, resourceGroupName string, healthModelName string, resource HealthModel, options *HealthModelsClientBeginCreateOptions) (*http.Response, error) { + var err error + const operationName = "HealthModelsClient.BeginCreate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createCreateRequest(ctx, resourceGroupName, healthModelName, resource, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createCreateRequest creates the Create request. +func (client *HealthModelsClient) createCreateRequest(ctx context.Context, resourceGroupName string, healthModelName string, resource HealthModel, _ *HealthModelsClientBeginCreateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if healthModelName == "" { + return nil, errors.New("parameter healthModelName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{healthModelName}", url.PathEscape(healthModelName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-10-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Delete a HealthModel +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-10-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - healthModelName - Name of health model resource +// - options - HealthModelsClientBeginDeleteOptions contains the optional parameters for the HealthModelsClient.BeginDelete +// method. +func (client *HealthModelsClient) BeginDelete(ctx context.Context, resourceGroupName string, healthModelName string, options *HealthModelsClientBeginDeleteOptions) (*runtime.Poller[HealthModelsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, healthModelName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[HealthModelsClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[HealthModelsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Delete a HealthModel +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-10-01-preview +func (client *HealthModelsClient) deleteOperation(ctx context.Context, resourceGroupName string, healthModelName string, options *HealthModelsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "HealthModelsClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, healthModelName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *HealthModelsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, healthModelName string, _ *HealthModelsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if healthModelName == "" { + return nil, errors.New("parameter healthModelName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{healthModelName}", url.PathEscape(healthModelName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-10-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Get a HealthModel +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-10-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - healthModelName - Name of health model resource +// - options - HealthModelsClientGetOptions contains the optional parameters for the HealthModelsClient.Get method. +func (client *HealthModelsClient) Get(ctx context.Context, resourceGroupName string, healthModelName string, options *HealthModelsClientGetOptions) (HealthModelsClientGetResponse, error) { + var err error + const operationName = "HealthModelsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, healthModelName, options) + if err != nil { + return HealthModelsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return HealthModelsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return HealthModelsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *HealthModelsClient) getCreateRequest(ctx context.Context, resourceGroupName string, healthModelName string, _ *HealthModelsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if healthModelName == "" { + return nil, errors.New("parameter healthModelName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{healthModelName}", url.PathEscape(healthModelName)) + 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-10-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *HealthModelsClient) getHandleResponse(resp *http.Response) (HealthModelsClientGetResponse, error) { + result := HealthModelsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.HealthModel); err != nil { + return HealthModelsClientGetResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - List HealthModel resources by resource group +// +// Generated from API version 2023-10-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - options - HealthModelsClientListByResourceGroupOptions contains the optional parameters for the HealthModelsClient.NewListByResourceGroupPager +// method. +func (client *HealthModelsClient) NewListByResourceGroupPager(resourceGroupName string, options *HealthModelsClientListByResourceGroupOptions) *runtime.Pager[HealthModelsClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[HealthModelsClientListByResourceGroupResponse]{ + More: func(page HealthModelsClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *HealthModelsClientListByResourceGroupResponse) (HealthModelsClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "HealthModelsClient.NewListByResourceGroupPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options) + }, nil) + if err != nil { + return HealthModelsClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *HealthModelsClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, _ *HealthModelsClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-10-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *HealthModelsClient) listByResourceGroupHandleResponse(resp *http.Response) (HealthModelsClientListByResourceGroupResponse, error) { + result := HealthModelsClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.HealthModelListResult); err != nil { + return HealthModelsClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// NewListBySubscriptionPager - List HealthModel resources by subscription ID +// +// Generated from API version 2023-10-01-preview +// - options - HealthModelsClientListBySubscriptionOptions contains the optional parameters for the HealthModelsClient.NewListBySubscriptionPager +// method. +func (client *HealthModelsClient) NewListBySubscriptionPager(options *HealthModelsClientListBySubscriptionOptions) *runtime.Pager[HealthModelsClientListBySubscriptionResponse] { + return runtime.NewPager(runtime.PagingHandler[HealthModelsClientListBySubscriptionResponse]{ + More: func(page HealthModelsClientListBySubscriptionResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *HealthModelsClientListBySubscriptionResponse) (HealthModelsClientListBySubscriptionResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "HealthModelsClient.NewListBySubscriptionPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listBySubscriptionCreateRequest(ctx, options) + }, nil) + if err != nil { + return HealthModelsClientListBySubscriptionResponse{}, err + } + return client.listBySubscriptionHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listBySubscriptionCreateRequest creates the ListBySubscription request. +func (client *HealthModelsClient) listBySubscriptionCreateRequest(ctx context.Context, _ *HealthModelsClientListBySubscriptionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.CloudHealth/healthmodels" + 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-10-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listBySubscriptionHandleResponse handles the ListBySubscription response. +func (client *HealthModelsClient) listBySubscriptionHandleResponse(resp *http.Response) (HealthModelsClientListBySubscriptionResponse, error) { + result := HealthModelsClientListBySubscriptionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.HealthModelListResult); err != nil { + return HealthModelsClientListBySubscriptionResponse{}, err + } + return result, nil +} + +// BeginUpdate - Update a HealthModel +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-10-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - healthModelName - Name of health model resource +// - properties - The resource properties to be updated. +// - options - HealthModelsClientBeginUpdateOptions contains the optional parameters for the HealthModelsClient.BeginUpdate +// method. +func (client *HealthModelsClient) BeginUpdate(ctx context.Context, resourceGroupName string, healthModelName string, properties HealthModelUpdate, options *HealthModelsClientBeginUpdateOptions) (*runtime.Poller[HealthModelsClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, healthModelName, properties, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[HealthModelsClientUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[HealthModelsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Update a HealthModel +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-10-01-preview +func (client *HealthModelsClient) update(ctx context.Context, resourceGroupName string, healthModelName string, properties HealthModelUpdate, options *HealthModelsClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "HealthModelsClient.BeginUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, healthModelName, properties, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *HealthModelsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, healthModelName string, properties HealthModelUpdate, _ *HealthModelsClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if healthModelName == "" { + return nil, errors.New("parameter healthModelName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{healthModelName}", url.PathEscape(healthModelName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-10-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, properties); err != nil { + return nil, err + } + return req, nil +} diff --git a/sdk/resourcemanager/cloudhealth/armcloudhealth/interfaces.go b/sdk/resourcemanager/cloudhealth/armcloudhealth/interfaces.go new file mode 100644 index 000000000000..3db54472abee --- /dev/null +++ b/sdk/resourcemanager/cloudhealth/armcloudhealth/interfaces.go @@ -0,0 +1,25 @@ +// 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 armcloudhealth + +// AuthenticationSettingPropertiesClassification provides polymorphic access to related types. +// Call the interface's GetAuthenticationSettingProperties() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *AuthenticationSettingProperties, *ManagedIdentityAuthenticationSettingProperties +type AuthenticationSettingPropertiesClassification interface { + // GetAuthenticationSettingProperties returns the AuthenticationSettingProperties content of the underlying type. + GetAuthenticationSettingProperties() *AuthenticationSettingProperties +} + +// SignalDefinitionPropertiesClassification provides polymorphic access to related types. +// Call the interface's GetSignalDefinitionProperties() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *LogAnalyticsQuerySignalDefinitionProperties, *PrometheusMetricsSignalDefinitionProperties, *ResourceMetricSignalDefinitionProperties, +// - *SignalDefinitionProperties +type SignalDefinitionPropertiesClassification interface { + // GetSignalDefinitionProperties returns the SignalDefinitionProperties content of the underlying type. + GetSignalDefinitionProperties() *SignalDefinitionProperties +} diff --git a/sdk/resourcemanager/cloudhealth/armcloudhealth/models.go b/sdk/resourcemanager/cloudhealth/armcloudhealth/models.go new file mode 100644 index 000000000000..8735a5b2cb5d --- /dev/null +++ b/sdk/resourcemanager/cloudhealth/armcloudhealth/models.go @@ -0,0 +1,823 @@ +// 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 armcloudhealth + +import "time" + +// AlertConfiguration - Alert configuration details +type AlertConfiguration struct { + // REQUIRED; The severity of triggered alert. + Severity *AlertSeverity + + // Optional list of action group resource IDs to be notified when the alert is triggered. + ActionGroupIDs []*string + + // The alert rule description. + Description *string +} + +// AuthenticationSetting - An authentication setting in a health model +type AuthenticationSetting struct { + // The resource-specific properties for this resource. + Properties AuthenticationSettingPropertiesClassification + + // 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 +} + +// AuthenticationSettingListResult - The response of a AuthenticationSetting list operation. +type AuthenticationSettingListResult struct { + // REQUIRED; The AuthenticationSetting items on this page + Value []*AuthenticationSetting + + // The link to the next page of items + NextLink *string +} + +// AuthenticationSettingProperties - Authentication setting properties +type AuthenticationSettingProperties struct { + // REQUIRED; Kind of the authentication setting + AuthenticationKind *AuthenticationKind + + // Display name + DisplayName *string + + // READ-ONLY; The status of the last operation. + ProvisioningState *HealthModelProvisioningState +} + +// GetAuthenticationSettingProperties implements the AuthenticationSettingPropertiesClassification interface for type AuthenticationSettingProperties. +func (a *AuthenticationSettingProperties) GetAuthenticationSettingProperties() *AuthenticationSettingProperties { + return a +} + +// AzureMonitorWorkspaceSignalGroup - A grouping of signal assignments for a Azure Monitor Workspace +type AzureMonitorWorkspaceSignalGroup struct { + // REQUIRED; Reference to the name of the authentication setting which is used for querying the data source + AuthenticationSetting *string + + // REQUIRED; Azure Monitor workspace resource ID + AzureMonitorWorkspaceResourceID *string + + // Signal definitions which are assigned to this signal group. All assignments are combined with an OR operator. + SignalAssignments []*SignalAssignment +} + +// AzureResourceSignalGroup - A grouping of signal assignments for an Azure resource +type AzureResourceSignalGroup struct { + // REQUIRED; Reference to the name of the authentication setting which is used for querying the data source + AuthenticationSetting *string + + // REQUIRED; Azure resource ID + AzureResourceID *string + + // Signal definitions which are assigned to this signal group. All assignments are combined with an OR operator. + SignalAssignments []*SignalAssignment +} + +// DependenciesSignalGroup - Properties for dependent entities, i.e. child entities +type DependenciesSignalGroup struct { + // REQUIRED; Aggregation type for child dependencies. + AggregationType *DependenciesAggregationType + + // Degraded threshold for aggregating the propagated health state of child dependencies. Can be either an absolute number + // that is greater than 0, or a percentage between 1-100%. The entity will be + // considered degraded when the number of not healthy child dependents (unhealthy, degraded, unknown) is equal to or above + // the threshold value. Must only be set when AggregationType is 'Thresholds'. + DegradedThreshold *string + + // Unhealthy threshold for aggregating the propagated health state of child dependencies. Can be either an absolute number + // that is greater than 0, or a percentage between 1-100%. The entity will be + // considered unhealthy when the number of not healthy child dependents (unhealthy, degraded, unknown) is equal to or above + // the threshold value. Must only be set when AggregationType is 'Thresholds'. + UnhealthyThreshold *string +} + +// DiscoveryRule - A discovery rule which automatically finds entities and relationships in a health model based on an Azure +// Resource Graph query +type DiscoveryRule struct { + // The resource-specific properties for this resource. + Properties *DiscoveryRuleProperties + + // 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 +} + +// DiscoveryRuleListResult - The response of a DiscoveryRule list operation. +type DiscoveryRuleListResult struct { + // REQUIRED; The DiscoveryRule items on this page + Value []*DiscoveryRule + + // The link to the next page of items + NextLink *string +} + +// DiscoveryRuleProperties - Discovery rule properties +type DiscoveryRuleProperties struct { + // REQUIRED; Whether to add all recommended signals to the discovered entities. + AddRecommendedSignals *DiscoveryRuleRecommendedSignalsBehavior + + // REQUIRED; Reference to the name of the authentication setting which is used for querying Azure Resource Graph. The same + // authentication setting will also be assigned to any discovered entities. + AuthenticationSetting *string + + // REQUIRED; Whether to create relationships between the discovered entities based on a set of built-in rules. These relationships + // cannot be manually deleted. + DiscoverRelationships *DiscoveryRuleRelationshipDiscoveryBehavior + + // REQUIRED; Azure Resource Graph query text in KQL syntax. The query must return at least a column named 'id' which contains + // the resource ID of the discovered resources. + ResourceGraphQuery *string + + // READ-ONLY; Name of the entity which represents the discovery rule. Note: It might take a few minutes after creating the + // discovery rule until the entity is created. + EntityName *string + + // Display name + DisplayName *string + + // READ-ONLY; Date when the discovery rule was (soft-)deleted. + DeletionDate *time.Time + + // READ-ONLY; Error message if the last discovery operation failed. + ErrorMessage *string + + // READ-ONLY; Number of discovered entities in the last discovery operation. + NumberOfDiscoveredEntities *int32 + + // READ-ONLY; The status of the last operation. + ProvisioningState *HealthModelProvisioningState +} + +// DynamicDetectionRule - ML-based evaluation rule for a signal definition +type DynamicDetectionRule struct { + // REQUIRED; Threshold direction + DynamicThresholdDirection *DynamicThresholdDirection + + // REQUIRED; ML model to use for dynamic thresholds + DynamicThresholdModel *DynamicThresholdModel + + // REQUIRED; ML model sensitivity. Lowest value = high sensitivity. Supported step size = 0.5 + ModelSensitivity *float32 + + // Start time of the training in UTC. + TrainingStartTime *time.Time +} + +// Entity - An entity (aka node) of a health model +type Entity struct { + // The resource-specific properties for this resource. + Properties *EntityProperties + + // 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 +} + +// EntityAlerts - Alert configuration for an entity +type EntityAlerts struct { + // Alert to be triggered on state change to degraded + Degraded *AlertConfiguration + + // Alert to be triggered on state change to unhealthy + Unhealthy *AlertConfiguration +} + +// EntityCoordinates - Visual position of the entity +type EntityCoordinates struct { + // REQUIRED; X Coordinate + X *float32 + + // REQUIRED; Y Coordinate + Y *float32 +} + +// EntityListResult - The response of a Entity list operation. +type EntityListResult struct { + // REQUIRED; The Entity items on this page + Value []*Entity + + // The link to the next page of items + NextLink *string +} + +// EntityProperties - Properties which are common across all kinds of entities +type EntityProperties struct { + // Alert configuration for this entity + Alerts *EntityAlerts + + // Positioning of the entity on the model canvas + CanvasPosition *EntityCoordinates + + // Display name + DisplayName *string + + // Health objective as a percentage of time the entity should be healthy. + HealthObjective *float32 + + // Visual icon definition. If not set, a default icon is used. + Icon *IconDefinition + + // Impact of the entity in health state propagation + Impact *EntityImpact + + // Entity kind + Kind *string + + // Optional set of labels (key-value pairs) + Labels map[string]*string + + // Signal groups which are assigned to this entity + Signals *SignalGroup + + // READ-ONLY; Date when the entity was (soft-)deleted + DeletionDate *time.Time + + // READ-ONLY; Discovered by which discovery rule. If set, the entity cannot be deleted manually. + DiscoveredBy *string + + // READ-ONLY; Health state of this entity + HealthState *HealthState + + // READ-ONLY; The status of the last operation. + ProvisioningState *HealthModelProvisioningState +} + +// EvaluationRule - Evaluation rule for a signal definition +type EvaluationRule struct { + // Degraded rule with static threshold. When used, dynamicDetectionRule must not be set. + DegradedRule *ThresholdRule + + // Configure to use ML-based dynamic thresholds. When used, degradedRule and unhealthyRule must not be set. + DynamicDetectionRule *DynamicDetectionRule + + // Unhealthy rule with static threshold. When used, dynamicDetectionRule must not be set. + UnhealthyRule *ThresholdRule +} + +// HealthModel - A HealthModel resource +type HealthModel struct { + // REQUIRED; The geo-location where the resource lives + Location *string + + // The managed service identities assigned to this resource. + Identity *ManagedServiceIdentity + + // The resource-specific properties for this resource. + Properties *HealthModelProperties + + // Resource tags. + Tags map[string]*string + + // 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 +} + +// HealthModelListResult - The response of a HealthModel list operation. +type HealthModelListResult struct { + // REQUIRED; The HealthModel items on this page + Value []*HealthModel + + // The link to the next page of items + NextLink *string +} + +// HealthModelProperties - HealthModel properties +type HealthModelProperties struct { + // Configure to automatically discover entities from a given scope, such as a Service Group. The discovered entities will + // be linked to the root entity of the health model. + Discovery *ModelDiscoverySettings + + // READ-ONLY; The data plane endpoint for interacting with health data + DataplaneEndpoint *string + + // READ-ONLY; The status of the last operation. + ProvisioningState *HealthModelProvisioningState +} + +// HealthModelUpdate - The type used for update operations of the HealthModel. +type HealthModelUpdate struct { + // The managed service identities assigned to this resource. + Identity *ManagedServiceIdentity + + // The resource-specific properties for this resource. + Properties *HealthModelUpdateProperties + + // Resource tags. + Tags map[string]*string +} + +// HealthModelUpdateProperties - The updatable properties of the HealthModel. +type HealthModelUpdateProperties struct { + // Configure to automatically discover entities from a given scope, such as a Service Group. The discovered entities will + // be linked to the root entity of the health model. + Discovery *ModelDiscoverySettingsUpdate +} + +// IconDefinition - Visual icon definition of an entity +type IconDefinition struct { + // REQUIRED; Name of the built-in icon, or 'Custom' to use customData + IconName *string + + // Custom data. Base64-encoded SVG data. If set, this overrides the built-in icon. + CustomData *string +} + +// LogAnalyticsQuerySignalDefinitionProperties - Log Analytics Query Signal Definition properties +type LogAnalyticsQuerySignalDefinitionProperties struct { + // REQUIRED; Evaluation rules for the signal definition + EvaluationRules *EvaluationRule + + // REQUIRED; Query text in KQL syntax + QueryText *string + + // REQUIRED; Kind of the signal definition + SignalKind *SignalKind + + // Unit of the signal result (e.g. Bytes, MilliSeconds, Percent, Count)) + DataUnit *string + + // Display name + DisplayName *string + + // Optional set of labels (key-value pairs) + Labels map[string]*string + + // Interval in which the signal is being evaluated. Defaults to PT1M (1 minute). + RefreshInterval *RefreshInterval + + // Time range of signal. ISO duration format like PT10M. If not specified, the KQL query must define a time range. + TimeGrain *string + + // Name of the column in the result set to evaluate against the thresholds. Defaults to the first column in the result set + // if not specified. The column must be numeric. + ValueColumnName *string + + // READ-ONLY; Date when the signal definition was (soft-)deleted + DeletionDate *time.Time + + // READ-ONLY; The status of the last operation. + ProvisioningState *HealthModelProvisioningState +} + +// GetSignalDefinitionProperties implements the SignalDefinitionPropertiesClassification interface for type LogAnalyticsQuerySignalDefinitionProperties. +func (l *LogAnalyticsQuerySignalDefinitionProperties) GetSignalDefinitionProperties() *SignalDefinitionProperties { + return &SignalDefinitionProperties{ + DataUnit: l.DataUnit, + DeletionDate: l.DeletionDate, + DisplayName: l.DisplayName, + EvaluationRules: l.EvaluationRules, + Labels: l.Labels, + ProvisioningState: l.ProvisioningState, + RefreshInterval: l.RefreshInterval, + SignalKind: l.SignalKind, + } +} + +// LogAnalyticsSignalGroup - A grouping of signal assignments for a Log Analytics Workspace +type LogAnalyticsSignalGroup struct { + // REQUIRED; Reference to the name of the authentication setting which is used for querying the data source + AuthenticationSetting *string + + // REQUIRED; Log Analytics Workspace resource ID + LogAnalyticsWorkspaceResourceID *string + + // Signal definitions which are assigned to this signal group. All assignments are combined with an OR operator. + SignalAssignments []*SignalAssignment +} + +// ManagedIdentityAuthenticationSettingProperties - Authentication setting properties for Azure Managed Identity +type ManagedIdentityAuthenticationSettingProperties struct { + // REQUIRED; Kind of the authentication setting + AuthenticationKind *AuthenticationKind + + // REQUIRED; Name of the managed identity to use. Either 'SystemAssigned' or the resourceId of a user-assigned identity. + ManagedIdentityName *string + + // Display name + DisplayName *string + + // READ-ONLY; The status of the last operation. + ProvisioningState *HealthModelProvisioningState +} + +// GetAuthenticationSettingProperties implements the AuthenticationSettingPropertiesClassification interface for type ManagedIdentityAuthenticationSettingProperties. +func (m *ManagedIdentityAuthenticationSettingProperties) GetAuthenticationSettingProperties() *AuthenticationSettingProperties { + return &AuthenticationSettingProperties{ + AuthenticationKind: m.AuthenticationKind, + DisplayName: m.DisplayName, + ProvisioningState: m.ProvisioningState, + } +} + +// ManagedServiceIdentity - Managed service identity (system assigned and/or user assigned identities) +type ManagedServiceIdentity struct { + // REQUIRED; Type of managed service identity (where both SystemAssigned and UserAssigned types are allowed). + Type *ManagedServiceIdentityType + + // The set of user assigned identities associated with the resource. The userAssignedIdentities dictionary keys will be ARM + // resource ids in the form: + // '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}. + // The dictionary values can be empty objects ({}) in + // requests. + UserAssignedIdentities map[string]*UserAssignedIdentity + + // READ-ONLY; The service principal ID of the system assigned identity. This property will only be provided for a system assigned + // identity. + PrincipalID *string + + // READ-ONLY; The tenant ID of the system assigned identity. This property will only be provided for a system assigned identity. + TenantID *string +} + +// ModelDiscoverySettings - Settings for automatically discovering entities for the health model. +type ModelDiscoverySettings struct { + // REQUIRED; Whether to add all recommended signals to the discovered entities. + AddRecommendedSignals *DiscoveryRuleRecommendedSignalsBehavior + + // REQUIRED; The scope from which entities should be automatically discovered. For example, the resource id of a Service Group. + Scope *string + + // Which Managed Identity of the health model to use for discovery. Defaults to SystemAssigned, if not set. Can be set to + // 'SystemAssigned' or to the resource id of a user-assigned managed identity which + // is linked to the health model. + Identity *string +} + +// ModelDiscoverySettingsUpdate - Settings for automatically discovering entities for the health model. +type ModelDiscoverySettingsUpdate struct { + // Whether to add all recommended signals to the discovered entities. + AddRecommendedSignals *DiscoveryRuleRecommendedSignalsBehavior + + // Which Managed Identity of the health model to use for discovery. Defaults to SystemAssigned, if not set. Can be set to + // 'SystemAssigned' or to the resource id of a user-assigned managed identity which + // is linked to the health model. + Identity *string + + // The scope from which entities should be automatically discovered. For example, the resource id of a Service Group. + Scope *string +} + +// Operation - Details of a REST API operation, returned from the Resource Provider Operations API +type Operation struct { + // Localized display information for this particular operation. + Display *OperationDisplay + + // READ-ONLY; Enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. + ActionType *ActionType + + // READ-ONLY; Whether the operation applies to data-plane. This is "true" for data-plane operations and "false" for ARM/control-plane + // operations. + IsDataAction *bool + + // READ-ONLY; The name of the operation, as per Resource-Based Access Control (RBAC). Examples: "Microsoft.Compute/virtualMachines/write", + // "Microsoft.Compute/virtualMachines/capture/action" + Name *string + + // READ-ONLY; The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default + // value is "user,system" + Origin *Origin +} + +// OperationDisplay - Localized display information for this particular operation. +type OperationDisplay struct { + // READ-ONLY; The short, localized friendly description of the operation; suitable for tool tips and detailed views. + Description *string + + // READ-ONLY; The concise, localized friendly name for the operation; suitable for dropdowns. E.g. "Create or Update Virtual + // Machine", "Restart Virtual Machine". + Operation *string + + // READ-ONLY; The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft + // Compute". + Provider *string + + // READ-ONLY; The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or "Job + // Schedule Collections". + Resource *string +} + +// OperationListResult - A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to +// get the next set of results. +type OperationListResult struct { + // READ-ONLY; URL to get the next set of operation list results (if there are any). + NextLink *string + + // READ-ONLY; List of operations supported by the resource provider + Value []*Operation +} + +// PrometheusMetricsSignalDefinitionProperties - Prometheus Metrics Signal Definition properties +type PrometheusMetricsSignalDefinitionProperties struct { + // REQUIRED; Evaluation rules for the signal definition + EvaluationRules *EvaluationRule + + // REQUIRED; Query text in PromQL syntax + QueryText *string + + // REQUIRED; Kind of the signal definition + SignalKind *SignalKind + + // Unit of the signal result (e.g. Bytes, MilliSeconds, Percent, Count)) + DataUnit *string + + // Display name + DisplayName *string + + // Optional set of labels (key-value pairs) + Labels map[string]*string + + // Interval in which the signal is being evaluated. Defaults to PT1M (1 minute). + RefreshInterval *RefreshInterval + + // Time range of signal. ISO duration format like PT10M. + TimeGrain *string + + // READ-ONLY; Date when the signal definition was (soft-)deleted + DeletionDate *time.Time + + // READ-ONLY; The status of the last operation. + ProvisioningState *HealthModelProvisioningState +} + +// GetSignalDefinitionProperties implements the SignalDefinitionPropertiesClassification interface for type PrometheusMetricsSignalDefinitionProperties. +func (p *PrometheusMetricsSignalDefinitionProperties) GetSignalDefinitionProperties() *SignalDefinitionProperties { + return &SignalDefinitionProperties{ + DataUnit: p.DataUnit, + DeletionDate: p.DeletionDate, + DisplayName: p.DisplayName, + EvaluationRules: p.EvaluationRules, + Labels: p.Labels, + ProvisioningState: p.ProvisioningState, + RefreshInterval: p.RefreshInterval, + SignalKind: p.SignalKind, + } +} + +// Relationship - A relationship (aka edge) between two entities in a health model +type Relationship struct { + // The resource-specific properties for this resource. + Properties *RelationshipProperties + + // 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 +} + +// RelationshipListResult - The response of a Relationship list operation. +type RelationshipListResult struct { + // REQUIRED; The Relationship items on this page + Value []*Relationship + + // The link to the next page of items + NextLink *string +} + +// RelationshipProperties - Relationship properties +type RelationshipProperties struct { + // REQUIRED; Resource name of the child entity + ChildEntityName *string + + // REQUIRED; Resource name of the parent entity + ParentEntityName *string + + // Display name + DisplayName *string + + // Optional set of labels (key-value pairs) + Labels map[string]*string + + // READ-ONLY; Date when the relationship was (soft-)deleted + DeletionDate *time.Time + + // READ-ONLY; Discovered by which discovery rule. If set, the relationship cannot be deleted manually. + DiscoveredBy *string + + // READ-ONLY; The status of the last operation. + ProvisioningState *HealthModelProvisioningState +} + +// ResourceMetricSignalDefinitionProperties - Azure Resource Metric Signal Definition properties +type ResourceMetricSignalDefinitionProperties struct { + // REQUIRED; Type of aggregation to apply to the metric + AggregationType *MetricAggregationType + + // REQUIRED; Evaluation rules for the signal definition + EvaluationRules *EvaluationRule + + // REQUIRED; Name of the metric + MetricName *string + + // REQUIRED; Metric namespace + MetricNamespace *string + + // REQUIRED; Kind of the signal definition + SignalKind *SignalKind + + // REQUIRED; Time range of signal. ISO duration format like PT10M. + TimeGrain *string + + // Unit of the signal result (e.g. Bytes, MilliSeconds, Percent, Count)) + DataUnit *string + + // Optional: Dimension to split by + Dimension *string + + // Optional: Dimension filter to apply to the dimension. Must only be set if also Dimension is set. + DimensionFilter *string + + // Display name + DisplayName *string + + // Optional set of labels (key-value pairs) + Labels map[string]*string + + // Interval in which the signal is being evaluated. Defaults to PT1M (1 minute). + RefreshInterval *RefreshInterval + + // READ-ONLY; Date when the signal definition was (soft-)deleted + DeletionDate *time.Time + + // READ-ONLY; The status of the last operation. + ProvisioningState *HealthModelProvisioningState +} + +// GetSignalDefinitionProperties implements the SignalDefinitionPropertiesClassification interface for type ResourceMetricSignalDefinitionProperties. +func (r *ResourceMetricSignalDefinitionProperties) GetSignalDefinitionProperties() *SignalDefinitionProperties { + return &SignalDefinitionProperties{ + DataUnit: r.DataUnit, + DeletionDate: r.DeletionDate, + DisplayName: r.DisplayName, + EvaluationRules: r.EvaluationRules, + Labels: r.Labels, + ProvisioningState: r.ProvisioningState, + RefreshInterval: r.RefreshInterval, + SignalKind: r.SignalKind, + } +} + +// SignalAssignment - Group of signal definition assignments +type SignalAssignment struct { + // REQUIRED; Signal definitions referenced by their names. All definitions are combined with an AND operator. + SignalDefinitions []*string +} + +// SignalDefinition - A signal definition in a health model +type SignalDefinition struct { + // The resource-specific properties for this resource. + Properties SignalDefinitionPropertiesClassification + + // 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 +} + +// SignalDefinitionListResult - The response of a SignalDefinition list operation. +type SignalDefinitionListResult struct { + // REQUIRED; The SignalDefinition items on this page + Value []*SignalDefinition + + // The link to the next page of items + NextLink *string +} + +// SignalDefinitionProperties - SignalDefinition properties +type SignalDefinitionProperties struct { + // REQUIRED; Evaluation rules for the signal definition + EvaluationRules *EvaluationRule + + // REQUIRED; Kind of the signal definition + SignalKind *SignalKind + + // Unit of the signal result (e.g. Bytes, MilliSeconds, Percent, Count)) + DataUnit *string + + // Display name + DisplayName *string + + // Optional set of labels (key-value pairs) + Labels map[string]*string + + // Interval in which the signal is being evaluated. Defaults to PT1M (1 minute). + RefreshInterval *RefreshInterval + + // READ-ONLY; Date when the signal definition was (soft-)deleted + DeletionDate *time.Time + + // READ-ONLY; The status of the last operation. + ProvisioningState *HealthModelProvisioningState +} + +// GetSignalDefinitionProperties implements the SignalDefinitionPropertiesClassification interface for type SignalDefinitionProperties. +func (s *SignalDefinitionProperties) GetSignalDefinitionProperties() *SignalDefinitionProperties { + return s +} + +// SignalGroup - Contains various signal groups that can be assigned to an entity +type SignalGroup struct { + // Log Analytics Signal Group + AzureLogAnalytics *LogAnalyticsSignalGroup + + // Azure Monitor Workspace Signal Group + AzureMonitorWorkspace *AzureMonitorWorkspaceSignalGroup + + // Azure Resource Signal Group + AzureResource *AzureResourceSignalGroup + + // Settings for dependency signals to control how the health state of child entities influences the health state of the parent + // entity. + Dependencies *DependenciesSignalGroup +} + +// 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 +} + +// ThresholdRule - Threshold-based evaluation rule for a signal definition +type ThresholdRule struct { + // REQUIRED; Operator how to compare the signal value with the threshold + Operator *SignalOperator + + // REQUIRED; Threshold value + Threshold *string +} + +// UserAssignedIdentity - User assigned identity properties +type UserAssignedIdentity struct { + // READ-ONLY; The client ID of the assigned identity. + ClientID *string + + // READ-ONLY; The principal ID of the assigned identity. + PrincipalID *string +} diff --git a/sdk/resourcemanager/cloudhealth/armcloudhealth/models_serde.go b/sdk/resourcemanager/cloudhealth/armcloudhealth/models_serde.go new file mode 100644 index 000000000000..99e25b660870 --- /dev/null +++ b/sdk/resourcemanager/cloudhealth/armcloudhealth/models_serde.go @@ -0,0 +1,1852 @@ +// 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 armcloudhealth + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type AlertConfiguration. +func (a AlertConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "actionGroupIds", a.ActionGroupIDs) + populate(objectMap, "description", a.Description) + populate(objectMap, "severity", a.Severity) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AlertConfiguration. +func (a *AlertConfiguration) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "actionGroupIds": + err = unpopulate(val, "ActionGroupIDs", &a.ActionGroupIDs) + delete(rawMsg, key) + case "description": + err = unpopulate(val, "Description", &a.Description) + delete(rawMsg, key) + case "severity": + err = unpopulate(val, "Severity", &a.Severity) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AuthenticationSetting. +func (a AuthenticationSetting) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", a.ID) + populate(objectMap, "name", a.Name) + populate(objectMap, "properties", a.Properties) + populate(objectMap, "systemData", a.SystemData) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AuthenticationSetting. +func (a *AuthenticationSetting) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &a.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &a.Name) + delete(rawMsg, key) + case "properties": + a.Properties, err = unmarshalAuthenticationSettingPropertiesClassification(val) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &a.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &a.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AuthenticationSettingListResult. +func (a AuthenticationSettingListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", a.NextLink) + populate(objectMap, "value", a.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AuthenticationSettingListResult. +func (a *AuthenticationSettingListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &a.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &a.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AuthenticationSettingProperties. +func (a AuthenticationSettingProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + objectMap["authenticationKind"] = a.AuthenticationKind + populate(objectMap, "displayName", a.DisplayName) + populate(objectMap, "provisioningState", a.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AuthenticationSettingProperties. +func (a *AuthenticationSettingProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "authenticationKind": + err = unpopulate(val, "AuthenticationKind", &a.AuthenticationKind) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &a.DisplayName) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &a.ProvisioningState) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AzureMonitorWorkspaceSignalGroup. +func (a AzureMonitorWorkspaceSignalGroup) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "authenticationSetting", a.AuthenticationSetting) + populate(objectMap, "azureMonitorWorkspaceResourceId", a.AzureMonitorWorkspaceResourceID) + populate(objectMap, "signalAssignments", a.SignalAssignments) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AzureMonitorWorkspaceSignalGroup. +func (a *AzureMonitorWorkspaceSignalGroup) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "authenticationSetting": + err = unpopulate(val, "AuthenticationSetting", &a.AuthenticationSetting) + delete(rawMsg, key) + case "azureMonitorWorkspaceResourceId": + err = unpopulate(val, "AzureMonitorWorkspaceResourceID", &a.AzureMonitorWorkspaceResourceID) + delete(rawMsg, key) + case "signalAssignments": + err = unpopulate(val, "SignalAssignments", &a.SignalAssignments) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AzureResourceSignalGroup. +func (a AzureResourceSignalGroup) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "authenticationSetting", a.AuthenticationSetting) + populate(objectMap, "azureResourceId", a.AzureResourceID) + populate(objectMap, "signalAssignments", a.SignalAssignments) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AzureResourceSignalGroup. +func (a *AzureResourceSignalGroup) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "authenticationSetting": + err = unpopulate(val, "AuthenticationSetting", &a.AuthenticationSetting) + delete(rawMsg, key) + case "azureResourceId": + err = unpopulate(val, "AzureResourceID", &a.AzureResourceID) + delete(rawMsg, key) + case "signalAssignments": + err = unpopulate(val, "SignalAssignments", &a.SignalAssignments) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DependenciesSignalGroup. +func (d DependenciesSignalGroup) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "aggregationType", d.AggregationType) + populate(objectMap, "degradedThreshold", d.DegradedThreshold) + populate(objectMap, "unhealthyThreshold", d.UnhealthyThreshold) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DependenciesSignalGroup. +func (d *DependenciesSignalGroup) 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", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "aggregationType": + err = unpopulate(val, "AggregationType", &d.AggregationType) + delete(rawMsg, key) + case "degradedThreshold": + err = unpopulate(val, "DegradedThreshold", &d.DegradedThreshold) + delete(rawMsg, key) + case "unhealthyThreshold": + err = unpopulate(val, "UnhealthyThreshold", &d.UnhealthyThreshold) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DiscoveryRule. +func (d DiscoveryRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", d.ID) + populate(objectMap, "name", d.Name) + populate(objectMap, "properties", d.Properties) + populate(objectMap, "systemData", d.SystemData) + populate(objectMap, "type", d.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DiscoveryRule. +func (d *DiscoveryRule) 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", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &d.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &d.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &d.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &d.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &d.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DiscoveryRuleListResult. +func (d DiscoveryRuleListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", d.NextLink) + populate(objectMap, "value", d.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DiscoveryRuleListResult. +func (d *DiscoveryRuleListResult) 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", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &d.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &d.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DiscoveryRuleProperties. +func (d DiscoveryRuleProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "addRecommendedSignals", d.AddRecommendedSignals) + populate(objectMap, "authenticationSetting", d.AuthenticationSetting) + populateDateTimeRFC3339(objectMap, "deletionDate", d.DeletionDate) + populate(objectMap, "discoverRelationships", d.DiscoverRelationships) + populate(objectMap, "displayName", d.DisplayName) + populate(objectMap, "entityName", d.EntityName) + populate(objectMap, "errorMessage", d.ErrorMessage) + populate(objectMap, "numberOfDiscoveredEntities", d.NumberOfDiscoveredEntities) + populate(objectMap, "provisioningState", d.ProvisioningState) + populate(objectMap, "resourceGraphQuery", d.ResourceGraphQuery) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DiscoveryRuleProperties. +func (d *DiscoveryRuleProperties) 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", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "addRecommendedSignals": + err = unpopulate(val, "AddRecommendedSignals", &d.AddRecommendedSignals) + delete(rawMsg, key) + case "authenticationSetting": + err = unpopulate(val, "AuthenticationSetting", &d.AuthenticationSetting) + delete(rawMsg, key) + case "deletionDate": + err = unpopulateDateTimeRFC3339(val, "DeletionDate", &d.DeletionDate) + delete(rawMsg, key) + case "discoverRelationships": + err = unpopulate(val, "DiscoverRelationships", &d.DiscoverRelationships) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &d.DisplayName) + delete(rawMsg, key) + case "entityName": + err = unpopulate(val, "EntityName", &d.EntityName) + delete(rawMsg, key) + case "errorMessage": + err = unpopulate(val, "ErrorMessage", &d.ErrorMessage) + delete(rawMsg, key) + case "numberOfDiscoveredEntities": + err = unpopulate(val, "NumberOfDiscoveredEntities", &d.NumberOfDiscoveredEntities) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &d.ProvisioningState) + delete(rawMsg, key) + case "resourceGraphQuery": + err = unpopulate(val, "ResourceGraphQuery", &d.ResourceGraphQuery) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DynamicDetectionRule. +func (d DynamicDetectionRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "dynamicThresholdDirection", d.DynamicThresholdDirection) + populate(objectMap, "dynamicThresholdModel", d.DynamicThresholdModel) + populate(objectMap, "modelSensitivity", d.ModelSensitivity) + populateDateTimeRFC3339(objectMap, "trainingStartTime", d.TrainingStartTime) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DynamicDetectionRule. +func (d *DynamicDetectionRule) 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", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "dynamicThresholdDirection": + err = unpopulate(val, "DynamicThresholdDirection", &d.DynamicThresholdDirection) + delete(rawMsg, key) + case "dynamicThresholdModel": + err = unpopulate(val, "DynamicThresholdModel", &d.DynamicThresholdModel) + delete(rawMsg, key) + case "modelSensitivity": + err = unpopulate(val, "ModelSensitivity", &d.ModelSensitivity) + delete(rawMsg, key) + case "trainingStartTime": + err = unpopulateDateTimeRFC3339(val, "TrainingStartTime", &d.TrainingStartTime) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Entity. +func (e Entity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", e.ID) + populate(objectMap, "name", e.Name) + populate(objectMap, "properties", e.Properties) + populate(objectMap, "systemData", e.SystemData) + populate(objectMap, "type", e.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Entity. +func (e *Entity) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &e.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &e.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &e.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &e.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &e.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type EntityAlerts. +func (e EntityAlerts) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "degraded", e.Degraded) + populate(objectMap, "unhealthy", e.Unhealthy) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EntityAlerts. +func (e *EntityAlerts) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "degraded": + err = unpopulate(val, "Degraded", &e.Degraded) + delete(rawMsg, key) + case "unhealthy": + err = unpopulate(val, "Unhealthy", &e.Unhealthy) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type EntityCoordinates. +func (e EntityCoordinates) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "x", e.X) + populate(objectMap, "y", e.Y) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EntityCoordinates. +func (e *EntityCoordinates) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "x": + err = unpopulate(val, "X", &e.X) + delete(rawMsg, key) + case "y": + err = unpopulate(val, "Y", &e.Y) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type EntityListResult. +func (e EntityListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", e.NextLink) + populate(objectMap, "value", e.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EntityListResult. +func (e *EntityListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &e.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &e.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type EntityProperties. +func (e EntityProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "alerts", e.Alerts) + populate(objectMap, "canvasPosition", e.CanvasPosition) + populateDateTimeRFC3339(objectMap, "deletionDate", e.DeletionDate) + populate(objectMap, "discoveredBy", e.DiscoveredBy) + populate(objectMap, "displayName", e.DisplayName) + populate(objectMap, "healthObjective", e.HealthObjective) + populate(objectMap, "healthState", e.HealthState) + populate(objectMap, "icon", e.Icon) + populate(objectMap, "impact", e.Impact) + populate(objectMap, "kind", e.Kind) + populate(objectMap, "labels", e.Labels) + populate(objectMap, "provisioningState", e.ProvisioningState) + populate(objectMap, "signals", e.Signals) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EntityProperties. +func (e *EntityProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "alerts": + err = unpopulate(val, "Alerts", &e.Alerts) + delete(rawMsg, key) + case "canvasPosition": + err = unpopulate(val, "CanvasPosition", &e.CanvasPosition) + delete(rawMsg, key) + case "deletionDate": + err = unpopulateDateTimeRFC3339(val, "DeletionDate", &e.DeletionDate) + delete(rawMsg, key) + case "discoveredBy": + err = unpopulate(val, "DiscoveredBy", &e.DiscoveredBy) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &e.DisplayName) + delete(rawMsg, key) + case "healthObjective": + err = unpopulate(val, "HealthObjective", &e.HealthObjective) + delete(rawMsg, key) + case "healthState": + err = unpopulate(val, "HealthState", &e.HealthState) + delete(rawMsg, key) + case "icon": + err = unpopulate(val, "Icon", &e.Icon) + delete(rawMsg, key) + case "impact": + err = unpopulate(val, "Impact", &e.Impact) + delete(rawMsg, key) + case "kind": + err = unpopulate(val, "Kind", &e.Kind) + delete(rawMsg, key) + case "labels": + err = unpopulate(val, "Labels", &e.Labels) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &e.ProvisioningState) + delete(rawMsg, key) + case "signals": + err = unpopulate(val, "Signals", &e.Signals) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type EvaluationRule. +func (e EvaluationRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "degradedRule", e.DegradedRule) + populate(objectMap, "dynamicDetectionRule", e.DynamicDetectionRule) + populate(objectMap, "unhealthyRule", e.UnhealthyRule) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EvaluationRule. +func (e *EvaluationRule) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "degradedRule": + err = unpopulate(val, "DegradedRule", &e.DegradedRule) + delete(rawMsg, key) + case "dynamicDetectionRule": + err = unpopulate(val, "DynamicDetectionRule", &e.DynamicDetectionRule) + delete(rawMsg, key) + case "unhealthyRule": + err = unpopulate(val, "UnhealthyRule", &e.UnhealthyRule) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type HealthModel. +func (h HealthModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", h.ID) + populate(objectMap, "identity", h.Identity) + populate(objectMap, "location", h.Location) + populate(objectMap, "name", h.Name) + populate(objectMap, "properties", h.Properties) + populate(objectMap, "systemData", h.SystemData) + populate(objectMap, "tags", h.Tags) + populate(objectMap, "type", h.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type HealthModel. +func (h *HealthModel) 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", h, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &h.ID) + delete(rawMsg, key) + case "identity": + err = unpopulate(val, "Identity", &h.Identity) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &h.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &h.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &h.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &h.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &h.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &h.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", h, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type HealthModelListResult. +func (h HealthModelListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", h.NextLink) + populate(objectMap, "value", h.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type HealthModelListResult. +func (h *HealthModelListResult) 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", h, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &h.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &h.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", h, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type HealthModelProperties. +func (h HealthModelProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "dataplaneEndpoint", h.DataplaneEndpoint) + populate(objectMap, "discovery", h.Discovery) + populate(objectMap, "provisioningState", h.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type HealthModelProperties. +func (h *HealthModelProperties) 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", h, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "dataplaneEndpoint": + err = unpopulate(val, "DataplaneEndpoint", &h.DataplaneEndpoint) + delete(rawMsg, key) + case "discovery": + err = unpopulate(val, "Discovery", &h.Discovery) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &h.ProvisioningState) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", h, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type HealthModelUpdate. +func (h HealthModelUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "identity", h.Identity) + populate(objectMap, "properties", h.Properties) + populate(objectMap, "tags", h.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type HealthModelUpdate. +func (h *HealthModelUpdate) 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", h, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "identity": + err = unpopulate(val, "Identity", &h.Identity) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &h.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &h.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", h, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type HealthModelUpdateProperties. +func (h HealthModelUpdateProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "discovery", h.Discovery) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type HealthModelUpdateProperties. +func (h *HealthModelUpdateProperties) 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", h, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "discovery": + err = unpopulate(val, "Discovery", &h.Discovery) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", h, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type IconDefinition. +func (i IconDefinition) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "customData", i.CustomData) + populate(objectMap, "iconName", i.IconName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type IconDefinition. +func (i *IconDefinition) 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", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "customData": + err = unpopulate(val, "CustomData", &i.CustomData) + delete(rawMsg, key) + case "iconName": + err = unpopulate(val, "IconName", &i.IconName) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type LogAnalyticsQuerySignalDefinitionProperties. +func (l LogAnalyticsQuerySignalDefinitionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "dataUnit", l.DataUnit) + populateDateTimeRFC3339(objectMap, "deletionDate", l.DeletionDate) + populate(objectMap, "displayName", l.DisplayName) + populate(objectMap, "evaluationRules", l.EvaluationRules) + populate(objectMap, "labels", l.Labels) + populate(objectMap, "provisioningState", l.ProvisioningState) + populate(objectMap, "queryText", l.QueryText) + populate(objectMap, "refreshInterval", l.RefreshInterval) + objectMap["signalKind"] = SignalKindLogAnalyticsQuery + populate(objectMap, "timeGrain", l.TimeGrain) + populate(objectMap, "valueColumnName", l.ValueColumnName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LogAnalyticsQuerySignalDefinitionProperties. +func (l *LogAnalyticsQuerySignalDefinitionProperties) 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", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "dataUnit": + err = unpopulate(val, "DataUnit", &l.DataUnit) + delete(rawMsg, key) + case "deletionDate": + err = unpopulateDateTimeRFC3339(val, "DeletionDate", &l.DeletionDate) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &l.DisplayName) + delete(rawMsg, key) + case "evaluationRules": + err = unpopulate(val, "EvaluationRules", &l.EvaluationRules) + delete(rawMsg, key) + case "labels": + err = unpopulate(val, "Labels", &l.Labels) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &l.ProvisioningState) + delete(rawMsg, key) + case "queryText": + err = unpopulate(val, "QueryText", &l.QueryText) + delete(rawMsg, key) + case "refreshInterval": + err = unpopulate(val, "RefreshInterval", &l.RefreshInterval) + delete(rawMsg, key) + case "signalKind": + err = unpopulate(val, "SignalKind", &l.SignalKind) + delete(rawMsg, key) + case "timeGrain": + err = unpopulate(val, "TimeGrain", &l.TimeGrain) + delete(rawMsg, key) + case "valueColumnName": + err = unpopulate(val, "ValueColumnName", &l.ValueColumnName) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type LogAnalyticsSignalGroup. +func (l LogAnalyticsSignalGroup) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "authenticationSetting", l.AuthenticationSetting) + populate(objectMap, "logAnalyticsWorkspaceResourceId", l.LogAnalyticsWorkspaceResourceID) + populate(objectMap, "signalAssignments", l.SignalAssignments) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LogAnalyticsSignalGroup. +func (l *LogAnalyticsSignalGroup) 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", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "authenticationSetting": + err = unpopulate(val, "AuthenticationSetting", &l.AuthenticationSetting) + delete(rawMsg, key) + case "logAnalyticsWorkspaceResourceId": + err = unpopulate(val, "LogAnalyticsWorkspaceResourceID", &l.LogAnalyticsWorkspaceResourceID) + delete(rawMsg, key) + case "signalAssignments": + err = unpopulate(val, "SignalAssignments", &l.SignalAssignments) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ManagedIdentityAuthenticationSettingProperties. +func (m ManagedIdentityAuthenticationSettingProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + objectMap["authenticationKind"] = AuthenticationKindManagedIdentity + populate(objectMap, "displayName", m.DisplayName) + populate(objectMap, "managedIdentityName", m.ManagedIdentityName) + populate(objectMap, "provisioningState", m.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagedIdentityAuthenticationSettingProperties. +func (m *ManagedIdentityAuthenticationSettingProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "authenticationKind": + err = unpopulate(val, "AuthenticationKind", &m.AuthenticationKind) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &m.DisplayName) + delete(rawMsg, key) + case "managedIdentityName": + err = unpopulate(val, "ManagedIdentityName", &m.ManagedIdentityName) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &m.ProvisioningState) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ManagedServiceIdentity. +func (m ManagedServiceIdentity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "principalId", m.PrincipalID) + populate(objectMap, "tenantId", m.TenantID) + populate(objectMap, "type", m.Type) + populate(objectMap, "userAssignedIdentities", m.UserAssignedIdentities) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagedServiceIdentity. +func (m *ManagedServiceIdentity) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "principalId": + err = unpopulate(val, "PrincipalID", &m.PrincipalID) + delete(rawMsg, key) + case "tenantId": + err = unpopulate(val, "TenantID", &m.TenantID) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &m.Type) + delete(rawMsg, key) + case "userAssignedIdentities": + err = unpopulate(val, "UserAssignedIdentities", &m.UserAssignedIdentities) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ModelDiscoverySettings. +func (m ModelDiscoverySettings) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "addRecommendedSignals", m.AddRecommendedSignals) + populate(objectMap, "identity", m.Identity) + populate(objectMap, "scope", m.Scope) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ModelDiscoverySettings. +func (m *ModelDiscoverySettings) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "addRecommendedSignals": + err = unpopulate(val, "AddRecommendedSignals", &m.AddRecommendedSignals) + delete(rawMsg, key) + case "identity": + err = unpopulate(val, "Identity", &m.Identity) + delete(rawMsg, key) + case "scope": + err = unpopulate(val, "Scope", &m.Scope) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ModelDiscoverySettingsUpdate. +func (m ModelDiscoverySettingsUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "addRecommendedSignals", m.AddRecommendedSignals) + populate(objectMap, "identity", m.Identity) + populate(objectMap, "scope", m.Scope) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ModelDiscoverySettingsUpdate. +func (m *ModelDiscoverySettingsUpdate) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "addRecommendedSignals": + err = unpopulate(val, "AddRecommendedSignals", &m.AddRecommendedSignals) + delete(rawMsg, key) + case "identity": + err = unpopulate(val, "Identity", &m.Identity) + delete(rawMsg, key) + case "scope": + err = unpopulate(val, "Scope", &m.Scope) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Operation. +func (o Operation) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "actionType", o.ActionType) + populate(objectMap, "display", o.Display) + populate(objectMap, "isDataAction", o.IsDataAction) + populate(objectMap, "name", o.Name) + populate(objectMap, "origin", o.Origin) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Operation. +func (o *Operation) 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", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "actionType": + err = unpopulate(val, "ActionType", &o.ActionType) + delete(rawMsg, key) + case "display": + err = unpopulate(val, "Display", &o.Display) + delete(rawMsg, key) + case "isDataAction": + err = unpopulate(val, "IsDataAction", &o.IsDataAction) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &o.Name) + delete(rawMsg, key) + case "origin": + err = unpopulate(val, "Origin", &o.Origin) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationDisplay. +func (o OperationDisplay) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", o.Description) + populate(objectMap, "operation", o.Operation) + populate(objectMap, "provider", o.Provider) + populate(objectMap, "resource", o.Resource) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationDisplay. +func (o *OperationDisplay) 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", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &o.Description) + delete(rawMsg, key) + case "operation": + err = unpopulate(val, "Operation", &o.Operation) + delete(rawMsg, key) + case "provider": + err = unpopulate(val, "Provider", &o.Provider) + delete(rawMsg, key) + case "resource": + err = unpopulate(val, "Resource", &o.Resource) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationListResult. +func (o OperationListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", o.NextLink) + populate(objectMap, "value", o.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationListResult. +func (o *OperationListResult) 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", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &o.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &o.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrometheusMetricsSignalDefinitionProperties. +func (p PrometheusMetricsSignalDefinitionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "dataUnit", p.DataUnit) + populateDateTimeRFC3339(objectMap, "deletionDate", p.DeletionDate) + populate(objectMap, "displayName", p.DisplayName) + populate(objectMap, "evaluationRules", p.EvaluationRules) + populate(objectMap, "labels", p.Labels) + populate(objectMap, "provisioningState", p.ProvisioningState) + populate(objectMap, "queryText", p.QueryText) + populate(objectMap, "refreshInterval", p.RefreshInterval) + objectMap["signalKind"] = SignalKindPrometheusMetricsQuery + populate(objectMap, "timeGrain", p.TimeGrain) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrometheusMetricsSignalDefinitionProperties. +func (p *PrometheusMetricsSignalDefinitionProperties) 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 "dataUnit": + err = unpopulate(val, "DataUnit", &p.DataUnit) + delete(rawMsg, key) + case "deletionDate": + err = unpopulateDateTimeRFC3339(val, "DeletionDate", &p.DeletionDate) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &p.DisplayName) + delete(rawMsg, key) + case "evaluationRules": + err = unpopulate(val, "EvaluationRules", &p.EvaluationRules) + delete(rawMsg, key) + case "labels": + err = unpopulate(val, "Labels", &p.Labels) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &p.ProvisioningState) + delete(rawMsg, key) + case "queryText": + err = unpopulate(val, "QueryText", &p.QueryText) + delete(rawMsg, key) + case "refreshInterval": + err = unpopulate(val, "RefreshInterval", &p.RefreshInterval) + delete(rawMsg, key) + case "signalKind": + err = unpopulate(val, "SignalKind", &p.SignalKind) + delete(rawMsg, key) + case "timeGrain": + err = unpopulate(val, "TimeGrain", &p.TimeGrain) + 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 Relationship. +func (r Relationship) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", r.ID) + populate(objectMap, "name", r.Name) + populate(objectMap, "properties", r.Properties) + populate(objectMap, "systemData", r.SystemData) + populate(objectMap, "type", r.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Relationship. +func (r *Relationship) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &r.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &r.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &r.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &r.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &r.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RelationshipListResult. +func (r RelationshipListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", r.NextLink) + populate(objectMap, "value", r.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RelationshipListResult. +func (r *RelationshipListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &r.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &r.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RelationshipProperties. +func (r RelationshipProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "childEntityName", r.ChildEntityName) + populateDateTimeRFC3339(objectMap, "deletionDate", r.DeletionDate) + populate(objectMap, "discoveredBy", r.DiscoveredBy) + populate(objectMap, "displayName", r.DisplayName) + populate(objectMap, "labels", r.Labels) + populate(objectMap, "parentEntityName", r.ParentEntityName) + populate(objectMap, "provisioningState", r.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RelationshipProperties. +func (r *RelationshipProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "childEntityName": + err = unpopulate(val, "ChildEntityName", &r.ChildEntityName) + delete(rawMsg, key) + case "deletionDate": + err = unpopulateDateTimeRFC3339(val, "DeletionDate", &r.DeletionDate) + delete(rawMsg, key) + case "discoveredBy": + err = unpopulate(val, "DiscoveredBy", &r.DiscoveredBy) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &r.DisplayName) + delete(rawMsg, key) + case "labels": + err = unpopulate(val, "Labels", &r.Labels) + delete(rawMsg, key) + case "parentEntityName": + err = unpopulate(val, "ParentEntityName", &r.ParentEntityName) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &r.ProvisioningState) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ResourceMetricSignalDefinitionProperties. +func (r ResourceMetricSignalDefinitionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "aggregationType", r.AggregationType) + populate(objectMap, "dataUnit", r.DataUnit) + populateDateTimeRFC3339(objectMap, "deletionDate", r.DeletionDate) + populate(objectMap, "dimension", r.Dimension) + populate(objectMap, "dimensionFilter", r.DimensionFilter) + populate(objectMap, "displayName", r.DisplayName) + populate(objectMap, "evaluationRules", r.EvaluationRules) + populate(objectMap, "labels", r.Labels) + populate(objectMap, "metricName", r.MetricName) + populate(objectMap, "metricNamespace", r.MetricNamespace) + populate(objectMap, "provisioningState", r.ProvisioningState) + populate(objectMap, "refreshInterval", r.RefreshInterval) + objectMap["signalKind"] = SignalKindAzureResourceMetric + populate(objectMap, "timeGrain", r.TimeGrain) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceMetricSignalDefinitionProperties. +func (r *ResourceMetricSignalDefinitionProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "aggregationType": + err = unpopulate(val, "AggregationType", &r.AggregationType) + delete(rawMsg, key) + case "dataUnit": + err = unpopulate(val, "DataUnit", &r.DataUnit) + delete(rawMsg, key) + case "deletionDate": + err = unpopulateDateTimeRFC3339(val, "DeletionDate", &r.DeletionDate) + delete(rawMsg, key) + case "dimension": + err = unpopulate(val, "Dimension", &r.Dimension) + delete(rawMsg, key) + case "dimensionFilter": + err = unpopulate(val, "DimensionFilter", &r.DimensionFilter) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &r.DisplayName) + delete(rawMsg, key) + case "evaluationRules": + err = unpopulate(val, "EvaluationRules", &r.EvaluationRules) + delete(rawMsg, key) + case "labels": + err = unpopulate(val, "Labels", &r.Labels) + delete(rawMsg, key) + case "metricName": + err = unpopulate(val, "MetricName", &r.MetricName) + delete(rawMsg, key) + case "metricNamespace": + err = unpopulate(val, "MetricNamespace", &r.MetricNamespace) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &r.ProvisioningState) + delete(rawMsg, key) + case "refreshInterval": + err = unpopulate(val, "RefreshInterval", &r.RefreshInterval) + delete(rawMsg, key) + case "signalKind": + err = unpopulate(val, "SignalKind", &r.SignalKind) + delete(rawMsg, key) + case "timeGrain": + err = unpopulate(val, "TimeGrain", &r.TimeGrain) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SignalAssignment. +func (s SignalAssignment) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "signalDefinitions", s.SignalDefinitions) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SignalAssignment. +func (s *SignalAssignment) 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 "signalDefinitions": + err = unpopulate(val, "SignalDefinitions", &s.SignalDefinitions) + 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 SignalDefinition. +func (s SignalDefinition) 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 SignalDefinition. +func (s *SignalDefinition) 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": + s.Properties, err = unmarshalSignalDefinitionPropertiesClassification(val) + 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 SignalDefinitionListResult. +func (s SignalDefinitionListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", s.NextLink) + populate(objectMap, "value", s.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SignalDefinitionListResult. +func (s *SignalDefinitionListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &s.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &s.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SignalDefinitionProperties. +func (s SignalDefinitionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "dataUnit", s.DataUnit) + populateDateTimeRFC3339(objectMap, "deletionDate", s.DeletionDate) + populate(objectMap, "displayName", s.DisplayName) + populate(objectMap, "evaluationRules", s.EvaluationRules) + populate(objectMap, "labels", s.Labels) + populate(objectMap, "provisioningState", s.ProvisioningState) + populate(objectMap, "refreshInterval", s.RefreshInterval) + objectMap["signalKind"] = s.SignalKind + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SignalDefinitionProperties. +func (s *SignalDefinitionProperties) 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 "dataUnit": + err = unpopulate(val, "DataUnit", &s.DataUnit) + delete(rawMsg, key) + case "deletionDate": + err = unpopulateDateTimeRFC3339(val, "DeletionDate", &s.DeletionDate) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &s.DisplayName) + delete(rawMsg, key) + case "evaluationRules": + err = unpopulate(val, "EvaluationRules", &s.EvaluationRules) + delete(rawMsg, key) + case "labels": + err = unpopulate(val, "Labels", &s.Labels) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &s.ProvisioningState) + delete(rawMsg, key) + case "refreshInterval": + err = unpopulate(val, "RefreshInterval", &s.RefreshInterval) + delete(rawMsg, key) + case "signalKind": + err = unpopulate(val, "SignalKind", &s.SignalKind) + 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 SignalGroup. +func (s SignalGroup) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "azureLogAnalytics", s.AzureLogAnalytics) + populate(objectMap, "azureMonitorWorkspace", s.AzureMonitorWorkspace) + populate(objectMap, "azureResource", s.AzureResource) + populate(objectMap, "dependencies", s.Dependencies) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SignalGroup. +func (s *SignalGroup) 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 "azureLogAnalytics": + err = unpopulate(val, "AzureLogAnalytics", &s.AzureLogAnalytics) + delete(rawMsg, key) + case "azureMonitorWorkspace": + err = unpopulate(val, "AzureMonitorWorkspace", &s.AzureMonitorWorkspace) + delete(rawMsg, key) + case "azureResource": + err = unpopulate(val, "AzureResource", &s.AzureResource) + delete(rawMsg, key) + case "dependencies": + err = unpopulate(val, "Dependencies", &s.Dependencies) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SystemData. +func (s SystemData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateDateTimeRFC3339(objectMap, "createdAt", s.CreatedAt) + populate(objectMap, "createdBy", s.CreatedBy) + populate(objectMap, "createdByType", s.CreatedByType) + populateDateTimeRFC3339(objectMap, "lastModifiedAt", s.LastModifiedAt) + populate(objectMap, "lastModifiedBy", s.LastModifiedBy) + populate(objectMap, "lastModifiedByType", s.LastModifiedByType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SystemData. +func (s *SystemData) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "createdAt": + err = unpopulateDateTimeRFC3339(val, "CreatedAt", &s.CreatedAt) + delete(rawMsg, key) + case "createdBy": + err = unpopulate(val, "CreatedBy", &s.CreatedBy) + delete(rawMsg, key) + case "createdByType": + err = unpopulate(val, "CreatedByType", &s.CreatedByType) + delete(rawMsg, key) + case "lastModifiedAt": + err = unpopulateDateTimeRFC3339(val, "LastModifiedAt", &s.LastModifiedAt) + delete(rawMsg, key) + case "lastModifiedBy": + err = unpopulate(val, "LastModifiedBy", &s.LastModifiedBy) + delete(rawMsg, key) + case "lastModifiedByType": + err = unpopulate(val, "LastModifiedByType", &s.LastModifiedByType) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ThresholdRule. +func (t ThresholdRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "operator", t.Operator) + populate(objectMap, "threshold", t.Threshold) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ThresholdRule. +func (t *ThresholdRule) 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 "operator": + err = unpopulate(val, "Operator", &t.Operator) + delete(rawMsg, key) + case "threshold": + err = unpopulate(val, "Threshold", &t.Threshold) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UserAssignedIdentity. +func (u UserAssignedIdentity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "clientId", u.ClientID) + populate(objectMap, "principalId", u.PrincipalID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UserAssignedIdentity. +func (u *UserAssignedIdentity) 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", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "clientId": + err = unpopulate(val, "ClientID", &u.ClientID) + delete(rawMsg, key) + case "principalId": + err = unpopulate(val, "PrincipalID", &u.PrincipalID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/sdk/resourcemanager/cloudhealth/armcloudhealth/operations_client.go b/sdk/resourcemanager/cloudhealth/armcloudhealth/operations_client.go new file mode 100644 index 000000000000..24a1ed8cbef5 --- /dev/null +++ b/sdk/resourcemanager/cloudhealth/armcloudhealth/operations_client.go @@ -0,0 +1,85 @@ +// 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 armcloudhealth + +import ( + "context" + "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" +) + +// OperationsClient contains the methods for the Operations group. +// Don't use this type directly, use NewOperationsClient() instead. +type OperationsClient struct { + internal *arm.Client +} + +// NewOperationsClient creates a new instance of OperationsClient with the specified values. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewOperationsClient(credential azcore.TokenCredential, options *arm.ClientOptions) (*OperationsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &OperationsClient{ + internal: cl, + } + return client, nil +} + +// NewListPager - List the operations for the provider +// +// Generated from API version 2023-10-01-preview +// - options - OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +func (client *OperationsClient) NewListPager(options *OperationsClientListOptions) *runtime.Pager[OperationsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[OperationsClientListResponse]{ + More: func(page OperationsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *OperationsClientListResponse) (OperationsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "OperationsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, options) + }, nil) + if err != nil { + return OperationsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *OperationsClient) listCreateRequest(ctx context.Context, _ *OperationsClientListOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.CloudHealth/operations" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-10-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *OperationsClient) listHandleResponse(resp *http.Response) (OperationsClientListResponse, error) { + result := OperationsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.OperationListResult); err != nil { + return OperationsClientListResponse{}, err + } + return result, nil +} diff --git a/sdk/resourcemanager/cloudhealth/armcloudhealth/options.go b/sdk/resourcemanager/cloudhealth/armcloudhealth/options.go new file mode 100644 index 000000000000..6c82c41351af --- /dev/null +++ b/sdk/resourcemanager/cloudhealth/armcloudhealth/options.go @@ -0,0 +1,165 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armcloudhealth + +import "time" + +// AuthenticationSettingsClientCreateOrUpdateOptions contains the optional parameters for the AuthenticationSettingsClient.CreateOrUpdate +// method. +type AuthenticationSettingsClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// AuthenticationSettingsClientDeleteOptions contains the optional parameters for the AuthenticationSettingsClient.Delete +// method. +type AuthenticationSettingsClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// AuthenticationSettingsClientGetOptions contains the optional parameters for the AuthenticationSettingsClient.Get method. +type AuthenticationSettingsClientGetOptions struct { + // placeholder for future optional parameters +} + +// AuthenticationSettingsClientListByHealthModelOptions contains the optional parameters for the AuthenticationSettingsClient.NewListByHealthModelPager +// method. +type AuthenticationSettingsClientListByHealthModelOptions struct { + // placeholder for future optional parameters +} + +// DiscoveryRulesClientCreateOrUpdateOptions contains the optional parameters for the DiscoveryRulesClient.CreateOrUpdate +// method. +type DiscoveryRulesClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// DiscoveryRulesClientDeleteOptions contains the optional parameters for the DiscoveryRulesClient.Delete method. +type DiscoveryRulesClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// DiscoveryRulesClientGetOptions contains the optional parameters for the DiscoveryRulesClient.Get method. +type DiscoveryRulesClientGetOptions struct { + // placeholder for future optional parameters +} + +// DiscoveryRulesClientListByHealthModelOptions contains the optional parameters for the DiscoveryRulesClient.NewListByHealthModelPager +// method. +type DiscoveryRulesClientListByHealthModelOptions struct { + // Timestamp to use for the operation. When specified, the version of the resource at this point in time is retrieved. If + // not specified, the latest version is used. + Timestamp *time.Time +} + +// EntitiesClientCreateOrUpdateOptions contains the optional parameters for the EntitiesClient.CreateOrUpdate method. +type EntitiesClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// EntitiesClientDeleteOptions contains the optional parameters for the EntitiesClient.Delete method. +type EntitiesClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// EntitiesClientGetOptions contains the optional parameters for the EntitiesClient.Get method. +type EntitiesClientGetOptions struct { + // placeholder for future optional parameters +} + +// EntitiesClientListByHealthModelOptions contains the optional parameters for the EntitiesClient.NewListByHealthModelPager +// method. +type EntitiesClientListByHealthModelOptions struct { + // Timestamp to use for the operation. When specified, the version of the resource at this point in time is retrieved. If + // not specified, the latest version is used. + Timestamp *time.Time +} + +// HealthModelsClientBeginCreateOptions contains the optional parameters for the HealthModelsClient.BeginCreate method. +type HealthModelsClientBeginCreateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// HealthModelsClientBeginDeleteOptions contains the optional parameters for the HealthModelsClient.BeginDelete method. +type HealthModelsClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// HealthModelsClientBeginUpdateOptions contains the optional parameters for the HealthModelsClient.BeginUpdate method. +type HealthModelsClientBeginUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// HealthModelsClientGetOptions contains the optional parameters for the HealthModelsClient.Get method. +type HealthModelsClientGetOptions struct { + // placeholder for future optional parameters +} + +// HealthModelsClientListByResourceGroupOptions contains the optional parameters for the HealthModelsClient.NewListByResourceGroupPager +// method. +type HealthModelsClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// HealthModelsClientListBySubscriptionOptions contains the optional parameters for the HealthModelsClient.NewListBySubscriptionPager +// method. +type HealthModelsClientListBySubscriptionOptions struct { + // placeholder for future optional parameters +} + +// OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +type OperationsClientListOptions struct { + // placeholder for future optional parameters +} + +// RelationshipsClientCreateOrUpdateOptions contains the optional parameters for the RelationshipsClient.CreateOrUpdate method. +type RelationshipsClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// RelationshipsClientDeleteOptions contains the optional parameters for the RelationshipsClient.Delete method. +type RelationshipsClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// RelationshipsClientGetOptions contains the optional parameters for the RelationshipsClient.Get method. +type RelationshipsClientGetOptions struct { + // placeholder for future optional parameters +} + +// RelationshipsClientListByHealthModelOptions contains the optional parameters for the RelationshipsClient.NewListByHealthModelPager +// method. +type RelationshipsClientListByHealthModelOptions struct { + // Timestamp to use for the operation. When specified, the version of the resource at this point in time is retrieved. If + // not specified, the latest version is used. + Timestamp *time.Time +} + +// SignalDefinitionsClientCreateOrUpdateOptions contains the optional parameters for the SignalDefinitionsClient.CreateOrUpdate +// method. +type SignalDefinitionsClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// SignalDefinitionsClientDeleteOptions contains the optional parameters for the SignalDefinitionsClient.Delete method. +type SignalDefinitionsClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// SignalDefinitionsClientGetOptions contains the optional parameters for the SignalDefinitionsClient.Get method. +type SignalDefinitionsClientGetOptions struct { + // placeholder for future optional parameters +} + +// SignalDefinitionsClientListByHealthModelOptions contains the optional parameters for the SignalDefinitionsClient.NewListByHealthModelPager +// method. +type SignalDefinitionsClientListByHealthModelOptions struct { + // Timestamp to use for the operation. When specified, the version of the resource at this point in time is retrieved. If + // not specified, the latest version is used. + Timestamp *time.Time +} diff --git a/sdk/resourcemanager/cloudhealth/armcloudhealth/polymorphic_helpers.go b/sdk/resourcemanager/cloudhealth/armcloudhealth/polymorphic_helpers.go new file mode 100644 index 000000000000..ccbdd3aa990c --- /dev/null +++ b/sdk/resourcemanager/cloudhealth/armcloudhealth/polymorphic_helpers.go @@ -0,0 +1,54 @@ +// 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 armcloudhealth + +import "encoding/json" + +func unmarshalAuthenticationSettingPropertiesClassification(rawMsg json.RawMessage) (AuthenticationSettingPropertiesClassification, error) { + if rawMsg == nil || string(rawMsg) == "null" { + return nil, nil + } + var m map[string]any + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b AuthenticationSettingPropertiesClassification + switch m["authenticationKind"] { + case string(AuthenticationKindManagedIdentity): + b = &ManagedIdentityAuthenticationSettingProperties{} + default: + b = &AuthenticationSettingProperties{} + } + if err := json.Unmarshal(rawMsg, b); err != nil { + return nil, err + } + return b, nil +} + +func unmarshalSignalDefinitionPropertiesClassification(rawMsg json.RawMessage) (SignalDefinitionPropertiesClassification, error) { + if rawMsg == nil || string(rawMsg) == "null" { + return nil, nil + } + var m map[string]any + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b SignalDefinitionPropertiesClassification + switch m["signalKind"] { + case string(SignalKindAzureResourceMetric): + b = &ResourceMetricSignalDefinitionProperties{} + case string(SignalKindLogAnalyticsQuery): + b = &LogAnalyticsQuerySignalDefinitionProperties{} + case string(SignalKindPrometheusMetricsQuery): + b = &PrometheusMetricsSignalDefinitionProperties{} + default: + b = &SignalDefinitionProperties{} + } + if err := json.Unmarshal(rawMsg, b); err != nil { + return nil, err + } + return b, nil +} diff --git a/sdk/resourcemanager/cloudhealth/armcloudhealth/relationships_client.go b/sdk/resourcemanager/cloudhealth/armcloudhealth/relationships_client.go new file mode 100644 index 000000000000..6eaabb2cd823 --- /dev/null +++ b/sdk/resourcemanager/cloudhealth/armcloudhealth/relationships_client.go @@ -0,0 +1,315 @@ +// 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 armcloudhealth + +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" + "time" +) + +// RelationshipsClient contains the methods for the Relationships group. +// Don't use this type directly, use NewRelationshipsClient() instead. +type RelationshipsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewRelationshipsClient creates a new instance of RelationshipsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewRelationshipsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*RelationshipsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &RelationshipsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CreateOrUpdate - Create a Relationship +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-10-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - healthModelName - Name of health model resource +// - relationshipName - Name of the relationship. Must be unique within a health model. For example, a concatenation of parentEntityName +// and childEntityName can be used as the name. +// - resource - Resource create parameters. +// - options - RelationshipsClientCreateOrUpdateOptions contains the optional parameters for the RelationshipsClient.CreateOrUpdate +// method. +func (client *RelationshipsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, healthModelName string, relationshipName string, resource Relationship, options *RelationshipsClientCreateOrUpdateOptions) (RelationshipsClientCreateOrUpdateResponse, error) { + var err error + const operationName = "RelationshipsClient.CreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, healthModelName, relationshipName, resource, options) + if err != nil { + return RelationshipsClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return RelationshipsClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return RelationshipsClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *RelationshipsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, healthModelName string, relationshipName string, resource Relationship, _ *RelationshipsClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/relationships/{relationshipName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if healthModelName == "" { + return nil, errors.New("parameter healthModelName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{healthModelName}", url.PathEscape(healthModelName)) + if relationshipName == "" { + return nil, errors.New("parameter relationshipName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{relationshipName}", url.PathEscape(relationshipName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-10-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *RelationshipsClient) createOrUpdateHandleResponse(resp *http.Response) (RelationshipsClientCreateOrUpdateResponse, error) { + result := RelationshipsClientCreateOrUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Relationship); err != nil { + return RelationshipsClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// Delete - Delete a Relationship +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-10-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - healthModelName - Name of health model resource +// - relationshipName - Name of the relationship. Must be unique within a health model. For example, a concatenation of parentEntityName +// and childEntityName can be used as the name. +// - options - RelationshipsClientDeleteOptions contains the optional parameters for the RelationshipsClient.Delete method. +func (client *RelationshipsClient) Delete(ctx context.Context, resourceGroupName string, healthModelName string, relationshipName string, options *RelationshipsClientDeleteOptions) (RelationshipsClientDeleteResponse, error) { + var err error + const operationName = "RelationshipsClient.Delete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, healthModelName, relationshipName, options) + if err != nil { + return RelationshipsClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return RelationshipsClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return RelationshipsClientDeleteResponse{}, err + } + return RelationshipsClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *RelationshipsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, healthModelName string, relationshipName string, _ *RelationshipsClientDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/relationships/{relationshipName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if healthModelName == "" { + return nil, errors.New("parameter healthModelName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{healthModelName}", url.PathEscape(healthModelName)) + if relationshipName == "" { + return nil, errors.New("parameter relationshipName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{relationshipName}", url.PathEscape(relationshipName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-10-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Get a Relationship +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-10-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - healthModelName - Name of health model resource +// - relationshipName - Name of the relationship. Must be unique within a health model. For example, a concatenation of parentEntityName +// and childEntityName can be used as the name. +// - options - RelationshipsClientGetOptions contains the optional parameters for the RelationshipsClient.Get method. +func (client *RelationshipsClient) Get(ctx context.Context, resourceGroupName string, healthModelName string, relationshipName string, options *RelationshipsClientGetOptions) (RelationshipsClientGetResponse, error) { + var err error + const operationName = "RelationshipsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, healthModelName, relationshipName, options) + if err != nil { + return RelationshipsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return RelationshipsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return RelationshipsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *RelationshipsClient) getCreateRequest(ctx context.Context, resourceGroupName string, healthModelName string, relationshipName string, _ *RelationshipsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/relationships/{relationshipName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if healthModelName == "" { + return nil, errors.New("parameter healthModelName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{healthModelName}", url.PathEscape(healthModelName)) + if relationshipName == "" { + return nil, errors.New("parameter relationshipName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{relationshipName}", url.PathEscape(relationshipName)) + 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-10-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *RelationshipsClient) getHandleResponse(resp *http.Response) (RelationshipsClientGetResponse, error) { + result := RelationshipsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Relationship); err != nil { + return RelationshipsClientGetResponse{}, err + } + return result, nil +} + +// NewListByHealthModelPager - List Relationship resources by HealthModel +// +// Generated from API version 2023-10-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - healthModelName - Name of health model resource +// - options - RelationshipsClientListByHealthModelOptions contains the optional parameters for the RelationshipsClient.NewListByHealthModelPager +// method. +func (client *RelationshipsClient) NewListByHealthModelPager(resourceGroupName string, healthModelName string, options *RelationshipsClientListByHealthModelOptions) *runtime.Pager[RelationshipsClientListByHealthModelResponse] { + return runtime.NewPager(runtime.PagingHandler[RelationshipsClientListByHealthModelResponse]{ + More: func(page RelationshipsClientListByHealthModelResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *RelationshipsClientListByHealthModelResponse) (RelationshipsClientListByHealthModelResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "RelationshipsClient.NewListByHealthModelPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByHealthModelCreateRequest(ctx, resourceGroupName, healthModelName, options) + }, nil) + if err != nil { + return RelationshipsClientListByHealthModelResponse{}, err + } + return client.listByHealthModelHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByHealthModelCreateRequest creates the ListByHealthModel request. +func (client *RelationshipsClient) listByHealthModelCreateRequest(ctx context.Context, resourceGroupName string, healthModelName string, options *RelationshipsClientListByHealthModelOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/relationships" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if healthModelName == "" { + return nil, errors.New("parameter healthModelName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{healthModelName}", url.PathEscape(healthModelName)) + 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-10-01-preview") + if options != nil && options.Timestamp != nil { + reqQP.Set("timestamp", options.Timestamp.Format(time.RFC3339Nano)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByHealthModelHandleResponse handles the ListByHealthModel response. +func (client *RelationshipsClient) listByHealthModelHandleResponse(resp *http.Response) (RelationshipsClientListByHealthModelResponse, error) { + result := RelationshipsClientListByHealthModelResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RelationshipListResult); err != nil { + return RelationshipsClientListByHealthModelResponse{}, err + } + return result, nil +} diff --git a/sdk/resourcemanager/cloudhealth/armcloudhealth/responses.go b/sdk/resourcemanager/cloudhealth/armcloudhealth/responses.go new file mode 100644 index 000000000000..64bccf375a85 --- /dev/null +++ b/sdk/resourcemanager/cloudhealth/armcloudhealth/responses.go @@ -0,0 +1,164 @@ +// 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 armcloudhealth + +// AuthenticationSettingsClientCreateOrUpdateResponse contains the response from method AuthenticationSettingsClient.CreateOrUpdate. +type AuthenticationSettingsClientCreateOrUpdateResponse struct { + // An authentication setting in a health model + AuthenticationSetting +} + +// AuthenticationSettingsClientDeleteResponse contains the response from method AuthenticationSettingsClient.Delete. +type AuthenticationSettingsClientDeleteResponse struct { + // placeholder for future response values +} + +// AuthenticationSettingsClientGetResponse contains the response from method AuthenticationSettingsClient.Get. +type AuthenticationSettingsClientGetResponse struct { + // An authentication setting in a health model + AuthenticationSetting +} + +// AuthenticationSettingsClientListByHealthModelResponse contains the response from method AuthenticationSettingsClient.NewListByHealthModelPager. +type AuthenticationSettingsClientListByHealthModelResponse struct { + // The response of a AuthenticationSetting list operation. + AuthenticationSettingListResult +} + +// DiscoveryRulesClientCreateOrUpdateResponse contains the response from method DiscoveryRulesClient.CreateOrUpdate. +type DiscoveryRulesClientCreateOrUpdateResponse struct { + // A discovery rule which automatically finds entities and relationships in a health model based on an Azure Resource Graph + // query + DiscoveryRule +} + +// DiscoveryRulesClientDeleteResponse contains the response from method DiscoveryRulesClient.Delete. +type DiscoveryRulesClientDeleteResponse struct { + // placeholder for future response values +} + +// DiscoveryRulesClientGetResponse contains the response from method DiscoveryRulesClient.Get. +type DiscoveryRulesClientGetResponse struct { + // A discovery rule which automatically finds entities and relationships in a health model based on an Azure Resource Graph + // query + DiscoveryRule +} + +// DiscoveryRulesClientListByHealthModelResponse contains the response from method DiscoveryRulesClient.NewListByHealthModelPager. +type DiscoveryRulesClientListByHealthModelResponse struct { + // The response of a DiscoveryRule list operation. + DiscoveryRuleListResult +} + +// EntitiesClientCreateOrUpdateResponse contains the response from method EntitiesClient.CreateOrUpdate. +type EntitiesClientCreateOrUpdateResponse struct { + // An entity (aka node) of a health model + Entity +} + +// EntitiesClientDeleteResponse contains the response from method EntitiesClient.Delete. +type EntitiesClientDeleteResponse struct { + // placeholder for future response values +} + +// EntitiesClientGetResponse contains the response from method EntitiesClient.Get. +type EntitiesClientGetResponse struct { + // An entity (aka node) of a health model + Entity +} + +// EntitiesClientListByHealthModelResponse contains the response from method EntitiesClient.NewListByHealthModelPager. +type EntitiesClientListByHealthModelResponse struct { + // The response of a Entity list operation. + EntityListResult +} + +// HealthModelsClientCreateResponse contains the response from method HealthModelsClient.BeginCreate. +type HealthModelsClientCreateResponse struct { + // A HealthModel resource + HealthModel +} + +// HealthModelsClientDeleteResponse contains the response from method HealthModelsClient.BeginDelete. +type HealthModelsClientDeleteResponse struct { + // placeholder for future response values +} + +// HealthModelsClientGetResponse contains the response from method HealthModelsClient.Get. +type HealthModelsClientGetResponse struct { + // A HealthModel resource + HealthModel +} + +// HealthModelsClientListByResourceGroupResponse contains the response from method HealthModelsClient.NewListByResourceGroupPager. +type HealthModelsClientListByResourceGroupResponse struct { + // The response of a HealthModel list operation. + HealthModelListResult +} + +// HealthModelsClientListBySubscriptionResponse contains the response from method HealthModelsClient.NewListBySubscriptionPager. +type HealthModelsClientListBySubscriptionResponse struct { + // The response of a HealthModel list operation. + HealthModelListResult +} + +// HealthModelsClientUpdateResponse contains the response from method HealthModelsClient.BeginUpdate. +type HealthModelsClientUpdateResponse struct { + // A HealthModel resource + HealthModel +} + +// OperationsClientListResponse contains the response from method OperationsClient.NewListPager. +type OperationsClientListResponse struct { + // A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of results. + OperationListResult +} + +// RelationshipsClientCreateOrUpdateResponse contains the response from method RelationshipsClient.CreateOrUpdate. +type RelationshipsClientCreateOrUpdateResponse struct { + // A relationship (aka edge) between two entities in a health model + Relationship +} + +// RelationshipsClientDeleteResponse contains the response from method RelationshipsClient.Delete. +type RelationshipsClientDeleteResponse struct { + // placeholder for future response values +} + +// RelationshipsClientGetResponse contains the response from method RelationshipsClient.Get. +type RelationshipsClientGetResponse struct { + // A relationship (aka edge) between two entities in a health model + Relationship +} + +// RelationshipsClientListByHealthModelResponse contains the response from method RelationshipsClient.NewListByHealthModelPager. +type RelationshipsClientListByHealthModelResponse struct { + // The response of a Relationship list operation. + RelationshipListResult +} + +// SignalDefinitionsClientCreateOrUpdateResponse contains the response from method SignalDefinitionsClient.CreateOrUpdate. +type SignalDefinitionsClientCreateOrUpdateResponse struct { + // A signal definition in a health model + SignalDefinition +} + +// SignalDefinitionsClientDeleteResponse contains the response from method SignalDefinitionsClient.Delete. +type SignalDefinitionsClientDeleteResponse struct { + // placeholder for future response values +} + +// SignalDefinitionsClientGetResponse contains the response from method SignalDefinitionsClient.Get. +type SignalDefinitionsClientGetResponse struct { + // A signal definition in a health model + SignalDefinition +} + +// SignalDefinitionsClientListByHealthModelResponse contains the response from method SignalDefinitionsClient.NewListByHealthModelPager. +type SignalDefinitionsClientListByHealthModelResponse struct { + // The response of a SignalDefinition list operation. + SignalDefinitionListResult +} diff --git a/sdk/resourcemanager/cloudhealth/armcloudhealth/signaldefinitions_client.go b/sdk/resourcemanager/cloudhealth/armcloudhealth/signaldefinitions_client.go new file mode 100644 index 000000000000..088a05d7d874 --- /dev/null +++ b/sdk/resourcemanager/cloudhealth/armcloudhealth/signaldefinitions_client.go @@ -0,0 +1,313 @@ +// 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 armcloudhealth + +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" + "time" +) + +// SignalDefinitionsClient contains the methods for the SignalDefinitions group. +// Don't use this type directly, use NewSignalDefinitionsClient() instead. +type SignalDefinitionsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewSignalDefinitionsClient creates a new instance of SignalDefinitionsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewSignalDefinitionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*SignalDefinitionsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &SignalDefinitionsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CreateOrUpdate - Create a SignalDefinition +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-10-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - healthModelName - Name of health model resource +// - signalDefinitionName - Name of the signal definition. Must be unique within a health model. +// - resource - Resource create parameters. +// - options - SignalDefinitionsClientCreateOrUpdateOptions contains the optional parameters for the SignalDefinitionsClient.CreateOrUpdate +// method. +func (client *SignalDefinitionsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, healthModelName string, signalDefinitionName string, resource SignalDefinition, options *SignalDefinitionsClientCreateOrUpdateOptions) (SignalDefinitionsClientCreateOrUpdateResponse, error) { + var err error + const operationName = "SignalDefinitionsClient.CreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, healthModelName, signalDefinitionName, resource, options) + if err != nil { + return SignalDefinitionsClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SignalDefinitionsClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return SignalDefinitionsClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *SignalDefinitionsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, healthModelName string, signalDefinitionName string, resource SignalDefinition, _ *SignalDefinitionsClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/signaldefinitions/{signalDefinitionName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if healthModelName == "" { + return nil, errors.New("parameter healthModelName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{healthModelName}", url.PathEscape(healthModelName)) + if signalDefinitionName == "" { + return nil, errors.New("parameter signalDefinitionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{signalDefinitionName}", url.PathEscape(signalDefinitionName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-10-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *SignalDefinitionsClient) createOrUpdateHandleResponse(resp *http.Response) (SignalDefinitionsClientCreateOrUpdateResponse, error) { + result := SignalDefinitionsClientCreateOrUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SignalDefinition); err != nil { + return SignalDefinitionsClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// Delete - Delete a SignalDefinition +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-10-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - healthModelName - Name of health model resource +// - signalDefinitionName - Name of the signal definition. Must be unique within a health model. +// - options - SignalDefinitionsClientDeleteOptions contains the optional parameters for the SignalDefinitionsClient.Delete +// method. +func (client *SignalDefinitionsClient) Delete(ctx context.Context, resourceGroupName string, healthModelName string, signalDefinitionName string, options *SignalDefinitionsClientDeleteOptions) (SignalDefinitionsClientDeleteResponse, error) { + var err error + const operationName = "SignalDefinitionsClient.Delete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, healthModelName, signalDefinitionName, options) + if err != nil { + return SignalDefinitionsClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SignalDefinitionsClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SignalDefinitionsClientDeleteResponse{}, err + } + return SignalDefinitionsClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *SignalDefinitionsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, healthModelName string, signalDefinitionName string, _ *SignalDefinitionsClientDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/signaldefinitions/{signalDefinitionName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if healthModelName == "" { + return nil, errors.New("parameter healthModelName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{healthModelName}", url.PathEscape(healthModelName)) + if signalDefinitionName == "" { + return nil, errors.New("parameter signalDefinitionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{signalDefinitionName}", url.PathEscape(signalDefinitionName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2023-10-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Get a SignalDefinition +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2023-10-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - healthModelName - Name of health model resource +// - signalDefinitionName - Name of the signal definition. Must be unique within a health model. +// - options - SignalDefinitionsClientGetOptions contains the optional parameters for the SignalDefinitionsClient.Get method. +func (client *SignalDefinitionsClient) Get(ctx context.Context, resourceGroupName string, healthModelName string, signalDefinitionName string, options *SignalDefinitionsClientGetOptions) (SignalDefinitionsClientGetResponse, error) { + var err error + const operationName = "SignalDefinitionsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, healthModelName, signalDefinitionName, options) + if err != nil { + return SignalDefinitionsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SignalDefinitionsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return SignalDefinitionsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *SignalDefinitionsClient) getCreateRequest(ctx context.Context, resourceGroupName string, healthModelName string, signalDefinitionName string, _ *SignalDefinitionsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/signaldefinitions/{signalDefinitionName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if healthModelName == "" { + return nil, errors.New("parameter healthModelName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{healthModelName}", url.PathEscape(healthModelName)) + if signalDefinitionName == "" { + return nil, errors.New("parameter signalDefinitionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{signalDefinitionName}", url.PathEscape(signalDefinitionName)) + 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-10-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *SignalDefinitionsClient) getHandleResponse(resp *http.Response) (SignalDefinitionsClientGetResponse, error) { + result := SignalDefinitionsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SignalDefinition); err != nil { + return SignalDefinitionsClientGetResponse{}, err + } + return result, nil +} + +// NewListByHealthModelPager - List SignalDefinition resources by HealthModel +// +// Generated from API version 2023-10-01-preview +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - healthModelName - Name of health model resource +// - options - SignalDefinitionsClientListByHealthModelOptions contains the optional parameters for the SignalDefinitionsClient.NewListByHealthModelPager +// method. +func (client *SignalDefinitionsClient) NewListByHealthModelPager(resourceGroupName string, healthModelName string, options *SignalDefinitionsClientListByHealthModelOptions) *runtime.Pager[SignalDefinitionsClientListByHealthModelResponse] { + return runtime.NewPager(runtime.PagingHandler[SignalDefinitionsClientListByHealthModelResponse]{ + More: func(page SignalDefinitionsClientListByHealthModelResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *SignalDefinitionsClientListByHealthModelResponse) (SignalDefinitionsClientListByHealthModelResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "SignalDefinitionsClient.NewListByHealthModelPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByHealthModelCreateRequest(ctx, resourceGroupName, healthModelName, options) + }, nil) + if err != nil { + return SignalDefinitionsClientListByHealthModelResponse{}, err + } + return client.listByHealthModelHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByHealthModelCreateRequest creates the ListByHealthModel request. +func (client *SignalDefinitionsClient) listByHealthModelCreateRequest(ctx context.Context, resourceGroupName string, healthModelName string, options *SignalDefinitionsClientListByHealthModelOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/signaldefinitions" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if healthModelName == "" { + return nil, errors.New("parameter healthModelName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{healthModelName}", url.PathEscape(healthModelName)) + 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-10-01-preview") + if options != nil && options.Timestamp != nil { + reqQP.Set("timestamp", options.Timestamp.Format(time.RFC3339Nano)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByHealthModelHandleResponse handles the ListByHealthModel response. +func (client *SignalDefinitionsClient) listByHealthModelHandleResponse(resp *http.Response) (SignalDefinitionsClientListByHealthModelResponse, error) { + result := SignalDefinitionsClientListByHealthModelResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SignalDefinitionListResult); err != nil { + return SignalDefinitionsClientListByHealthModelResponse{}, err + } + return result, nil +} diff --git a/sdk/resourcemanager/cloudhealth/armcloudhealth/time_rfc3339.go b/sdk/resourcemanager/cloudhealth/armcloudhealth/time_rfc3339.go new file mode 100644 index 000000000000..0882ef09f77b --- /dev/null +++ b/sdk/resourcemanager/cloudhealth/armcloudhealth/time_rfc3339.go @@ -0,0 +1,110 @@ +// 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 armcloudhealth + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" + "regexp" + "strings" + "time" +) + +// Azure reports time in UTC but it doesn't include the 'Z' time zone suffix in some cases. +var tzOffsetRegex = regexp.MustCompile(`(?:Z|z|\+|-)(?:\d+:\d+)*"*$`) + +const ( + 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 + +func (t dateTimeRFC3339) MarshalJSON() ([]byte, error) { + tt := time.Time(t) + return tt.MarshalJSON() +} + +func (t dateTimeRFC3339) MarshalText() ([]byte, error) { + tt := time.Time(t) + return tt.MarshalText() +} + +func (t *dateTimeRFC3339) UnmarshalJSON(data []byte) error { + 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 { + if len(data) == 0 { + return nil + } + tzOffset := tzOffsetRegex.Match(data) + hasT := strings.Contains(string(data), "T") || strings.Contains(string(data), "t") + var layout string + if tzOffset && hasT { + layout = time.RFC3339Nano + } else if tzOffset { + layout = dateTimeNoT + } else if hasT { + layout = utcDateTime + } else { + layout = utcDateTimeNoT + } + return t.Parse(layout, string(data)) +} + +func (t *dateTimeRFC3339) Parse(layout, value string) error { + p, err := time.Parse(layout, strings.ToUpper(value)) + *t = dateTimeRFC3339(p) + 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 + } else if azcore.IsNullValue(t) { + m[k] = nil + return + } else if reflect.ValueOf(t).IsNil() { + return + } + m[k] = (*dateTimeRFC3339)(t) +} + +func unpopulateDateTimeRFC3339(data json.RawMessage, fn string, t **time.Time) error { + if data == nil || string(data) == "null" { + return nil + } + var aux dateTimeRFC3339 + if err := json.Unmarshal(data, &aux); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + *t = (*time.Time)(&aux) + return nil +}